diff --git a/build/three.core.js b/build/three.core.js index 3d9343f14f380c..616ad851ff51b0 100644 --- a/build/three.core.js +++ b/build/three.core.js @@ -7030,10 +7030,10 @@ let _sourceId = 0; * The main purpose of this class is to decouple the data definition from the texture * definition so the same data can be used with multiple texture instances. */ -class Source { +class TextureSource { /** - * Constructs a new video texture. + * Constructs a new texture source. * * @param {any} [data=null] - The data definition of a texture. */ @@ -7046,12 +7046,12 @@ class Source { * @readonly * @default true */ - this.isSource = true; + this.isTextureSource = true; /** * The ID of the source. * - * @name Source#id + * @name TextureSource#id * @type {number} * @readonly */ @@ -7073,7 +7073,7 @@ class Source { this.data = data; /** - * This property is only relevant when {@link Source#needsUpdate} is set to `true` and + * This property is only relevant when {@link TextureSource#needsUpdate} is set to `true` and * provides more control on how texture data should be processed. When `dataReady` is set * to `false`, the engine performs the memory allocation (if necessary) but does not transfer * the data into the GPU memory. @@ -7084,7 +7084,7 @@ class Source { this.dataReady = true; /** - * This starts at `0` and counts how many times {@link Source#needsUpdate} is set to `true`. + * This starts at `0` and counts how many times {@link TextureSource#needsUpdate} is set to `true`. * * @type {number} * @readonly @@ -7247,6 +7247,37 @@ function serializeImage( image ) { } +/** + * @deprecated since r186. Use {@link TextureSource} instead. `Source` has been renamed to `TextureSource`. + */ +class Source extends TextureSource { + + /** + * Constructs a new texture source. + * + * @param {any} [data=null] - The data definition of a texture. + * @deprecated since r186. Use {@link TextureSource} instead. + */ + constructor( data = null ) { + + warnOnce( 'Source: "Source" has been renamed to "TextureSource". Please update your code to use "THREE.TextureSource" instead.' ); // @deprecated, r186 + + super( data ); + + /** + * This flag can be used for type testing. + * + * @deprecated since r186. Use {@link TextureSource#isTextureSource} instead. + * @type {boolean} + * @readonly + * @default true + */ + this.isSource = true; + + } + +} + let _textureId = 0; const _tempVec3 = /*@__PURE__*/ new Vector3(); @@ -7318,9 +7349,9 @@ class Texture extends EventDispatcher { * where multiple textures render the same data but with different texture * transformations. * - * @type {Source} + * @type {TextureSource} */ - this.source = new Source( image ); + this.source = new TextureSource( image ); /** * An array holding user-defined mipmaps. @@ -9533,7 +9564,7 @@ class RenderTarget extends EventDispatcher { // ensure image object is not shared, see #20328 const image = Object.assign( {}, source.textures[ i ].image ); - this.textures[ i ].source = new Source( image ); + this.textures[ i ].source = new TextureSource( image ); } @@ -16411,13 +16442,13 @@ class Box3 { } // compute box center and extents - this.getCenter( _center ); - _extents.subVectors( this.max, _center ); + this.getCenter( _center$1 ); + _extents.subVectors( this.max, _center$1 ); // translate triangle to aabb origin - _v0$1.subVectors( triangle.a, _center ); - _v1$4.subVectors( triangle.b, _center ); - _v2$3.subVectors( triangle.c, _center ); + _v0$1.subVectors( triangle.a, _center$1 ); + _v1$4.subVectors( triangle.b, _center$1 ); + _v2$3.subVectors( triangle.c, _center$1 ); // compute edge vectors for triangle _f0.subVectors( _v1$4, _v0$1 ); @@ -16655,7 +16686,7 @@ const _f0 = /*@__PURE__*/ new Vector3(); const _f1 = /*@__PURE__*/ new Vector3(); const _f2 = /*@__PURE__*/ new Vector3(); -const _center = /*@__PURE__*/ new Vector3(); +const _center$1 = /*@__PURE__*/ new Vector3(); const _extents = /*@__PURE__*/ new Vector3(); const _triangleNormal = /*@__PURE__*/ new Vector3(); const _testAxis = /*@__PURE__*/ new Vector3(); @@ -26528,6 +26559,7 @@ class BatchedMesh extends Mesh { this._multiDrawCounts = new Int32Array( maxInstanceCount ); this._multiDrawStarts = new Int32Array( maxInstanceCount ); this._multiDrawCount = 0; + this._multiDrawBytesPerElement = 1; // Local matrix per geometry by using data texture this._matricesTexture = null; @@ -27730,6 +27762,7 @@ class BatchedMesh extends Mesh { this._geometryInitialized = source._geometryInitialized; this._multiDrawCounts = source._multiDrawCounts.slice(); this._multiDrawStarts = source._multiDrawStarts.slice(); + this._multiDrawBytesPerElement = source._multiDrawBytesPerElement; this._indirectTexture = source._indirectTexture.clone(); this._indirectTexture.image.data = this._indirectTexture.image.data.slice(); @@ -27934,6 +27967,7 @@ class BatchedMesh extends Mesh { indirectTexture.needsUpdate = true; this._multiDrawCount = multiDrawCount; + this._multiDrawBytesPerElement = bytesPerElement; this._visibilityChanged = false; } @@ -29644,7 +29678,7 @@ class DepthTexture extends Texture { super.copy( source ); - this.source = new Source( Object.assign( {}, source.image ) ); // see #30540 + this.source = new TextureSource( Object.assign( {}, source.image ) ); // see #30540 this.compareFunction = source.compareFunction; return this; @@ -46052,77 +46086,6 @@ class Light extends Object3D { } -/** - * A light source positioned directly above the scene, with color fading from - * the sky color to the ground color. - * - * This light cannot be used to cast shadows. - * - * ```js - * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 ); - * scene.add( light ); - * ``` - * - * @augments Light - */ -class HemisphereLight extends Light { - - /** - * Constructs a new hemisphere light. - * - * @param {(number|Color|string)} [skyColor=0xffffff] - The light's sky color. - * @param {(number|Color|string)} [groundColor=0xffffff] - The light's ground color. - * @param {number} [intensity=1] - The light's strength/intensity. - */ - constructor( skyColor, groundColor, intensity ) { - - super( skyColor, intensity ); - - /** - * This flag can be used for type testing. - * - * @type {boolean} - * @readonly - * @default true - */ - this.isHemisphereLight = true; - - this.type = 'HemisphereLight'; - - this.position.copy( Object3D.DEFAULT_UP ); - this.updateMatrix(); - - /** - * The light's ground color. - * - * @type {Color} - */ - this.groundColor = new Color( groundColor ); - - } - - copy( source, recursive ) { - - super.copy( source, recursive ); - - this.groundColor.copy( source.groundColor ); - - return this; - - } - - toJSON( meta ) { - - const data = super.toJSON( meta ); - - data.object.groundColor = this.groundColor.getHex(); - - return data; - - } - -} - const _projScreenMatrix = /*@__PURE__*/ new Matrix4(); const _lightPositionWorld = /*@__PURE__*/ new Vector3(); const _lookTarget = /*@__PURE__*/ new Vector3(); @@ -46300,6 +46263,18 @@ class LightShadow { } + /** + * Used internally by the renderer to get the camera that renders the given viewport. + * + * @param {number} [viewportIndex=0] - The viewport index. + * @return {Camera} The shadow camera. + */ + getCamera( /* viewportIndex */ ) { + + return this.camera; + + } + /** * Gets the shadow cameras frustum. Used internally by the renderer to cull objects. * @@ -46319,23 +46294,41 @@ class LightShadow { updateMatrices( light ) { const shadowCamera = this.camera; - const shadowMatrix = this.matrix; - _lightPositionWorld.setFromMatrixPosition( light.matrixWorld ); shadowCamera.position.copy( _lightPositionWorld ); _lookTarget.setFromMatrixPosition( light.target.matrixWorld ); shadowCamera.lookAt( _lookTarget ); shadowCamera.updateMatrixWorld(); + this._updateMatrix( shadowCamera, this.matrix, this._frustum ); + + } + + /** + * Updates a shadow projection matrix and its corresponding frustum. + * + * @private + * @param {Camera} shadowCamera - The shadow camera. + * @param {Matrix4} shadowMatrix - The target shadow matrix. + * @param {Frustum} frustum - The target frustum. + * @param {Vector4} [viewport] - The viewport within the shadow atlas. + */ + _updateMatrix( shadowCamera, shadowMatrix, frustum, viewport ) { _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse ); - this._frustum.setFromProjectionMatrix( _projScreenMatrix, shadowCamera.coordinateSystem, shadowCamera.reversedDepth ); + frustum.setFromProjectionMatrix( _projScreenMatrix, shadowCamera.coordinateSystem, shadowCamera.reversedDepth ); + + const frameExtents = this._frameExtents; + const scaleX = viewport ? viewport.z / frameExtents.x : 1; + const scaleY = viewport ? viewport.w / frameExtents.y : 1; + const offsetX = viewport ? viewport.x / frameExtents.x : 0; + const offsetY = viewport ? viewport.y / frameExtents.y : 0; if ( shadowCamera.coordinateSystem === WebGPUCoordinateSystem || shadowCamera.reversedDepth ) { shadowMatrix.set( - 0.5, 0.0, 0.0, 0.5, - 0.0, 0.5, 0.0, 0.5, + 0.5 * scaleX, 0.0, 0.0, 0.5 * scaleX + offsetX, + 0.0, 0.5 * scaleY, 0.0, 0.5 * scaleY + offsetY, 0.0, 0.0, 1.0, 0.0, // Identity Z (preserving the correct [0, 1] range from the projection matrix) 0.0, 0.0, 0.0, 1.0 ); @@ -46343,8 +46336,8 @@ class LightShadow { } else { shadowMatrix.set( - 0.5, 0.0, 0.0, 0.5, - 0.0, 0.5, 0.0, 0.5, + 0.5 * scaleX, 0.0, 0.0, 0.5 * scaleX + offsetX, + 0.0, 0.5 * scaleY, 0.0, 0.5 * scaleY + offsetY, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0 ); @@ -46616,34 +46609,33 @@ class Camera extends Object3D { } -const _v3$1 = /*@__PURE__*/ new Vector3(); -const _minTarget = /*@__PURE__*/ new Vector2(); -const _maxTarget = /*@__PURE__*/ new Vector2(); - /** - * Camera that uses [perspective projection](https://en.wikipedia.org/wiki/Perspective_(graphical)). + * Camera that uses [orthographic projection](https://en.wikipedia.org/wiki/Orthographic_projection). * - * This projection mode is designed to mimic the way the human eye sees. It - * is the most common projection mode used for rendering a 3D scene. + * In this projection mode, an object's size in the rendered image stays + * constant regardless of its distance from the camera. This can be useful + * for rendering 2D scenes and UI elements, amongst other things. * * ```js - * const camera = new THREE.PerspectiveCamera( 45, width / height, 1, 1000 ); + * const camera = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, 1, 1000 ); * scene.add( camera ); * ``` * * @augments Camera */ -class PerspectiveCamera extends Camera { +class OrthographicCamera extends Camera { /** - * Constructs a new perspective camera. + * Constructs a new orthographic camera. * - * @param {number} [fov=50] - The vertical field of view. - * @param {number} [aspect=1] - The aspect ratio. + * @param {number} [left=-1] - The left plane of the camera's frustum. + * @param {number} [right=1] - The right plane of the camera's frustum. + * @param {number} [top=1] - The top plane of the camera's frustum. + * @param {number} [bottom=-1] - The bottom plane of the camera's frustum. * @param {number} [near=0.1] - The camera's near plane. * @param {number} [far=2000] - The camera's far plane. */ - constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) { + constructor( left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000 ) { super(); @@ -46654,18 +46646,9 @@ class PerspectiveCamera extends Camera { * @readonly * @default true */ - this.isPerspectiveCamera = true; - - this.type = 'PerspectiveCamera'; + this.isOrthographicCamera = true; - /** - * The vertical field of view, from bottom to top of view, - * in degrees. - * - * @type {number} - * @default 50 - */ - this.fov = fov; + this.type = 'OrthographicCamera'; /** * The zoom factor of the camera. @@ -46676,70 +46659,66 @@ class PerspectiveCamera extends Camera { this.zoom = 1; /** - * The camera's near plane. The valid range is greater than `0` - * and less than the current value of {@link PerspectiveCamera#far}. - * - * Note that, unlike for the {@link OrthographicCamera}, `0` is not a - * valid value for a perspective camera's near plane. + * Represents the frustum window specification. This property should not be edited + * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}. * - * @type {number} - * @default 0.1 + * @type {?Object} + * @default null */ - this.near = near; + this.view = null; /** - * The camera's far plane. Must be greater than the - * current value of {@link PerspectiveCamera#near}. + * The left plane of the camera's frustum. * * @type {number} - * @default 2000 + * @default -1 */ - this.far = far; + this.left = left; /** - * Object distance used for stereoscopy and depth-of-field effects. This - * parameter does not influence the projection matrix unless a - * {@link StereoCamera} is being used. + * The right plane of the camera's frustum. * * @type {number} - * @default 10 + * @default 1 */ - this.focus = 10; + this.right = right; /** - * The aspect ratio, usually the canvas width / canvas height. + * The top plane of the camera's frustum. * * @type {number} * @default 1 */ - this.aspect = aspect; + this.top = top; /** - * Represents the frustum window specification. This property should not be edited - * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}. + * The bottom plane of the camera's frustum. * - * @type {?Object} - * @default null + * @type {number} + * @default -1 */ - this.view = null; + this.bottom = bottom; /** - * Film size used for the larger axis. Default is `35` (millimeters). This - * parameter does not influence the projection matrix unless {@link PerspectiveCamera#filmOffset} - * is set to a nonzero value. + * The camera's near plane. The valid range is greater than `0` + * and less than the current value of {@link OrthographicCamera#far}. + * + * Note that, unlike for the {@link PerspectiveCamera}, `0` is a + * valid value for an orthographic camera's near plane. * * @type {number} - * @default 35 + * @default 0.1 */ - this.filmGauge = 35; + this.near = near; /** - * Horizontal off-center offset in the same unit as {@link PerspectiveCamera#filmGauge}. + * The camera's far plane. Must be greater than the + * current value of {@link OrthographicCamera#near}. * * @type {number} - * @default 0 + * @default 2000 */ - this.filmOffset = 0; + this.far = far; this.updateProjectionMatrix(); @@ -46749,175 +46728,876 @@ class PerspectiveCamera extends Camera { super.copy( source, recursive ); - this.fov = source.fov; - this.zoom = source.zoom; - + this.left = source.left; + this.right = source.right; + this.top = source.top; + this.bottom = source.bottom; this.near = source.near; this.far = source.far; - this.focus = source.focus; - this.aspect = source.aspect; + this.zoom = source.zoom; this.view = source.view === null ? null : Object.assign( {}, source.view ); - this.filmGauge = source.filmGauge; - this.filmOffset = source.filmOffset; - return this; } - /** - * Sets the FOV by focal length in respect to the current {@link PerspectiveCamera#filmGauge}. - * - * The default film gauge is 35, so that the focal length can be specified for - * a 35mm (full frame) camera. - * - * @param {number} focalLength - Values for focal length and film gauge must have the same unit. - */ - setFocalLength( focalLength ) { - - /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */ - const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength; - - this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope ); - this.updateProjectionMatrix(); - - } - - /** - * Returns the focal length from the current {@link PerspectiveCamera#fov} and - * {@link PerspectiveCamera#filmGauge}. - * - * @return {number} The computed focal length. - */ - getFocalLength() { - - const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov ); - - return 0.5 * this.getFilmHeight() / vExtentSlope; - - } - - /** - * Returns the current vertical field of view angle in degrees considering {@link PerspectiveCamera#zoom}. - * - * @return {number} The effective FOV. - */ - getEffectiveFOV() { - - return RAD2DEG * 2 * Math.atan( - Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom ); - - } - - /** - * Returns the width of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or - * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}. - * - * @return {number} The film width. - */ - getFilmWidth() { - - // film not completely covered in portrait format (aspect < 1) - return this.filmGauge * Math.min( this.aspect, 1 ); - - } - - /** - * Returns the height of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or - * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}. - * - * @return {number} The film width. - */ - getFilmHeight() { - - // film not completely covered in landscape format (aspect > 1) - return this.filmGauge / Math.max( this.aspect, 1 ); - - } - - /** - * 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. - * - * @param {number} distance - The viewing distance. - * @param {Vector2} minTarget - The lower-left corner of the view rectangle is written into this vector. - * @param {Vector2} maxTarget - The upper-right corner of the view rectangle is written into this vector. - */ - 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. - * - * @param {number} distance - The viewing distance. - * @param {Vector2} target - The target vector that is used to store result where x is width and y is height. - * @returns {Vector2} The view size. - */ - 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. * - * For example, if you have 3x2 monitors and each monitor is 1920x1080 and - * the monitors are in grid like this - *``` - * +---+---+---+ - * | A | B | C | - * +---+---+---+ - * | D | E | F | - * +---+---+---+ - *``` - * then for each monitor you would call it like this: - *```js - * const w = 1920; - * const h = 1080; - * const fullWidth = w * 3; - * const fullHeight = h * 2; - * - * // --A-- - * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h ); - * // --B-- - * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h ); - * // --C-- - * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h ); - * // --D-- - * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h ); - * // --E-- - * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h ); - * // --F-- - * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h ); - * ``` - * - * Note there is no reason monitors have to be the same size or in a grid. - * * @param {number} fullWidth - The full width of multiview setup. * @param {number} fullHeight - The full height of multiview setup. * @param {number} x - The horizontal offset of the subcamera. * @param {number} y - The vertical offset of the subcamera. * @param {number} width - The width of subcamera. * @param {number} height - The height of subcamera. + * @see {@link PerspectiveCamera#setViewOffset} */ setViewOffset( fullWidth, fullHeight, x, y, width, height ) { - this.aspect = fullWidth / fullHeight; - + if ( this.view === null ) { + + this.view = { + enabled: true, + fullWidth: 1, + fullHeight: 1, + offsetX: 0, + offsetY: 0, + width: 1, + height: 1 + }; + + } + + this.view.enabled = true; + this.view.fullWidth = fullWidth; + this.view.fullHeight = fullHeight; + this.view.offsetX = x; + this.view.offsetY = y; + this.view.width = width; + this.view.height = height; + + this.updateProjectionMatrix(); + + } + + /** + * Removes the view offset from the projection matrix. + */ + clearViewOffset() { + + if ( this.view !== null ) { + + this.view.enabled = false; + + } + + this.updateProjectionMatrix(); + + } + + /** + * Updates the camera's projection matrix. Must be called after any change of + * camera properties. + */ + updateProjectionMatrix() { + + const dx = ( this.right - this.left ) / ( 2 * this.zoom ); + const dy = ( this.top - this.bottom ) / ( 2 * this.zoom ); + const cx = ( this.right + this.left ) / 2; + const cy = ( this.top + this.bottom ) / 2; + + let left = cx - dx; + let right = cx + dx; + let top = cy + dy; + let bottom = cy - dy; + + if ( this.view !== null && this.view.enabled ) { + + const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom; + const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom; + + left += scaleW * this.view.offsetX; + right = left + scaleW * this.view.width; + top -= scaleH * this.view.offsetY; + bottom = top - scaleH * this.view.height; + + } + + this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem, this.reversedDepth ); + + this.projectionMatrixInverse.copy( this.projectionMatrix ).invert(); + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + data.object.zoom = this.zoom; + data.object.left = this.left; + data.object.right = this.right; + data.object.top = this.top; + data.object.bottom = this.bottom; + data.object.near = this.near; + data.object.far = this.far; + + if ( this.view !== null ) data.object.view = Object.assign( {}, this.view ); + + return data; + + } + +} + +const _lightOrientationMatrix = /*@__PURE__*/ new Matrix4(); +const _viewToLightMatrix = /*@__PURE__*/ new Matrix4(); +const _lightDirection = /*@__PURE__*/ new Vector3(); +const _up$1 = /*@__PURE__*/ new Vector3(); +const _center = /*@__PURE__*/ new Vector3(); +const _corner = /*@__PURE__*/ new Vector3(); +const _nearCorners = [ new Vector3(), new Vector3(), new Vector3(), new Vector3() ]; +const _farCorners = [ new Vector3(), new Vector3(), new Vector3(), new Vector3() ]; +const _cascadeCorners = [ new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3() ]; + +// must match the cascade count in the sun shadow shader chunks + +const _cascadeCount = 4; + +// fraction of each cascade's depth range that blends into the next cascade + +const _cascadeFade = 0.1; + +/** + * Represents the shadow configuration of {@link SunLight}, using four + * cascaded shadow maps (CSM). + * + * The shadow camera projection is fitted automatically to slices of the view + * frustum, up to a distance of `camera.far` (or the view camera's far plane, + * whichever is smaller), and adjacent cascades blend into each other over a + * small depth range. `camera.left/right/top/bottom` are ignored. + * + * The default `mapSize` is `1024x1024` per cascade. + * + * @augments LightShadow + */ +class SunLightShadow extends LightShadow { + + /** + * Constructs a new sun light shadow. + */ + constructor() { + + super( new OrthographicCamera( -5, 5, 5, -5, 0.5, 500 ) ); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isSunLightShadow = true; + + this.mapSize.set( 1024, 1024 ); + + this._cameras = []; + this._matrices = []; + this._frustums = []; + this._cascadeSplits = new Array( _cascadeCount + 1 ).fill( 0 ); + + // per cascade ( begin, end, fade start ) view depths, consumed by the renderer + + this._cascadeData = []; + + this._viewportCount = _cascadeCount; + this._frameExtents.set( 2, 2 ); + + for ( let i = 0; i < _cascadeCount; i ++ ) { + + this._cameras.push( new OrthographicCamera() ); + this._matrices.push( new Matrix4() ); + this._frustums.push( new Frustum() ); + this._cascadeData.push( new Vector4() ); + + } + + while ( this._viewports.length < _cascadeCount ) this._viewports.push( new Vector4() ); + + } + + /** + * Returns the shadow camera of the given cascade. + * + * @param {number} [cascadeIndex=0] - The cascade index. + * @return {OrthographicCamera} The shadow camera. + */ + getCamera( cascadeIndex = 0 ) { + + return this._cameras[ cascadeIndex ]; + + } + + /** + * Returns the shadow matrix of the given cascade. + * + * @param {number} [cascadeIndex=0] - The cascade index. + * @return {Matrix4} The shadow matrix. + */ + getMatrix( cascadeIndex = 0 ) { + + return this._matrices[ cascadeIndex ]; + + } + + /** + * Returns the shadow camera frustum of the given cascade. Used internally by + * the renderer to cull objects. + * + * @param {number} [cascadeIndex=0] - The cascade index. + * @return {Frustum} The shadow camera frustum. + */ + getFrustum( cascadeIndex = 0 ) { + + return this._frustums[ cascadeIndex ]; + + } + + /** + * Update the matrices for the cascade cameras and shadows, used internally + * by the renderer. + * + * @param {Light} light - The light for which the shadow is being rendered. + * @param {Camera} viewCamera - The camera the scene is rendered with. + */ + updateMatrices( light, viewCamera ) { + + if ( viewCamera === undefined ) return; + + // inset the cascade viewports so shadow filtering cannot read across atlas tiles + + const insetX = Math.min( 0.25, ( Math.ceil( this.radius ) + 1 ) / this.mapSize.x ); + const insetY = Math.min( 0.25, ( Math.ceil( this.radius ) + 1 ) / this.mapSize.y ); + + for ( let i = 0; i < _cascadeCount; i ++ ) { + + this._viewports[ i ].set( i % 2 + insetX, Math.floor( i / 2 ) + insetY, 1 - 2 * insetX, 1 - 2 * insetY ); + + } + + const camera = this.camera; + const cameraNear = viewCamera.near; + const cameraFar = Math.max( cameraNear + 1e-6, Math.min( camera.far, viewCamera.far ) ); + + // practical split scheme: the average of uniform and logarithmic splits + + const splits = this._cascadeSplits; + splits[ 0 ] = cameraNear; + + for ( let i = 1; i < _cascadeCount; i ++ ) { + + const amount = i / _cascadeCount; + const uniform = cameraNear + ( cameraFar - cameraNear ) * amount; + const logarithmic = cameraNear > 0 ? cameraNear * Math.pow( cameraFar / cameraNear, amount ) : uniform; + splits[ i ] = ( uniform + logarithmic ) * 0.5; + + } + + splits[ _cascadeCount ] = cameraFar; + + _lightDirection.setFromMatrixPosition( light.matrixWorld ).negate().normalize(); + + _up$1.set( 0, 1, 0 ); + if ( Math.abs( _up$1.dot( _lightDirection ) ) > 0.99 ) _up$1.set( 0, 0, 1 ); + + _lightOrientationMatrix.lookAt( _center.set( 0, 0, 0 ), _lightDirection, _up$1 ); + _viewToLightMatrix.copy( _lightOrientationMatrix ).transpose().multiply( viewCamera.matrixWorld ); + + // view frustum corners in light space; the rotation preserves distances, + // so the cascades can be fitted and snapped directly in this space + + const zNear = viewCamera.reversedDepth ? 1 : -1; + const inverseProjectionMatrix = viewCamera.projectionMatrixInverse; + + let globalMaxZ = - Infinity; + + for ( let i = 0; i < 4; i ++ ) { + + const x = i === 0 || i === 1 ? 1 : -1; + const y = i === 0 || i === 3 ? 1 : -1; + + const nearCorner = _nearCorners[ i ].set( x, y, zNear ).applyMatrix4( inverseProjectionMatrix ); + const farCorner = _farCorners[ i ]; + + if ( viewCamera.isPerspectiveCamera === true ) { + + farCorner.copy( nearCorner ).multiplyScalar( cameraFar / cameraNear ); + + } else { + + farCorner.set( nearCorner.x, nearCorner.y, - cameraFar ); + + } + + nearCorner.applyMatrix4( _viewToLightMatrix ); + farCorner.applyMatrix4( _viewToLightMatrix ); + + globalMaxZ = Math.max( globalMaxZ, nearCorner.z, farCorner.z ); + + } + + // raise the ceiling one shadow range towards the light so casters outside + // the view frustum still cast into it + + globalMaxZ += cameraFar; + + const shadowNear = camera.near; + + for ( let i = 0; i < _cascadeCount; i ++ ) { + + // each cascade covers the fade band of the previous one so both can be sampled while blending + + const cascadeNear = i === 0 ? splits[ 0 ] : this._cascadeData[ i - 1 ].z; + const cascadeFar = splits[ i + 1 ]; + const fadeStart = cascadeFar - _cascadeFade * ( cascadeFar - splits[ i ] ); + + this._cascadeData[ i ].set( i === 0 ? -1e10 : cascadeNear, cascadeFar, fadeStart, 0 ); + + // bounding sphere of the cascade slice for a rotation-stable projection + + const nearAlpha = ( cascadeNear - cameraNear ) / ( cameraFar - cameraNear ); + const farAlpha = ( cascadeFar - cameraNear ) / ( cameraFar - cameraNear ); + + _center.set( 0, 0, 0 ); + + for ( let j = 0; j < 4; j ++ ) { + + _cascadeCorners[ j * 2 ].lerpVectors( _nearCorners[ j ], _farCorners[ j ], nearAlpha ); + _cascadeCorners[ j * 2 + 1 ].lerpVectors( _nearCorners[ j ], _farCorners[ j ], farAlpha ); + _center.add( _cascadeCorners[ j * 2 ] ).add( _cascadeCorners[ j * 2 + 1 ] ); + + } + + _center.multiplyScalar( 1 / 8 ); + + let radiusSq = 0; + let minZ = Infinity; + + for ( let j = 0; j < 8; j ++ ) { + + radiusSq = Math.max( radiusSq, _cascadeCorners[ j ].distanceToSquared( _center ) ); + minZ = Math.min( minZ, _cascadeCorners[ j ].z ); + + } + + let radius = Math.sqrt( radiusSq ); + + // snap to the texel grid to avoid shimmering when the view camera moves + + const resolutionX = this.mapSize.width * this._viewports[ i ].z; + const resolutionY = this.mapSize.height * this._viewports[ i ].w; + const resolution = Math.min( resolutionX, resolutionY ); + + if ( resolution > 1 ) { + + // pad by half a texel so snapping cannot clip a frustum corner + radius /= 1 - 1 / resolution; + const texelSizeX = 2 * radius / resolutionX; + const texelSizeY = 2 * radius / resolutionY; + _center.x = Math.round( _center.x / texelSizeX ) * texelSizeX; + _center.y = Math.round( _center.y / texelSizeY ) * texelSizeY; + + } + + // place the near plane at the caster ceiling + + _center.z = globalMaxZ + shadowNear; + _center.applyMatrix4( _lightOrientationMatrix ); + + const cascadeCamera = this._cameras[ i ]; + cascadeCamera.position.copy( _center ); + cascadeCamera.up.copy( _up$1 ); + cascadeCamera.lookAt( _corner.copy( _center ).add( _lightDirection ) ); + cascadeCamera.left = - radius; + cascadeCamera.right = radius; + cascadeCamera.top = radius; + cascadeCamera.bottom = - radius; + cascadeCamera.near = shadowNear; + cascadeCamera.far = globalMaxZ - minZ + 2 * shadowNear; + cascadeCamera.coordinateSystem = camera.coordinateSystem; + cascadeCamera._reversedDepth = camera.reversedDepth; + cascadeCamera.updateProjectionMatrix(); + cascadeCamera.updateMatrixWorld(); + + this._updateMatrix( cascadeCamera, this._matrices[ i ], this._frustums[ i ], this._viewports[ i ] ); + + } + + } + +} + +/** + * A sun-like light that gets emitted in a specific direction, with rays that + * are all parallel, and casts cascaded shadow maps via {@link SunLightShadow}, + * suited for lighting large scenes. + * + * Unlike {@link DirectionalLight}, the light has no target: like + * {@link HemisphereLight}, its direction is defined by its position. The + * light shines from its position towards the origin and points straight + * down by default. + * + * ```js + * const sun = new SunLight( 0xfff2e3, 3 ); + * sun.position.set( 1, 1, 1 ); + * sun.castShadow = true; + * scene.add( sun ); + * ``` + * + * This light is only supported by `WebGLRenderer`. When using `WebGPURenderer`, + * use {@link DirectionalLight} with `CSMShadowNode` instead. + * + * @augments Light + */ +class SunLight extends Light { + + /** + * Constructs a new sun light. + * + * @param {(number|Color|string)} [color=0xffffff] - The light's color. + * @param {number} [intensity=1] - The light's strength/intensity. + */ + constructor( color, intensity ) { + + super( color, intensity ); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isSunLight = true; + + this.type = 'SunLight'; + + /** + * The light's shadow configuration. + * + * @type {SunLightShadow} + */ + this.shadow = new SunLightShadow(); + + this.position.set( 0, 1, 0 ); + this.updateMatrix(); + + } + + dispose() { + + super.dispose(); + + this.shadow.dispose(); + + } + + copy( source ) { + + super.copy( source ); + + this.shadow = source.shadow.clone(); + + return this; + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + data.object.shadow = this.shadow.toJSON(); + + return data; + + } + +} + +/** + * A light source positioned directly above the scene, with color fading from + * the sky color to the ground color. + * + * This light cannot be used to cast shadows. + * + * ```js + * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 ); + * scene.add( light ); + * ``` + * + * @augments Light + */ +class HemisphereLight extends Light { + + /** + * Constructs a new hemisphere light. + * + * @param {(number|Color|string)} [skyColor=0xffffff] - The light's sky color. + * @param {(number|Color|string)} [groundColor=0xffffff] - The light's ground color. + * @param {number} [intensity=1] - The light's strength/intensity. + */ + constructor( skyColor, groundColor, intensity ) { + + super( skyColor, intensity ); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isHemisphereLight = true; + + this.type = 'HemisphereLight'; + + this.position.copy( Object3D.DEFAULT_UP ); + this.updateMatrix(); + + /** + * The light's ground color. + * + * @type {Color} + */ + this.groundColor = new Color( groundColor ); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.groundColor.copy( source.groundColor ); + + return this; + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + data.object.groundColor = this.groundColor.getHex(); + + return data; + + } + +} + +const _v3$1 = /*@__PURE__*/ new Vector3(); +const _minTarget = /*@__PURE__*/ new Vector2(); +const _maxTarget = /*@__PURE__*/ new Vector2(); + +/** + * Camera that uses [perspective projection](https://en.wikipedia.org/wiki/Perspective_(graphical)). + * + * This projection mode is designed to mimic the way the human eye sees. It + * is the most common projection mode used for rendering a 3D scene. + * + * ```js + * const camera = new THREE.PerspectiveCamera( 45, width / height, 1, 1000 ); + * scene.add( camera ); + * ``` + * + * @augments Camera + */ +class PerspectiveCamera extends Camera { + + /** + * Constructs a new perspective camera. + * + * @param {number} [fov=50] - The vertical field of view. + * @param {number} [aspect=1] - The aspect ratio. + * @param {number} [near=0.1] - The camera's near plane. + * @param {number} [far=2000] - The camera's far plane. + */ + constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) { + + super(); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isPerspectiveCamera = true; + + this.type = 'PerspectiveCamera'; + + /** + * The vertical field of view, from bottom to top of view, + * in degrees. + * + * @type {number} + * @default 50 + */ + this.fov = fov; + + /** + * The zoom factor of the camera. + * + * @type {number} + * @default 1 + */ + this.zoom = 1; + + /** + * The camera's near plane. The valid range is greater than `0` + * and less than the current value of {@link PerspectiveCamera#far}. + * + * Note that, unlike for the {@link OrthographicCamera}, `0` is not a + * valid value for a perspective camera's near plane. + * + * @type {number} + * @default 0.1 + */ + this.near = near; + + /** + * The camera's far plane. Must be greater than the + * current value of {@link PerspectiveCamera#near}. + * + * @type {number} + * @default 2000 + */ + this.far = far; + + /** + * Object distance used for stereoscopy and depth-of-field effects. This + * parameter does not influence the projection matrix unless a + * {@link StereoCamera} is being used. + * + * @type {number} + * @default 10 + */ + this.focus = 10; + + /** + * The aspect ratio, usually the canvas width / canvas height. + * + * @type {number} + * @default 1 + */ + this.aspect = aspect; + + /** + * Represents the frustum window specification. This property should not be edited + * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}. + * + * @type {?Object} + * @default null + */ + this.view = null; + + /** + * Film size used for the larger axis. Default is `35` (millimeters). This + * parameter does not influence the projection matrix unless {@link PerspectiveCamera#filmOffset} + * is set to a nonzero value. + * + * @type {number} + * @default 35 + */ + this.filmGauge = 35; + + /** + * Horizontal off-center offset in the same unit as {@link PerspectiveCamera#filmGauge}. + * + * @type {number} + * @default 0 + */ + this.filmOffset = 0; + + this.updateProjectionMatrix(); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.fov = source.fov; + this.zoom = source.zoom; + + this.near = source.near; + this.far = source.far; + this.focus = source.focus; + + this.aspect = source.aspect; + this.view = source.view === null ? null : Object.assign( {}, source.view ); + + this.filmGauge = source.filmGauge; + this.filmOffset = source.filmOffset; + + return this; + + } + + /** + * Sets the FOV by focal length in respect to the current {@link PerspectiveCamera#filmGauge}. + * + * The default film gauge is 35, so that the focal length can be specified for + * a 35mm (full frame) camera. + * + * @param {number} focalLength - Values for focal length and film gauge must have the same unit. + */ + setFocalLength( focalLength ) { + + /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */ + const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength; + + this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope ); + this.updateProjectionMatrix(); + + } + + /** + * Returns the focal length from the current {@link PerspectiveCamera#fov} and + * {@link PerspectiveCamera#filmGauge}. + * + * @return {number} The computed focal length. + */ + getFocalLength() { + + const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov ); + + return 0.5 * this.getFilmHeight() / vExtentSlope; + + } + + /** + * Returns the current vertical field of view angle in degrees considering {@link PerspectiveCamera#zoom}. + * + * @return {number} The effective FOV. + */ + getEffectiveFOV() { + + return RAD2DEG * 2 * Math.atan( + Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom ); + + } + + /** + * Returns the width of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or + * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}. + * + * @return {number} The film width. + */ + getFilmWidth() { + + // film not completely covered in portrait format (aspect < 1) + return this.filmGauge * Math.min( this.aspect, 1 ); + + } + + /** + * Returns the height of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or + * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}. + * + * @return {number} The film width. + */ + getFilmHeight() { + + // film not completely covered in landscape format (aspect > 1) + return this.filmGauge / Math.max( this.aspect, 1 ); + + } + + /** + * 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. + * + * @param {number} distance - The viewing distance. + * @param {Vector2} minTarget - The lower-left corner of the view rectangle is written into this vector. + * @param {Vector2} maxTarget - The upper-right corner of the view rectangle is written into this vector. + */ + 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. + * + * @param {number} distance - The viewing distance. + * @param {Vector2} target - The target vector that is used to store result where x is width and y is height. + * @returns {Vector2} The view size. + */ + 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. + * + * For example, if you have 3x2 monitors and each monitor is 1920x1080 and + * the monitors are in grid like this + *``` + * +---+---+---+ + * | A | B | C | + * +---+---+---+ + * | D | E | F | + * +---+---+---+ + *``` + * then for each monitor you would call it like this: + *```js + * const w = 1920; + * const h = 1080; + * const fullWidth = w * 3; + * const fullHeight = h * 2; + * + * // --A-- + * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h ); + * // --B-- + * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h ); + * // --C-- + * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h ); + * // --D-- + * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h ); + * // --E-- + * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h ); + * // --F-- + * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h ); + * ``` + * + * Note there is no reason monitors have to be the same size or in a grid. + * + * @param {number} fullWidth - The full width of multiview setup. + * @param {number} fullHeight - The full height of multiview setup. + * @param {number} x - The horizontal offset of the subcamera. + * @param {number} y - The vertical offset of the subcamera. + * @param {number} width - The width of subcamera. + * @param {number} height - The height of subcamera. + */ + setViewOffset( fullWidth, fullHeight, x, y, width, height ) { + + this.aspect = fullWidth / fullHeight; + if ( this.view === null ) { this.view = { @@ -47453,248 +48133,6 @@ class PointLight extends Light { } -/** - * Camera that uses [orthographic projection](https://en.wikipedia.org/wiki/Orthographic_projection). - * - * In this projection mode, an object's size in the rendered image stays - * constant regardless of its distance from the camera. This can be useful - * for rendering 2D scenes and UI elements, amongst other things. - * - * ```js - * const camera = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, 1, 1000 ); - * scene.add( camera ); - * ``` - * - * @augments Camera - */ -class OrthographicCamera extends Camera { - - /** - * Constructs a new orthographic camera. - * - * @param {number} [left=-1] - The left plane of the camera's frustum. - * @param {number} [right=1] - The right plane of the camera's frustum. - * @param {number} [top=1] - The top plane of the camera's frustum. - * @param {number} [bottom=-1] - The bottom plane of the camera's frustum. - * @param {number} [near=0.1] - The camera's near plane. - * @param {number} [far=2000] - The camera's far plane. - */ - constructor( left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000 ) { - - super(); - - /** - * This flag can be used for type testing. - * - * @type {boolean} - * @readonly - * @default true - */ - this.isOrthographicCamera = true; - - this.type = 'OrthographicCamera'; - - /** - * The zoom factor of the camera. - * - * @type {number} - * @default 1 - */ - this.zoom = 1; - - /** - * Represents the frustum window specification. This property should not be edited - * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}. - * - * @type {?Object} - * @default null - */ - this.view = null; - - /** - * The left plane of the camera's frustum. - * - * @type {number} - * @default -1 - */ - this.left = left; - - /** - * The right plane of the camera's frustum. - * - * @type {number} - * @default 1 - */ - this.right = right; - - /** - * The top plane of the camera's frustum. - * - * @type {number} - * @default 1 - */ - this.top = top; - - /** - * The bottom plane of the camera's frustum. - * - * @type {number} - * @default -1 - */ - this.bottom = bottom; - - /** - * The camera's near plane. The valid range is greater than `0` - * and less than the current value of {@link OrthographicCamera#far}. - * - * Note that, unlike for the {@link PerspectiveCamera}, `0` is a - * valid value for an orthographic camera's near plane. - * - * @type {number} - * @default 0.1 - */ - this.near = near; - - /** - * The camera's far plane. Must be greater than the - * current value of {@link OrthographicCamera#near}. - * - * @type {number} - * @default 2000 - */ - this.far = far; - - this.updateProjectionMatrix(); - - } - - copy( source, recursive ) { - - super.copy( source, recursive ); - - this.left = source.left; - this.right = source.right; - this.top = source.top; - this.bottom = source.bottom; - this.near = source.near; - this.far = source.far; - - this.zoom = source.zoom; - this.view = source.view === null ? null : Object.assign( {}, source.view ); - - return this; - - } - - /** - * Sets an offset in a larger frustum. This is useful for multi-window or - * multi-monitor/multi-machine setups. - * - * @param {number} fullWidth - The full width of multiview setup. - * @param {number} fullHeight - The full height of multiview setup. - * @param {number} x - The horizontal offset of the subcamera. - * @param {number} y - The vertical offset of the subcamera. - * @param {number} width - The width of subcamera. - * @param {number} height - The height of subcamera. - * @see {@link PerspectiveCamera#setViewOffset} - */ - setViewOffset( fullWidth, fullHeight, x, y, width, height ) { - - if ( this.view === null ) { - - this.view = { - enabled: true, - fullWidth: 1, - fullHeight: 1, - offsetX: 0, - offsetY: 0, - width: 1, - height: 1 - }; - - } - - this.view.enabled = true; - this.view.fullWidth = fullWidth; - this.view.fullHeight = fullHeight; - this.view.offsetX = x; - this.view.offsetY = y; - this.view.width = width; - this.view.height = height; - - this.updateProjectionMatrix(); - - } - - /** - * Removes the view offset from the projection matrix. - */ - clearViewOffset() { - - if ( this.view !== null ) { - - this.view.enabled = false; - - } - - this.updateProjectionMatrix(); - - } - - /** - * Updates the camera's projection matrix. Must be called after any change of - * camera properties. - */ - updateProjectionMatrix() { - - const dx = ( this.right - this.left ) / ( 2 * this.zoom ); - const dy = ( this.top - this.bottom ) / ( 2 * this.zoom ); - const cx = ( this.right + this.left ) / 2; - const cy = ( this.top + this.bottom ) / 2; - - let left = cx - dx; - let right = cx + dx; - let top = cy + dy; - let bottom = cy - dy; - - if ( this.view !== null && this.view.enabled ) { - - const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom; - const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom; - - left += scaleW * this.view.offsetX; - right = left + scaleW * this.view.width; - top -= scaleH * this.view.offsetY; - bottom = top - scaleH * this.view.height; - - } - - this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem, this.reversedDepth ); - - this.projectionMatrixInverse.copy( this.projectionMatrix ).invert(); - - } - - toJSON( meta ) { - - const data = super.toJSON( meta ); - - data.object.zoom = this.zoom; - data.object.left = this.left; - data.object.right = this.right; - data.object.top = this.top; - data.object.bottom = this.bottom; - data.object.near = this.near; - data.object.far = this.far; - - if ( this.view !== null ) data.object.view = Object.assign( {}, this.view ); - - return data; - - } - -} - /** * Represents the shadow configuration of directional lights. * @@ -49407,14 +49845,14 @@ class ObjectLoader extends Loader { } - images[ image.uuid ] = new Source( imageArray ); + images[ image.uuid ] = new TextureSource( imageArray ); } else { // load single image const deserializedImage = deserializeImage( image.url ); - images[ image.uuid ] = new Source( deserializedImage ); + images[ image.uuid ] = new TextureSource( deserializedImage ); } @@ -49504,14 +49942,14 @@ class ObjectLoader extends Loader { } - images[ image.uuid ] = new Source( imageArray ); + images[ image.uuid ] = new TextureSource( imageArray ); } else { // load single image const deserializedImage = await deserializeImage( image.url ); - images[ image.uuid ] = new Source( deserializedImage ); + images[ image.uuid ] = new TextureSource( deserializedImage ); } @@ -49780,6 +50218,12 @@ class ObjectLoader extends Loader { break; + case 'SunLight': + + object = new SunLight( data.color, data.intensity ); + + break; + case 'DirectionalLight': object = new DirectionalLight( data.color, data.intensity ); @@ -60451,4 +60895,4 @@ if ( typeof window !== 'undefined' ) { } -export { ACESFilmicToneMapping, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BackSide, BasicDepthPacking, BasicShadowMap, BatchedMesh, BezierInterpolant, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxGeometry, BoxHelper, BufferAttribute, BufferGeometry, BufferGeometryLoader, ByteType, Cache, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CineonToneMapping, CircleGeometry, ClampToEdgeWrapping, Clock, Color, ColorKeyframeTrack, ColorManagement, Compatibility, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, ConstantAlphaFactor, ConstantColorFactor, Controls, CubeCamera, CubeDepthTexture, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeUVReflectionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CustomToneMapping, CylinderGeometry, Cylindrical, Data3DTexture, DataArrayTexture, DataTexture, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthFormat, DepthStencilFormat, DepthTexture, DetachedBindMode, DirectionalLight, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, EqualCompare, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExternalTexture, ExtrudeGeometry, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, Fog, FogExp2, FramebufferTexture, FrontSide, Frustum, FrustumArray, GLBufferAttribute, GLSL1, GLSL3, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HTMLTexture, HalfFloatType, HemisphereLight, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, IncrementStencilOp, IncrementWrapStencilOp, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateBezier, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InterpolationSamplingMode, InterpolationSamplingType, InvertStencilOp, KeepStencilOp, KeyframeTrack, LOD, LatheGeometry, Layers, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, Line, Line3, LineBasicMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineLoop, LineSegments, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, LinearTransfer, Loader, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, MOUSE, Material, MaterialBlending, MaterialLoader, MathUtils, Matrix2, Matrix3, Matrix4, MaxEquation, Mesh, MeshBasicMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshLambertMaterial, MeshMatcapMaterial, MeshNormalMaterial, MeshPhongMaterial, MeshPhysicalMaterial, MeshStandardMaterial, MeshToonMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoNormalPacking, NoToneMapping, NormalAnimationBlendMode, NormalBlending, NormalGAPacking, NormalRGPacking, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, ObjectLoader, ObjectSpaceNormalMap, OctahedronGeometry, OneFactor, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, PCFShadowMap, PCFSoftShadowMap, Path, PerspectiveCamera, Plane, PlaneGeometry, PlaneHelper, PointLight, PointLightHelper, Points, PointsMaterial, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, R11_EAC_Format, RAD2DEG, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RG11_EAC_Format, 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, RGBDepthPacking, RGBFormat, RGBIntegerFormat, 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, RGDepthPacking, RGFormat, RGIntegerFormat, RawShaderMaterial, Ray, Raycaster, RectAreaLight, RedFormat, RedIntegerFormat, ReinhardToneMapping, RenderObjectRefreshType, RenderTarget, RenderTarget3D, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, ReversedDepthFuncs, RingGeometry, SIGNED_R11_EAC_Format, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SIGNED_RG11_EAC_Format, SRGBColorSpace, SRGBTransfer, Scene, ShaderMaterial, ShadowMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, Source, Sphere, SphereGeometry, Spherical, SphericalHarmonics3, SplineCurve, SpotLight, SpotLightHelper, Sprite, SpriteMaterial, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TOUCH, TangentSpaceNormalMap, TetrahedronGeometry, Texture, TextureLoader, TextureUtils, Timer, TimestampQuery, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, UniformsUtils, UnsignedByteType, UnsignedInt101111Type, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, VSMShadowMap, Vector2, Vector3, Vector4, VectorKeyframeTrack, VideoFrameTexture, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLCoordinateSystem, WebGLRenderTarget, WebGPUCoordinateSystem, WebXRController, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, cloneUniforms, createCanvasElement, createElementNS, error, getByteLength, getConsoleFunction, getUnlitUniformColorSpace, isTypedArray, log, mergeUniforms, probeAsync, setConsoleFunction, warn, warnOnce, yieldToMain }; +export { ACESFilmicToneMapping, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BackSide, BasicDepthPacking, BasicShadowMap, BatchedMesh, BezierInterpolant, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxGeometry, BoxHelper, BufferAttribute, BufferGeometry, BufferGeometryLoader, ByteType, Cache, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CineonToneMapping, CircleGeometry, ClampToEdgeWrapping, Clock, Color, ColorKeyframeTrack, ColorManagement, Compatibility, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, ConstantAlphaFactor, ConstantColorFactor, Controls, CubeCamera, CubeDepthTexture, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeUVReflectionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CustomToneMapping, CylinderGeometry, Cylindrical, Data3DTexture, DataArrayTexture, DataTexture, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthFormat, DepthStencilFormat, DepthTexture, DetachedBindMode, DirectionalLight, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, EqualCompare, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExternalTexture, ExtrudeGeometry, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, Fog, FogExp2, FramebufferTexture, FrontSide, Frustum, FrustumArray, GLBufferAttribute, GLSL1, GLSL3, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HTMLTexture, HalfFloatType, HemisphereLight, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, IncrementStencilOp, IncrementWrapStencilOp, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateBezier, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InterpolationSamplingMode, InterpolationSamplingType, InvertStencilOp, KeepStencilOp, KeyframeTrack, LOD, LatheGeometry, Layers, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, Line, Line3, LineBasicMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineLoop, LineSegments, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, LinearTransfer, Loader, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, MOUSE, Material, MaterialBlending, MaterialLoader, MathUtils, Matrix2, Matrix3, Matrix4, MaxEquation, Mesh, MeshBasicMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshLambertMaterial, MeshMatcapMaterial, MeshNormalMaterial, MeshPhongMaterial, MeshPhysicalMaterial, MeshStandardMaterial, MeshToonMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoNormalPacking, NoToneMapping, NormalAnimationBlendMode, NormalBlending, NormalGAPacking, NormalRGPacking, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, ObjectLoader, ObjectSpaceNormalMap, OctahedronGeometry, OneFactor, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, PCFShadowMap, PCFSoftShadowMap, Path, PerspectiveCamera, Plane, PlaneGeometry, PlaneHelper, PointLight, PointLightHelper, Points, PointsMaterial, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, R11_EAC_Format, RAD2DEG, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RG11_EAC_Format, 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, RGBDepthPacking, RGBFormat, RGBIntegerFormat, 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, RGDepthPacking, RGFormat, RGIntegerFormat, RawShaderMaterial, Ray, Raycaster, RectAreaLight, RedFormat, RedIntegerFormat, ReinhardToneMapping, RenderObjectRefreshType, RenderTarget, RenderTarget3D, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, ReversedDepthFuncs, RingGeometry, SIGNED_R11_EAC_Format, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SIGNED_RG11_EAC_Format, SRGBColorSpace, SRGBTransfer, Scene, ShaderMaterial, ShadowMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, Source, Sphere, SphereGeometry, Spherical, SphericalHarmonics3, SplineCurve, SpotLight, SpotLightHelper, Sprite, SpriteMaterial, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, SunLight, SunLightShadow, TOUCH, TangentSpaceNormalMap, TetrahedronGeometry, Texture, TextureLoader, TextureSource, TextureUtils, Timer, TimestampQuery, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, UniformsUtils, UnsignedByteType, UnsignedInt101111Type, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, VSMShadowMap, Vector2, Vector3, Vector4, VectorKeyframeTrack, VideoFrameTexture, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLCoordinateSystem, WebGLRenderTarget, WebGPUCoordinateSystem, WebXRController, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, cloneUniforms, createCanvasElement, createElementNS, error, getByteLength, getConsoleFunction, getUnlitUniformColorSpace, isTypedArray, log, mergeUniforms, probeAsync, setConsoleFunction, warn, warnOnce, yieldToMain }; diff --git a/build/three.module.js b/build/three.module.js index 47f1a5b349733b..cfce529a9c9d90 100644 --- a/build/three.module.js +++ b/build/three.module.js @@ -4,7 +4,7 @@ * SPDX-License-Identifier: MIT */ import { Matrix3, Vector2, Color, Vector3, mergeUniforms, CubeUVReflectionMapping, Mesh, BoxGeometry, ShaderMaterial, BackSide, cloneUniforms, Matrix4, ColorManagement, SRGBTransfer, PlaneGeometry, FrontSide, getUnlitUniformColorSpace, IntType, warn, HalfFloatType, UnsignedByteType, FloatType, RGBAFormat, Plane, CubeReflectionMapping, CubeRefractionMapping, BufferGeometry, OrthographicCamera, PerspectiveCamera, NoToneMapping, MeshBasicMaterial, NoBlending, WebGLRenderTarget, BufferAttribute, LinearSRGBColorSpace, LinearFilter, CubeTexture, LinearMipmapLinearFilter, CubeCamera, EquirectangularReflectionMapping, EquirectangularRefractionMapping, warnOnce, Uint32BufferAttribute, Uint16BufferAttribute, error, DataArrayTexture, Vector4, Float32BufferAttribute, RawShaderMaterial, CustomToneMapping, NeutralToneMapping, AgXToneMapping, ACESFilmicToneMapping, CineonToneMapping, ReinhardToneMapping, LinearToneMapping, Data3DTexture, GreaterEqualCompare, LessEqualCompare, DepthTexture, Texture, GLSL3, VSMShadowMap, PCFShadowMap, AddOperation, MixOperation, MultiplyOperation, LinearTransfer, UniformsUtils, DoubleSide, NormalBlending, TangentSpaceNormalMap, ObjectSpaceNormalMap, Layers, RGFormat, RG11_EAC_Format, RED_GREEN_RGTC2_Format, MeshDepthMaterial, MeshDistanceMaterial, PCFSoftShadowMap, DepthFormat, NearestFilter, CubeDepthTexture, UnsignedIntType, Frustum, LessEqualDepth, ReverseSubtractEquation, SubtractEquation, AddEquation, OneMinusConstantAlphaFactor, ConstantAlphaFactor, OneMinusConstantColorFactor, ConstantColorFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, DstAlphaFactor, DstColorFactor, SrcAlphaSaturateFactor, SrcAlphaFactor, SrcColorFactor, OneFactor, ZeroFactor, NotEqualDepth, GreaterDepth, GreaterEqualDepth, EqualDepth, LessDepth, AlwaysDepth, NeverDepth, CullFaceNone, CullFaceBack, CullFaceFront, CustomBlending, MultiplyBlending, SubtractiveBlending, AdditiveBlending, ReversedDepthFuncs, MinEquation, MaxEquation, MirroredRepeatWrapping, ClampToEdgeWrapping, RepeatWrapping, LinearMipmapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NotEqualCompare, GreaterCompare, EqualCompare, LessCompare, AlwaysCompare, NeverCompare, NoColorSpace, DepthStencilFormat, getByteLength, UnsignedInt248Type, UnsignedShortType, createElementNS, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedInt5999Type, UnsignedInt101111Type, ByteType, ShortType, AlphaFormat, RGBFormat, RedFormat, RedIntegerFormat, RGIntegerFormat, RGBAIntegerFormat, RGB_S3TC_DXT1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGB_PVRTC_4BPPV1_Format, RGB_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_PVRTC_2BPPV1_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGBA_ETC2_EAC_Format, R11_EAC_Format, SIGNED_R11_EAC_Format, SIGNED_RG11_EAC_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_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_10x10_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_BPTC_Format, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RED_RGTC1_Format, SIGNED_RED_RGTC1_Format, SIGNED_RED_GREEN_RGTC2_Format, ExternalTexture, EventDispatcher, ArrayCamera, WebXRController, RAD2DEG, DataTexture, createCanvasElement, SRGBColorSpace, REVISION, log, WebGLCoordinateSystem, probeAsync } from './three.core.js'; -export { AdditiveAnimationBlendMode, AlwaysStencilFunc, AmbientLight, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BasicDepthPacking, BasicShadowMap, BatchedMesh, BezierInterpolant, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxHelper, BufferGeometryLoader, Cache, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CircleGeometry, Clock, ColorKeyframeTrack, Compatibility, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, Controls, CubeTextureLoader, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceFrontBack, Curve, CurvePath, CylinderGeometry, Cylindrical, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DetachedBindMode, DirectionalLight, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, EqualStencilFunc, Euler, ExtrudeGeometry, FileLoader, Float16BufferAttribute, Fog, FogExp2, FramebufferTexture, FrustumArray, GLBufferAttribute, GLSL1, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HTMLTexture, HemisphereLight, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, IncrementStencilOp, IncrementWrapStencilOp, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateBezier, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InterpolationSamplingMode, InterpolationSamplingType, InvertStencilOp, KeepStencilOp, KeyframeTrack, LOD, LatheGeometry, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, Line, Line3, LineBasicMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineLoop, LineSegments, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, Loader, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, MOUSE, Material, MaterialBlending, MaterialLoader, MathUtils, Matrix2, MeshLambertMaterial, MeshMatcapMaterial, MeshNormalMaterial, MeshPhongMaterial, MeshPhysicalMaterial, MeshStandardMaterial, MeshToonMaterial, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NeverStencilFunc, NoNormalPacking, NormalAnimationBlendMode, NormalGAPacking, NormalRGPacking, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, ObjectLoader, OctahedronGeometry, Path, PlaneHelper, PointLight, PointLightHelper, Points, PointsMaterial, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RGBADepthPacking, RGBDepthPacking, RGBIntegerFormat, RGDepthPacking, Ray, Raycaster, RectAreaLight, RenderObjectRefreshType, RenderTarget, RenderTarget3D, ReplaceStencilOp, RingGeometry, Scene, ShadowMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, Skeleton, SkeletonHelper, SkinnedMesh, Source, Sphere, SphereGeometry, Spherical, SphericalHarmonics3, SplineCurve, SpotLight, SpotLightHelper, Sprite, SpriteMaterial, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, TOUCH, TetrahedronGeometry, TextureLoader, TextureUtils, Timer, TimestampQuery, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, UVMapping, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, VectorKeyframeTrack, VideoFrameTexture, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGPUCoordinateSystem, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroSlopeEnding, ZeroStencilOp, getConsoleFunction, setConsoleFunction } from './three.core.js'; +export { AdditiveAnimationBlendMode, AlwaysStencilFunc, AmbientLight, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BasicDepthPacking, BasicShadowMap, BatchedMesh, BezierInterpolant, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxHelper, BufferGeometryLoader, Cache, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CircleGeometry, Clock, ColorKeyframeTrack, Compatibility, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, Controls, CubeTextureLoader, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceFrontBack, Curve, CurvePath, CylinderGeometry, Cylindrical, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DetachedBindMode, DirectionalLight, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, EqualStencilFunc, Euler, ExtrudeGeometry, FileLoader, Float16BufferAttribute, Fog, FogExp2, FramebufferTexture, FrustumArray, GLBufferAttribute, GLSL1, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HTMLTexture, HemisphereLight, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, IncrementStencilOp, IncrementWrapStencilOp, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateBezier, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InterpolationSamplingMode, InterpolationSamplingType, InvertStencilOp, KeepStencilOp, KeyframeTrack, LOD, LatheGeometry, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, Line, Line3, LineBasicMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineLoop, LineSegments, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, Loader, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, MOUSE, Material, MaterialBlending, MaterialLoader, MathUtils, Matrix2, MeshLambertMaterial, MeshMatcapMaterial, MeshNormalMaterial, MeshPhongMaterial, MeshPhysicalMaterial, MeshStandardMaterial, MeshToonMaterial, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NeverStencilFunc, NoNormalPacking, NormalAnimationBlendMode, NormalGAPacking, NormalRGPacking, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, ObjectLoader, OctahedronGeometry, Path, PlaneHelper, PointLight, PointLightHelper, Points, PointsMaterial, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RGBADepthPacking, RGBDepthPacking, RGBIntegerFormat, RGDepthPacking, Ray, Raycaster, RectAreaLight, RenderObjectRefreshType, RenderTarget, RenderTarget3D, ReplaceStencilOp, RingGeometry, Scene, ShadowMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, Skeleton, SkeletonHelper, SkinnedMesh, Source, Sphere, SphereGeometry, Spherical, SphericalHarmonics3, SplineCurve, SpotLight, SpotLightHelper, Sprite, SpriteMaterial, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SunLight, SunLightShadow, TOUCH, TetrahedronGeometry, TextureLoader, TextureSource, TextureUtils, Timer, TimestampQuery, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, UVMapping, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, VectorKeyframeTrack, VideoFrameTexture, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGPUCoordinateSystem, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroSlopeEnding, ZeroStencilOp, getConsoleFunction, setConsoleFunction } from './three.core.js'; function WebGLAnimation() { @@ -384,7 +384,7 @@ var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor var 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"; -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 = transformNormalByInverseViewMatrix( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif ( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif\n#include "; +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 = transformNormalByInverseViewMatrix( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif ( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_SUN_LIGHTS > 0\n\tstruct SunLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform SunLight sunLights[ NUM_SUN_LIGHTS ];\n\tvoid getSunLightInfo( const in SunLight sunLight, out IncidentLight light ) {\n\t\tlight.color = sunLight.color;\n\t\tlight.direction = sunLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif\n#include "; 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 = transformNormalByInverseViewMatrix( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 reflectVec = reflect( - viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, pow4( roughness ) ) );\n\t\t\treflectVec = transformDirectionByInverseViewMatrix( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\t#ifdef USE_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"; @@ -400,7 +400,7 @@ var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColo var lights_physical_pars_fragment = "uniform sampler2D dfgLUT;\nstruct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tvec3 diffuseContribution;\n\tvec3 specularColor;\n\tvec3 specularColorBlended;\n\tfloat roughness;\n\tfloat metalness;\n\tfloat specularF90;\n\tfloat dispersion;\n\tvec2 dfg;\n\tvec3 multiScatteringCompensation;\n\t#ifdef USE_RETROREFLECTION\n\t\tfloat retroreflectivity;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tfloat iridescence;\n\t\tfloat iridescenceIOR;\n\t\tfloat iridescenceThickness;\n\t\tvec3 iridescenceFresnel;\n\t\tvec3 iridescenceF0Dielectric;\n\t\tvec3 iridescenceF0Metallic;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n\t#ifdef IOR\n\t\tfloat ior;\n\t#endif\n\t#ifdef USE_TRANSMISSION\n\t\tfloat transmission;\n\t\tfloat transmissionAlpha;\n\t\tfloat thickness;\n\t\tfloat attenuationDistance;\n\t\tvec3 attenuationColor;\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat anisotropy;\n\t\tfloat alphaT;\n\t\tvec3 anisotropyT;\n\t\tvec3 anisotropyB;\n\t#endif\n};\nvec3 clearcoatSpecularDirect = vec3( 0.0 );\nvec3 clearcoatSpecularIndirect = vec3( 0.0 );\nvec3 sheenSpecularDirect = vec3( 0.0 );\nvec3 sheenSpecularIndirect = vec3(0.0 );\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\n float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\n float x2 = x * x;\n float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\n return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\n#ifdef USE_ANISOTROPY\n\tfloat V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {\n\t\tfloat gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );\n\t\tfloat gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );\n\t\treturn 0.5 / max( gv + gl, EPSILON );\n\t}\n\tfloat D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {\n\t\tfloat a2 = alphaT * alphaB;\n\t\thighp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );\n\t\thighp float v2 = dot( v, v );\n\t\tfloat w2 = a2 / v2;\n\t\treturn RECIPROCAL_PI * a2 * pow2 ( w2 );\n\t}\n#endif\n#ifdef USE_CLEARCOAT\n\tvec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {\n\t\tvec3 f0 = material.clearcoatF0;\n\t\tfloat f90 = material.clearcoatF90;\n\t\tfloat roughness = material.clearcoatRoughness;\n\t\tfloat alpha = pow2( roughness );\n\t\tvec3 halfDir = normalize( lightDir + viewDir );\n\t\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\t\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\t\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\t\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\t\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t\treturn F * ( V * D );\n\t}\n#endif\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\n\tvec3 f0 = material.specularColorBlended;\n\tfloat f90 = material.specularF90;\n\tfloat roughness = material.roughness;\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t#ifdef USE_IRIDESCENCE\n\t\tF = mix( F, material.iridescenceFresnel, material.iridescence );\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat dotTL = dot( material.anisotropyT, lightDir );\n\t\tfloat dotTV = dot( material.anisotropyT, viewDir );\n\t\tfloat dotTH = dot( material.anisotropyT, halfDir );\n\t\tfloat dotBL = dot( material.anisotropyB, lightDir );\n\t\tfloat dotBV = dot( material.anisotropyB, viewDir );\n\t\tfloat dotBH = dot( material.anisotropyB, halfDir );\n\t\tfloat V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );\n\t\tfloat D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );\n\t#else\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t#endif\n\treturn F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transpose( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat rInv = 1.0 / ( roughness + 0.1 );\n\tfloat a = -1.9362 + 1.0678 * roughness + 0.4573 * r2 - 0.8469 * rInv;\n\tfloat b = -0.6014 + 0.5538 * roughness - 0.4670 * r2 - 0.1255 * rInv;\n\tfloat DG = exp( a * dotNV + b );\n\treturn saturate( DG );\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg;\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec2 fab, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec2 fab, const in vec3 specularColor, const in float specularF90, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tvec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n\t#else\n\t\tvec3 Fr = specularColor;\n\t#endif\n\tvec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometryNormal;\n\t\tvec3 viewDir = geometryViewDir;\n\t\tvec3 position = geometryPosition;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColorBlended * t2.x + ( material.specularF90 - material.specularColorBlended ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseContribution * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t\t#ifdef USE_CLEARCOAT\n\t\t\tvec3 Ncc = geometryClearcoatNormal;\n\t\t\tvec2 uvClearcoat = LTC_Uv( Ncc, viewDir, material.clearcoatRoughness );\n\t\t\tvec4 t1Clearcoat = texture2D( ltc_1, uvClearcoat );\n\t\t\tvec4 t2Clearcoat = texture2D( ltc_2, uvClearcoat );\n\t\t\tmat3 mInvClearcoat = mat3(\n\t\t\t\tvec3( t1Clearcoat.x, 0, t1Clearcoat.y ),\n\t\t\t\tvec3( 0, 1, 0 ),\n\t\t\t\tvec3( t1Clearcoat.z, 0, t1Clearcoat.w )\n\t\t\t);\n\t\t\tvec3 fresnelClearcoat = material.clearcoatF0 * t2Clearcoat.x + ( material.clearcoatF90 - material.clearcoatF0 ) * t2Clearcoat.y;\n\t\t\tclearcoatSpecularDirect += lightColor * fresnelClearcoat * LTC_Evaluate( Ncc, viewDir, position, mInvClearcoat, rectCoords );\n\t\t#endif\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );\n\t#endif\n\t#ifdef USE_SHEEN\n \n \t\tsheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );\n \n \t\tfloat sheenAlbedoV = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n \t\tfloat sheenAlbedoL = IBLSheenBRDF( geometryNormal, directLight.direction, material.sheenRoughness );\n \n \t\tfloat sheenEnergyComp = 1.0 - max3( material.sheenColor ) * max( sheenAlbedoV, sheenAlbedoL );\n \n \t\tirradiance *= sheenEnergyComp;\n \n \t#endif\n\tvec3 specularBRDF = BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );\n\t#ifdef USE_RETROREFLECTION\n\t\tvec3 retroViewDir = reflect( - geometryViewDir, geometryNormal );\n\t\tvec3 retroSpecularBRDF = BRDF_GGX( directLight.direction, retroViewDir, geometryNormal, material );\n\t\tspecularBRDF = mix( specularBRDF, retroSpecularBRDF, saturate( material.retroreflectivity ) );\n\t#endif\n\treflectedLight.directSpecular += irradiance * specularBRDF * material.multiScatteringCompensation;\n\tvec3 halfDir = normalize( directLight.direction + geometryViewDir );\n\tfloat dotVH = saturate( dot( geometryViewDir, halfDir ) );\n\tvec3 F = F_Schlick( material.specularColor, material.specularF90, dotVH );\n\t#ifdef USE_RETROREFLECTION\n\t\tvec3 retroHalfDir = normalize( directLight.direction + retroViewDir );\n\t\tfloat dotRetroVH = saturate( dot( retroViewDir, retroHalfDir ) );\n\t\tvec3 retroF = F_Schlick( material.specularColor, material.specularF90, dotRetroVH );\n\t\tF = mix( F, retroF, saturate( material.retroreflectivity ) );\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseContribution ) * ( 1.0 - F );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( material.dfg, material.specularColor, material.specularF90, material.iridescence, material.iridescenceF0Dielectric, singleScattering, multiScattering );\n\t#else\n\t\tcomputeMultiscattering( material.dfg, material.specularColor, material.specularF90, singleScattering, multiScattering );\n\t#endif\n\tvec3 diffuse = irradiance * BRDF_Lambert( material.diffuseContribution ) * ( 1.0 - singleScattering - multiScattering );\n\t#ifdef USE_SHEEN\n\t\tfloat sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n\t\tsheenSpecularIndirect += irradiance * material.sheenColor * sheenAlbedo * RECIPROCAL_PI;\n\t\tfloat sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo;\n\t\tdiffuse *= sheenEnergyComp;\n\t#endif\n\treflectedLight.indirectDiffuse += diffuse;\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ) * RECIPROCAL_PI;\n \t#endif\n\tvec3 singleScatteringDielectric = vec3( 0.0 );\n\tvec3 multiScatteringDielectric = vec3( 0.0 );\n\tvec3 singleScatteringMetallic = vec3( 0.0 );\n\tvec3 multiScatteringMetallic = vec3( 0.0 );\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( material.dfg, material.specularColor, material.specularF90, material.iridescence, material.iridescenceF0Dielectric, singleScatteringDielectric, multiScatteringDielectric );\n\t\tcomputeMultiscatteringIridescence( material.dfg, material.diffuseColor, material.specularF90, material.iridescence, material.iridescenceF0Metallic, singleScatteringMetallic, multiScatteringMetallic );\n\t#else\n\t\tcomputeMultiscattering( material.dfg, material.specularColor, material.specularF90, singleScatteringDielectric, multiScatteringDielectric );\n\t\tcomputeMultiscattering( material.dfg, material.diffuseColor, material.specularF90, singleScatteringMetallic, multiScatteringMetallic );\n\t#endif\n\tvec3 singleScattering = mix( singleScatteringDielectric, singleScatteringMetallic, material.metalness );\n\tvec3 multiScattering = mix( multiScatteringDielectric, multiScatteringMetallic, material.metalness );\n\tvec3 totalScatteringDielectric = singleScatteringDielectric + multiScatteringDielectric;\n\tvec3 diffuse = material.diffuseContribution * ( 1.0 - totalScatteringDielectric );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tvec3 indirectSpecular = radiance * singleScattering;\n\tindirectSpecular += multiScattering * cosineWeightedIrradiance;\n\tvec3 indirectDiffuse = diffuse * cosineWeightedIrradiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n\t\tfloat sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo;\n\t\tindirectSpecular *= sheenEnergyComp;\n\t\tindirectDiffuse *= sheenEnergyComp;\n\t#endif\n\treflectedLight.indirectSpecular += indirectSpecular;\n\treflectedLight.indirectDiffuse += indirectDiffuse;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}"; -var lights_fragment_begin = "\nvec3 geometryPosition = - vViewPosition;\nvec3 geometryNormal = normal;\nvec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\nvec3 geometryClearcoatNormal = vec3( 0.0 );\n#ifdef USE_CLEARCOAT\n\tgeometryClearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometryViewDir ) );\n\tif ( material.iridescenceThickness == 0.0 ) {\n\t\tmaterial.iridescence = 0.0;\n\t} else {\n\t\tmaterial.iridescence = saturate( material.iridescence );\n\t}\n\tif ( material.iridescence > 0.0 ) {\n\t\tvec3 iridescenceFresnelDielectric = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tvec3 iridescenceFresnelMetallic = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.diffuseColor );\n\t\tmaterial.iridescenceFresnel = mix( iridescenceFresnelDielectric, iridescenceFresnelMetallic, material.metalness );\n\t\tmaterial.iridescenceF0Dielectric = Schlick_to_F0( iridescenceFresnelDielectric, 1.0, dotNVi );\n\t\tmaterial.iridescenceF0Metallic = Schlick_to_F0( iridescenceFresnelMetallic, 1.0, dotNVi );\n\t}\n#endif\n#ifdef STANDARD\n\tfloat dotNVms = saturate( dot( geometryNormal, geometryViewDir ) );\n\tmaterial.dfg = texture2D( dfgLUT, vec2( material.roughness, dotNVms ) ).rg;\n\t#if ( NUM_DIR_LIGHTS > 0 || NUM_POINT_LIGHTS > 0 || NUM_SPOT_LIGHTS > 0 )\n\t\tfloat EssMs = material.dfg.x + material.dfg.y;\n\t\tmaterial.multiScatteringCompensation = 1.0 + material.specularColorBlended * ( 1.0 / EssMs - 1.0 );\n\t#endif\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometryPosition, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tvec4 spotColor;\n\tvec3 spotLightCoord;\n\tbool inSpotLightMap;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometryPosition, directLight );\n\t\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n\t\t#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n\t\t#else\n\t\t#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#endif\n\t\t#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n\t\t\tspotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n\t\t\tinSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n\t\t\tspotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n\t\t\tdirectLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\n\t\t#endif\n\t\t#undef SPOT_LIGHT_MAP_INDEX\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#if defined( USE_LIGHT_PROBES )\n\t\tirradiance += getLightProbeIrradiance( lightProbe, geometryNormal );\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n\t#ifdef USE_LIGHT_PROBES_GRID\n\t\tvec3 probeWorldPos = ( ( vec4( geometryPosition, 1.0 ) - viewMatrix[ 3 ] ) * viewMatrix ).xyz;\n\t\tvec3 probeWorldNormal = transformNormalByInverseViewMatrix( geometryNormal, viewMatrix );\n\t\tirradiance += getLightProbeGridIrradiance( probeWorldPos, probeWorldNormal );\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif"; +var lights_fragment_begin = "\nvec3 geometryPosition = - vViewPosition;\nvec3 geometryNormal = normal;\nvec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\nvec3 geometryClearcoatNormal = vec3( 0.0 );\n#ifdef USE_CLEARCOAT\n\tgeometryClearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometryViewDir ) );\n\tif ( material.iridescenceThickness == 0.0 ) {\n\t\tmaterial.iridescence = 0.0;\n\t} else {\n\t\tmaterial.iridescence = saturate( material.iridescence );\n\t}\n\tif ( material.iridescence > 0.0 ) {\n\t\tvec3 iridescenceFresnelDielectric = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tvec3 iridescenceFresnelMetallic = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.diffuseColor );\n\t\tmaterial.iridescenceFresnel = mix( iridescenceFresnelDielectric, iridescenceFresnelMetallic, material.metalness );\n\t\tmaterial.iridescenceF0Dielectric = Schlick_to_F0( iridescenceFresnelDielectric, 1.0, dotNVi );\n\t\tmaterial.iridescenceF0Metallic = Schlick_to_F0( iridescenceFresnelMetallic, 1.0, dotNVi );\n\t}\n#endif\n#ifdef STANDARD\n\tfloat dotNVms = saturate( dot( geometryNormal, geometryViewDir ) );\n\tmaterial.dfg = texture2D( dfgLUT, vec2( material.roughness, dotNVms ) ).rg;\n\t#if ( NUM_SUN_LIGHTS > 0 || NUM_DIR_LIGHTS > 0 || NUM_POINT_LIGHTS > 0 || NUM_SPOT_LIGHTS > 0 )\n\t\tfloat EssMs = material.dfg.x + material.dfg.y;\n\t\tmaterial.multiScatteringCompensation = 1.0 + material.specularColorBlended * ( 1.0 / EssMs - 1.0 );\n\t#endif\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometryPosition, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tvec4 spotColor;\n\tvec3 spotLightCoord;\n\tbool inSpotLightMap;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometryPosition, directLight );\n\t\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n\t\t#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n\t\t#else\n\t\t#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#endif\n\t\t#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n\t\t\tspotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n\t\t\tinSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n\t\t\tspotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n\t\t\tdirectLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\n\t\t#endif\n\t\t#undef SPOT_LIGHT_MAP_INDEX\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SUN_LIGHTS > 0 ) && defined( RE_Direct )\n\tSunLight sunLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_SUN_LIGHT_SHADOWS > 0\n\tSunLightShadow sunLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SUN_LIGHTS; i ++ ) {\n\t\tsunLight = sunLights[ i ];\n\t\tgetSunLightInfo( sunLight, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SUN_LIGHT_SHADOWS )\n\t\tsunLightShadow = sunLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getSunShadow( sunShadowMap[ i ], sunLightShadow, UNROLLED_LOOP_INDEX ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#if defined( USE_LIGHT_PROBES )\n\t\tirradiance += getLightProbeIrradiance( lightProbe, geometryNormal );\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n\t#ifdef USE_LIGHT_PROBES_GRID\n\t\tvec3 probeWorldPos = ( ( vec4( geometryPosition, 1.0 ) - viewMatrix[ 3 ] ) * viewMatrix ).xyz;\n\t\tvec3 probeWorldNormal = transformNormalByInverseViewMatrix( geometryNormal, viewMatrix );\n\t\tirradiance += getLightProbeGridIrradiance( probeWorldPos, probeWorldNormal );\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif"; var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\t#if defined( STANDARD ) || defined( LAMBERT ) || defined( PHONG )\n\t\t\tiblIrradiance += getIBLIrradiance( geometryNormal );\n\t\t#endif\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\t#ifdef USE_ANISOTROPY\n\t\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"; @@ -474,13 +474,13 @@ var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUG var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif"; -var 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\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform sampler2DShadow directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\t#else\n\t\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\t#endif\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform sampler2DShadow spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\t#else\n\t\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\t#endif\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform samplerCubeShadow pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\t#elif defined( SHADOWMAP_TYPE_BASIC )\n\t\t\tuniform samplerCube pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\t#endif\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\tfloat interleavedGradientNoise( vec2 position ) {\n\t\t\treturn fract( 52.9829189 * fract( dot( position, vec2( 0.06711056, 0.00583715 ) ) ) );\n\t\t}\n\t\tvec2 vogelDiskSample( int sampleIndex, int samplesCount, float phi ) {\n\t\t\tconst float goldenAngle = 2.399963229728653;\n\t\t\tfloat r = sqrt( ( float( sampleIndex ) + 0.5 ) / float( samplesCount ) );\n\t\t\tfloat theta = float( sampleIndex ) * goldenAngle + phi;\n\t\t\treturn vec2( cos( theta ), sin( theta ) ) * r;\n\t\t}\n\t#endif\n\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\tfloat getShadow( sampler2DShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\t\tfloat shadow = 1.0;\n\t\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\t\tshadowCoord.z += shadowBias;\n\t\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\t\tif ( frustumTest ) {\n\t\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\t\tfloat radius = shadowRadius * texelSize.x;\n\t\t\t\tfloat phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2;\n\t\t\t\tshadow = (\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 0, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 1, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 2, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 3, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 4, 5, phi ) * radius, shadowCoord.z ) )\n\t\t\t\t) * 0.2;\n\t\t\t}\n\t\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t\t}\n\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\t\tfloat shadow = 1.0;\n\t\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\tshadowCoord.z -= shadowBias;\n\t\t\t#else\n\t\t\t\tshadowCoord.z += shadowBias;\n\t\t\t#endif\n\t\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\t\tif ( frustumTest ) {\n\t\t\t\tvec2 distribution = texture2D( shadowMap, shadowCoord.xy ).rg;\n\t\t\t\tfloat mean = distribution.x;\n\t\t\t\tfloat variance = distribution.y * distribution.y;\n\t\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\t\tfloat hard_shadow = step( mean, shadowCoord.z );\n\t\t\t\t#else\n\t\t\t\t\tfloat hard_shadow = step( shadowCoord.z, mean );\n\t\t\t\t#endif\n\t\t\t\t\n\t\t\t\tif ( hard_shadow == 1.0 ) {\n\t\t\t\t\tshadow = 1.0;\n\t\t\t\t} else {\n\t\t\t\t\tvariance = max( variance, 0.0000001 );\n\t\t\t\t\tfloat d = shadowCoord.z - mean;\n\t\t\t\t\tfloat p_max = variance / ( variance + d * d );\n\t\t\t\t\tp_max = clamp( ( p_max - 0.3 ) / 0.65, 0.0, 1.0 );\n\t\t\t\t\tshadow = max( hard_shadow, p_max );\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t\t}\n\t#else\n\t\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\t\tfloat shadow = 1.0;\n\t\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\tshadowCoord.z -= shadowBias;\n\t\t\t#else\n\t\t\t\tshadowCoord.z += shadowBias;\n\t\t\t#endif\n\t\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\t\tif ( frustumTest ) {\n\t\t\t\tfloat depth = texture2D( shadowMap, shadowCoord.xy ).r;\n\t\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\t\tshadow = step( depth, shadowCoord.z );\n\t\t\t\t#else\n\t\t\t\t\tshadow = step( shadowCoord.z, depth );\n\t\t\t\t#endif\n\t\t\t}\n\t\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t\t}\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#if defined( SHADOWMAP_TYPE_PCF )\n\tfloat getPointShadow( samplerCubeShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tfloat shadow = 1.0;\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\tvec3 absVec = abs( lightToPosition );\n\t\tfloat viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z );\n\t\tif ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) {\n\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\tfloat dp = ( shadowCameraNear * ( shadowCameraFar - viewSpaceZ ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );\n\t\t\t\tdp -= shadowBias;\n\t\t\t#else\n\t\t\t\tfloat dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );\n\t\t\t\tdp += shadowBias;\n\t\t\t#endif\n\t\t\tfloat texelSize = shadowRadius / shadowMapSize.x;\n\t\t\tvec3 absDir = abs( bd3D );\n\t\t\tvec3 tangent = absDir.x > absDir.z ? vec3( 0.0, 1.0, 0.0 ) : vec3( 1.0, 0.0, 0.0 );\n\t\t\ttangent = normalize( cross( bd3D, tangent ) );\n\t\t\tvec3 bitangent = cross( bd3D, tangent );\n\t\t\tfloat phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2;\n\t\t\tvec2 sample0 = vogelDiskSample( 0, 5, phi );\n\t\t\tvec2 sample1 = vogelDiskSample( 1, 5, phi );\n\t\t\tvec2 sample2 = vogelDiskSample( 2, 5, phi );\n\t\t\tvec2 sample3 = vogelDiskSample( 3, 5, phi );\n\t\t\tvec2 sample4 = vogelDiskSample( 4, 5, phi );\n\t\t\tshadow = (\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample0.x + bitangent * sample0.y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample1.x + bitangent * sample1.y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample2.x + bitangent * sample2.y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample3.x + bitangent * sample3.y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample4.x + bitangent * sample4.y ) * texelSize, dp ) )\n\t\t\t) * 0.2;\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n\t#elif defined( SHADOWMAP_TYPE_BASIC )\n\tfloat getPointShadow( samplerCube shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tfloat shadow = 1.0;\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 absVec = abs( lightToPosition );\n\t\tfloat viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z );\n\t\tif ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) {\n\t\t\tfloat dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );\n\t\t\tdp += shadowBias;\n\t\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t\tfloat depth = textureCube( shadowMap, bd3D ).r;\n\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\tdepth = 1.0 - depth;\n\t\t\t#endif\n\t\t\tshadow = step( dp, depth );\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n\t#endif\n\t#endif\n#endif"; +var shadowmap_pars_fragment = "#if NUM_SPOT_LIGHT_COORDS > 0\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n\tuniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_SUN_LIGHT_SHADOWS > 0\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform sampler2DShadow sunShadowMap[ NUM_SUN_LIGHT_SHADOWS ];\n\t\t#else\n\t\t\tuniform sampler2D sunShadowMap[ NUM_SUN_LIGHT_SHADOWS ];\n\t\t#endif\n\t\tuniform mat4 sunShadowMatrix[ NUM_SUN_LIGHT_SHADOWS * 4 ];\n\t\tuniform vec4 sunShadowCascade[ NUM_SUN_LIGHT_SHADOWS * 4 ];\n\t\tvarying vec4 vSunShadowWorldPosition;\n\t\tvarying vec3 vSunShadowWorldNormal;\n\t\tstruct SunLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SunLightShadow sunLightShadows[ NUM_SUN_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform sampler2DShadow directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\t#else\n\t\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\t#endif\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform sampler2DShadow spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\t#else\n\t\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\t#endif\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform samplerCubeShadow pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\t#elif defined( SHADOWMAP_TYPE_BASIC )\n\t\t\tuniform samplerCube pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\t#endif\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\tfloat interleavedGradientNoise( vec2 position ) {\n\t\t\treturn fract( 52.9829189 * fract( dot( position, vec2( 0.06711056, 0.00583715 ) ) ) );\n\t\t}\n\t\tvec2 vogelDiskSample( int sampleIndex, int samplesCount, float phi ) {\n\t\t\tconst float goldenAngle = 2.399963229728653;\n\t\t\tfloat r = sqrt( ( float( sampleIndex ) + 0.5 ) / float( samplesCount ) );\n\t\t\tfloat theta = float( sampleIndex ) * goldenAngle + phi;\n\t\t\treturn vec2( cos( theta ), sin( theta ) ) * r;\n\t\t}\n\t#endif\n\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\tfloat getShadow( sampler2DShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\t\tfloat shadow = 1.0;\n\t\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\t\tshadowCoord.z += shadowBias;\n\t\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\t\tif ( frustumTest ) {\n\t\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\t\tfloat radius = shadowRadius * texelSize.x;\n\t\t\t\tfloat phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2;\n\t\t\t\tshadow = (\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 0, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 1, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 2, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 3, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 4, 5, phi ) * radius, shadowCoord.z ) )\n\t\t\t\t) * 0.2;\n\t\t\t}\n\t\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t\t}\n\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\t\tfloat shadow = 1.0;\n\t\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\tshadowCoord.z -= shadowBias;\n\t\t\t#else\n\t\t\t\tshadowCoord.z += shadowBias;\n\t\t\t#endif\n\t\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\t\tif ( frustumTest ) {\n\t\t\t\tvec2 distribution = texture2D( shadowMap, shadowCoord.xy ).rg;\n\t\t\t\tfloat mean = distribution.x;\n\t\t\t\tfloat variance = distribution.y * distribution.y;\n\t\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\t\tfloat hard_shadow = step( mean, shadowCoord.z );\n\t\t\t\t#else\n\t\t\t\t\tfloat hard_shadow = step( shadowCoord.z, mean );\n\t\t\t\t#endif\n\t\t\t\t\n\t\t\t\tif ( hard_shadow == 1.0 ) {\n\t\t\t\t\tshadow = 1.0;\n\t\t\t\t} else {\n\t\t\t\t\tvariance = max( variance, 0.0000001 );\n\t\t\t\t\tfloat d = shadowCoord.z - mean;\n\t\t\t\t\tfloat p_max = variance / ( variance + d * d );\n\t\t\t\t\tp_max = clamp( ( p_max - 0.3 ) / 0.65, 0.0, 1.0 );\n\t\t\t\t\tshadow = max( hard_shadow, p_max );\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t\t}\n\t#else\n\t\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\t\tfloat shadow = 1.0;\n\t\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\tshadowCoord.z -= shadowBias;\n\t\t\t#else\n\t\t\t\tshadowCoord.z += shadowBias;\n\t\t\t#endif\n\t\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\t\tif ( frustumTest ) {\n\t\t\t\tfloat depth = texture2D( shadowMap, shadowCoord.xy ).r;\n\t\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\t\tshadow = step( depth, shadowCoord.z );\n\t\t\t\t#else\n\t\t\t\t\tshadow = step( shadowCoord.z, depth );\n\t\t\t\t#endif\n\t\t\t}\n\t\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t\t}\n\t#endif\n\t#if NUM_SUN_LIGHT_SHADOWS > 0\n\t\tfloat getSunShadow(\n\t\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\t\tsampler2DShadow shadowMap,\n\t\t\t#else\n\t\t\t\tsampler2D shadowMap,\n\t\t\t#endif\n\t\t\tSunLightShadow sunLightShadow,\n\t\t\tconst in int shadowIndex\n\t\t) {\n\t\t\tvec4 shadowWorldPosition = vec4( vSunShadowWorldPosition.xyz + vSunShadowWorldNormal * sunLightShadow.shadowNormalBias, 1.0 );\n\t\t\tfloat viewDepth = vSunShadowWorldPosition.w;\n\t\t\tint cascadeOffset = shadowIndex * 4;\n\t\t\tfloat shadow = 1.0;\n\t\t\tfor ( int i = 3; i >= 0; i -- ) {\n\t\t\t\tvec4 cascade = sunShadowCascade[ cascadeOffset + i ];\n\t\t\t\tif ( viewDepth >= cascade.x && viewDepth < cascade.y ) {\n\t\t\t\t\tfloat cascadeShadow = getShadow( shadowMap, sunLightShadow.shadowMapSize, sunLightShadow.shadowIntensity, sunLightShadow.shadowBias, sunLightShadow.shadowRadius, sunShadowMatrix[ cascadeOffset + i ] * shadowWorldPosition );\n\t\t\t\t\tshadow = viewDepth < cascade.z ? cascadeShadow : mix( cascadeShadow, shadow, smoothstep( cascade.z, cascade.y, viewDepth ) );\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn shadow;\n\t\t}\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#if defined( SHADOWMAP_TYPE_PCF )\n\tfloat getPointShadow( samplerCubeShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tfloat shadow = 1.0;\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\tvec3 absVec = abs( lightToPosition );\n\t\tfloat viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z );\n\t\tif ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) {\n\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\tfloat dp = ( shadowCameraNear * ( shadowCameraFar - viewSpaceZ ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );\n\t\t\t\tdp -= shadowBias;\n\t\t\t#else\n\t\t\t\tfloat dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );\n\t\t\t\tdp += shadowBias;\n\t\t\t#endif\n\t\t\tfloat texelSize = shadowRadius / shadowMapSize.x;\n\t\t\tvec3 absDir = abs( bd3D );\n\t\t\tvec3 tangent = absDir.x > absDir.z ? vec3( 0.0, 1.0, 0.0 ) : vec3( 1.0, 0.0, 0.0 );\n\t\t\ttangent = normalize( cross( bd3D, tangent ) );\n\t\t\tvec3 bitangent = cross( bd3D, tangent );\n\t\t\tfloat phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2;\n\t\t\tvec2 sample0 = vogelDiskSample( 0, 5, phi );\n\t\t\tvec2 sample1 = vogelDiskSample( 1, 5, phi );\n\t\t\tvec2 sample2 = vogelDiskSample( 2, 5, phi );\n\t\t\tvec2 sample3 = vogelDiskSample( 3, 5, phi );\n\t\t\tvec2 sample4 = vogelDiskSample( 4, 5, phi );\n\t\t\tshadow = (\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample0.x + bitangent * sample0.y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample1.x + bitangent * sample1.y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample2.x + bitangent * sample2.y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample3.x + bitangent * sample3.y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample4.x + bitangent * sample4.y ) * texelSize, dp ) )\n\t\t\t) * 0.2;\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n\t#elif defined( SHADOWMAP_TYPE_BASIC )\n\tfloat getPointShadow( samplerCube shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tfloat shadow = 1.0;\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 absVec = abs( lightToPosition );\n\t\tfloat viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z );\n\t\tif ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) {\n\t\t\tfloat dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );\n\t\t\tdp += shadowBias;\n\t\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t\tfloat depth = textureCube( shadowMap, bd3D ).r;\n\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\tdepth = 1.0 - depth;\n\t\t\t#endif\n\t\t\tshadow = step( dp, depth );\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n\t#endif\n\t#endif\n#endif"; -var shadowmap_pars_vertex = "#if NUM_SPOT_LIGHT_COORDS > 0\n\tuniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif"; +var shadowmap_pars_vertex = "#if NUM_SPOT_LIGHT_COORDS > 0\n\tuniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_SUN_LIGHT_SHADOWS > 0\n\t\tvarying vec4 vSunShadowWorldPosition;\n\t\tvarying vec3 vSunShadowWorldNormal;\n\t#endif\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif"; -var shadowmap_vertex = "#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n\t#ifdef HAS_NORMAL\n\t\tvec3 shadowWorldNormal = transformNormalByInverseViewMatrix( transformedNormal, viewMatrix );\n\t#else\n\t\tvec3 shadowWorldNormal = vec3( 0.0 );\n\t#endif\n\tvec4 shadowWorldPosition;\n#endif\n#if defined( USE_SHADOWMAP )\n\t#if NUM_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"; +var shadowmap_vertex = "#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SUN_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n\t#ifdef HAS_NORMAL\n\t\tvec3 shadowWorldNormal = transformNormalByInverseViewMatrix( transformedNormal, viewMatrix );\n\t#else\n\t\tvec3 shadowWorldNormal = vec3( 0.0 );\n\t#endif\n\tvec4 shadowWorldPosition;\n#endif\n#if defined( USE_SHADOWMAP )\n\t#if NUM_SUN_LIGHT_SHADOWS > 0\n\t\tvSunShadowWorldPosition = vec4( worldPosition.xyz, - mvPosition.z );\n\t\tvSunShadowWorldNormal = shadowWorldNormal;\n\t#endif\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if NUM_SPOT_LIGHT_COORDS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition;\n\t\t#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t\tshadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;\n\t\t#endif\n\t\tvSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n#endif"; -var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0 && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) )\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}"; +var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_SUN_LIGHT_SHADOWS > 0\n\tSunLightShadow sunLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SUN_LIGHT_SHADOWS; i ++ ) {\n\t\tsunLight = sunLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getSunShadow( sunShadowMap[ i ], sunLight, UNROLLED_LOOP_INDEX ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0 && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) )\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}"; var 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"; @@ -843,6 +843,22 @@ const UniformsLib = { lightProbe: { value: [] }, + sunLights: { value: [], properties: { + direction: {}, + color: {} + } }, + + sunLightShadows: { value: [], properties: { + shadowIntensity: 1, + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {} + } }, + + sunShadowMatrix: { value: [] }, + sunShadowCascade: { value: [] }, + directionalLights: { value: [], properties: { direction: {}, color: {} @@ -6359,6 +6375,7 @@ function replaceLightNums( string, parameters ) { const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps; return string + .replace( /NUM_SUN_LIGHTS/g, parameters.numSunLights ) .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights ) .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights ) .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps ) @@ -6366,6 +6383,7 @@ function replaceLightNums( string, parameters ) { .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights ) .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights ) .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights ) + .replace( /NUM_SUN_LIGHT_SHADOWS/g, parameters.numSunLightShadows ) .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows ) .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps ) .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows ) @@ -7620,6 +7638,7 @@ function WebGLPrograms( renderer, environments, extensions, capabilities, bindin morphTargetsCount: morphTargetsCount, morphTextureStride: morphTextureStride, + numSunLights: lights.sun.length, numDirLights: lights.directional.length, numPointLights: lights.point.length, numSpotLights: lights.spot.length, @@ -7627,6 +7646,7 @@ function WebGLPrograms( renderer, environments, extensions, capabilities, bindin numRectAreaLights: lights.rectArea.length, numHemiLights: lights.hemi.length, + numSunLightShadows: lights.sunShadowMap.length, numDirLightShadows: lights.directionalShadowMap.length, numPointLightShadows: lights.pointShadowMap.length, numSpotLightShadows: lights.spotShadowMap.length, @@ -7754,12 +7774,14 @@ function WebGLPrograms( renderer, environments, extensions, capabilities, bindin array.push( parameters.sizeAttenuation ); array.push( parameters.morphTargetsCount ); array.push( parameters.morphAttributeCount ); + array.push( parameters.numSunLights ); array.push( parameters.numDirLights ); array.push( parameters.numPointLights ); array.push( parameters.numSpotLights ); array.push( parameters.numSpotLightMaps ); array.push( parameters.numHemiLights ); array.push( parameters.numRectAreaLights ); + array.push( parameters.numSunLightShadows ); array.push( parameters.numDirLightShadows ); array.push( parameters.numPointLightShadows ); array.push( parameters.numSpotLightShadows ); @@ -8296,6 +8318,7 @@ function UniformsCache() { switch ( light.type ) { + case 'SunLight': case 'DirectionalLight': uniforms = { direction: new Vector3(), @@ -8371,6 +8394,7 @@ function ShadowUniformsCache() { switch ( light.type ) { + case 'SunLight': case 'DirectionalLight': uniforms = { shadowIntensity: 1, @@ -8438,12 +8462,14 @@ function WebGLLights( extensions ) { version: 0, hash: { + sunLength: -1, directionalLength: -1, pointLength: -1, spotLength: -1, rectAreaLength: -1, hemiLength: -1, + numSunShadows: -1, numDirectionalShadows: -1, numPointShadows: -1, numSpotShadows: -1, @@ -8454,6 +8480,11 @@ function WebGLLights( extensions ) { ambient: [ 0, 0, 0 ], probe: [], + sun: [], + sunShadow: [], + sunShadowMap: [], + sunShadowMatrix: [], + sunShadowCascade: [], directional: [], directionalShadow: [], directionalShadowMap: [], @@ -8488,6 +8519,8 @@ function WebGLLights( extensions ) { for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 ); + let sunLength = 0; + let numSunShadows = 0; let directionalLength = 0; let pointLength = 0; let spotLength = 0; @@ -8547,6 +8580,44 @@ function WebGLLights( extensions ) { numLightProbes ++; + } else if ( light.isSunLight ) { + + const uniforms = cache.get( light ); + + uniforms.color.copy( light.color ).multiplyScalar( light.intensity ); + + if ( light.castShadow ) { + + const shadow = light.shadow; + + const shadowUniforms = shadowCache.get( light ); + + shadowUniforms.shadowIntensity = shadow.intensity; + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize.copy( shadow.mapSize ).multiply( shadow.getFrameExtents() ); + + state.sunShadow[ numSunShadows ] = shadowUniforms; + state.sunShadowMap[ numSunShadows ] = shadowMap; + + // four cascades per sun light, matching the sun shadow shader chunks + + for ( let i = 0; i < 4; i ++ ) { + + state.sunShadowMatrix[ numSunShadows * 4 + i ] = shadow.getMatrix( i ); + state.sunShadowCascade[ numSunShadows * 4 + i ] = shadow._cascadeData[ i ]; + + } + + numSunShadows ++; + + } + + state.sun[ sunLength ] = uniforms; + + sunLength ++; + } else if ( light.isDirectionalLight ) { const uniforms = cache.get( light ); @@ -8712,42 +8783,51 @@ function WebGLLights( extensions ) { const hash = state.hash; - if ( hash.directionalLength !== directionalLength || + if ( hash.sunLength !== sunLength || + hash.directionalLength !== directionalLength || hash.pointLength !== pointLength || hash.spotLength !== spotLength || hash.rectAreaLength !== rectAreaLength || hash.hemiLength !== hemiLength || + hash.numSunShadows !== numSunShadows || hash.numDirectionalShadows !== numDirectionalShadows || hash.numPointShadows !== numPointShadows || hash.numSpotShadows !== numSpotShadows || hash.numSpotMaps !== numSpotMaps || hash.numLightProbes !== numLightProbes ) { + state.sun.length = sunLength; state.directional.length = directionalLength; state.spot.length = spotLength; state.rectArea.length = rectAreaLength; state.point.length = pointLength; state.hemi.length = hemiLength; + state.sunShadow.length = numSunShadows; + state.sunShadowMap.length = numSunShadows; + state.sunShadowMatrix.length = numSunShadows * 4; + state.sunShadowCascade.length = numSunShadows * 4; state.directionalShadow.length = numDirectionalShadows; state.directionalShadowMap.length = numDirectionalShadows; + state.directionalShadowMatrix.length = numDirectionalShadows; state.pointShadow.length = numPointShadows; state.pointShadowMap.length = numPointShadows; state.spotShadow.length = numSpotShadows; state.spotShadowMap.length = numSpotShadows; - state.directionalShadowMatrix.length = numDirectionalShadows; state.pointShadowMatrix.length = numPointShadows; state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps; state.spotLightMap.length = numSpotMaps; state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps; state.numLightProbes = numLightProbes; + hash.sunLength = sunLength; hash.directionalLength = directionalLength; hash.pointLength = pointLength; hash.spotLength = spotLength; hash.rectAreaLength = rectAreaLength; hash.hemiLength = hemiLength; + hash.numSunShadows = numSunShadows; hash.numDirectionalShadows = numDirectionalShadows; hash.numPointShadows = numPointShadows; hash.numSpotShadows = numSpotShadows; @@ -8763,6 +8843,7 @@ function WebGLLights( extensions ) { function setupView( lights, camera ) { + let sunLength = 0; let directionalLength = 0; let pointLength = 0; let spotLength = 0; @@ -8775,7 +8856,16 @@ function WebGLLights( extensions ) { const light = lights[ i ]; - if ( light.isDirectionalLight ) { + if ( light.isSunLight ) { + + const uniforms = state.sun[ sunLength ]; + + uniforms.direction.setFromMatrixPosition( light.matrixWorld ); + uniforms.direction.transformDirection( viewMatrix ); + + sunLength ++; + + } else if ( light.isDirectionalLight ) { const uniforms = state.directional[ directionalLength ]; @@ -9130,6 +9220,7 @@ function WebGLShadowMap( renderer, objects, capabilities ) { _shadowMapSize.copy( shadow.mapSize ); + const viewportCount = shadow.getViewportCount(); const shadowFrameExtents = shadow.getFrameExtents(); _shadowMapSize.multiply( shadowFrameExtents ); @@ -9237,39 +9328,21 @@ function WebGLShadowMap( renderer, objects, capabilities ) { } - // For cube render targets (PointLights), render all 6 faces. Otherwise, render once. - const faceCount = shadow.map.isWebGLCubeRenderTarget ? 6 : 1; - - for ( let face = 0; face < faceCount; face ++ ) { + if ( shadow.map.isWebGLCubeRenderTarget !== true && ( shadow.map.width !== _shadowMapSize.x || shadow.map.height !== _shadowMapSize.y ) ) { - // For cube render targets, render to each face separately - if ( shadow.map.isWebGLCubeRenderTarget ) { + shadow.map.setSize( _shadowMapSize.x, _shadowMapSize.y ); - renderer.setRenderTarget( shadow.map, face ); - renderer.clear(); - - } else { - - // For 2D render targets, use viewports - if ( face === 0 ) { - - renderer.setRenderTarget( shadow.map ); - renderer.clear(); - - } + } - const viewport = shadow.getViewport( face ); + // For cube render targets (PointLights), render all 6 faces. Sun lights + // render one atlas viewport per cascade. + const faceCount = shadow.map.isWebGLCubeRenderTarget ? 6 : viewportCount; - _viewport.set( - _viewportSize.x * viewport.x, - _viewportSize.y * viewport.y, - _viewportSize.x * viewport.z, - _viewportSize.y * viewport.w - ); + if ( light.isPointLight !== true ) shadow.updateMatrices( light, camera ); - _state.viewport( _viewport ); + for ( let face = 0; face < faceCount; face ++ ) { - } + const shadowCamera = shadow.getCamera( face ); if ( light.isPointLight ) { @@ -9299,15 +9372,40 @@ function WebGLShadowMap( renderer, objects, capabilities ) { _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); shadow._frustum.setFromProjectionMatrix( _projScreenMatrix, camera.coordinateSystem, camera.reversedDepth ); + } + + // For cube render targets, render to each face separately + if ( shadow.map.isWebGLCubeRenderTarget ) { + + renderer.setRenderTarget( shadow.map, face ); + renderer.clear(); + } else { - shadow.updateMatrices( light ); + // For 2D render targets, use viewports + if ( face === 0 ) { + + renderer.setRenderTarget( shadow.map ); + renderer.clear(); + + } + + const viewport = shadow.getViewport( face ); + + _viewport.set( + _viewportSize.x * viewport.x, + _viewportSize.y * viewport.y, + _viewportSize.x * viewport.z, + _viewportSize.y * viewport.w + ); + + _state.viewport( _viewport ); } - _frustum = shadow.getFrustum(); + _frustum = shadow.getFrustum( face ); - renderObject( scene, camera, shadow.camera, light, this.type ); + renderObject( scene, camera, shadowCamera, light, this.type ); } @@ -9352,12 +9450,16 @@ function WebGLShadowMap( renderer, objects, capabilities ) { type: HalfFloatType } ); + } else if ( shadow.mapPass.width !== shadow.map.width || shadow.mapPass.height !== shadow.map.height ) { + + shadow.mapPass.setSize( shadow.map.width, shadow.map.height ); + } // vertical pass - read from native depth texture shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.depthTexture; - shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize; + shadowMaterialVertical.uniforms.resolution.value.set( shadow.map.width, shadow.map.height ); shadowMaterialVertical.uniforms.radius.value = shadow.radius; renderer.setRenderTarget( shadow.mapPass ); renderer.clear(); @@ -9366,7 +9468,7 @@ function WebGLShadowMap( renderer, objects, capabilities ) { // horizontal pass shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture; - shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize; + shadowMaterialHorizontal.uniforms.resolution.value.set( shadow.map.width, shadow.map.height ); shadowMaterialHorizontal.uniforms.radius.value = shadow.radius; renderer.setRenderTarget( shadow.map ); renderer.clear(); @@ -10929,7 +11031,7 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, const _htmlTextures = new Set(); let _canvas; - const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source + const _sources = new WeakMap(); // maps WebglTexture objects to instances of TextureSource // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas, // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")! @@ -11635,7 +11737,7 @@ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, } - // create Source <-> WebGLTextures mapping if necessary + // create TextureSource <-> WebGLTextures mapping if necessary const source = texture.source; let webglTextures = _sources.get( source ); @@ -17287,6 +17389,8 @@ class WebGLRenderer { function prepareMaterial( material, scene, object ) { + if ( _nodesHandler !== null && material.isNodeMaterial ) _nodesHandler.setObject( object, material ); + if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) { material.side = BackSide; @@ -17322,6 +17426,7 @@ class WebGLRenderer { this.compile = function ( scene, camera, targetScene = null ) { if ( targetScene === null ) targetScene = scene; + if ( _nodesHandler !== null ) _nodesHandler.renderStart( scene, camera, targetScene ); currentRenderState = renderStates.get( targetScene ); currentRenderState.init( camera ); @@ -17367,6 +17472,11 @@ class WebGLRenderer { } currentRenderState.setupLights(); + if ( _nodesHandler !== null ) _nodesHandler.updateLights( currentRenderState.state.lightsArray ); + + // node materials reference the shadow map when they are built, so it must exist by now + + if ( _nodesHandler !== null ) shadowMap.render( currentRenderState.state.shadowsArray, targetScene, camera ); // Only initialize materials in the new scene, not the targetScene. @@ -17407,6 +17517,7 @@ class WebGLRenderer { } ); currentRenderState = renderStateStack.pop(); + if ( _nodesHandler !== null ) _nodesHandler.renderEnd(); return materials; @@ -17623,6 +17734,7 @@ class WebGLRenderer { projectObject( scene, camera, 0, _this.sortObjects ); currentRenderList.finish(); + if ( _nodesHandler !== null ) _nodesHandler.updateLights( currentRenderState.state.lightsArray ); if ( _this.sortObjects === true ) { @@ -18067,6 +18179,7 @@ class WebGLRenderer { function renderObject( object, scene, camera, geometry, material, group ) { + if ( _nodesHandler !== null && material.isNodeMaterial ) _nodesHandler.setObject( object, material ); object.onBeforeRender( _this, scene, camera, geometry, material, group ); object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld ); @@ -18187,6 +18300,8 @@ class WebGLRenderer { uniforms.ambientLightColor.value = lights.state.ambient; uniforms.lightProbe.value = lights.state.probe; + uniforms.sunLights.value = lights.state.sun; + uniforms.sunLightShadows.value = lights.state.sunShadow; uniforms.directionalLights.value = lights.state.directional; uniforms.directionalLightShadows.value = lights.state.directionalShadow; uniforms.spotLights.value = lights.state.spot; @@ -18198,6 +18313,8 @@ class WebGLRenderer { uniforms.pointLightShadows.value = lights.state.pointShadow; uniforms.hemisphereLights.value = lights.state.hemi; + uniforms.sunShadowMatrix.value = lights.state.sunShadowMatrix; + uniforms.sunShadowCascade.value = lights.state.sunShadowCascade; uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix; uniforms.spotLightMatrix.value = lights.state.spotLightMatrix; uniforms.spotLightMap.value = lights.state.spotLightMap; @@ -18562,6 +18679,12 @@ class WebGLRenderer { if ( materialProperties.needsLights ) { // Set shadow map uniforms first to ensure they get the first texture units + if ( lights.state.sunShadowMap.length > 0 ) { + + p_uniforms.setValue( _gl, 'sunShadowMap', lights.state.sunShadowMap, textures ); + + } + if ( lights.state.directionalShadowMap.length > 0 ) { p_uniforms.setValue( _gl, 'directionalShadowMap', lights.state.directionalShadowMap, textures ); @@ -18741,6 +18864,8 @@ class WebGLRenderer { uniforms.ambientLightColor.needsUpdate = value; uniforms.lightProbe.needsUpdate = value; + uniforms.sunLights.needsUpdate = value; + uniforms.sunLightShadows.needsUpdate = value; uniforms.directionalLights.needsUpdate = value; uniforms.directionalLightShadows.needsUpdate = value; uniforms.pointLights.needsUpdate = value; diff --git a/build/three.webgpu.js b/build/three.webgpu.js index f871534f076875..b0c2d40f950ee5 100644 --- a/build/three.webgpu.js +++ b/build/three.webgpu.js @@ -4,7 +4,7 @@ * SPDX-License-Identifier: MIT */ import { DynamicDrawUsage, RenderObjectRefreshType, Color, Vector2, Vector3, Vector4, Matrix2, Matrix3, Matrix4, UnsignedIntType, IntType, error, RedFormat, RedIntegerFormat, DepthFormat, DepthStencilFormat, AlphaFormat, RGFormat, RGIntegerFormat, RGBFormat, RGBIntegerFormat, EventDispatcher, MathUtils, warn, WebGLCoordinateSystem, WebGPUCoordinateSystem, ColorManagement, SRGBTransfer, NoToneMapping, StaticDrawUsage, InterleavedBufferAttribute, InterleavedBuffer, NoColorSpace, log as log$1, warnOnce, Texture, Compatibility, LessCompare, LessEqualCompare, GreaterCompare, GreaterEqualCompare, NearestFilter, Sphere, BackSide, DoubleSide, CubeTexture, CubeReflectionMapping, CubeRefractionMapping, TangentSpaceNormalMap, NoNormalPacking, NormalRGPacking, NormalGAPacking, ObjectSpaceNormalMap, RED_GREEN_RGTC2_Format, RG11_EAC_Format, InstancedBufferAttribute, InstancedInterleavedBuffer, DataTexture, RGBAFormat, FloatType, DataArrayTexture, FramebufferTexture, LinearMipmapLinearFilter, DepthTexture, Material, LineBasicMaterial, LineDashedMaterial, NoBlending, MeshNormalMaterial, SRGBColorSpace, RenderTarget, BoxGeometry, Mesh, Scene, LinearFilter, CubeCamera, EquirectangularReflectionMapping, EquirectangularRefractionMapping, AddOperation, MixOperation, MultiplyOperation, MeshBasicMaterial, MeshLambertMaterial, MeshPhongMaterial, HalfFloatType, ClampToEdgeWrapping, BufferGeometry, OrthographicCamera, PerspectiveCamera, LinearSRGBColorSpace, CubeUVReflectionMapping, BufferAttribute, MeshStandardMaterial, MeshPhysicalMaterial, MeshToonMaterial, MeshMatcapMaterial, SpriteMaterial, PointsMaterial, ShadowMaterial, Uint32BufferAttribute, Uint16BufferAttribute, ByteType, UnsignedByteType, ShortType, UnsignedShortType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedInt248Type, UnsignedInt5999Type, UnsignedInt101111Type, NormalBlending, SrcAlphaFactor, OneMinusSrcAlphaFactor, AddEquation, MaterialBlending, Object3D, LinearMipMapLinearFilter, Plane, Float32BufferAttribute, UVMapping, PCFShadowMap, VSMShadowMap, BasicShadowMap, CubeDepthTexture, SphereGeometry, LinearMipmapNearestFilter, NearestMipmapLinearFilter, Float16BufferAttribute, yieldToMain, REVISION, ArrayCamera, PlaneGeometry, FrontSide, CustomBlending, ZeroFactor, CylinderGeometry, Quaternion, WebXRController, RAD2DEG, PCFSoftShadowMap, FrustumArray, Frustum, RGBAIntegerFormat, TimestampQuery, createCanvasElement, MaxEquation, MinEquation, ReverseSubtractEquation, SubtractEquation, OneMinusConstantAlphaFactor, ConstantAlphaFactor, OneMinusConstantColorFactor, ConstantColorFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcColorFactor, DstAlphaFactor, DstColorFactor, SrcAlphaSaturateFactor, SrcColorFactor, OneFactor, CullFaceNone, CullFaceBack, CullFaceFront, MultiplyBlending, SubtractiveBlending, AdditiveBlending, NotEqualDepth, GreaterDepth, GreaterEqualDepth, EqualDepth, LessEqualDepth, LessDepth, AlwaysDepth, NeverDepth, ReversedDepthFuncs, RGB_S3TC_DXT1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGB_PVRTC_4BPPV1_Format, RGB_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_PVRTC_2BPPV1_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGBA_ETC2_EAC_Format, R11_EAC_Format, SIGNED_R11_EAC_Format, SIGNED_RG11_EAC_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_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_10x10_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_BPTC_Format, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RED_RGTC1_Format, SIGNED_RED_RGTC1_Format, SIGNED_RED_GREEN_RGTC2_Format, MirroredRepeatWrapping, RepeatWrapping, NearestMipmapNearestFilter, NotEqualCompare, EqualCompare, AlwaysCompare, NeverCompare, LinearTransfer, getByteLength, isTypedArray, NotEqualStencilFunc, GreaterStencilFunc, GreaterEqualStencilFunc, EqualStencilFunc, LessEqualStencilFunc, LessStencilFunc, AlwaysStencilFunc, NeverStencilFunc, DecrementWrapStencilOp, IncrementWrapStencilOp, DecrementStencilOp, IncrementStencilOp, InvertStencilOp, ReplaceStencilOp, ZeroStencilOp, KeepStencilOp, SpotLight, PointLight, DirectionalLight, RectAreaLight, AmbientLight, HemisphereLight, LightProbe, LinearToneMapping, ReinhardToneMapping, CineonToneMapping, ACESFilmicToneMapping, AgXToneMapping, NeutralToneMapping, Group, Loader, FileLoader, MaterialLoader, ObjectLoader } from './three.core.js'; -export { AdditiveAnimationBlendMode, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BasicDepthPacking, BatchedMesh, BezierInterpolant, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxHelper, BufferGeometryLoader, Cache, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CircleGeometry, Clock, ColorKeyframeTrack, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, Controls, CubeTextureLoader, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceFrontBack, Curve, CurvePath, CustomToneMapping, Cylindrical, Data3DTexture, DataTextureLoader, DataUtils, DefaultLoadingManager, DetachedBindMode, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry, DynamicCopyUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, Euler, ExternalTexture, ExtrudeGeometry, Fog, FogExp2, GLBufferAttribute, GLSL1, GLSL3, GridHelper, HTMLTexture, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, InstancedBufferGeometry, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, Interpolant, InterpolateBezier, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InterpolationSamplingMode, InterpolationSamplingType, KeyframeTrack, LOD, LatheGeometry, Layers, Light, Line, Line3, LineCurve, LineCurve3, LineLoop, LineSegments, LinearInterpolant, LinearMipMapNearestFilter, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, MOUSE, MeshDepthMaterial, MeshDistanceMaterial, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NormalAnimationBlendMode, NumberKeyframeTrack, OctahedronGeometry, Path, PlaneHelper, PointLightHelper, Points, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RGBADepthPacking, RGBDepthPacking, RGDepthPacking, RawShaderMaterial, Ray, Raycaster, RenderTarget3D, RingGeometry, ShaderMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, Skeleton, SkeletonHelper, SkinnedMesh, Source, Spherical, SphericalHarmonics3, SplineCurve, SpotLightHelper, Sprite, StaticCopyUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, TOUCH, TetrahedronGeometry, TextureLoader, TextureUtils, Timer, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, VectorKeyframeTrack, VideoFrameTexture, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLRenderTarget, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroSlopeEnding, getConsoleFunction, setConsoleFunction } from './three.core.js'; +export { AdditiveAnimationBlendMode, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BasicDepthPacking, BatchedMesh, BezierInterpolant, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxHelper, BufferGeometryLoader, Cache, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CircleGeometry, Clock, ColorKeyframeTrack, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, Controls, CubeTextureLoader, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceFrontBack, Curve, CurvePath, CustomToneMapping, Cylindrical, Data3DTexture, DataTextureLoader, DataUtils, DefaultLoadingManager, DetachedBindMode, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry, DynamicCopyUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, Euler, ExternalTexture, ExtrudeGeometry, Fog, FogExp2, GLBufferAttribute, GLSL1, GLSL3, GridHelper, HTMLTexture, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, InstancedBufferGeometry, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, Interpolant, InterpolateBezier, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InterpolationSamplingMode, InterpolationSamplingType, KeyframeTrack, LOD, LatheGeometry, Layers, Light, Line, Line3, LineCurve, LineCurve3, LineLoop, LineSegments, LinearInterpolant, LinearMipMapNearestFilter, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, MOUSE, MeshDepthMaterial, MeshDistanceMaterial, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NormalAnimationBlendMode, NumberKeyframeTrack, OctahedronGeometry, Path, PlaneHelper, PointLightHelper, Points, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RGBADepthPacking, RGBDepthPacking, RGDepthPacking, RawShaderMaterial, Ray, Raycaster, RenderTarget3D, RingGeometry, ShaderMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, Skeleton, SkeletonHelper, SkinnedMesh, Source, Spherical, SphericalHarmonics3, SplineCurve, SpotLightHelper, Sprite, StaticCopyUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SunLight, SunLightShadow, TOUCH, TetrahedronGeometry, TextureLoader, TextureSource, TextureUtils, Timer, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, VectorKeyframeTrack, VideoFrameTexture, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLRenderTarget, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroSlopeEnding, getConsoleFunction, setConsoleFunction } from './three.core.js'; const refreshUniforms = [ 'alphaMap', @@ -9316,7 +9316,6 @@ const Const = ( node, name = null ) => createVar( node, name, true ).toStack(); * @tsl * @function * @param {Node} node - The node for which a variable should be created. - * @param {?string} name - The name of the variable in the shader. * @returns {VarNode} */ const VarIntent = ( node ) => { @@ -11899,7 +11898,6 @@ addMethodChaining( 'debug', debug ); /** * InspectorBase is the base class for all inspectors. * - * @class InspectorBase * @augments EventDispatcher */ class InspectorBase extends EventDispatcher { @@ -19432,10 +19430,11 @@ class LoopNode extends Node { // const inputs = {}; + const params = this._getInternalParams(); - for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) { + for ( let i = 0, l = params.length - 1; i < l; i ++ ) { - const param = this.params[ i ]; + const param = params[ i ]; const name = ( param.isNode !== true && param.name ) || this.getVarName( i ); const type = ( param.isNode !== true && param.type ) || 'int'; @@ -19446,16 +19445,16 @@ class LoopNode extends Node { const stack = builder.addStack(); - const fnCall = this.params[ this.params.length - 1 ]( inputs ); + const fnCall = params[ params.length - 1 ]( inputs ); properties.returnsNode = fnCall.context( { nodeLoop: fnCall } ); properties.stackNode = stack; - const baseParam = this.params[ 0 ]; + const baseParam = params[ 0 ]; if ( baseParam.isNode !== true && typeof baseParam.update === 'function' ) { - const fnUpdateCall = Fn( this.params[ 0 ].update )( inputs ); + const fnUpdateCall = Fn( baseParam.update )( inputs ); properties.updateNode = fnUpdateCall.context( { nodeLoop: fnUpdateCall } ); @@ -19467,6 +19466,20 @@ class LoopNode extends Node { } + _getInternalParams() { + + const params = this.params; + + if ( typeof params[ 0 ] === 'function' ) { + + return [ bool( true ), params[ 0 ] ]; + + } + + return params; + + } + setup( builder ) { // setup properties @@ -19486,7 +19499,7 @@ class LoopNode extends Node { const properties = this.getProperties( builder ); - const params = this.params; + const params = this._getInternalParams(); const stackNode = properties.stackNode; for ( let i = 0, l = params.length - 1; i < l; i ++ ) { @@ -19650,7 +19663,7 @@ class LoopNode extends Node { builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet ); - for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) { + for ( let i = 0, l = params.length - 1; i < l; i ++ ) { builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab(); @@ -22045,7 +22058,6 @@ class NodeMaterial extends Material { * Setups the computation of the material's diffuse color. * * @param {NodeBuilder} builder - The current node builder. - * @param {BufferGeometry} geometry - The geometry. */ setupDiffuseColor( builder ) { @@ -35732,7 +35744,6 @@ class StackNode extends Node { * Represents a `switch` statement in TSL. * * @param {any} expression - Represents the expression. - * @param {Function} method - TSL code which is executed if the condition evaluates to `true`. * @return {StackNode} A reference to this stack node. */ Switch( expression ) { @@ -49992,7 +50003,6 @@ class BindGroup { * * @param {string} name - The bind group's name. * @param {Array} bindings - An array of bindings. - * @param {number} index - The group index. */ constructor( name = '', bindings = [] ) { @@ -80827,7 +80837,6 @@ class WGSLNodeBuilder extends NodeBuilder { * @param {string} gatherSnippet - A WGSL snippet that represents the index of the channel to read. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture. - * @param {?string} flipYSnippet - A WGSL snippet that represents the y-flip. Only used for WebGL. * @return {string} The WGSL snippet. */ generateTextureGather( texture, textureProperty, uvSnippet, gatherSnippet, depthSnippet, offsetSnippet ) { @@ -80865,7 +80874,6 @@ class WGSLNodeBuilder extends NodeBuilder { * @param {string} compareSnippet - A WGSL snippet that represents the reference value. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture. - * @param {?string} flipYSnippet - A WGSL snippet that represents the y-flip. Only used for WebGL. * @return {string} The WGSL snippet. */ generateTextureGatherCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet ) { @@ -80901,7 +80909,6 @@ class WGSLNodeBuilder extends NodeBuilder { * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture. - * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for. * @return {string} The WGSL snippet. */ generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) { @@ -87538,14 +87545,7 @@ class WebGPUBackend extends Backend { const starts = object._multiDrawStarts; const counts = object._multiDrawCounts; const drawCount = object._multiDrawCount; - - let bytesPerElement = ( hasIndex === true ) ? index.array.BYTES_PER_ELEMENT : 1; - - if ( material.wireframe ) { - - bytesPerElement = object.geometry.attributes.position.count > 65535 ? 4 : 2; - - } + const bytesPerElement = object._multiDrawBytesPerElement; for ( let i = 0; i < drawCount; i ++ ) { diff --git a/build/three.webgpu.nodes.js b/build/three.webgpu.nodes.js index 5a07916f678909..d89012f55978f3 100644 --- a/build/three.webgpu.nodes.js +++ b/build/three.webgpu.nodes.js @@ -4,7 +4,7 @@ * SPDX-License-Identifier: MIT */ import { DynamicDrawUsage, RenderObjectRefreshType, Color, Vector2, Vector3, Vector4, Matrix2, Matrix3, Matrix4, UnsignedIntType, IntType, error, RedFormat, RedIntegerFormat, DepthFormat, DepthStencilFormat, AlphaFormat, RGFormat, RGIntegerFormat, RGBFormat, RGBIntegerFormat, EventDispatcher, MathUtils, warn, WebGLCoordinateSystem, WebGPUCoordinateSystem, ColorManagement, SRGBTransfer, NoToneMapping, StaticDrawUsage, InterleavedBufferAttribute, InterleavedBuffer, NoColorSpace, log as log$1, warnOnce, Texture, Compatibility, LessCompare, LessEqualCompare, GreaterCompare, GreaterEqualCompare, NearestFilter, Sphere, BackSide, DoubleSide, CubeTexture, CubeReflectionMapping, CubeRefractionMapping, TangentSpaceNormalMap, NoNormalPacking, NormalRGPacking, NormalGAPacking, ObjectSpaceNormalMap, RED_GREEN_RGTC2_Format, RG11_EAC_Format, InstancedBufferAttribute, InstancedInterleavedBuffer, DataTexture, RGBAFormat, FloatType, DataArrayTexture, FramebufferTexture, LinearMipmapLinearFilter, DepthTexture, Material, LineBasicMaterial, LineDashedMaterial, NoBlending, MeshNormalMaterial, SRGBColorSpace, RenderTarget, BoxGeometry, Mesh, Scene, LinearFilter, CubeCamera, EquirectangularReflectionMapping, EquirectangularRefractionMapping, AddOperation, MixOperation, MultiplyOperation, MeshBasicMaterial, MeshLambertMaterial, MeshPhongMaterial, HalfFloatType, ClampToEdgeWrapping, BufferGeometry, OrthographicCamera, PerspectiveCamera, LinearSRGBColorSpace, CubeUVReflectionMapping, BufferAttribute, MeshStandardMaterial, MeshPhysicalMaterial, MeshToonMaterial, MeshMatcapMaterial, SpriteMaterial, PointsMaterial, ShadowMaterial, Uint32BufferAttribute, Uint16BufferAttribute, ByteType, UnsignedByteType, ShortType, UnsignedShortType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedInt248Type, UnsignedInt5999Type, UnsignedInt101111Type, NormalBlending, SrcAlphaFactor, OneMinusSrcAlphaFactor, AddEquation, MaterialBlending, Object3D, LinearMipMapLinearFilter, Plane, Float32BufferAttribute, UVMapping, PCFShadowMap, VSMShadowMap, BasicShadowMap, CubeDepthTexture, SphereGeometry, LinearMipmapNearestFilter, NearestMipmapLinearFilter, Float16BufferAttribute, yieldToMain, REVISION, ArrayCamera, PlaneGeometry, FrontSide, CustomBlending, ZeroFactor, CylinderGeometry, Quaternion, WebXRController, RAD2DEG, PCFSoftShadowMap, FrustumArray, Frustum, RGBAIntegerFormat, TimestampQuery, createCanvasElement, MaxEquation, MinEquation, ReverseSubtractEquation, SubtractEquation, OneMinusConstantAlphaFactor, ConstantAlphaFactor, OneMinusConstantColorFactor, ConstantColorFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcColorFactor, DstAlphaFactor, DstColorFactor, SrcAlphaSaturateFactor, SrcColorFactor, OneFactor, CullFaceNone, CullFaceBack, CullFaceFront, MultiplyBlending, SubtractiveBlending, AdditiveBlending, NotEqualDepth, GreaterDepth, GreaterEqualDepth, EqualDepth, LessEqualDepth, LessDepth, AlwaysDepth, NeverDepth, ReversedDepthFuncs, RGB_S3TC_DXT1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGB_PVRTC_4BPPV1_Format, RGB_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_PVRTC_2BPPV1_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGBA_ETC2_EAC_Format, R11_EAC_Format, SIGNED_R11_EAC_Format, SIGNED_RG11_EAC_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_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_10x10_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_BPTC_Format, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RED_RGTC1_Format, SIGNED_RED_RGTC1_Format, SIGNED_RED_GREEN_RGTC2_Format, MirroredRepeatWrapping, RepeatWrapping, NearestMipmapNearestFilter, NotEqualCompare, EqualCompare, AlwaysCompare, NeverCompare, LinearTransfer, getByteLength, isTypedArray, NotEqualStencilFunc, GreaterStencilFunc, GreaterEqualStencilFunc, EqualStencilFunc, LessEqualStencilFunc, LessStencilFunc, AlwaysStencilFunc, NeverStencilFunc, DecrementWrapStencilOp, IncrementWrapStencilOp, DecrementStencilOp, IncrementStencilOp, InvertStencilOp, ReplaceStencilOp, ZeroStencilOp, KeepStencilOp, SpotLight, PointLight, DirectionalLight, RectAreaLight, AmbientLight, HemisphereLight, LightProbe, LinearToneMapping, ReinhardToneMapping, CineonToneMapping, ACESFilmicToneMapping, AgXToneMapping, NeutralToneMapping, Group, Loader, FileLoader, MaterialLoader, ObjectLoader } from './three.core.js'; -export { AdditiveAnimationBlendMode, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BasicDepthPacking, BatchedMesh, BezierInterpolant, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxHelper, BufferGeometryLoader, Cache, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CircleGeometry, Clock, ColorKeyframeTrack, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, Controls, CubeTextureLoader, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceFrontBack, Curve, CurvePath, CustomToneMapping, Cylindrical, Data3DTexture, DataTextureLoader, DataUtils, DefaultLoadingManager, DetachedBindMode, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry, DynamicCopyUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, Euler, ExternalTexture, ExtrudeGeometry, Fog, FogExp2, GLBufferAttribute, GLSL1, GLSL3, GridHelper, HTMLTexture, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, InstancedBufferGeometry, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, Interpolant, InterpolateBezier, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InterpolationSamplingMode, InterpolationSamplingType, KeyframeTrack, LOD, LatheGeometry, Layers, Light, Line, Line3, LineCurve, LineCurve3, LineLoop, LineSegments, LinearInterpolant, LinearMipMapNearestFilter, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, MOUSE, MeshDepthMaterial, MeshDistanceMaterial, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NormalAnimationBlendMode, NumberKeyframeTrack, OctahedronGeometry, Path, PlaneHelper, PointLightHelper, Points, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RGBADepthPacking, RGBDepthPacking, RGDepthPacking, RawShaderMaterial, Ray, Raycaster, RenderTarget3D, RingGeometry, ShaderMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, Skeleton, SkeletonHelper, SkinnedMesh, Source, Spherical, SphericalHarmonics3, SplineCurve, SpotLightHelper, Sprite, StaticCopyUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, TOUCH, TetrahedronGeometry, TextureLoader, TextureUtils, Timer, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, VectorKeyframeTrack, VideoFrameTexture, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLRenderTarget, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroSlopeEnding, getConsoleFunction, setConsoleFunction } from './three.core.js'; +export { AdditiveAnimationBlendMode, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BasicDepthPacking, BatchedMesh, BezierInterpolant, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxHelper, BufferGeometryLoader, Cache, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CircleGeometry, Clock, ColorKeyframeTrack, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, Controls, CubeTextureLoader, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceFrontBack, Curve, CurvePath, CustomToneMapping, Cylindrical, Data3DTexture, DataTextureLoader, DataUtils, DefaultLoadingManager, DetachedBindMode, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry, DynamicCopyUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, Euler, ExternalTexture, ExtrudeGeometry, Fog, FogExp2, GLBufferAttribute, GLSL1, GLSL3, GridHelper, HTMLTexture, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, InstancedBufferGeometry, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, Interpolant, InterpolateBezier, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InterpolationSamplingMode, InterpolationSamplingType, KeyframeTrack, LOD, LatheGeometry, Layers, Light, Line, Line3, LineCurve, LineCurve3, LineLoop, LineSegments, LinearInterpolant, LinearMipMapNearestFilter, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, MOUSE, MeshDepthMaterial, MeshDistanceMaterial, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NormalAnimationBlendMode, NumberKeyframeTrack, OctahedronGeometry, Path, PlaneHelper, PointLightHelper, Points, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RGBADepthPacking, RGBDepthPacking, RGDepthPacking, RawShaderMaterial, Ray, Raycaster, RenderTarget3D, RingGeometry, ShaderMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, Skeleton, SkeletonHelper, SkinnedMesh, Source, Spherical, SphericalHarmonics3, SplineCurve, SpotLightHelper, Sprite, StaticCopyUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SunLight, SunLightShadow, TOUCH, TetrahedronGeometry, TextureLoader, TextureSource, TextureUtils, Timer, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, VectorKeyframeTrack, VideoFrameTexture, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLRenderTarget, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroSlopeEnding, getConsoleFunction, setConsoleFunction } from './three.core.js'; const refreshUniforms = [ 'alphaMap', @@ -9316,7 +9316,6 @@ const Const = ( node, name = null ) => createVar( node, name, true ).toStack(); * @tsl * @function * @param {Node} node - The node for which a variable should be created. - * @param {?string} name - The name of the variable in the shader. * @returns {VarNode} */ const VarIntent = ( node ) => { @@ -11899,7 +11898,6 @@ addMethodChaining( 'debug', debug ); /** * InspectorBase is the base class for all inspectors. * - * @class InspectorBase * @augments EventDispatcher */ class InspectorBase extends EventDispatcher { @@ -19432,10 +19430,11 @@ class LoopNode extends Node { // const inputs = {}; + const params = this._getInternalParams(); - for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) { + for ( let i = 0, l = params.length - 1; i < l; i ++ ) { - const param = this.params[ i ]; + const param = params[ i ]; const name = ( param.isNode !== true && param.name ) || this.getVarName( i ); const type = ( param.isNode !== true && param.type ) || 'int'; @@ -19446,16 +19445,16 @@ class LoopNode extends Node { const stack = builder.addStack(); - const fnCall = this.params[ this.params.length - 1 ]( inputs ); + const fnCall = params[ params.length - 1 ]( inputs ); properties.returnsNode = fnCall.context( { nodeLoop: fnCall } ); properties.stackNode = stack; - const baseParam = this.params[ 0 ]; + const baseParam = params[ 0 ]; if ( baseParam.isNode !== true && typeof baseParam.update === 'function' ) { - const fnUpdateCall = Fn( this.params[ 0 ].update )( inputs ); + const fnUpdateCall = Fn( baseParam.update )( inputs ); properties.updateNode = fnUpdateCall.context( { nodeLoop: fnUpdateCall } ); @@ -19467,6 +19466,20 @@ class LoopNode extends Node { } + _getInternalParams() { + + const params = this.params; + + if ( typeof params[ 0 ] === 'function' ) { + + return [ bool( true ), params[ 0 ] ]; + + } + + return params; + + } + setup( builder ) { // setup properties @@ -19486,7 +19499,7 @@ class LoopNode extends Node { const properties = this.getProperties( builder ); - const params = this.params; + const params = this._getInternalParams(); const stackNode = properties.stackNode; for ( let i = 0, l = params.length - 1; i < l; i ++ ) { @@ -19650,7 +19663,7 @@ class LoopNode extends Node { builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet ); - for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) { + for ( let i = 0, l = params.length - 1; i < l; i ++ ) { builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab(); @@ -22045,7 +22058,6 @@ class NodeMaterial extends Material { * Setups the computation of the material's diffuse color. * * @param {NodeBuilder} builder - The current node builder. - * @param {BufferGeometry} geometry - The geometry. */ setupDiffuseColor( builder ) { @@ -35732,7 +35744,6 @@ class StackNode extends Node { * Represents a `switch` statement in TSL. * * @param {any} expression - Represents the expression. - * @param {Function} method - TSL code which is executed if the condition evaluates to `true`. * @return {StackNode} A reference to this stack node. */ Switch( expression ) { @@ -49992,7 +50003,6 @@ class BindGroup { * * @param {string} name - The bind group's name. * @param {Array} bindings - An array of bindings. - * @param {number} index - The group index. */ constructor( name = '', bindings = [] ) { @@ -80827,7 +80837,6 @@ class WGSLNodeBuilder extends NodeBuilder { * @param {string} gatherSnippet - A WGSL snippet that represents the index of the channel to read. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture. - * @param {?string} flipYSnippet - A WGSL snippet that represents the y-flip. Only used for WebGL. * @return {string} The WGSL snippet. */ generateTextureGather( texture, textureProperty, uvSnippet, gatherSnippet, depthSnippet, offsetSnippet ) { @@ -80865,7 +80874,6 @@ class WGSLNodeBuilder extends NodeBuilder { * @param {string} compareSnippet - A WGSL snippet that represents the reference value. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture. - * @param {?string} flipYSnippet - A WGSL snippet that represents the y-flip. Only used for WebGL. * @return {string} The WGSL snippet. */ generateTextureGatherCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet ) { @@ -80901,7 +80909,6 @@ class WGSLNodeBuilder extends NodeBuilder { * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture. - * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for. * @return {string} The WGSL snippet. */ generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) { @@ -87538,14 +87545,7 @@ class WebGPUBackend extends Backend { const starts = object._multiDrawStarts; const counts = object._multiDrawCounts; const drawCount = object._multiDrawCount; - - let bytesPerElement = ( hasIndex === true ) ? index.array.BYTES_PER_ELEMENT : 1; - - if ( material.wireframe ) { - - bytesPerElement = object.geometry.attributes.position.count > 65535 ? 4 : 2; - - } + const bytesPerElement = object._multiDrawBytesPerElement; for ( let i = 0; i < drawCount; i ++ ) { diff --git a/examples/files.json b/examples/files.json index bff0b18c6edb3c..8ab08300fb3e07 100644 --- a/examples/files.json +++ b/examples/files.json @@ -64,6 +64,7 @@ "webgl_lights_physical", "webgl_lights_spotlight", "webgl_lights_spotlights", + "webgl_lights_sunlight", "webgl_lights_rectarealight", "webgl_lines_colors", "webgl_lines_dashed", diff --git a/examples/jsm/lighting/LightProbeGridWebGL.js b/examples/jsm/lighting/LightProbeGridWebGL.js index 25784a778d0f3c..670b6b832684dd 100644 --- a/examples/jsm/lighting/LightProbeGridWebGL.js +++ b/examples/jsm/lighting/LightProbeGridWebGL.js @@ -1,6 +1,7 @@ import { Box3, CubeCamera, + DirectionalLight, FloatType, HalfFloatType, LinearFilter, @@ -12,6 +13,7 @@ import { RGBAFormat, Scene, ShaderMaterial, + Sphere, Vector3, Vector4, WebGL3DRenderTarget, @@ -47,6 +49,82 @@ const _position = /*@__PURE__*/ new Vector3(); const _size = /*@__PURE__*/ new Vector3(); const _currentViewport = /*@__PURE__*/ new Vector4(); const _currentScissor = /*@__PURE__*/ new Vector4(); +const _casterBox = /*@__PURE__*/ new Box3(); +const _casterSphere = /*@__PURE__*/ new Sphere(); +const _sunDirection = /*@__PURE__*/ new Vector3(); + +// SunLight shadow cascades are fitted to the active camera every render, which +// the frozen shadow maps of a bake cannot provide: each shadow-casting SunLight +// is swapped for an equivalent DirectionalLight fitted to the shadow casters. + +function _replaceSunLights( scene ) { + + const sunLights = []; + + scene.traverse( ( object ) => { + + if ( object.isSunLight === true && object.visible === true && object.castShadow === true ) sunLights.push( object ); + + } ); + + if ( sunLights.length === 0 ) return null; + + _casterBox.makeEmpty(); + + scene.traverse( ( object ) => { + + if ( object.isMesh === true && object.castShadow === true ) _casterBox.expandByObject( object ); + + } ); + + _casterBox.getBoundingSphere( _casterSphere ); + + const center = _casterSphere.center; + const radius = Math.max( _casterSphere.radius, 1 ); + + const replacements = []; + + for ( const sunLight of sunLights ) { + + const bakeLight = new DirectionalLight( sunLight.color, sunLight.intensity ); + bakeLight.castShadow = true; + bakeLight.shadow.mapSize.copy( sunLight.shadow.mapSize ); + bakeLight.shadow.camera.left = - radius; + bakeLight.shadow.camera.right = radius; + bakeLight.shadow.camera.top = radius; + bakeLight.shadow.camera.bottom = - radius; + bakeLight.shadow.camera.near = radius * 0.5; + bakeLight.shadow.camera.far = radius * 3.5; + + _sunDirection.setFromMatrixPosition( sunLight.matrixWorld ).normalize(); + bakeLight.target.position.copy( center ); + bakeLight.position.copy( center ).addScaledVector( _sunDirection, radius * 2 ); + + scene.add( bakeLight, bakeLight.target ); + bakeLight.target.updateMatrixWorld(); + bakeLight.updateMatrixWorld(); + + sunLight.visible = false; + + replacements.push( { sunLight, bakeLight } ); + + } + + return replacements; + +} + +function _restoreSunLights( scene, replacements ) { + + for ( const { sunLight, bakeLight } of replacements ) { + + scene.remove( bakeLight, bakeLight.target ); + bakeLight.dispose(); + sunLight.visible = true; + + } + +} // Number of padding texels added at each boundary of every sub-volume in the atlas. const ATLAS_PADDING = 1; @@ -210,6 +288,10 @@ class LightProbeGridWebGL extends Object3D { * atlas as indirect light, so a grid added to the scene before baking * accumulates one bounce per extra pass. * + * Shadow-casting instances of `SunLight` are temporarily replaced with + * equivalent directional lights, since their view-fitted shadow cascades + * cannot be frozen across probe renders. + * * @param {WebGLRenderer} renderer - The renderer. * @param {Scene} scene - The scene to render. * @param {Object} [options] - Bake options. @@ -238,6 +320,8 @@ class LightProbeGridWebGL extends Object3D { renderer.getScissor( _currentScissor ); const currentScissorTest = renderer.getScissorTest(); + const replacedSunLights = _replaceSunLights( scene ); + // Scene is static across the bake — update once and disable per-render auto updates. const currentMatrixWorldAutoUpdate = scene.matrixWorldAutoUpdate; if ( currentMatrixWorldAutoUpdate === true ) { @@ -360,6 +444,8 @@ class LightProbeGridWebGL extends Object3D { renderer.setScissor( _currentScissor ); renderer.setScissorTest( currentScissorTest ); + if ( replacedSunLights !== null ) _restoreSunLights( scene, replacedSunLights ); + scene.matrixWorldAutoUpdate = currentMatrixWorldAutoUpdate; // console.log( `LightProbeGridWebGL: bake complete ${ ( performance.now() - t0 ).toFixed( 1 ) }ms` ); diff --git a/examples/screenshots/webgl_animation_multiple.jpg b/examples/screenshots/webgl_animation_multiple.jpg index 824a4393d5df04..061a2537ae4fe8 100644 Binary files a/examples/screenshots/webgl_animation_multiple.jpg and b/examples/screenshots/webgl_animation_multiple.jpg differ diff --git a/examples/screenshots/webgl_animation_skinning_additive_blending.jpg b/examples/screenshots/webgl_animation_skinning_additive_blending.jpg index e8567217fc5b55..f1bd306c629029 100644 Binary files a/examples/screenshots/webgl_animation_skinning_additive_blending.jpg and b/examples/screenshots/webgl_animation_skinning_additive_blending.jpg differ diff --git a/examples/screenshots/webgl_animation_skinning_blending.jpg b/examples/screenshots/webgl_animation_skinning_blending.jpg index ffbbfb2394adb8..1bac4df7b5cc13 100644 Binary files a/examples/screenshots/webgl_animation_skinning_blending.jpg and b/examples/screenshots/webgl_animation_skinning_blending.jpg differ diff --git a/examples/screenshots/webgl_animation_walk.jpg b/examples/screenshots/webgl_animation_walk.jpg index 1b5221c8b779a5..99a11291243556 100644 Binary files a/examples/screenshots/webgl_animation_walk.jpg and b/examples/screenshots/webgl_animation_walk.jpg differ diff --git a/examples/screenshots/webgl_gpgpu_water.jpg b/examples/screenshots/webgl_gpgpu_water.jpg index ee89a706015600..698c4eb42055e0 100644 Binary files a/examples/screenshots/webgl_gpgpu_water.jpg and b/examples/screenshots/webgl_gpgpu_water.jpg differ diff --git a/examples/screenshots/webgl_instancing_morph.jpg b/examples/screenshots/webgl_instancing_morph.jpg index e0cf4e6512e371..03f2554e0e8b24 100644 Binary files a/examples/screenshots/webgl_instancing_morph.jpg and b/examples/screenshots/webgl_instancing_morph.jpg differ diff --git a/examples/screenshots/webgl_lightprobes_sponza.jpg b/examples/screenshots/webgl_lightprobes_sponza.jpg index 5df162349247ec..eb5006834c14c6 100644 Binary files a/examples/screenshots/webgl_lightprobes_sponza.jpg and b/examples/screenshots/webgl_lightprobes_sponza.jpg differ diff --git a/examples/screenshots/webgl_lights_sunlight.jpg b/examples/screenshots/webgl_lights_sunlight.jpg new file mode 100644 index 00000000000000..831df268376648 Binary files /dev/null and b/examples/screenshots/webgl_lights_sunlight.jpg differ diff --git a/examples/screenshots/webgl_loader_3mf_materials.jpg b/examples/screenshots/webgl_loader_3mf_materials.jpg index 06b6a8a5fd0234..8ca1b67b0cd090 100644 Binary files a/examples/screenshots/webgl_loader_3mf_materials.jpg and b/examples/screenshots/webgl_loader_3mf_materials.jpg differ diff --git a/examples/screenshots/webgl_loader_fbx.jpg b/examples/screenshots/webgl_loader_fbx.jpg index 352bb432497df2..6e7c4b290b9ae2 100644 Binary files a/examples/screenshots/webgl_loader_fbx.jpg and b/examples/screenshots/webgl_loader_fbx.jpg differ diff --git a/examples/screenshots/webgl_loader_md2_control.jpg b/examples/screenshots/webgl_loader_md2_control.jpg index a50a3c20a097e6..0ad3cf07223ab2 100644 Binary files a/examples/screenshots/webgl_loader_md2_control.jpg and b/examples/screenshots/webgl_loader_md2_control.jpg differ diff --git a/examples/screenshots/webgl_postprocessing_outline.jpg b/examples/screenshots/webgl_postprocessing_outline.jpg index b664df2e9b15f2..251c9e3955f4c4 100644 Binary files a/examples/screenshots/webgl_postprocessing_outline.jpg and b/examples/screenshots/webgl_postprocessing_outline.jpg differ diff --git a/examples/screenshots/webgl_shadowmap_performance.jpg b/examples/screenshots/webgl_shadowmap_performance.jpg index 20b32f7989dfc2..411986710dd30e 100644 Binary files a/examples/screenshots/webgl_shadowmap_performance.jpg and b/examples/screenshots/webgl_shadowmap_performance.jpg differ diff --git a/examples/screenshots/webgpu_materials_toon.jpg b/examples/screenshots/webgpu_materials_toon.jpg index 75b18bc5fcb460..cc8ead6fa8b382 100644 Binary files a/examples/screenshots/webgpu_materials_toon.jpg and b/examples/screenshots/webgpu_materials_toon.jpg differ diff --git a/examples/screenshots/webgpu_performance_renderbundle.jpg b/examples/screenshots/webgpu_performance_renderbundle.jpg index 0c1e0b70978d09..de5d0ebd49cc4e 100644 Binary files a/examples/screenshots/webgpu_performance_renderbundle.jpg and b/examples/screenshots/webgpu_performance_renderbundle.jpg differ diff --git a/examples/webgl_animation_multiple.html b/examples/webgl_animation_multiple.html index bf5ce4df46b5a5..87233925bee5b7 100644 --- a/examples/webgl_animation_multiple.html +++ b/examples/webgl_animation_multiple.html @@ -61,18 +61,11 @@ hemiLight.position.set( 0, 20, 0 ); scene.add( hemiLight ); - const dirLight = new THREE.DirectionalLight( 0xffffff, 3 ); - dirLight.position.set( - 3, 10, - 10 ); - dirLight.castShadow = true; - dirLight.shadow.camera.top = 4; - dirLight.shadow.camera.bottom = - 4; - dirLight.shadow.camera.left = - 4; - dirLight.shadow.camera.right = 4; - dirLight.shadow.camera.near = 0.1; - dirLight.shadow.camera.far = 40; - scene.add( dirLight ); - - // scene.add( new THREE.CameraHelper( dirLight.shadow.camera ) ); + const sunLight = new THREE.SunLight( 0xffffff, 3 ); + sunLight.position.set( - 3, 10, - 10 ); + sunLight.castShadow = true; + sunLight.shadow.camera.far = 20; + scene.add( sunLight ); // ground diff --git a/examples/webgl_animation_skinning_additive_blending.html b/examples/webgl_animation_skinning_additive_blending.html index 4b0f5c513c9f6d..36f3725be13f22 100644 --- a/examples/webgl_animation_skinning_additive_blending.html +++ b/examples/webgl_animation_skinning_additive_blending.html @@ -79,16 +79,11 @@ hemiLight.position.set( 0, 20, 0 ); scene.add( hemiLight ); - const dirLight = new THREE.DirectionalLight( 0xffffff, 3 ); - dirLight.position.set( 3, 10, 10 ); - dirLight.castShadow = true; - dirLight.shadow.camera.top = 2; - dirLight.shadow.camera.bottom = - 2; - dirLight.shadow.camera.left = - 2; - dirLight.shadow.camera.right = 2; - dirLight.shadow.camera.near = 0.1; - dirLight.shadow.camera.far = 40; - scene.add( dirLight ); + const sunLight = new THREE.SunLight( 0xffffff, 3 ); + sunLight.position.set( 3, 10, 10 ); + sunLight.castShadow = true; + sunLight.shadow.camera.far = 20; + scene.add( sunLight ); // ground diff --git a/examples/webgl_animation_skinning_blending.html b/examples/webgl_animation_skinning_blending.html index 6ae2e648a36b56..db4df6bec73913 100644 --- a/examples/webgl_animation_skinning_blending.html +++ b/examples/webgl_animation_skinning_blending.html @@ -74,18 +74,11 @@ hemiLight.position.set( 0, 20, 0 ); scene.add( hemiLight ); - const dirLight = new THREE.DirectionalLight( 0xffffff, 3 ); - dirLight.position.set( - 3, 10, - 10 ); - dirLight.castShadow = true; - dirLight.shadow.camera.top = 2; - dirLight.shadow.camera.bottom = - 2; - dirLight.shadow.camera.left = - 2; - dirLight.shadow.camera.right = 2; - dirLight.shadow.camera.near = 0.1; - dirLight.shadow.camera.far = 40; - scene.add( dirLight ); - - // scene.add( new THREE.CameraHelper( dirLight.shadow.camera ) ); + const sunLight = new THREE.SunLight( 0xffffff, 3 ); + sunLight.position.set( - 3, 10, - 10 ); + sunLight.castShadow = true; + sunLight.shadow.camera.far = 20; + scene.add( sunLight ); // ground diff --git a/examples/webgl_animation_walk.html b/examples/webgl_animation_walk.html index 9a1512e63e9887..a3e1c271b6232f 100644 --- a/examples/webgl_animation_walk.html +++ b/examples/webgl_animation_walk.html @@ -43,7 +43,7 @@ import { HDRLoader } from 'three/addons/loaders/HDRLoader.js'; let scene, renderer, camera, floor, orbitControls; - let group, followGroup, model, skeleton, mixer, timer; + let group, model, skeleton, mixer, timer; let actions; @@ -91,22 +91,11 @@ group = new THREE.Group(); scene.add( group ); - followGroup = new THREE.Group(); - scene.add( followGroup ); - - const dirLight = new THREE.DirectionalLight( 0xffffff, 5 ); - dirLight.position.set( - 2, 5, - 3 ); - dirLight.castShadow = true; - const cam = dirLight.shadow.camera; - cam.top = cam.right = 2; - cam.bottom = cam.left = - 2; - cam.near = 3; - cam.far = 8; - dirLight.shadow.mapSize.set( 1024, 1024 ); - followGroup.add( dirLight ); - followGroup.add( dirLight.target ); - - //scene.add( new THREE.CameraHelper( cam ) ); + const sunLight = new THREE.SunLight( 0xffffff, 5 ); + sunLight.position.set( - 2, 5, - 3 ); + sunLight.castShadow = true; + sunLight.shadow.camera.far = 20; + scene.add( sunLight ); renderer = new THREE.WebGLRenderer( { antialias: true } ); renderer.setPixelRatio( window.devicePixelRatio ); @@ -336,7 +325,6 @@ group.quaternion.rotateTowards( rotate, controls.rotateSpeed ); orbitControls.target.copy( position ).add( { x: 0, y: 1, z: 0 } ); - followGroup.position.copy( position ); // Move the floor without any limit const dx = ( position.x - floor.position.x ); diff --git a/examples/webgl_gpgpu_water.html b/examples/webgl_gpgpu_water.html index 89f19de21e9630..71aa9f85d72d8a 100644 --- a/examples/webgl_gpgpu_water.html +++ b/examples/webgl_gpgpu_water.html @@ -216,7 +216,7 @@ scene = new THREE.Scene(); - sun = new THREE.DirectionalLight( 0xFFFFFF, 4.0 ); + sun = new THREE.SunLight( 0xFFFFFF, 4.0 ); sun.position.set( - 1, 2.6, 1.4 ); scene.add( sun ); @@ -444,14 +444,9 @@ renderer.shadowMap.type = THREE.VSMShadowMap; const shadow = sun.shadow; - shadow.mapSize.width = shadow.mapSize.height = 2048; shadow.radius = 2; shadow.bias = - 0.0005; - const shadowCam = shadow.camera, s = 5; - shadowCam.near = 0.1; - shadowCam.far = 6; - shadowCam.right = shadowCam.top = s; - shadowCam.left = shadowCam.bottom = - s; + shadow.camera.far = 6; } else { @@ -459,9 +454,6 @@ } - // debug shadow - //scene.add( new THREE.CameraHelper(shadowCam) ); - } // function smoothWater() { diff --git a/examples/webgl_instancing_morph.html b/examples/webgl_instancing_morph.html index d2fcd74233d943..ba3532303faa6a 100644 --- a/examples/webgl_instancing_morph.html +++ b/examples/webgl_instancing_morph.html @@ -55,25 +55,19 @@ scene.fog = new THREE.Fog( 0x99DDFF, 5000, 10000 ); - const light = new THREE.DirectionalLight( 0xffffff, 1 ); + const light = new THREE.SunLight( 0xffffff, 2 ); light.position.set( 200, 1000, 50 ); light.castShadow = true; - light.shadow.camera.left = - 5000; - light.shadow.camera.right = 5000; - light.shadow.camera.top = 5000; - light.shadow.camera.bottom = - 5000; - light.shadow.camera.far = 2000; + light.shadow.camera.far = 10000; - light.shadow.bias = - 0.01; - - light.shadow.camera.updateProjectionMatrix(); + light.shadow.mapSize.setScalar( 2048 ); scene.add( light ); - const hemi = new THREE.HemisphereLight( 0x99DDFF, 0x669933, 1 / 3 ); + const hemi = new THREE.HemisphereLight( 0x99DDFF, 0x669933, 0.5 ); scene.add( hemi ); @@ -135,7 +129,6 @@ renderer.setAnimationLoop( animate ); document.body.appendChild( renderer.domElement ); renderer.shadowMap.enabled = true; - renderer.shadowMap.type = THREE.VSMShadowMap; // stats = new Stats(); diff --git a/examples/webgl_lightprobes_sponza.html b/examples/webgl_lightprobes_sponza.html index 1eab575cff91d9..922de361952266 100644 --- a/examples/webgl_lightprobes_sponza.html +++ b/examples/webgl_lightprobes_sponza.html @@ -45,13 +45,10 @@ let camera, scene, renderer, controls, timer; let probes = null, probesHelper = null; let modelSize = null; - let dirLight = null, sky = null; + let sunLight = null, sky = null; - const sun = new THREE.Vector3(); - const _box = new THREE.Box3(); const _size = new THREE.Vector3(); - const _center = new THREE.Vector3(); init(); @@ -74,6 +71,7 @@ skyUniforms[ 'rayleigh' ].value = 2; skyUniforms[ 'mieCoefficient' ].value = 0.005; skyUniforms[ 'mieDirectionalG' ].value = 0.8; + skyUniforms[ 'showSunDisc' ].value = false; // the sun is represented by the light renderer = new THREE.WebGLRenderer( { antialias: true } ); renderer.setPixelRatio( Math.min( window.devicePixelRatio, 1.5 ) ); @@ -134,27 +132,16 @@ _box.setFromObject( model ); modelSize = _box.getSize( _size ).clone(); - const modelCenter = _box.getCenter( _center ).clone(); - const targetY = modelCenter.y + modelSize.y * 0.2; - const lightBaseDistance = Math.max( modelSize.x, modelSize.z ); const probeFar = Math.max( modelSize.x, modelSize.y, modelSize.z ) * 2.0; let rebakeTimer = null; let isBaking = false; let bakeQueued = false; - dirLight = new THREE.DirectionalLight( 0xfff2dc, 100.0 ); - dirLight.target.position.set( modelCenter.x, targetY, modelCenter.z ); - scene.add( dirLight.target ); - dirLight.castShadow = true; - dirLight.shadow.mapSize.setScalar( 2048 ); - const shadowExtent = Math.max( modelSize.x, modelSize.z ) * 0.7; - dirLight.shadow.camera.left = - shadowExtent; - dirLight.shadow.camera.right = shadowExtent; - dirLight.shadow.camera.top = shadowExtent; - dirLight.shadow.camera.bottom = - shadowExtent; - dirLight.shadow.camera.near = 0.1; - dirLight.shadow.camera.far = modelSize.y * 4.0; - scene.add( dirLight ); + sunLight = new THREE.SunLight( 0xfff2dc, 100.0 ); + sunLight.castShadow = true; + sunLight.shadow.camera.far = 50; + sunLight.shadow.mapSize.setScalar( 2048 ); + scene.add( sunLight ); const params = { enabled: true, @@ -170,32 +157,19 @@ countY: 7, countZ: 7, bounces: 1, - lightAzimuth: - 45, - lightElevation: 55, + lightAzimuth: - 75, + lightElevation: 60, lightIntensity: 100.0, shadows: true }; function updateLightPosition() { - const azimuth = THREE.MathUtils.degToRad( params.lightAzimuth ); const elevation = THREE.MathUtils.degToRad( params.lightElevation ); - const radius = lightBaseDistance; - const horizontal = Math.cos( elevation ) * radius; - const vertical = Math.sin( elevation ) * radius; - - dirLight.position.set( - modelCenter.x + Math.cos( azimuth ) * horizontal, - targetY + vertical, - modelCenter.z + Math.sin( azimuth ) * horizontal - ); - dirLight.target.position.set( modelCenter.x, targetY, modelCenter.z ); - dirLight.target.updateMatrixWorld(); - - const phi = THREE.MathUtils.degToRad( 90 - params.lightElevation ); - const theta = THREE.MathUtils.degToRad( params.lightAzimuth ); - sun.setFromSphericalCoords( 1, phi, theta ); - sky.material.uniforms[ 'sunPosition' ].value.copy( sun ); + const azimuth = THREE.MathUtils.degToRad( params.lightAzimuth ); + + sunLight.position.setFromSphericalCoords( 1, Math.PI / 2 - elevation, azimuth ); + sky.material.uniforms[ 'sunPosition' ].value.copy( sunLight.position ); } @@ -293,7 +267,7 @@ } ); gui.add( params, 'lightIntensity', 0, 100, 0.1 ).name( 'Light Intensity' ).onChange( ( value ) => { - dirLight.intensity = value; + sunLight.intensity = value; scheduleRebake(); } ); @@ -370,10 +344,10 @@ function setShadowsEnabled( enabled ) { - if ( ! renderer || ! dirLight ) return; + if ( ! renderer || ! sunLight ) return; renderer.shadowMap.enabled = enabled; - dirLight.castShadow = enabled; + sunLight.castShadow = enabled; } diff --git a/examples/webgl_lights_sunlight.html b/examples/webgl_lights_sunlight.html new file mode 100644 index 00000000000000..0c855796ae566c --- /dev/null +++ b/examples/webgl_lights_sunlight.html @@ -0,0 +1,261 @@ + + + + three.js webgl - lights - sunlight + + + + + + + + + + +
+
+ three.js webgl - sunlight
+ WASD to move, mouse to look around +
+ + + + + + + diff --git a/examples/webgl_loader_3mf_materials.html b/examples/webgl_loader_3mf_materials.html index af6c74e591b947..a0dac5fc4d70ea 100644 --- a/examples/webgl_loader_3mf_materials.html +++ b/examples/webgl_loader_3mf_materials.html @@ -57,19 +57,11 @@ hemiLight.position.set( 0, 100, 0 ); scene.add( hemiLight ); - const dirLight = new THREE.DirectionalLight( 0xffffff, 3 ); - dirLight.position.set( - 0, 40, 50 ); - dirLight.castShadow = true; - dirLight.shadow.camera.top = 50; - dirLight.shadow.camera.bottom = - 25; - dirLight.shadow.camera.left = - 25; - dirLight.shadow.camera.right = 25; - dirLight.shadow.camera.near = 0.1; - dirLight.shadow.camera.far = 200; - dirLight.shadow.mapSize.set( 1024, 1024 ); - scene.add( dirLight ); - - // scene.add( new THREE.CameraHelper( dirLight.shadow.camera ) ); + const sunLight = new THREE.SunLight( 0xffffff, 3 ); + sunLight.position.set( 0, 40, 50 ); + sunLight.castShadow = true; + sunLight.shadow.camera.far = 100; + scene.add( sunLight ); // diff --git a/examples/webgl_loader_fbx.html b/examples/webgl_loader_fbx.html index 685e354ea60efb..1f612eca33f573 100644 --- a/examples/webgl_loader_fbx.html +++ b/examples/webgl_loader_fbx.html @@ -90,16 +90,10 @@ hemiLight.position.set( 0, 200, 0 ); scene.add( hemiLight ); - const dirLight = new THREE.DirectionalLight( 0xffffff, 5 ); - dirLight.position.set( 0, 200, 100 ); - dirLight.castShadow = true; - dirLight.shadow.camera.top = 180; - dirLight.shadow.camera.bottom = - 100; - dirLight.shadow.camera.left = - 120; - dirLight.shadow.camera.right = 120; - scene.add( dirLight ); - - // scene.add( new THREE.CameraHelper( dirLight.shadow.camera ) ); + const sunLight = new THREE.SunLight( 0xffffff, 5 ); + sunLight.position.set( 0, 200, 100 ); + sunLight.castShadow = true; + scene.add( sunLight ); // ground const mesh = new THREE.Mesh( new THREE.PlaneGeometry( 2000, 2000 ), new THREE.MeshPhongMaterial( { color: 0x999999, depthWrite: false } ) ); diff --git a/examples/webgl_loader_md2_control.html b/examples/webgl_loader_md2_control.html index 70b2623677fd73..edff9fec2cbb0b 100644 --- a/examples/webgl_loader_md2_control.html +++ b/examples/webgl_loader_md2_control.html @@ -92,24 +92,11 @@ scene.add( new THREE.AmbientLight( 0x666666, 3 ) ); - const light = new THREE.DirectionalLight( 0xffffff, 7 ); - light.position.set( 200, 450, 500 ); - - light.castShadow = true; - - light.shadow.mapSize.width = 1024; - light.shadow.mapSize.height = 512; - - light.shadow.camera.near = 100; - light.shadow.camera.far = 1200; - - light.shadow.camera.left = - 1000; - light.shadow.camera.right = 1000; - light.shadow.camera.top = 350; - light.shadow.camera.bottom = - 350; - - scene.add( light ); - // scene.add( new THREE.CameraHelper( light.shadow.camera ) ); + const sunLight = new THREE.SunLight( 0xffffff, 7 ); + sunLight.position.set( 200, 450, 500 ); + sunLight.castShadow = true; + sunLight.shadow.camera.far = 2000; + scene.add( sunLight ); // GROUND @@ -233,7 +220,6 @@ const gyro = new Gyroscope(); gyro.add( camera ); - gyro.add( light, light.target ); characters[ Math.floor( nSkins / 2 ) ].root.add( gyro ); diff --git a/examples/webgl_postprocessing_outline.html b/examples/webgl_postprocessing_outline.html index f9293721aeefc5..54b9973b6634bb 100644 --- a/examples/webgl_postprocessing_outline.html +++ b/examples/webgl_postprocessing_outline.html @@ -151,20 +151,11 @@ scene.add( new THREE.AmbientLight( 0xaaaaaa, 0.6 ) ); - const light = new THREE.DirectionalLight( 0xddffdd, 2 ); + const light = new THREE.SunLight( 0xddffdd, 2 ); light.position.set( 5, 5, 5 ); light.castShadow = true; - light.shadow.mapSize.width = 1024; - light.shadow.mapSize.height = 1024; - - const d = 10; - - light.shadow.camera.left = - d; - light.shadow.camera.right = d; - light.shadow.camera.top = d; - light.shadow.camera.bottom = - d; - light.shadow.camera.far = 25; - + light.shadow.camera.far = 40; + light.shadow.mapSize.setScalar( 2048 ); scene.add( light ); // model diff --git a/examples/webgl_shadowmap_performance.html b/examples/webgl_shadowmap_performance.html index 30bb9d6f412533..6b96e126d2969a 100644 --- a/examples/webgl_shadowmap_performance.html +++ b/examples/webgl_shadowmap_performance.html @@ -38,8 +38,6 @@ import { FontLoader } from 'three/addons/loaders/FontLoader.js'; import { TextGeometry } from 'three/addons/geometries/TextGeometry.js'; - const SHADOW_MAP_WIDTH = 2048, SHADOW_MAP_HEIGHT = 1024; - let SCREEN_WIDTH = window.innerWidth; let SCREEN_HEIGHT = window.innerHeight; const FLOOR = - 250; @@ -81,21 +79,12 @@ const ambient = new THREE.AmbientLight( 0xffffff ); scene.add( ambient ); - const light = new THREE.DirectionalLight( 0xffffff, 3 ); - light.position.set( 0, 1500, 1000 ); - light.castShadow = true; - light.shadow.camera.top = 2000; - light.shadow.camera.bottom = - 2000; - light.shadow.camera.left = - 2000; - light.shadow.camera.right = 2000; - light.shadow.camera.near = 1200; - light.shadow.camera.far = 2500; - light.shadow.bias = 0.0001; - - light.shadow.mapSize.width = SHADOW_MAP_WIDTH; - light.shadow.mapSize.height = SHADOW_MAP_HEIGHT; - - scene.add( light ); + const sunLight = new THREE.SunLight( 0xffffff, 3 ); + sunLight.position.set( 0, 1500, 1000 ); + sunLight.castShadow = true; + sunLight.shadow.camera.far = FAR; + sunLight.shadow.normalBias = 1; + scene.add( sunLight ); createScene(); diff --git a/src/Three.Core.js b/src/Three.Core.js index a67148a67ae2b9..3186280a6c5ffc 100644 --- a/src/Three.Core.js +++ b/src/Three.Core.js @@ -60,6 +60,8 @@ export { SpotLight } from './lights/SpotLight.js'; export { PointLight } from './lights/PointLight.js'; export { RectAreaLight } from './lights/RectAreaLight.js'; export { HemisphereLight } from './lights/HemisphereLight.js'; +export { SunLight } from './lights/SunLight.js'; +export { SunLightShadow } from './lights/SunLightShadow.js'; export { DirectionalLight } from './lights/DirectionalLight.js'; export { AmbientLight } from './lights/AmbientLight.js'; export { Light } from './lights/Light.js'; diff --git a/src/lights/LightShadow.js b/src/lights/LightShadow.js index cf98b66cfc4c65..34d472fa58a81d 100644 --- a/src/lights/LightShadow.js +++ b/src/lights/LightShadow.js @@ -182,6 +182,18 @@ class LightShadow { } + /** + * Used internally by the renderer to get the camera that renders the given viewport. + * + * @param {number} [viewportIndex=0] - The viewport index. + * @return {Camera} The shadow camera. + */ + getCamera( /* viewportIndex */ ) { + + return this.camera; + + } + /** * Gets the shadow cameras frustum. Used internally by the renderer to cull objects. * @@ -201,23 +213,41 @@ class LightShadow { updateMatrices( light ) { const shadowCamera = this.camera; - const shadowMatrix = this.matrix; - _lightPositionWorld.setFromMatrixPosition( light.matrixWorld ); shadowCamera.position.copy( _lightPositionWorld ); _lookTarget.setFromMatrixPosition( light.target.matrixWorld ); shadowCamera.lookAt( _lookTarget ); shadowCamera.updateMatrixWorld(); + this._updateMatrix( shadowCamera, this.matrix, this._frustum ); + + } + + /** + * Updates a shadow projection matrix and its corresponding frustum. + * + * @private + * @param {Camera} shadowCamera - The shadow camera. + * @param {Matrix4} shadowMatrix - The target shadow matrix. + * @param {Frustum} frustum - The target frustum. + * @param {Vector4} [viewport] - The viewport within the shadow atlas. + */ + _updateMatrix( shadowCamera, shadowMatrix, frustum, viewport ) { _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse ); - this._frustum.setFromProjectionMatrix( _projScreenMatrix, shadowCamera.coordinateSystem, shadowCamera.reversedDepth ); + frustum.setFromProjectionMatrix( _projScreenMatrix, shadowCamera.coordinateSystem, shadowCamera.reversedDepth ); + + const frameExtents = this._frameExtents; + const scaleX = viewport ? viewport.z / frameExtents.x : 1; + const scaleY = viewport ? viewport.w / frameExtents.y : 1; + const offsetX = viewport ? viewport.x / frameExtents.x : 0; + const offsetY = viewport ? viewport.y / frameExtents.y : 0; if ( shadowCamera.coordinateSystem === WebGPUCoordinateSystem || shadowCamera.reversedDepth ) { shadowMatrix.set( - 0.5, 0.0, 0.0, 0.5, - 0.0, 0.5, 0.0, 0.5, + 0.5 * scaleX, 0.0, 0.0, 0.5 * scaleX + offsetX, + 0.0, 0.5 * scaleY, 0.0, 0.5 * scaleY + offsetY, 0.0, 0.0, 1.0, 0.0, // Identity Z (preserving the correct [0, 1] range from the projection matrix) 0.0, 0.0, 0.0, 1.0 ); @@ -225,8 +255,8 @@ class LightShadow { } else { shadowMatrix.set( - 0.5, 0.0, 0.0, 0.5, - 0.0, 0.5, 0.0, 0.5, + 0.5 * scaleX, 0.0, 0.0, 0.5 * scaleX + offsetX, + 0.0, 0.5 * scaleY, 0.0, 0.5 * scaleY + offsetY, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0 ); diff --git a/src/lights/SunLight.js b/src/lights/SunLight.js new file mode 100644 index 00000000000000..dd38710367d32d --- /dev/null +++ b/src/lights/SunLight.js @@ -0,0 +1,91 @@ +import { Light } from './Light.js'; +import { SunLightShadow } from './SunLightShadow.js'; + +/** + * A sun-like light that gets emitted in a specific direction, with rays that + * are all parallel, and casts cascaded shadow maps via {@link SunLightShadow}, + * suited for lighting large scenes. + * + * Unlike {@link DirectionalLight}, the light has no target: like + * {@link HemisphereLight}, its direction is defined by its position. The + * light shines from its position towards the origin and points straight + * down by default. + * + * ```js + * const sun = new SunLight( 0xfff2e3, 3 ); + * sun.position.set( 1, 1, 1 ); + * sun.castShadow = true; + * scene.add( sun ); + * ``` + * + * This light is only supported by `WebGLRenderer`. When using `WebGPURenderer`, + * use {@link DirectionalLight} with `CSMShadowNode` instead. + * + * @augments Light + */ +class SunLight extends Light { + + /** + * Constructs a new sun light. + * + * @param {(number|Color|string)} [color=0xffffff] - The light's color. + * @param {number} [intensity=1] - The light's strength/intensity. + */ + constructor( color, intensity ) { + + super( color, intensity ); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isSunLight = true; + + this.type = 'SunLight'; + + /** + * The light's shadow configuration. + * + * @type {SunLightShadow} + */ + this.shadow = new SunLightShadow(); + + this.position.set( 0, 1, 0 ); + this.updateMatrix(); + + } + + dispose() { + + super.dispose(); + + this.shadow.dispose(); + + } + + copy( source ) { + + super.copy( source ); + + this.shadow = source.shadow.clone(); + + return this; + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + data.object.shadow = this.shadow.toJSON(); + + return data; + + } + +} + +export { SunLight }; diff --git a/src/lights/SunLightShadow.js b/src/lights/SunLightShadow.js new file mode 100644 index 00000000000000..85a2db5c4fd39d --- /dev/null +++ b/src/lights/SunLightShadow.js @@ -0,0 +1,295 @@ +import { LightShadow } from './LightShadow.js'; +import { OrthographicCamera } from '../cameras/OrthographicCamera.js'; +import { Frustum } from '../math/Frustum.js'; +import { Matrix4 } from '../math/Matrix4.js'; +import { Vector3 } from '../math/Vector3.js'; +import { Vector4 } from '../math/Vector4.js'; + +const _lightOrientationMatrix = /*@__PURE__*/ new Matrix4(); +const _viewToLightMatrix = /*@__PURE__*/ new Matrix4(); +const _lightDirection = /*@__PURE__*/ new Vector3(); +const _up = /*@__PURE__*/ new Vector3(); +const _center = /*@__PURE__*/ new Vector3(); +const _corner = /*@__PURE__*/ new Vector3(); +const _nearCorners = [ new Vector3(), new Vector3(), new Vector3(), new Vector3() ]; +const _farCorners = [ new Vector3(), new Vector3(), new Vector3(), new Vector3() ]; +const _cascadeCorners = [ new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3() ]; + +// must match the cascade count in the sun shadow shader chunks + +const _cascadeCount = 4; + +// fraction of each cascade's depth range that blends into the next cascade + +const _cascadeFade = 0.1; + +/** + * Represents the shadow configuration of {@link SunLight}, using four + * cascaded shadow maps (CSM). + * + * The shadow camera projection is fitted automatically to slices of the view + * frustum, up to a distance of `camera.far` (or the view camera's far plane, + * whichever is smaller), and adjacent cascades blend into each other over a + * small depth range. `camera.left/right/top/bottom` are ignored. + * + * The default `mapSize` is `1024x1024` per cascade. + * + * @augments LightShadow + */ +class SunLightShadow extends LightShadow { + + /** + * Constructs a new sun light shadow. + */ + constructor() { + + super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) ); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isSunLightShadow = true; + + this.mapSize.set( 1024, 1024 ); + + this._cameras = []; + this._matrices = []; + this._frustums = []; + this._cascadeSplits = new Array( _cascadeCount + 1 ).fill( 0 ); + + // per cascade ( begin, end, fade start ) view depths, consumed by the renderer + + this._cascadeData = []; + + this._viewportCount = _cascadeCount; + this._frameExtents.set( 2, 2 ); + + for ( let i = 0; i < _cascadeCount; i ++ ) { + + this._cameras.push( new OrthographicCamera() ); + this._matrices.push( new Matrix4() ); + this._frustums.push( new Frustum() ); + this._cascadeData.push( new Vector4() ); + + } + + while ( this._viewports.length < _cascadeCount ) this._viewports.push( new Vector4() ); + + } + + /** + * Returns the shadow camera of the given cascade. + * + * @param {number} [cascadeIndex=0] - The cascade index. + * @return {OrthographicCamera} The shadow camera. + */ + getCamera( cascadeIndex = 0 ) { + + return this._cameras[ cascadeIndex ]; + + } + + /** + * Returns the shadow matrix of the given cascade. + * + * @param {number} [cascadeIndex=0] - The cascade index. + * @return {Matrix4} The shadow matrix. + */ + getMatrix( cascadeIndex = 0 ) { + + return this._matrices[ cascadeIndex ]; + + } + + /** + * Returns the shadow camera frustum of the given cascade. Used internally by + * the renderer to cull objects. + * + * @param {number} [cascadeIndex=0] - The cascade index. + * @return {Frustum} The shadow camera frustum. + */ + getFrustum( cascadeIndex = 0 ) { + + return this._frustums[ cascadeIndex ]; + + } + + /** + * Update the matrices for the cascade cameras and shadows, used internally + * by the renderer. + * + * @param {Light} light - The light for which the shadow is being rendered. + * @param {Camera} viewCamera - The camera the scene is rendered with. + */ + updateMatrices( light, viewCamera ) { + + if ( viewCamera === undefined ) return; + + // inset the cascade viewports so shadow filtering cannot read across atlas tiles + + const insetX = Math.min( 0.25, ( Math.ceil( this.radius ) + 1 ) / this.mapSize.x ); + const insetY = Math.min( 0.25, ( Math.ceil( this.radius ) + 1 ) / this.mapSize.y ); + + for ( let i = 0; i < _cascadeCount; i ++ ) { + + this._viewports[ i ].set( i % 2 + insetX, Math.floor( i / 2 ) + insetY, 1 - 2 * insetX, 1 - 2 * insetY ); + + } + + const camera = this.camera; + const cameraNear = viewCamera.near; + const cameraFar = Math.max( cameraNear + 1e-6, Math.min( camera.far, viewCamera.far ) ); + + // practical split scheme: the average of uniform and logarithmic splits + + const splits = this._cascadeSplits; + splits[ 0 ] = cameraNear; + + for ( let i = 1; i < _cascadeCount; i ++ ) { + + const amount = i / _cascadeCount; + const uniform = cameraNear + ( cameraFar - cameraNear ) * amount; + const logarithmic = cameraNear > 0 ? cameraNear * Math.pow( cameraFar / cameraNear, amount ) : uniform; + splits[ i ] = ( uniform + logarithmic ) * 0.5; + + } + + splits[ _cascadeCount ] = cameraFar; + + _lightDirection.setFromMatrixPosition( light.matrixWorld ).negate().normalize(); + + _up.set( 0, 1, 0 ); + if ( Math.abs( _up.dot( _lightDirection ) ) > 0.99 ) _up.set( 0, 0, 1 ); + + _lightOrientationMatrix.lookAt( _center.set( 0, 0, 0 ), _lightDirection, _up ); + _viewToLightMatrix.copy( _lightOrientationMatrix ).transpose().multiply( viewCamera.matrixWorld ); + + // view frustum corners in light space; the rotation preserves distances, + // so the cascades can be fitted and snapped directly in this space + + const zNear = viewCamera.reversedDepth ? 1 : - 1; + const inverseProjectionMatrix = viewCamera.projectionMatrixInverse; + + let globalMaxZ = - Infinity; + + for ( let i = 0; i < 4; i ++ ) { + + const x = i === 0 || i === 1 ? 1 : - 1; + const y = i === 0 || i === 3 ? 1 : - 1; + + const nearCorner = _nearCorners[ i ].set( x, y, zNear ).applyMatrix4( inverseProjectionMatrix ); + const farCorner = _farCorners[ i ]; + + if ( viewCamera.isPerspectiveCamera === true ) { + + farCorner.copy( nearCorner ).multiplyScalar( cameraFar / cameraNear ); + + } else { + + farCorner.set( nearCorner.x, nearCorner.y, - cameraFar ); + + } + + nearCorner.applyMatrix4( _viewToLightMatrix ); + farCorner.applyMatrix4( _viewToLightMatrix ); + + globalMaxZ = Math.max( globalMaxZ, nearCorner.z, farCorner.z ); + + } + + // raise the ceiling one shadow range towards the light so casters outside + // the view frustum still cast into it + + globalMaxZ += cameraFar; + + const shadowNear = camera.near; + + for ( let i = 0; i < _cascadeCount; i ++ ) { + + // each cascade covers the fade band of the previous one so both can be sampled while blending + + const cascadeNear = i === 0 ? splits[ 0 ] : this._cascadeData[ i - 1 ].z; + const cascadeFar = splits[ i + 1 ]; + const fadeStart = cascadeFar - _cascadeFade * ( cascadeFar - splits[ i ] ); + + this._cascadeData[ i ].set( i === 0 ? - 1e10 : cascadeNear, cascadeFar, fadeStart, 0 ); + + // bounding sphere of the cascade slice for a rotation-stable projection + + const nearAlpha = ( cascadeNear - cameraNear ) / ( cameraFar - cameraNear ); + const farAlpha = ( cascadeFar - cameraNear ) / ( cameraFar - cameraNear ); + + _center.set( 0, 0, 0 ); + + for ( let j = 0; j < 4; j ++ ) { + + _cascadeCorners[ j * 2 ].lerpVectors( _nearCorners[ j ], _farCorners[ j ], nearAlpha ); + _cascadeCorners[ j * 2 + 1 ].lerpVectors( _nearCorners[ j ], _farCorners[ j ], farAlpha ); + _center.add( _cascadeCorners[ j * 2 ] ).add( _cascadeCorners[ j * 2 + 1 ] ); + + } + + _center.multiplyScalar( 1 / 8 ); + + let radiusSq = 0; + let minZ = Infinity; + + for ( let j = 0; j < 8; j ++ ) { + + radiusSq = Math.max( radiusSq, _cascadeCorners[ j ].distanceToSquared( _center ) ); + minZ = Math.min( minZ, _cascadeCorners[ j ].z ); + + } + + let radius = Math.sqrt( radiusSq ); + + // snap to the texel grid to avoid shimmering when the view camera moves + + const resolutionX = this.mapSize.width * this._viewports[ i ].z; + const resolutionY = this.mapSize.height * this._viewports[ i ].w; + const resolution = Math.min( resolutionX, resolutionY ); + + if ( resolution > 1 ) { + + // pad by half a texel so snapping cannot clip a frustum corner + radius /= 1 - 1 / resolution; + const texelSizeX = 2 * radius / resolutionX; + const texelSizeY = 2 * radius / resolutionY; + _center.x = Math.round( _center.x / texelSizeX ) * texelSizeX; + _center.y = Math.round( _center.y / texelSizeY ) * texelSizeY; + + } + + // place the near plane at the caster ceiling + + _center.z = globalMaxZ + shadowNear; + _center.applyMatrix4( _lightOrientationMatrix ); + + const cascadeCamera = this._cameras[ i ]; + cascadeCamera.position.copy( _center ); + cascadeCamera.up.copy( _up ); + cascadeCamera.lookAt( _corner.copy( _center ).add( _lightDirection ) ); + cascadeCamera.left = - radius; + cascadeCamera.right = radius; + cascadeCamera.top = radius; + cascadeCamera.bottom = - radius; + cascadeCamera.near = shadowNear; + cascadeCamera.far = globalMaxZ - minZ + 2 * shadowNear; + cascadeCamera.coordinateSystem = camera.coordinateSystem; + cascadeCamera._reversedDepth = camera.reversedDepth; + cascadeCamera.updateProjectionMatrix(); + cascadeCamera.updateMatrixWorld(); + + this._updateMatrix( cascadeCamera, this._matrices[ i ], this._frustums[ i ], this._viewports[ i ] ); + + } + + } + +} + +export { SunLightShadow }; diff --git a/src/loaders/ObjectLoader.js b/src/loaders/ObjectLoader.js index 9be1220b963620..56a9acf5cea24f 100644 --- a/src/loaders/ObjectLoader.js +++ b/src/loaders/ObjectLoader.js @@ -18,6 +18,7 @@ import { LinearMipmapLinearFilter } from '../constants.js'; import { InstancedBufferAttribute } from '../core/InstancedBufferAttribute.js'; +import { SunLight } from '../lights/SunLight.js'; import { Color } from '../math/Color.js'; import { Vector3 } from '../math/Vector3.js'; import { Object3D } from '../core/Object3D.js'; @@ -921,6 +922,12 @@ class ObjectLoader extends Loader { break; + case 'SunLight': + + object = new SunLight( data.color, data.intensity ); + + break; + case 'DirectionalLight': object = new DirectionalLight( data.color, data.intensity ); diff --git a/src/nodes/Nodes.js b/src/nodes/Nodes.js index f1385ffb670638..5a27ea0e7e69b7 100644 --- a/src/nodes/Nodes.js +++ b/src/nodes/Nodes.js @@ -55,6 +55,7 @@ export { default as ModelNode } from './accessors/ModelNode.js'; export { default as Object3DNode } from './accessors/Object3DNode.js'; export { default as PointUVNode } from './accessors/PointUVNode.js'; export { default as ReferenceBaseNode } from './accessors/ReferenceBaseNode.js'; +export { default as ReferenceElementNode } from './accessors/ReferenceElementNode.js'; export { default as ReferenceNode } from './accessors/ReferenceNode.js'; export { default as RendererReferenceNode } from './accessors/RendererReferenceNode.js'; export { default as StorageBufferNode } from './accessors/StorageBufferNode.js'; diff --git a/src/nodes/accessors/ReferenceBaseNode.js b/src/nodes/accessors/ReferenceBaseNode.js index 0cdaab53d31247..1e56ea002046ca 100644 --- a/src/nodes/accessors/ReferenceBaseNode.js +++ b/src/nodes/accessors/ReferenceBaseNode.js @@ -2,79 +2,10 @@ import Node from '../core/Node.js'; import { NodeUpdateType } from '../core/constants.js'; import { uniform } from '../core/UniformNode.js'; import { nodeObject } from '../tsl/TSLCore.js'; -import ArrayElementNode from '../utils/ArrayElementNode.js'; +import ReferenceElementNode from './ReferenceElementNode.js'; // TODO: Avoid duplicated code and use only ReferenceBaseNode or ReferenceNode -/** - * This class is only relevant if the referenced property is array-like. - * In this case, `ReferenceElementNode` allows to refer to a specific - * element inside the data structure via an index. - * - * @augments ArrayElementNode - */ -class ReferenceElementNode extends ArrayElementNode { - - static get type() { - - return 'ReferenceElementNode'; - - } - - /** - * Constructs a new reference element node. - * - * @param {ReferenceBaseNode} referenceNode - The reference node. - * @param {Node} indexNode - The index node that defines the element access. - */ - constructor( referenceNode, indexNode ) { - - super( referenceNode, indexNode ); - - /** - * Similar to {@link ReferenceBaseNode#reference}, an additional - * property references to the current node. - * - * @type {?ReferenceBaseNode} - * @default null - */ - this.referenceNode = referenceNode; - - /** - * This flag can be used for type testing. - * - * @type {boolean} - * @readonly - * @default true - */ - this.isReferenceElementNode = true; - - } - - /** - * This method is overwritten since the node type is inferred from - * the uniform type of the reference node. - * - * @return {string} The node type. - */ - generateNodeType() { - - return this.referenceNode.uniformType; - - } - - generate( builder ) { - - const snippet = super.generate( builder ); - const arrayType = this.referenceNode.getNodeType(); - const elementType = this.getNodeType(); - - return builder.format( snippet, arrayType, elementType ); - - } - -} - /** * Base class for nodes which establishes a reference to a property of another object. * In this way, the value of the node is automatically linked to the value of diff --git a/src/nodes/accessors/ReferenceElementNode.js b/src/nodes/accessors/ReferenceElementNode.js new file mode 100644 index 00000000000000..ce3d760d3cc14f --- /dev/null +++ b/src/nodes/accessors/ReferenceElementNode.js @@ -0,0 +1,72 @@ +import ArrayElementNode from '../utils/ArrayElementNode.js'; + +/** + * This class is only relevant if the referenced property is array-like. + * In this case, `ReferenceElementNode` allows to refer to a specific + * element inside the data structure via an index. + * + * @augments ArrayElementNode + */ +class ReferenceElementNode extends ArrayElementNode { + + static get type() { + + return 'ReferenceElementNode'; + + } + + /** + * Constructs a new reference element node. + * + * @param {(ReferenceBaseNode|ReferenceNode)} referenceNode - The reference node. + * @param {Node} indexNode - The index node that defines the element access. + */ + constructor( referenceNode, indexNode ) { + + super( referenceNode, indexNode ); + + /** + * Similar to {@link ReferenceNode#reference}, an additional + * property references to the current node. + * + * @type {?(ReferenceBaseNode|ReferenceNode)} + * @default null + */ + this.referenceNode = referenceNode; + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isReferenceElementNode = true; + + } + + /** + * This method is overwritten since the node type is inferred from + * the uniform type of the reference node. + * + * @return {string} The node type. + */ + generateNodeType() { + + return this.referenceNode.uniformType; + + } + + generate( builder ) { + + const snippet = super.generate( builder ); + const arrayType = this.referenceNode.getNodeType( builder ); + const elementType = this.getNodeType( builder ); + + return builder.format( snippet, arrayType, elementType ); + + } + +} + +export default ReferenceElementNode; diff --git a/src/nodes/accessors/ReferenceNode.js b/src/nodes/accessors/ReferenceNode.js index 856d39f84d0771..9ccc4350944a8d 100644 --- a/src/nodes/accessors/ReferenceNode.js +++ b/src/nodes/accessors/ReferenceNode.js @@ -6,80 +6,11 @@ import { cubeTexture } from './CubeTextureNode.js'; import { buffer } from './BufferNode.js'; import { nodeObject } from '../tsl/TSLBase.js'; import { uniformArray } from './UniformArrayNode.js'; -import ArrayElementNode from '../utils/ArrayElementNode.js'; +import ReferenceElementNode from './ReferenceElementNode.js'; import { warn } from '../../utils.js'; // TODO: Avoid duplicated code and use only ReferenceBaseNode or ReferenceNode -/** - * This class is only relevant if the referenced property is array-like. - * In this case, `ReferenceElementNode` allows to refer to a specific - * element inside the data structure via an index. - * - * @augments ArrayElementNode - */ -class ReferenceElementNode extends ArrayElementNode { - - static get type() { - - return 'ReferenceElementNode'; - - } - - /** - * Constructs a new reference element node. - * - * @param {?ReferenceNode} referenceNode - The reference node. - * @param {Node} indexNode - The index node that defines the element access. - */ - constructor( referenceNode, indexNode ) { - - super( referenceNode, indexNode ); - - /** - * Similar to {@link ReferenceNode#reference}, an additional - * property references to the current node. - * - * @type {?ReferenceNode} - * @default null - */ - this.referenceNode = referenceNode; - - /** - * This flag can be used for type testing. - * - * @type {boolean} - * @readonly - * @default true - */ - this.isReferenceElementNode = true; - - } - - /** - * This method is overwritten since the node type is inferred from - * the uniform type of the reference node. - * - * @return {string} The node type. - */ - generateNodeType() { - - return this.referenceNode.uniformType; - - } - - generate( builder ) { - - const snippet = super.generate( builder ); - const arrayType = this.referenceNode.getNodeType( builder ); - const elementType = this.getNodeType( builder ); - - return builder.format( snippet, arrayType, elementType ); - - } - -} - /** * This type of node establishes a reference to a property of another object. * In this way, the value of the node is automatically linked to the value of diff --git a/src/nodes/functions/ToonLightingModel.js b/src/nodes/functions/ToonLightingModel.js index 25df145f7551b6..8d43e46d11aba9 100644 --- a/src/nodes/functions/ToonLightingModel.js +++ b/src/nodes/functions/ToonLightingModel.js @@ -1,7 +1,7 @@ import LightingModel from '../core/LightingModel.js'; import BRDF_Lambert from './BSDF/BRDF_Lambert.js'; import { diffuseColor } from '../core/PropertyNode.js'; -import { normalGeometry } from '../accessors/Normal.js'; +import { normalView } from '../accessors/Normal.js'; import { Fn, float, vec2, vec3 } from '../tsl/TSLBase.js'; import { mix, smoothstep } from '../math/MathNode.js'; import { materialReference } from '../accessors/MaterialReferenceNode.js'; @@ -44,7 +44,7 @@ class ToonLightingModel extends LightingModel { */ direct( { lightDirection, lightColor, reflectedLight }, builder ) { - const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor ); + const irradiance = getGradientIrradiance( { normal: normalView, lightDirection, builder } ).mul( lightColor ); reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) ); diff --git a/src/renderers/WebGLRenderer.js b/src/renderers/WebGLRenderer.js index 965959aa659483..c15b688a9b95f5 100644 --- a/src/renderers/WebGLRenderer.js +++ b/src/renderers/WebGLRenderer.js @@ -2264,6 +2264,8 @@ class WebGLRenderer { uniforms.ambientLightColor.value = lights.state.ambient; uniforms.lightProbe.value = lights.state.probe; + uniforms.sunLights.value = lights.state.sun; + uniforms.sunLightShadows.value = lights.state.sunShadow; uniforms.directionalLights.value = lights.state.directional; uniforms.directionalLightShadows.value = lights.state.directionalShadow; uniforms.spotLights.value = lights.state.spot; @@ -2275,6 +2277,8 @@ class WebGLRenderer { uniforms.pointLightShadows.value = lights.state.pointShadow; uniforms.hemisphereLights.value = lights.state.hemi; + uniforms.sunShadowMatrix.value = lights.state.sunShadowMatrix; + uniforms.sunShadowCascade.value = lights.state.sunShadowCascade; uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix; uniforms.spotLightMatrix.value = lights.state.spotLightMatrix; uniforms.spotLightMap.value = lights.state.spotLightMap; @@ -2639,6 +2643,12 @@ class WebGLRenderer { if ( materialProperties.needsLights ) { // Set shadow map uniforms first to ensure they get the first texture units + if ( lights.state.sunShadowMap.length > 0 ) { + + p_uniforms.setValue( _gl, 'sunShadowMap', lights.state.sunShadowMap, textures ); + + } + if ( lights.state.directionalShadowMap.length > 0 ) { p_uniforms.setValue( _gl, 'directionalShadowMap', lights.state.directionalShadowMap, textures ); @@ -2818,6 +2828,8 @@ class WebGLRenderer { uniforms.ambientLightColor.needsUpdate = value; uniforms.lightProbe.needsUpdate = value; + uniforms.sunLights.needsUpdate = value; + uniforms.sunLightShadows.needsUpdate = value; uniforms.directionalLights.needsUpdate = value; uniforms.directionalLightShadows.needsUpdate = value; uniforms.pointLights.needsUpdate = value; diff --git a/src/renderers/common/InspectorBase.js b/src/renderers/common/InspectorBase.js index b1e61902c7df5a..71c13d63dc7fa0 100644 --- a/src/renderers/common/InspectorBase.js +++ b/src/renderers/common/InspectorBase.js @@ -3,7 +3,6 @@ import { EventDispatcher } from '../../core/EventDispatcher.js'; /** * InspectorBase is the base class for all inspectors. * - * @class InspectorBase * @augments EventDispatcher */ class InspectorBase extends EventDispatcher { diff --git a/src/renderers/shaders/ShaderChunk/lights_fragment_begin.glsl.js b/src/renderers/shaders/ShaderChunk/lights_fragment_begin.glsl.js index f9af80b4e6692a..0e223525c4838f 100644 --- a/src/renderers/shaders/ShaderChunk/lights_fragment_begin.glsl.js +++ b/src/renderers/shaders/ShaderChunk/lights_fragment_begin.glsl.js @@ -60,7 +60,7 @@ vec3 geometryClearcoatNormal = vec3( 0.0 ); material.dfg = texture2D( dfgLUT, vec2( material.roughness, dotNVms ) ).rg; - #if ( NUM_DIR_LIGHTS > 0 || NUM_POINT_LIGHTS > 0 || NUM_SPOT_LIGHTS > 0 ) + #if ( NUM_SUN_LIGHTS > 0 || NUM_DIR_LIGHTS > 0 || NUM_POINT_LIGHTS > 0 || NUM_SPOT_LIGHTS > 0 ) // Multi-scattering energy compensation for direct lighting // Based on "Practical Multiple Scattering Compensation for Microfacet Models" @@ -152,6 +152,32 @@ IncidentLight directLight; #endif +#if ( NUM_SUN_LIGHTS > 0 ) && defined( RE_Direct ) + + SunLight sunLight; + #if defined( USE_SHADOWMAP ) && NUM_SUN_LIGHT_SHADOWS > 0 + SunLightShadow sunLightShadow; + #endif + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SUN_LIGHTS; i ++ ) { + + sunLight = sunLights[ i ]; + + getSunLightInfo( sunLight, directLight ); + + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SUN_LIGHT_SHADOWS ) + sunLightShadow = sunLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getSunShadow( sunShadowMap[ i ], sunLightShadow, UNROLLED_LOOP_INDEX ) : 1.0; + #endif + + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + + } + #pragma unroll_loop_end + +#endif + #if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) DirectionalLight directionalLight; diff --git a/src/renderers/shaders/ShaderChunk/lights_pars_begin.glsl.js b/src/renderers/shaders/ShaderChunk/lights_pars_begin.glsl.js index a335fc2809df13..943d78279cf0b7 100644 --- a/src/renderers/shaders/ShaderChunk/lights_pars_begin.glsl.js +++ b/src/renderers/shaders/ShaderChunk/lights_pars_begin.glsl.js @@ -76,6 +76,25 @@ float getSpotAttenuation( const in float coneCosine, const in float penumbraCosi } +#if NUM_SUN_LIGHTS > 0 + + struct SunLight { + vec3 direction; + vec3 color; + }; + + uniform SunLight sunLights[ NUM_SUN_LIGHTS ]; + + void getSunLightInfo( const in SunLight sunLight, out IncidentLight light ) { + + light.color = sunLight.color; + light.direction = sunLight.direction; + light.visible = true; + + } + +#endif + #if NUM_DIR_LIGHTS > 0 struct DirectionalLight { diff --git a/src/renderers/shaders/ShaderChunk/shadowmap_pars_fragment.glsl.js b/src/renderers/shaders/ShaderChunk/shadowmap_pars_fragment.glsl.js index dd9e98257cc6ca..7cc8fc00f79457 100644 --- a/src/renderers/shaders/ShaderChunk/shadowmap_pars_fragment.glsl.js +++ b/src/renderers/shaders/ShaderChunk/shadowmap_pars_fragment.glsl.js @@ -13,6 +13,35 @@ export default /* glsl */` #ifdef USE_SHADOWMAP + #if NUM_SUN_LIGHT_SHADOWS > 0 + + #if defined( SHADOWMAP_TYPE_PCF ) + + uniform sampler2DShadow sunShadowMap[ NUM_SUN_LIGHT_SHADOWS ]; + + #else + + uniform sampler2D sunShadowMap[ NUM_SUN_LIGHT_SHADOWS ]; + + #endif + + uniform mat4 sunShadowMatrix[ NUM_SUN_LIGHT_SHADOWS * 4 ]; + uniform vec4 sunShadowCascade[ NUM_SUN_LIGHT_SHADOWS * 4 ]; + varying vec4 vSunShadowWorldPosition; + varying vec3 vSunShadowWorldNormal; + + struct SunLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + + uniform SunLightShadow sunLightShadows[ NUM_SUN_LIGHT_SHADOWS ]; + + #endif + #if NUM_DIR_LIGHT_SHADOWS > 0 #if defined( SHADOWMAP_TYPE_PCF ) @@ -258,6 +287,48 @@ export default /* glsl */` #endif + #if NUM_SUN_LIGHT_SHADOWS > 0 + + float getSunShadow( + #if defined( SHADOWMAP_TYPE_PCF ) + sampler2DShadow shadowMap, + #else + sampler2D shadowMap, + #endif + SunLightShadow sunLightShadow, + const in int shadowIndex + ) { + + vec4 shadowWorldPosition = vec4( vSunShadowWorldPosition.xyz + vSunShadowWorldNormal * sunLightShadow.shadowNormalBias, 1.0 ); + float viewDepth = vSunShadowWorldPosition.w; + int cascadeOffset = shadowIndex * 4; + + float shadow = 1.0; + + // walk the cascades back to front so each fade band can blend with the shadow behind it + + for ( int i = 3; i >= 0; i -- ) { + + // ( begin, end, fade start ) view depths of the cascade + + vec4 cascade = sunShadowCascade[ cascadeOffset + i ]; + + if ( viewDepth >= cascade.x && viewDepth < cascade.y ) { + + float cascadeShadow = getShadow( shadowMap, sunLightShadow.shadowMapSize, sunLightShadow.shadowIntensity, sunLightShadow.shadowBias, sunLightShadow.shadowRadius, sunShadowMatrix[ cascadeOffset + i ] * shadowWorldPosition ); + + shadow = viewDepth < cascade.z ? cascadeShadow : mix( cascadeShadow, shadow, smoothstep( cascade.z, cascade.y, viewDepth ) ); + + } + + } + + return shadow; + + } + + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 #if defined( SHADOWMAP_TYPE_PCF ) diff --git a/src/renderers/shaders/ShaderChunk/shadowmap_pars_vertex.glsl.js b/src/renderers/shaders/ShaderChunk/shadowmap_pars_vertex.glsl.js index 75911cdd018b82..4c3199255a3cad 100644 --- a/src/renderers/shaders/ShaderChunk/shadowmap_pars_vertex.glsl.js +++ b/src/renderers/shaders/ShaderChunk/shadowmap_pars_vertex.glsl.js @@ -9,6 +9,15 @@ export default /* glsl */` #ifdef USE_SHADOWMAP + #if NUM_SUN_LIGHT_SHADOWS > 0 + + // cascade selection and shadow coordinates are computed per fragment + + varying vec4 vSunShadowWorldPosition; + varying vec3 vSunShadowWorldNormal; + + #endif + #if NUM_DIR_LIGHT_SHADOWS > 0 uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ]; diff --git a/src/renderers/shaders/ShaderChunk/shadowmap_vertex.glsl.js b/src/renderers/shaders/ShaderChunk/shadowmap_vertex.glsl.js index b0d1a1556d103d..2f9e04c92e8b02 100644 --- a/src/renderers/shaders/ShaderChunk/shadowmap_vertex.glsl.js +++ b/src/renderers/shaders/ShaderChunk/shadowmap_vertex.glsl.js @@ -1,6 +1,6 @@ export default /* glsl */` -#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) +#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SUN_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) #ifdef HAS_NORMAL @@ -20,6 +20,13 @@ export default /* glsl */` #if defined( USE_SHADOWMAP ) + #if NUM_SUN_LIGHT_SHADOWS > 0 + + vSunShadowWorldPosition = vec4( worldPosition.xyz, - mvPosition.z ); + vSunShadowWorldNormal = shadowWorldNormal; + + #endif + #if NUM_DIR_LIGHT_SHADOWS > 0 #pragma unroll_loop_start diff --git a/src/renderers/shaders/ShaderChunk/shadowmask_pars_fragment.glsl.js b/src/renderers/shaders/ShaderChunk/shadowmask_pars_fragment.glsl.js index 88f58c0db117bf..752c1a23b4bec6 100644 --- a/src/renderers/shaders/ShaderChunk/shadowmask_pars_fragment.glsl.js +++ b/src/renderers/shaders/ShaderChunk/shadowmask_pars_fragment.glsl.js @@ -5,6 +5,21 @@ float getShadowMask() { #ifdef USE_SHADOWMAP + #if NUM_SUN_LIGHT_SHADOWS > 0 + + SunLightShadow sunLight; + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SUN_LIGHT_SHADOWS; i ++ ) { + + sunLight = sunLightShadows[ i ]; + shadow *= receiveShadow ? getSunShadow( sunShadowMap[ i ], sunLight, UNROLLED_LOOP_INDEX ) : 1.0; + + } + #pragma unroll_loop_end + + #endif + #if NUM_DIR_LIGHT_SHADOWS > 0 DirectionalLightShadow directionalLight; diff --git a/src/renderers/shaders/UniformsLib.js b/src/renderers/shaders/UniformsLib.js index 65a10b9641496a..66a52fd870401b 100644 --- a/src/renderers/shaders/UniformsLib.js +++ b/src/renderers/shaders/UniformsLib.js @@ -122,6 +122,22 @@ const UniformsLib = { lightProbe: { value: [] }, + sunLights: { value: [], properties: { + direction: {}, + color: {} + } }, + + sunLightShadows: { value: [], properties: { + shadowIntensity: 1, + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {} + } }, + + sunShadowMatrix: { value: [] }, + sunShadowCascade: { value: [] }, + directionalLights: { value: [], properties: { direction: {}, color: {} diff --git a/src/renderers/webgl/WebGLLights.js b/src/renderers/webgl/WebGLLights.js index e24f9266864354..52c5ce19766757 100644 --- a/src/renderers/webgl/WebGLLights.js +++ b/src/renderers/webgl/WebGLLights.js @@ -23,6 +23,7 @@ function UniformsCache() { switch ( light.type ) { + case 'SunLight': case 'DirectionalLight': uniforms = { direction: new Vector3(), @@ -98,6 +99,7 @@ function ShadowUniformsCache() { switch ( light.type ) { + case 'SunLight': case 'DirectionalLight': uniforms = { shadowIntensity: 1, @@ -165,12 +167,14 @@ function WebGLLights( extensions ) { version: 0, hash: { + sunLength: - 1, directionalLength: - 1, pointLength: - 1, spotLength: - 1, rectAreaLength: - 1, hemiLength: - 1, + numSunShadows: - 1, numDirectionalShadows: - 1, numPointShadows: - 1, numSpotShadows: - 1, @@ -181,6 +185,11 @@ function WebGLLights( extensions ) { ambient: [ 0, 0, 0 ], probe: [], + sun: [], + sunShadow: [], + sunShadowMap: [], + sunShadowMatrix: [], + sunShadowCascade: [], directional: [], directionalShadow: [], directionalShadowMap: [], @@ -215,6 +224,8 @@ function WebGLLights( extensions ) { for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 ); + let sunLength = 0; + let numSunShadows = 0; let directionalLength = 0; let pointLength = 0; let spotLength = 0; @@ -274,6 +285,44 @@ function WebGLLights( extensions ) { numLightProbes ++; + } else if ( light.isSunLight ) { + + const uniforms = cache.get( light ); + + uniforms.color.copy( light.color ).multiplyScalar( light.intensity ); + + if ( light.castShadow ) { + + const shadow = light.shadow; + + const shadowUniforms = shadowCache.get( light ); + + shadowUniforms.shadowIntensity = shadow.intensity; + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize.copy( shadow.mapSize ).multiply( shadow.getFrameExtents() ); + + state.sunShadow[ numSunShadows ] = shadowUniforms; + state.sunShadowMap[ numSunShadows ] = shadowMap; + + // four cascades per sun light, matching the sun shadow shader chunks + + for ( let i = 0; i < 4; i ++ ) { + + state.sunShadowMatrix[ numSunShadows * 4 + i ] = shadow.getMatrix( i ); + state.sunShadowCascade[ numSunShadows * 4 + i ] = shadow._cascadeData[ i ]; + + } + + numSunShadows ++; + + } + + state.sun[ sunLength ] = uniforms; + + sunLength ++; + } else if ( light.isDirectionalLight ) { const uniforms = cache.get( light ); @@ -439,42 +488,51 @@ function WebGLLights( extensions ) { const hash = state.hash; - if ( hash.directionalLength !== directionalLength || + if ( hash.sunLength !== sunLength || + hash.directionalLength !== directionalLength || hash.pointLength !== pointLength || hash.spotLength !== spotLength || hash.rectAreaLength !== rectAreaLength || hash.hemiLength !== hemiLength || + hash.numSunShadows !== numSunShadows || hash.numDirectionalShadows !== numDirectionalShadows || hash.numPointShadows !== numPointShadows || hash.numSpotShadows !== numSpotShadows || hash.numSpotMaps !== numSpotMaps || hash.numLightProbes !== numLightProbes ) { + state.sun.length = sunLength; state.directional.length = directionalLength; state.spot.length = spotLength; state.rectArea.length = rectAreaLength; state.point.length = pointLength; state.hemi.length = hemiLength; + state.sunShadow.length = numSunShadows; + state.sunShadowMap.length = numSunShadows; + state.sunShadowMatrix.length = numSunShadows * 4; + state.sunShadowCascade.length = numSunShadows * 4; state.directionalShadow.length = numDirectionalShadows; state.directionalShadowMap.length = numDirectionalShadows; + state.directionalShadowMatrix.length = numDirectionalShadows; state.pointShadow.length = numPointShadows; state.pointShadowMap.length = numPointShadows; state.spotShadow.length = numSpotShadows; state.spotShadowMap.length = numSpotShadows; - state.directionalShadowMatrix.length = numDirectionalShadows; state.pointShadowMatrix.length = numPointShadows; state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps; state.spotLightMap.length = numSpotMaps; state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps; state.numLightProbes = numLightProbes; + hash.sunLength = sunLength; hash.directionalLength = directionalLength; hash.pointLength = pointLength; hash.spotLength = spotLength; hash.rectAreaLength = rectAreaLength; hash.hemiLength = hemiLength; + hash.numSunShadows = numSunShadows; hash.numDirectionalShadows = numDirectionalShadows; hash.numPointShadows = numPointShadows; hash.numSpotShadows = numSpotShadows; @@ -490,6 +548,7 @@ function WebGLLights( extensions ) { function setupView( lights, camera ) { + let sunLength = 0; let directionalLength = 0; let pointLength = 0; let spotLength = 0; @@ -502,7 +561,16 @@ function WebGLLights( extensions ) { const light = lights[ i ]; - if ( light.isDirectionalLight ) { + if ( light.isSunLight ) { + + const uniforms = state.sun[ sunLength ]; + + uniforms.direction.setFromMatrixPosition( light.matrixWorld ); + uniforms.direction.transformDirection( viewMatrix ); + + sunLength ++; + + } else if ( light.isDirectionalLight ) { const uniforms = state.directional[ directionalLength ]; diff --git a/src/renderers/webgl/WebGLProgram.js b/src/renderers/webgl/WebGLProgram.js index 4d64b338ba5ee4..3bddcdcb9072ba 100644 --- a/src/renderers/webgl/WebGLProgram.js +++ b/src/renderers/webgl/WebGLProgram.js @@ -216,6 +216,7 @@ function replaceLightNums( string, parameters ) { const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps; return string + .replace( /NUM_SUN_LIGHTS/g, parameters.numSunLights ) .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights ) .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights ) .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps ) @@ -223,6 +224,7 @@ function replaceLightNums( string, parameters ) { .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights ) .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights ) .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights ) + .replace( /NUM_SUN_LIGHT_SHADOWS/g, parameters.numSunLightShadows ) .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows ) .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps ) .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows ) diff --git a/src/renderers/webgl/WebGLPrograms.js b/src/renderers/webgl/WebGLPrograms.js index b6a0fceaf49724..1af6f63f716fb9 100644 --- a/src/renderers/webgl/WebGLPrograms.js +++ b/src/renderers/webgl/WebGLPrograms.js @@ -337,6 +337,7 @@ function WebGLPrograms( renderer, environments, extensions, capabilities, bindin morphTargetsCount: morphTargetsCount, morphTextureStride: morphTextureStride, + numSunLights: lights.sun.length, numDirLights: lights.directional.length, numPointLights: lights.point.length, numSpotLights: lights.spot.length, @@ -344,6 +345,7 @@ function WebGLPrograms( renderer, environments, extensions, capabilities, bindin numRectAreaLights: lights.rectArea.length, numHemiLights: lights.hemi.length, + numSunLightShadows: lights.sunShadowMap.length, numDirLightShadows: lights.directionalShadowMap.length, numPointLightShadows: lights.pointShadowMap.length, numSpotLightShadows: lights.spotShadowMap.length, @@ -471,12 +473,14 @@ function WebGLPrograms( renderer, environments, extensions, capabilities, bindin array.push( parameters.sizeAttenuation ); array.push( parameters.morphTargetsCount ); array.push( parameters.morphAttributeCount ); + array.push( parameters.numSunLights ); array.push( parameters.numDirLights ); array.push( parameters.numPointLights ); array.push( parameters.numSpotLights ); array.push( parameters.numSpotLightMaps ); array.push( parameters.numHemiLights ); array.push( parameters.numRectAreaLights ); + array.push( parameters.numSunLightShadows ); array.push( parameters.numDirLightShadows ); array.push( parameters.numPointLightShadows ); array.push( parameters.numSpotLightShadows ); diff --git a/src/renderers/webgl/WebGLShadowMap.js b/src/renderers/webgl/WebGLShadowMap.js index aabef88fadc2f6..dcc5b906355fdc 100644 --- a/src/renderers/webgl/WebGLShadowMap.js +++ b/src/renderers/webgl/WebGLShadowMap.js @@ -171,6 +171,7 @@ function WebGLShadowMap( renderer, objects, capabilities ) { _shadowMapSize.copy( shadow.mapSize ); + const viewportCount = shadow.getViewportCount(); const shadowFrameExtents = shadow.getFrameExtents(); _shadowMapSize.multiply( shadowFrameExtents ); @@ -278,39 +279,21 @@ function WebGLShadowMap( renderer, objects, capabilities ) { } - // For cube render targets (PointLights), render all 6 faces. Otherwise, render once. - const faceCount = shadow.map.isWebGLCubeRenderTarget ? 6 : 1; + if ( shadow.map.isWebGLCubeRenderTarget !== true && ( shadow.map.width !== _shadowMapSize.x || shadow.map.height !== _shadowMapSize.y ) ) { - for ( let face = 0; face < faceCount; face ++ ) { - - // For cube render targets, render to each face separately - if ( shadow.map.isWebGLCubeRenderTarget ) { - - renderer.setRenderTarget( shadow.map, face ); - renderer.clear(); - - } else { - - // For 2D render targets, use viewports - if ( face === 0 ) { - - renderer.setRenderTarget( shadow.map ); - renderer.clear(); + shadow.map.setSize( _shadowMapSize.x, _shadowMapSize.y ); - } + } - const viewport = shadow.getViewport( face ); + // For cube render targets (PointLights), render all 6 faces. Sun lights + // render one atlas viewport per cascade. + const faceCount = shadow.map.isWebGLCubeRenderTarget ? 6 : viewportCount; - _viewport.set( - _viewportSize.x * viewport.x, - _viewportSize.y * viewport.y, - _viewportSize.x * viewport.z, - _viewportSize.y * viewport.w - ); + if ( light.isPointLight !== true ) shadow.updateMatrices( light, camera ); - _state.viewport( _viewport ); + for ( let face = 0; face < faceCount; face ++ ) { - } + const shadowCamera = shadow.getCamera( face ); if ( light.isPointLight ) { @@ -340,15 +323,40 @@ function WebGLShadowMap( renderer, objects, capabilities ) { _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); shadow._frustum.setFromProjectionMatrix( _projScreenMatrix, camera.coordinateSystem, camera.reversedDepth ); + } + + // For cube render targets, render to each face separately + if ( shadow.map.isWebGLCubeRenderTarget ) { + + renderer.setRenderTarget( shadow.map, face ); + renderer.clear(); + } else { - shadow.updateMatrices( light ); + // For 2D render targets, use viewports + if ( face === 0 ) { + + renderer.setRenderTarget( shadow.map ); + renderer.clear(); + + } + + const viewport = shadow.getViewport( face ); + + _viewport.set( + _viewportSize.x * viewport.x, + _viewportSize.y * viewport.y, + _viewportSize.x * viewport.z, + _viewportSize.y * viewport.w + ); + + _state.viewport( _viewport ); } - _frustum = shadow.getFrustum(); + _frustum = shadow.getFrustum( face ); - renderObject( scene, camera, shadow.camera, light, this.type ); + renderObject( scene, camera, shadowCamera, light, this.type ); } @@ -393,12 +401,16 @@ function WebGLShadowMap( renderer, objects, capabilities ) { type: HalfFloatType } ); + } else if ( shadow.mapPass.width !== shadow.map.width || shadow.mapPass.height !== shadow.map.height ) { + + shadow.mapPass.setSize( shadow.map.width, shadow.map.height ); + } // vertical pass - read from native depth texture shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.depthTexture; - shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize; + shadowMaterialVertical.uniforms.resolution.value.set( shadow.map.width, shadow.map.height ); shadowMaterialVertical.uniforms.radius.value = shadow.radius; renderer.setRenderTarget( shadow.mapPass ); renderer.clear(); @@ -407,7 +419,7 @@ function WebGLShadowMap( renderer, objects, capabilities ) { // horizontal pass shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture; - shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize; + shadowMaterialHorizontal.uniforms.resolution.value.set( shadow.map.width, shadow.map.height ); shadowMaterialHorizontal.uniforms.radius.value = shadow.radius; renderer.setRenderTarget( shadow.map ); renderer.clear(); diff --git a/test/unit/src/lights/SunLight.tests.js b/test/unit/src/lights/SunLight.tests.js new file mode 100644 index 00000000000000..4aa1c0eb023dad --- /dev/null +++ b/test/unit/src/lights/SunLight.tests.js @@ -0,0 +1,80 @@ +import { SunLight } from '../../../../src/lights/SunLight.js'; + +import { Light } from '../../../../src/lights/Light.js'; +import { ObjectLoader } from '../../../../src/loaders/ObjectLoader.js'; +import { Vector3 } from '../../../../src/math/Vector3.js'; + +export default QUnit.module( 'Lights', () => { + + QUnit.module( 'SunLight', () => { + + // INHERITANCE + QUnit.test( 'Extending', ( assert ) => { + + const object = new SunLight(); + assert.strictEqual( + object instanceof Light, true, + 'SunLight extends from Light' + ); + + } ); + + // INSTANCING + QUnit.test( 'Instancing', ( assert ) => { + + const object = new SunLight(); + assert.ok( object, 'Can instantiate a SunLight.' ); + + } ); + + // PROPERTIES + QUnit.test( 'type', ( assert ) => { + + const object = new SunLight(); + assert.ok( object.type === 'SunLight', 'SunLight.type should be SunLight' ); + + } ); + + QUnit.test( 'shadow', ( assert ) => { + + const object = new SunLight(); + assert.ok( object.shadow.isSunLightShadow, 'SunLight.shadow is a SunLightShadow' ); + + } ); + + // PUBLIC + QUnit.test( 'isSunLight', ( assert ) => { + + const object = new SunLight(); + assert.ok( object.isSunLight, 'SunLight.isSunLight should be true' ); + + } ); + + QUnit.test( 'position', ( assert ) => { + + const object = new SunLight(); + assert.ok( object.position.distanceTo( new Vector3( 0, 1, 0 ) ) < 1e-12, 'Shines straight down by default' ); + + } ); + + // OTHERS + QUnit.test( 'toJSON', ( assert ) => { + + const light = new SunLight( 0xffaa88, 2 ); + light.shadow.bias = 10; + light.position.setFromSphericalCoords( 1, 0.5, 1.2 ); + light.updateMatrix(); + + const json = light.toJSON(); + const newLight = new ObjectLoader().parse( json ); + + assert.ok( newLight.isSunLight, 'Reloaded light is a SunLight' ); + assert.ok( newLight.shadow.isSunLightShadow, 'Reloaded shadow is a SunLightShadow' ); + assert.ok( newLight.position.distanceTo( light.position ) < 1e-6, 'Reloaded light keeps its direction' ); + assert.smartEqual( newLight.shadow, light.shadow, 'Reloaded shadow is identical to the original one' ); + + } ); + + } ); + +} ); diff --git a/test/unit/src/lights/SunLightShadow.tests.js b/test/unit/src/lights/SunLightShadow.tests.js new file mode 100644 index 00000000000000..44cc1b616d6325 --- /dev/null +++ b/test/unit/src/lights/SunLightShadow.tests.js @@ -0,0 +1,271 @@ +import { SunLightShadow } from '../../../../src/lights/SunLightShadow.js'; + +import { LightShadow } from '../../../../src/lights/LightShadow.js'; +import { ObjectLoader } from '../../../../src/loaders/ObjectLoader.js'; +import { SunLight } from '../../../../src/lights/SunLight.js'; +import { PerspectiveCamera } from '../../../../src/cameras/PerspectiveCamera.js'; +import { OrthographicCamera } from '../../../../src/cameras/OrthographicCamera.js'; +import { Vector3 } from '../../../../src/math/Vector3.js'; + +export default QUnit.module( 'Lights', () => { + + QUnit.module( 'SunLightShadow', () => { + + // INHERITANCE + QUnit.test( 'Extending', ( assert ) => { + + const object = new SunLightShadow(); + assert.strictEqual( + object instanceof LightShadow, true, + 'SunLightShadow extends from LightShadow' + ); + + } ); + + // INSTANCING + QUnit.test( 'Instancing', ( assert ) => { + + const object = new SunLightShadow(); + assert.ok( object, 'Can instantiate a SunLightShadow.' ); + + } ); + + // PUBLIC + QUnit.test( 'isSunLightShadow', ( assert ) => { + + const object = new SunLightShadow(); + assert.ok( + object.isSunLightShadow, + 'SunLightShadow.isSunLightShadow should be true' + ); + + } ); + + QUnit.test( 'cascades', ( assert ) => { + + const light = new SunLight(); + const camera = new PerspectiveCamera( 60, 1, 0.1, 100 ); + const shadow = light.shadow; + light.position.setFromSphericalCoords( 1, Math.PI / 2 - 0.9, 0.7 ); + light.updateMatrixWorld(); + camera.updateMatrixWorld(); + + shadow.camera.far = 80; + shadow.updateMatrices( light, camera ); + + assert.strictEqual( shadow.getViewportCount(), 4, 'Creates four cascade viewports' ); + assert.deepEqual( shadow.getFrameExtents().toArray(), [ 2, 2 ], 'Uses a compact atlas layout' ); + assert.strictEqual( shadow._cascadeSplits.length, 5, 'Creates all cascade split boundaries' ); + assert.strictEqual( shadow._cascadeSplits[ 0 ], camera.near, 'Starts at the view camera near plane' ); + assert.strictEqual( shadow._cascadeSplits[ 4 ], shadow.camera.far, 'Ends at the shadow camera far plane' ); + + const orthographicCamera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 100 ); + orthographicCamera.updateMatrixWorld(); + shadow.updateMatrices( light, orthographicCamera ); + assert.ok( shadow._cascadeSplits.every( Number.isFinite ), 'Supports an orthographic view camera with a zero near plane' ); + + const infiniteCamera = new PerspectiveCamera( 60, 1, 0.1, 100 ); + infiniteCamera.projectionMatrix.elements[ 10 ] = - 1; + infiniteCamera.projectionMatrix.elements[ 14 ] = - 2 * infiniteCamera.near; + infiniteCamera.projectionMatrixInverse.copy( infiniteCamera.projectionMatrix ).invert(); + infiniteCamera.far = Infinity; + infiniteCamera.updateMatrixWorld(); + shadow.camera.far = 80; + shadow.updateMatrices( light, infiniteCamera ); + assert.ok( shadow._matrices.every( matrix => matrix.elements.every( Number.isFinite ) ), 'Supports an infinite-far projection matrix' ); + assert.strictEqual( shadow._cascadeSplits[ 4 ], shadow.camera.far, 'Falls back to the shadow camera for a non-finite view far plane' ); + + } ); + + QUnit.test( 'cascade fade', ( assert ) => { + + const light = new SunLight(); + const camera = new PerspectiveCamera( 60, 1, 0.1, 100 ); + const shadow = light.shadow; + light.position.setFromSphericalCoords( 1, Math.PI / 2 - 0.9, 0.7 ); + light.updateMatrixWorld(); + camera.updateMatrixWorld(); + + shadow.camera.far = 80; + shadow.updateMatrices( light, camera ); + + for ( let i = 0; i < 4; i ++ ) { + + const cascade = shadow._cascadeData[ i ]; + + assert.strictEqual( cascade.y, shadow._cascadeSplits[ i + 1 ], `Cascade ${i} ends at its split` ); + assert.ok( cascade.z < cascade.y && cascade.z >= shadow._cascadeSplits[ i ], `Cascade ${i} fades out within its own range` ); + + if ( i === 0 ) assert.ok( cascade.x < 0, 'First cascade is open below the near plane' ); + else assert.strictEqual( cascade.x, shadow._cascadeData[ i - 1 ].z, `Cascade ${i} begins where the previous fade starts` ); + + } + + } ); + + QUnit.test( 'cascade caster margin', ( assert ) => { + + const light = new SunLight(); + const camera = new PerspectiveCamera( 60, 1, 0.1, 100 ); + const shadow = light.shadow; + light.position.setFromSphericalCoords( 1, Math.PI / 2 - 0.9, 0.7 ); + light.updateMatrixWorld(); + camera.updateMatrixWorld(); + shadow.camera.far = 100; + shadow.updateMatrices( light, camera ); + + const lightDirection = light.position.clone().normalize().negate(); + + for ( let i = 0; i < 4; i ++ ) { + + const depth = ( shadow._cascadeSplits[ i ] + shadow._cascadeSplits[ i + 1 ] ) * 0.5; + const caster = new Vector3( 0, 0, - depth ).addScaledVector( lightDirection, - 90 ); + assert.ok( shadow.getFrustum( i ).containsPoint( caster ), `Cascade ${i} covers casters above the view frustum` ); + + } + + } ); + + QUnit.test( 'cascade containment', ( assert ) => { + + const light = new SunLight(); + const camera = new PerspectiveCamera( 60, 1, 0.01, 0.1 ); + const shadow = light.shadow; + light.position.setFromSphericalCoords( 1, Math.PI / 2 - 0.9, 0.7 ); + light.updateMatrixWorld(); + camera.updateMatrixWorld(); + shadow.camera.far = 1; + shadow.updateMatrices( light, camera ); + + for ( let i = 0; i < 4; i ++ ) { + + let containsSlice = true; + + for ( const depth of shadow._cascadeSplits.slice( i, i + 2 ) ) { + + const halfHeight = Math.tan( camera.fov * Math.PI / 360 ) * depth; + + for ( const x of [ - 1, 1 ] ) { + + for ( const y of [ - 1, 1 ] ) { + + containsSlice = containsSlice && shadow.getFrustum( i ).containsPoint( new Vector3( x * halfHeight, y * halfHeight, - depth ) ); + + } + + } + + } + + assert.ok( containsSlice, `Cascade ${i} contains its view slice` ); + + } + + } ); + + QUnit.test( 'cascade stabilization containment', ( assert ) => { + + const light = new SunLight(); + const camera = new PerspectiveCamera( 60, 1, 1, 10 ); + const shadow = light.shadow; + camera.updateMatrixWorld(); + light.position.setFromSphericalCoords( 1, Math.PI / 2 - 0.6, Math.PI / 4 ); + light.updateMatrixWorld(); + + shadow.mapSize.set( 16, 16 ); + shadow.updateMatrices( light, camera ); + + for ( const depth of shadow._cascadeSplits.slice( 0, 2 ) ) { + + const halfHeight = Math.tan( camera.fov * Math.PI / 360 ) * depth; + + for ( const x of [ - 1, 1 ] ) { + + for ( const y of [ - 1, 1 ] ) { + + const corner = new Vector3( x * halfHeight * camera.aspect, y * halfHeight, - depth ).applyMatrix4( camera.matrixWorld ); + assert.ok( shadow.getFrustum( 0 ).containsPoint( corner ), 'Texel stabilization keeps the slice corner inside its cascade' ); + + } + + } + + } + + } ); + + QUnit.test( 'reversed depth cascade containment', ( assert ) => { + + const light = new SunLight(); + const camera = new PerspectiveCamera( 60, 1, 0.1, 100 ); + const shadow = light.shadow; + light.position.setFromSphericalCoords( 1, Math.PI / 2 - 0.9, 0.7 ); + light.updateMatrixWorld(); + camera.updateMatrixWorld(); + + for ( const [ viewReversedDepth, shadowReversedDepth ] of [[ false, false ], [ false, true ], [ true, true ]] ) { + + camera._reversedDepth = viewReversedDepth; + camera.updateProjectionMatrix(); + shadow.camera._reversedDepth = shadowReversedDepth; + shadow.updateMatrices( light, camera ); + + for ( let i = 0; i < 4; i ++ ) { + + const cascadeCamera = shadow.getCamera( i ); + const depth = ( shadow._cascadeSplits[ i ] + shadow._cascadeSplits[ i + 1 ] ) * 0.5; + assert.strictEqual( cascadeCamera.reversedDepth, shadowReversedDepth, `Cascade ${i} uses the shadow map depth convention` ); + assert.ok( shadow.getMatrix( i ).elements.every( Number.isFinite ), `Cascade ${i} has a finite shadow matrix` ); + assert.ok( shadow.getFrustum( i ).containsPoint( new Vector3( 0, 0, - depth ) ), `Cascade ${i} contains its view slice` ); + + } + + } + + } ); + + // OTHERS + QUnit.test( 'clone/copy', ( assert ) => { + + const a = new SunLightShadow(); + const b = new SunLightShadow(); + + assert.notDeepEqual( a, b, 'Newly instanced shadows are not equal' ); + + const c = a.clone(); + assert.smartEqual( a, c, 'Shadows are identical after clone()' ); + + c.mapSize.set( 1024, 1024 ); + assert.notDeepEqual( a, c, 'Shadows are different again after change' ); + + b.copy( a ); + assert.smartEqual( a, b, 'Shadows are identical after copy()' ); + + b.mapSize.set( 512, 512 ); + assert.notDeepEqual( a, b, 'Shadows are different again after change' ); + + } ); + + QUnit.test( 'toJSON', ( assert ) => { + + const light = new SunLight(); + const shadow = light.shadow; + + shadow.bias = 10; + shadow.radius = 5; + shadow.mapSize.set( 1024, 1024 ); + + const json = light.toJSON(); + const newLight = new ObjectLoader().parse( json ); + + assert.ok( newLight.shadow.isSunLightShadow, 'Reloaded shadow is a SunLightShadow' ); + assert.smartEqual( + newLight.shadow, light.shadow, + 'Reloaded shadow is identical to the original one' + ); + + } ); + + } ); + +} ); diff --git a/test/unit/three.source.unit.js b/test/unit/three.source.unit.js index d545b5d81c438c..e4bb31ec642a1f 100644 --- a/test/unit/three.source.unit.js +++ b/test/unit/three.source.unit.js @@ -131,6 +131,8 @@ import './src/helpers/SpotLightHelper.tests.js'; import './src/lights/AmbientLight.tests.js'; import './src/lights/DirectionalLight.tests.js'; import './src/lights/DirectionalLightShadow.tests.js'; +import './src/lights/SunLight.tests.js'; +import './src/lights/SunLightShadow.tests.js'; import './src/lights/HemisphereLight.tests.js'; import './src/lights/Light.tests.js'; import './src/lights/LightProbe.tests.js';