diff --git a/build/three.js b/build/three.js index a04e6e27827d26..32a081840b762e 100644 --- a/build/three.js +++ b/build/three.js @@ -1,40888 +1,40967 @@ (function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : - typeof define === 'function' && define.amd ? define(['exports'], factory) : - (factory((global.THREE = global.THREE || {}))); -}(this, function (exports) { 'use strict'; + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (factory((global.THREE = global.THREE || {}))); +}(this, (function (exports) { 'use strict'; - // Polyfills + // Polyfills - if ( Number.EPSILON === undefined ) { + if ( Number.EPSILON === undefined ) { - Number.EPSILON = Math.pow( 2, - 52 ); + Number.EPSILON = Math.pow( 2, - 52 ); - } - - // - - if ( Math.sign === undefined ) { - - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign - - Math.sign = function ( x ) { - - return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x; - - }; - - } - - if ( Function.prototype.name === undefined ) { - - // Missing in IE9-11. - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name - - Object.defineProperty( Function.prototype, 'name', { - - get: function () { - - return this.toString().match( /^\s*function\s*(\S*)\s*\(/ )[ 1 ]; - - } - - } ); - - } - - if ( Object.assign === undefined ) { - - // Missing in IE. - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign - - ( function () { - - Object.assign = function ( target ) { - - 'use strict'; - - if ( target === undefined || target === null ) { - - throw new TypeError( 'Cannot convert undefined or null to object' ); - - } - - var output = Object( target ); - - for ( var index = 1; index < arguments.length; index ++ ) { - - var source = arguments[ index ]; - - if ( source !== undefined && source !== null ) { - - for ( var nextKey in source ) { - - if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) { - - output[ nextKey ] = source[ nextKey ]; - - } - - } - - } - - } - - return output; - - }; - - } )(); - - } - - /** - * https://github.com/mrdoob/eventdispatcher.js/ - */ - - function EventDispatcher() {} - - Object.assign( EventDispatcher.prototype, { - - addEventListener: function ( type, listener ) { - - if ( this._listeners === undefined ) this._listeners = {}; - - var listeners = this._listeners; - - if ( listeners[ type ] === undefined ) { - - listeners[ type ] = []; - - } - - if ( listeners[ type ].indexOf( listener ) === - 1 ) { - - listeners[ type ].push( listener ); - - } - - }, - - hasEventListener: function ( type, listener ) { - - if ( this._listeners === undefined ) return false; - - var listeners = this._listeners; - - if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) { - - return true; - - } - - return false; - - }, - - removeEventListener: function ( type, listener ) { - - if ( this._listeners === undefined ) return; - - var listeners = this._listeners; - var listenerArray = listeners[ type ]; - - if ( listenerArray !== undefined ) { - - var index = listenerArray.indexOf( listener ); - - if ( index !== - 1 ) { - - listenerArray.splice( index, 1 ); - - } - - } - - }, - - dispatchEvent: function ( event ) { - - if ( this._listeners === undefined ) return; - - var listeners = this._listeners; - var listenerArray = listeners[ event.type ]; - - if ( listenerArray !== undefined ) { - - event.target = this; - - var array = [], i = 0; - var length = listenerArray.length; - - for ( i = 0; i < length; i ++ ) { - - array[ i ] = listenerArray[ i ]; - - } - - for ( i = 0; i < length; i ++ ) { - - array[ i ].call( this, event ); - - } - - } - - } - - } ); - - var REVISION = '80dev'; - var MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 }; - var CullFaceNone = 0; - var CullFaceBack = 1; - var CullFaceFront = 2; - var CullFaceFrontBack = 3; - var FrontFaceDirectionCW = 0; - var FrontFaceDirectionCCW = 1; - var BasicShadowMap = 0; - var PCFShadowMap = 1; - var PCFSoftShadowMap = 2; - var FrontSide = 0; - var BackSide = 1; - var DoubleSide = 2; - var FlatShading = 1; - var SmoothShading = 2; - var NoColors = 0; - var FaceColors = 1; - var VertexColors = 2; - var NoBlending = 0; - var NormalBlending = 1; - var AdditiveBlending = 2; - var SubtractiveBlending = 3; - var MultiplyBlending = 4; - var CustomBlending = 5; - var AddEquation = 100; - var SubtractEquation = 101; - var ReverseSubtractEquation = 102; - var MinEquation = 103; - var MaxEquation = 104; - var ZeroFactor = 200; - var OneFactor = 201; - var SrcColorFactor = 202; - var OneMinusSrcColorFactor = 203; - var SrcAlphaFactor = 204; - var OneMinusSrcAlphaFactor = 205; - var DstAlphaFactor = 206; - var OneMinusDstAlphaFactor = 207; - var DstColorFactor = 208; - var OneMinusDstColorFactor = 209; - var SrcAlphaSaturateFactor = 210; - var NeverDepth = 0; - var AlwaysDepth = 1; - var LessDepth = 2; - var LessEqualDepth = 3; - var EqualDepth = 4; - var GreaterEqualDepth = 5; - var GreaterDepth = 6; - var NotEqualDepth = 7; - var MultiplyOperation = 0; - var MixOperation = 1; - var AddOperation = 2; - var NoToneMapping = 0; - var LinearToneMapping = 1; - var ReinhardToneMapping = 2; - var Uncharted2ToneMapping = 3; - var CineonToneMapping = 4; - var UVMapping = 300; - var CubeReflectionMapping = 301; - var CubeRefractionMapping = 302; - var EquirectangularReflectionMapping = 303; - var EquirectangularRefractionMapping = 304; - var SphericalReflectionMapping = 305; - var CubeUVReflectionMapping = 306; - var CubeUVRefractionMapping = 307; - var RepeatWrapping = 1000; - var ClampToEdgeWrapping = 1001; - var MirroredRepeatWrapping = 1002; - var NearestFilter = 1003; - var NearestMipMapNearestFilter = 1004; - var NearestMipMapLinearFilter = 1005; - var LinearFilter = 1006; - var LinearMipMapNearestFilter = 1007; - var LinearMipMapLinearFilter = 1008; - var UnsignedByteType = 1009; - var ByteType = 1010; - var ShortType = 1011; - var UnsignedShortType = 1012; - var IntType = 1013; - var UnsignedIntType = 1014; - var FloatType = 1015; - var HalfFloatType = 1016; - var UnsignedShort4444Type = 1017; - var UnsignedShort5551Type = 1018; - var UnsignedShort565Type = 1019; - var UnsignedInt248Type = 1020; - var AlphaFormat = 1021; - var RGBFormat = 1022; - var RGBAFormat = 1023; - var LuminanceFormat = 1024; - var LuminanceAlphaFormat = 1025; - var RGBEFormat = RGBAFormat; - var DepthFormat = 1026; - var DepthStencilFormat = 1027; - var RGB_S3TC_DXT1_Format = 2001; - var RGBA_S3TC_DXT1_Format = 2002; - var RGBA_S3TC_DXT3_Format = 2003; - var RGBA_S3TC_DXT5_Format = 2004; - var RGB_PVRTC_4BPPV1_Format = 2100; - var RGB_PVRTC_2BPPV1_Format = 2101; - var RGBA_PVRTC_4BPPV1_Format = 2102; - var RGBA_PVRTC_2BPPV1_Format = 2103; - var RGB_ETC1_Format = 2151; - var LoopOnce = 2200; - var LoopRepeat = 2201; - var LoopPingPong = 2202; - var InterpolateDiscrete = 2300; - var InterpolateLinear = 2301; - var InterpolateSmooth = 2302; - var ZeroCurvatureEnding = 2400; - var ZeroSlopeEnding = 2401; - var WrapAroundEnding = 2402; - var TrianglesDrawMode = 0; - var TriangleStripDrawMode = 1; - var TriangleFanDrawMode = 2; - var LinearEncoding = 3000; - var sRGBEncoding = 3001; - var GammaEncoding = 3007; - var RGBEEncoding = 3002; - var LogLuvEncoding = 3003; - var RGBM7Encoding = 3004; - var RGBM16Encoding = 3005; - var RGBDEncoding = 3006; - var BasicDepthPacking = 3200; - var RGBADepthPacking = 3201; - - /** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - */ - - exports.Math = { - - DEG2RAD: Math.PI / 180, - RAD2DEG: 180 / Math.PI, - - generateUUID: function () { - - // http://www.broofa.com/Tools/Math.uuid.htm - - var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' ); - var uuid = new Array( 36 ); - var rnd = 0, r; - - return function generateUUID() { - - for ( var i = 0; i < 36; i ++ ) { - - if ( i === 8 || i === 13 || i === 18 || i === 23 ) { - - uuid[ i ] = '-'; - - } else if ( i === 14 ) { - - uuid[ i ] = '4'; - - } else { - - if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0; - r = rnd & 0xf; - rnd = rnd >> 4; - uuid[ i ] = chars[ ( i === 19 ) ? ( r & 0x3 ) | 0x8 : r ]; - - } - - } - - return uuid.join( '' ); - - }; + } - }(), + // - clamp: function ( value, min, max ) { + if ( Math.sign === undefined ) { - return Math.max( min, Math.min( max, value ) ); + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign - }, + Math.sign = function ( x ) { - // compute euclidian modulo of m % n - // https://en.wikipedia.org/wiki/Modulo_operation + return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x; - euclideanModulo: function ( n, m ) { + }; - return ( ( n % m ) + m ) % m; + } - }, + if ( Function.prototype.name === undefined ) { - // Linear mapping from range to range + // Missing in IE9-11. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name - mapLinear: function ( x, a1, a2, b1, b2 ) { + Object.defineProperty( Function.prototype, 'name', { - return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 ); + get: function () { - }, + return this.toString().match( /^\s*function\s*(\S*)\s*\(/ )[ 1 ]; - // http://en.wikipedia.org/wiki/Smoothstep + } - smoothstep: function ( x, min, max ) { + } ); - if ( x <= min ) return 0; - if ( x >= max ) return 1; + } - x = ( x - min ) / ( max - min ); + if ( Object.assign === undefined ) { - return x * x * ( 3 - 2 * x ); + // Missing in IE. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign - }, + ( function () { - smootherstep: function ( x, min, max ) { + Object.assign = function ( target ) { - if ( x <= min ) return 0; - if ( x >= max ) return 1; + 'use strict'; - x = ( x - min ) / ( max - min ); + if ( target === undefined || target === null ) { - return x * x * x * ( x * ( x * 6 - 15 ) + 10 ); + throw new TypeError( 'Cannot convert undefined or null to object' ); - }, + } - random16: function () { + var output = Object( target ); - console.warn( 'THREE.Math.random16() has been deprecated. Use Math.random() instead.' ); - return Math.random(); + for ( var index = 1; index < arguments.length; index ++ ) { - }, + var source = arguments[ index ]; - // Random integer from interval + if ( source !== undefined && source !== null ) { - randInt: function ( low, high ) { + for ( var nextKey in source ) { - return low + Math.floor( Math.random() * ( high - low + 1 ) ); + if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) { - }, + output[ nextKey ] = source[ nextKey ]; - // Random float from interval + } - randFloat: function ( low, high ) { + } - return low + Math.random() * ( high - low ); + } - }, + } - // Random float from <-range/2, range/2> interval + return output; - randFloatSpread: function ( range ) { + }; - return range * ( 0.5 - Math.random() ); + } )(); - }, + } - degToRad: function ( degrees ) { + /** + * https://github.com/mrdoob/eventdispatcher.js/ + */ - return degrees * exports.Math.DEG2RAD; + function EventDispatcher() {} - }, + Object.assign( EventDispatcher.prototype, { - radToDeg: function ( radians ) { + addEventListener: function ( type, listener ) { - return radians * exports.Math.RAD2DEG; + if ( this._listeners === undefined ) this._listeners = {}; - }, + var listeners = this._listeners; - isPowerOfTwo: function ( value ) { + if ( listeners[ type ] === undefined ) { - return ( value & ( value - 1 ) ) === 0 && value !== 0; + listeners[ type ] = []; - }, + } - nearestPowerOfTwo: function ( value ) { + if ( listeners[ type ].indexOf( listener ) === - 1 ) { - return Math.pow( 2, Math.round( Math.log( value ) / Math.LN2 ) ); + listeners[ type ].push( listener ); - }, + } - nextPowerOfTwo: function ( value ) { + }, - value --; - value |= value >> 1; - value |= value >> 2; - value |= value >> 4; - value |= value >> 8; - value |= value >> 16; - value ++; + hasEventListener: function ( type, listener ) { - return value; + if ( this._listeners === undefined ) return false; - } + var listeners = this._listeners; - }; + if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) { - /** - * @author mrdoob / http://mrdoob.com/ - * @author philogb / http://blog.thejit.org/ - * @author egraether / http://egraether.com/ - * @author zz85 / http://www.lab4games.net/zz85/blog - */ + return true; - function Vector2( x, y ) { + } - this.x = x || 0; - this.y = y || 0; + return false; - }; + }, - Vector2.prototype = { + removeEventListener: function ( type, listener ) { - constructor: Vector2, + if ( this._listeners === undefined ) return; - isVector2: true, + var listeners = this._listeners; + var listenerArray = listeners[ type ]; - get width() { + if ( listenerArray !== undefined ) { - return this.x; + var index = listenerArray.indexOf( listener ); - }, + if ( index !== - 1 ) { - set width( value ) { + listenerArray.splice( index, 1 ); - this.x = value; + } - }, + } - get height() { + }, - return this.y; + dispatchEvent: function ( event ) { - }, + if ( this._listeners === undefined ) return; - set height( value ) { + var listeners = this._listeners; + var listenerArray = listeners[ event.type ]; - this.y = value; + if ( listenerArray !== undefined ) { - }, + event.target = this; - // + var array = [], i = 0; + var length = listenerArray.length; - set: function ( x, y ) { + for ( i = 0; i < length; i ++ ) { - this.x = x; - this.y = y; + array[ i ] = listenerArray[ i ]; - return this; + } - }, + for ( i = 0; i < length; i ++ ) { - setScalar: function ( scalar ) { + array[ i ].call( this, event ); - this.x = scalar; - this.y = scalar; + } - return this; + } - }, + } - setX: function ( x ) { + } ); + + var REVISION = '80dev'; + var MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 }; + var CullFaceNone = 0; + var CullFaceBack = 1; + var CullFaceFront = 2; + var CullFaceFrontBack = 3; + var FrontFaceDirectionCW = 0; + var FrontFaceDirectionCCW = 1; + var BasicShadowMap = 0; + var PCFShadowMap = 1; + var PCFSoftShadowMap = 2; + var FrontSide = 0; + var BackSide = 1; + var DoubleSide = 2; + var FlatShading = 1; + var SmoothShading = 2; + var NoColors = 0; + var FaceColors = 1; + var VertexColors = 2; + var NoBlending = 0; + var NormalBlending = 1; + var AdditiveBlending = 2; + var SubtractiveBlending = 3; + var MultiplyBlending = 4; + var CustomBlending = 5; + var AddEquation = 100; + var SubtractEquation = 101; + var ReverseSubtractEquation = 102; + var MinEquation = 103; + var MaxEquation = 104; + var ZeroFactor = 200; + var OneFactor = 201; + var SrcColorFactor = 202; + var OneMinusSrcColorFactor = 203; + var SrcAlphaFactor = 204; + var OneMinusSrcAlphaFactor = 205; + var DstAlphaFactor = 206; + var OneMinusDstAlphaFactor = 207; + var DstColorFactor = 208; + var OneMinusDstColorFactor = 209; + var SrcAlphaSaturateFactor = 210; + var NeverDepth = 0; + var AlwaysDepth = 1; + var LessDepth = 2; + var LessEqualDepth = 3; + var EqualDepth = 4; + var GreaterEqualDepth = 5; + var GreaterDepth = 6; + var NotEqualDepth = 7; + var MultiplyOperation = 0; + var MixOperation = 1; + var AddOperation = 2; + var NoToneMapping = 0; + var LinearToneMapping = 1; + var ReinhardToneMapping = 2; + var Uncharted2ToneMapping = 3; + var CineonToneMapping = 4; + var UVMapping = 300; + var CubeReflectionMapping = 301; + var CubeRefractionMapping = 302; + var EquirectangularReflectionMapping = 303; + var EquirectangularRefractionMapping = 304; + var SphericalReflectionMapping = 305; + var CubeUVReflectionMapping = 306; + var CubeUVRefractionMapping = 307; + var RepeatWrapping = 1000; + var ClampToEdgeWrapping = 1001; + var MirroredRepeatWrapping = 1002; + var NearestFilter = 1003; + var NearestMipMapNearestFilter = 1004; + var NearestMipMapLinearFilter = 1005; + var LinearFilter = 1006; + var LinearMipMapNearestFilter = 1007; + var LinearMipMapLinearFilter = 1008; + var UnsignedByteType = 1009; + var ByteType = 1010; + var ShortType = 1011; + var UnsignedShortType = 1012; + var IntType = 1013; + var UnsignedIntType = 1014; + var FloatType = 1015; + var HalfFloatType = 1016; + var UnsignedShort4444Type = 1017; + var UnsignedShort5551Type = 1018; + var UnsignedShort565Type = 1019; + var UnsignedInt248Type = 1020; + var AlphaFormat = 1021; + var RGBFormat = 1022; + var RGBAFormat = 1023; + var LuminanceFormat = 1024; + var LuminanceAlphaFormat = 1025; + var RGBEFormat = RGBAFormat; + var DepthFormat = 1026; + var DepthStencilFormat = 1027; + var RGB_S3TC_DXT1_Format = 2001; + var RGBA_S3TC_DXT1_Format = 2002; + var RGBA_S3TC_DXT3_Format = 2003; + var RGBA_S3TC_DXT5_Format = 2004; + var RGB_PVRTC_4BPPV1_Format = 2100; + var RGB_PVRTC_2BPPV1_Format = 2101; + var RGBA_PVRTC_4BPPV1_Format = 2102; + var RGBA_PVRTC_2BPPV1_Format = 2103; + var RGB_ETC1_Format = 2151; + var LoopOnce = 2200; + var LoopRepeat = 2201; + var LoopPingPong = 2202; + var InterpolateDiscrete = 2300; + var InterpolateLinear = 2301; + var InterpolateSmooth = 2302; + var ZeroCurvatureEnding = 2400; + var ZeroSlopeEnding = 2401; + var WrapAroundEnding = 2402; + var TrianglesDrawMode = 0; + var TriangleStripDrawMode = 1; + var TriangleFanDrawMode = 2; + var LinearEncoding = 3000; + var sRGBEncoding = 3001; + var GammaEncoding = 3007; + var RGBEEncoding = 3002; + var LogLuvEncoding = 3003; + var RGBM7Encoding = 3004; + var RGBM16Encoding = 3005; + var RGBDEncoding = 3006; + var BasicDepthPacking = 3200; + var RGBADepthPacking = 3201; + + /** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + */ + + exports.Math = { + + DEG2RAD: Math.PI / 180, + RAD2DEG: 180 / Math.PI, + + generateUUID: function () { + + // http://www.broofa.com/Tools/Math.uuid.htm + + var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' ); + var uuid = new Array( 36 ); + var rnd = 0, r; + + return function generateUUID() { + + for ( var i = 0; i < 36; i ++ ) { + + if ( i === 8 || i === 13 || i === 18 || i === 23 ) { + + uuid[ i ] = '-'; + + } else if ( i === 14 ) { + + uuid[ i ] = '4'; + + } else { + + if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0; + r = rnd & 0xf; + rnd = rnd >> 4; + uuid[ i ] = chars[ ( i === 19 ) ? ( r & 0x3 ) | 0x8 : r ]; + + } + + } + + return uuid.join( '' ); + + }; + + }(), + + clamp: function ( value, min, max ) { + + return Math.max( min, Math.min( max, value ) ); - this.x = x; + }, - return this; + // compute euclidian modulo of m % n + // https://en.wikipedia.org/wiki/Modulo_operation - }, + euclideanModulo: function ( n, m ) { - setY: function ( y ) { + return ( ( n % m ) + m ) % m; - this.y = y; + }, - return this; + // Linear mapping from range to range - }, + mapLinear: function ( x, a1, a2, b1, b2 ) { - setComponent: function ( index, value ) { + return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 ); - switch ( index ) { + }, - case 0: this.x = value; break; - case 1: this.y = value; break; - default: throw new Error( 'index is out of range: ' + index ); + // http://en.wikipedia.org/wiki/Smoothstep - } + smoothstep: function ( x, min, max ) { - }, + if ( x <= min ) return 0; + if ( x >= max ) return 1; - getComponent: function ( index ) { + x = ( x - min ) / ( max - min ); - switch ( index ) { + return x * x * ( 3 - 2 * x ); - case 0: return this.x; - case 1: return this.y; - default: throw new Error( 'index is out of range: ' + index ); + }, - } + smootherstep: function ( x, min, max ) { - }, + if ( x <= min ) return 0; + if ( x >= max ) return 1; - clone: function () { + x = ( x - min ) / ( max - min ); - return new this.constructor( this.x, this.y ); + return x * x * x * ( x * ( x * 6 - 15 ) + 10 ); - }, + }, - copy: function ( v ) { + random16: function () { - this.x = v.x; - this.y = v.y; + console.warn( 'THREE.Math.random16() has been deprecated. Use Math.random() instead.' ); + return Math.random(); - return this; + }, - }, + // Random integer from interval - add: function ( v, w ) { + randInt: function ( low, high ) { - if ( w !== undefined ) { + return low + Math.floor( Math.random() * ( high - low + 1 ) ); - console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); - return this.addVectors( v, w ); + }, - } + // Random float from interval - this.x += v.x; - this.y += v.y; + randFloat: function ( low, high ) { - return this; + return low + Math.random() * ( high - low ); - }, + }, - addScalar: function ( s ) { + // Random float from <-range/2, range/2> interval - this.x += s; - this.y += s; + randFloatSpread: function ( range ) { - return this; + return range * ( 0.5 - Math.random() ); - }, + }, - addVectors: function ( a, b ) { + degToRad: function ( degrees ) { - this.x = a.x + b.x; - this.y = a.y + b.y; + return degrees * exports.Math.DEG2RAD; - return this; + }, - }, + radToDeg: function ( radians ) { - addScaledVector: function ( v, s ) { + return radians * exports.Math.RAD2DEG; - this.x += v.x * s; - this.y += v.y * s; + }, - return this; + isPowerOfTwo: function ( value ) { - }, + return ( value & ( value - 1 ) ) === 0 && value !== 0; - sub: function ( v, w ) { + }, - if ( w !== undefined ) { + nearestPowerOfTwo: function ( value ) { - console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); - return this.subVectors( v, w ); + return Math.pow( 2, Math.round( Math.log( value ) / Math.LN2 ) ); - } + }, - this.x -= v.x; - this.y -= v.y; + nextPowerOfTwo: function ( value ) { - return this; + value --; + value |= value >> 1; + value |= value >> 2; + value |= value >> 4; + value |= value >> 8; + value |= value >> 16; + value ++; - }, + return value; - subScalar: function ( s ) { + } - this.x -= s; - this.y -= s; + }; - return this; + /** + * @author mrdoob / http://mrdoob.com/ + * @author philogb / http://blog.thejit.org/ + * @author egraether / http://egraether.com/ + * @author zz85 / http://www.lab4games.net/zz85/blog + */ - }, + function Vector2( x, y ) { - subVectors: function ( a, b ) { + this.x = x || 0; + this.y = y || 0; - this.x = a.x - b.x; - this.y = a.y - b.y; + } - return this; + Vector2.prototype = { - }, + constructor: Vector2, - multiply: function ( v ) { + isVector2: true, - this.x *= v.x; - this.y *= v.y; + get width() { - return this; + return this.x; - }, + }, - multiplyScalar: function ( scalar ) { + set width( value ) { - if ( isFinite( scalar ) ) { + this.x = value; - this.x *= scalar; - this.y *= scalar; + }, - } else { + get height() { - this.x = 0; - this.y = 0; + return this.y; - } + }, - return this; + set height( value ) { - }, + this.y = value; - divide: function ( v ) { + }, - this.x /= v.x; - this.y /= v.y; + // - return this; + set: function ( x, y ) { - }, + this.x = x; + this.y = y; - divideScalar: function ( scalar ) { + return this; - return this.multiplyScalar( 1 / scalar ); + }, - }, + setScalar: function ( scalar ) { - min: function ( v ) { + this.x = scalar; + this.y = scalar; - this.x = Math.min( this.x, v.x ); - this.y = Math.min( this.y, v.y ); + return this; - return this; + }, - }, + setX: function ( x ) { - max: function ( v ) { + this.x = x; - this.x = Math.max( this.x, v.x ); - this.y = Math.max( this.y, v.y ); + return this; - return this; + }, - }, + setY: function ( y ) { - clamp: function ( min, max ) { + this.y = y; - // This function assumes min < max, if this assumption isn't true it will not operate correctly + return this; - this.x = Math.max( min.x, Math.min( max.x, this.x ) ); - this.y = Math.max( min.y, Math.min( max.y, this.y ) ); + }, - return this; + setComponent: function ( index, value ) { - }, + switch ( index ) { - clampScalar: function () { + case 0: this.x = value; break; + case 1: this.y = value; break; + default: throw new Error( 'index is out of range: ' + index ); - var min, max; + } - return function clampScalar( minVal, maxVal ) { + }, - if ( min === undefined ) { + getComponent: function ( index ) { - min = new Vector2(); - max = new Vector2(); + switch ( index ) { - } + case 0: return this.x; + case 1: return this.y; + default: throw new Error( 'index is out of range: ' + index ); - min.set( minVal, minVal ); - max.set( maxVal, maxVal ); + } - return this.clamp( min, max ); + }, - }; + clone: function () { - }(), + return new this.constructor( this.x, this.y ); - clampLength: function ( min, max ) { + }, - var length = this.length(); + copy: function ( v ) { - return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length ); + this.x = v.x; + this.y = v.y; - }, + return this; - floor: function () { + }, - this.x = Math.floor( this.x ); - this.y = Math.floor( this.y ); + add: function ( v, w ) { - return this; + if ( w !== undefined ) { - }, + console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); + return this.addVectors( v, w ); - ceil: function () { + } - this.x = Math.ceil( this.x ); - this.y = Math.ceil( this.y ); + this.x += v.x; + this.y += v.y; - return this; + return this; - }, + }, - round: function () { + addScalar: function ( s ) { - this.x = Math.round( this.x ); - this.y = Math.round( this.y ); + this.x += s; + this.y += s; - return this; + return this; - }, + }, - roundToZero: function () { + addVectors: function ( a, b ) { - this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); - this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); + this.x = a.x + b.x; + this.y = a.y + b.y; - return this; + return this; - }, + }, - negate: function () { + addScaledVector: function ( v, s ) { - this.x = - this.x; - this.y = - this.y; + this.x += v.x * s; + this.y += v.y * s; - return this; + return this; - }, + }, - dot: function ( v ) { + sub: function ( v, w ) { - return this.x * v.x + this.y * v.y; + if ( w !== undefined ) { - }, + console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); + return this.subVectors( v, w ); - lengthSq: function () { + } - return this.x * this.x + this.y * this.y; + this.x -= v.x; + this.y -= v.y; - }, + return this; - length: function () { + }, - return Math.sqrt( this.x * this.x + this.y * this.y ); + subScalar: function ( s ) { - }, + this.x -= s; + this.y -= s; - lengthManhattan: function() { + return this; - return Math.abs( this.x ) + Math.abs( this.y ); + }, - }, + subVectors: function ( a, b ) { - normalize: function () { + this.x = a.x - b.x; + this.y = a.y - b.y; - return this.divideScalar( this.length() ); + return this; - }, + }, - angle: function () { + multiply: function ( v ) { - // computes the angle in radians with respect to the positive x-axis + this.x *= v.x; + this.y *= v.y; - var angle = Math.atan2( this.y, this.x ); + return this; - if ( angle < 0 ) angle += 2 * Math.PI; + }, - return angle; + multiplyScalar: function ( scalar ) { - }, + if ( isFinite( scalar ) ) { - distanceTo: function ( v ) { + this.x *= scalar; + this.y *= scalar; - return Math.sqrt( this.distanceToSquared( v ) ); + } else { - }, + this.x = 0; + this.y = 0; - distanceToSquared: function ( v ) { + } - var dx = this.x - v.x, dy = this.y - v.y; - return dx * dx + dy * dy; + return this; - }, + }, - distanceToManhattan: function ( v ) { + divide: function ( v ) { - return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ); + this.x /= v.x; + this.y /= v.y; - }, + return this; - setLength: function ( length ) { + }, - return this.multiplyScalar( length / this.length() ); + divideScalar: function ( scalar ) { - }, + return this.multiplyScalar( 1 / scalar ); - lerp: function ( v, alpha ) { + }, - this.x += ( v.x - this.x ) * alpha; - this.y += ( v.y - this.y ) * alpha; + min: function ( v ) { - return this; + this.x = Math.min( this.x, v.x ); + this.y = Math.min( this.y, v.y ); - }, + return this; - lerpVectors: function ( v1, v2, alpha ) { + }, - return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); + max: function ( v ) { - }, + this.x = Math.max( this.x, v.x ); + this.y = Math.max( this.y, v.y ); - equals: function ( v ) { + return this; - return ( ( v.x === this.x ) && ( v.y === this.y ) ); + }, - }, + clamp: function ( min, max ) { - fromArray: function ( array, offset ) { + // This function assumes min < max, if this assumption isn't true it will not operate correctly - if ( offset === undefined ) offset = 0; + this.x = Math.max( min.x, Math.min( max.x, this.x ) ); + this.y = Math.max( min.y, Math.min( max.y, this.y ) ); - this.x = array[ offset ]; - this.y = array[ offset + 1 ]; + return this; - return this; + }, - }, + clampScalar: function () { - toArray: function ( array, offset ) { + var min, max; - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + return function clampScalar( minVal, maxVal ) { - array[ offset ] = this.x; - array[ offset + 1 ] = this.y; + if ( min === undefined ) { - return array; + min = new Vector2(); + max = new Vector2(); - }, + } - fromAttribute: function ( attribute, index, offset ) { + min.set( minVal, minVal ); + max.set( maxVal, maxVal ); - if ( offset === undefined ) offset = 0; + return this.clamp( min, max ); - index = index * attribute.itemSize + offset; + }; - this.x = attribute.array[ index ]; - this.y = attribute.array[ index + 1 ]; + }(), - return this; + clampLength: function ( min, max ) { - }, + var length = this.length(); - rotateAround: function ( center, angle ) { + return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length ); - var c = Math.cos( angle ), s = Math.sin( angle ); + }, - var x = this.x - center.x; - var y = this.y - center.y; + floor: function () { - this.x = x * c - y * s + center.x; - this.y = x * s + y * c + center.y; + this.x = Math.floor( this.x ); + this.y = Math.floor( this.y ); - return this; + return this; - } + }, - }; + ceil: function () { - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * @author szimek / https://github.com/szimek/ - */ + this.x = Math.ceil( this.x ); + this.y = Math.ceil( this.y ); - function Texture( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) { + return this; - Object.defineProperty( this, 'id', { value: TextureIdCount() } ); + }, - this.uuid = exports.Math.generateUUID(); + round: function () { - this.name = ''; - this.sourceFile = ''; + this.x = Math.round( this.x ); + this.y = Math.round( this.y ); - this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE; - this.mipmaps = []; + return this; - this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING; + }, - this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping; - this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping; + roundToZero: function () { - this.magFilter = magFilter !== undefined ? magFilter : LinearFilter; - this.minFilter = minFilter !== undefined ? minFilter : LinearMipMapLinearFilter; + this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); + this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); - this.anisotropy = anisotropy !== undefined ? anisotropy : 1; + return this; - this.format = format !== undefined ? format : RGBAFormat; - this.type = type !== undefined ? type : UnsignedByteType; + }, - this.offset = new Vector2( 0, 0 ); - this.repeat = new Vector2( 1, 1 ); + negate: function () { - this.generateMipmaps = true; - this.premultiplyAlpha = false; - this.flipY = true; - this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml) + this.x = - this.x; + this.y = - this.y; + return this; - // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap. - // - // Also changing the encoding after already used by a Material will not automatically make the Material - // update. You need to explicitly call Material.needsUpdate to trigger it to recompile. - this.encoding = encoding !== undefined ? encoding : LinearEncoding; + }, - this.version = 0; - this.onUpdate = null; + dot: function ( v ) { - }; + return this.x * v.x + this.y * v.y; - Texture.DEFAULT_IMAGE = undefined; - Texture.DEFAULT_MAPPING = UVMapping; + }, - Texture.prototype = { + lengthSq: function () { - constructor: Texture, + return this.x * this.x + this.y * this.y; - isTexture: true, + }, - set needsUpdate( value ) { + length: function () { - if ( value === true ) this.version ++; + return Math.sqrt( this.x * this.x + this.y * this.y ); - }, + }, - clone: function () { + lengthManhattan: function() { - return new this.constructor().copy( this ); + return Math.abs( this.x ) + Math.abs( this.y ); - }, + }, - copy: function ( source ) { + normalize: function () { - this.image = source.image; - this.mipmaps = source.mipmaps.slice( 0 ); + return this.divideScalar( this.length() ); - this.mapping = source.mapping; + }, - this.wrapS = source.wrapS; - this.wrapT = source.wrapT; + angle: function () { - this.magFilter = source.magFilter; - this.minFilter = source.minFilter; + // computes the angle in radians with respect to the positive x-axis - this.anisotropy = source.anisotropy; + var angle = Math.atan2( this.y, this.x ); - this.format = source.format; - this.type = source.type; + if ( angle < 0 ) angle += 2 * Math.PI; - this.offset.copy( source.offset ); - this.repeat.copy( source.repeat ); + return angle; - this.generateMipmaps = source.generateMipmaps; - this.premultiplyAlpha = source.premultiplyAlpha; - this.flipY = source.flipY; - this.unpackAlignment = source.unpackAlignment; - this.encoding = source.encoding; + }, - return this; + distanceTo: function ( v ) { - }, + return Math.sqrt( this.distanceToSquared( v ) ); - toJSON: function ( meta ) { + }, - if ( meta.textures[ this.uuid ] !== undefined ) { + distanceToSquared: function ( v ) { - return meta.textures[ this.uuid ]; + var dx = this.x - v.x, dy = this.y - v.y; + return dx * dx + dy * dy; - } + }, - function getDataURL( image ) { + distanceToManhattan: function ( v ) { - var canvas; + return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ); - if ( image.toDataURL !== undefined ) { + }, - canvas = image; + setLength: function ( length ) { - } else { + return this.multiplyScalar( length / this.length() ); - canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); - canvas.width = image.width; - canvas.height = image.height; + }, - canvas.getContext( '2d' ).drawImage( image, 0, 0, image.width, image.height ); + lerp: function ( v, alpha ) { - } + this.x += ( v.x - this.x ) * alpha; + this.y += ( v.y - this.y ) * alpha; - if ( canvas.width > 2048 || canvas.height > 2048 ) { + return this; - return canvas.toDataURL( 'image/jpeg', 0.6 ); + }, - } else { + lerpVectors: function ( v1, v2, alpha ) { - return canvas.toDataURL( 'image/png' ); + return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); - } + }, - } + equals: function ( v ) { - var output = { - metadata: { - version: 4.4, - type: 'Texture', - generator: 'Texture.toJSON' - }, + return ( ( v.x === this.x ) && ( v.y === this.y ) ); - uuid: this.uuid, - name: this.name, + }, - mapping: this.mapping, + fromArray: function ( array, offset ) { - repeat: [ this.repeat.x, this.repeat.y ], - offset: [ this.offset.x, this.offset.y ], - wrap: [ this.wrapS, this.wrapT ], + if ( offset === undefined ) offset = 0; - minFilter: this.minFilter, - magFilter: this.magFilter, - anisotropy: this.anisotropy, + this.x = array[ offset ]; + this.y = array[ offset + 1 ]; - flipY: this.flipY - }; + return this; - if ( this.image !== undefined ) { + }, - // TODO: Move to THREE.Image + toArray: function ( array, offset ) { - var image = this.image; + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - if ( image.uuid === undefined ) { + array[ offset ] = this.x; + array[ offset + 1 ] = this.y; - image.uuid = exports.Math.generateUUID(); // UGH + return array; - } + }, - if ( meta.images[ image.uuid ] === undefined ) { + fromAttribute: function ( attribute, index, offset ) { - meta.images[ image.uuid ] = { - uuid: image.uuid, - url: getDataURL( image ) - }; + if ( offset === undefined ) offset = 0; - } + index = index * attribute.itemSize + offset; - output.image = image.uuid; + this.x = attribute.array[ index ]; + this.y = attribute.array[ index + 1 ]; - } + return this; - meta.textures[ this.uuid ] = output; + }, - return output; + rotateAround: function ( center, angle ) { - }, + var c = Math.cos( angle ), s = Math.sin( angle ); - dispose: function () { + var x = this.x - center.x; + var y = this.y - center.y; - this.dispatchEvent( { type: 'dispose' } ); + this.x = x * c - y * s + center.x; + this.y = x * s + y * c + center.y; - }, + return this; - transformUv: function ( uv ) { + } - if ( this.mapping !== UVMapping ) return; + }; - uv.multiply( this.repeat ); - uv.add( this.offset ); + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * @author szimek / https://github.com/szimek/ + */ - if ( uv.x < 0 || uv.x > 1 ) { + function Texture( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) { - switch ( this.wrapS ) { + Object.defineProperty( this, 'id', { value: TextureIdCount() } ); - case RepeatWrapping: + this.uuid = exports.Math.generateUUID(); - uv.x = uv.x - Math.floor( uv.x ); - break; + this.name = ''; + this.sourceFile = ''; - case ClampToEdgeWrapping: + this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE; + this.mipmaps = []; - uv.x = uv.x < 0 ? 0 : 1; - break; + this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING; - case MirroredRepeatWrapping: + this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping; + this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping; - if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) { + this.magFilter = magFilter !== undefined ? magFilter : LinearFilter; + this.minFilter = minFilter !== undefined ? minFilter : LinearMipMapLinearFilter; - uv.x = Math.ceil( uv.x ) - uv.x; + this.anisotropy = anisotropy !== undefined ? anisotropy : 1; - } else { + this.format = format !== undefined ? format : RGBAFormat; + this.type = type !== undefined ? type : UnsignedByteType; - uv.x = uv.x - Math.floor( uv.x ); + this.offset = new Vector2( 0, 0 ); + this.repeat = new Vector2( 1, 1 ); - } - break; + this.generateMipmaps = true; + this.premultiplyAlpha = false; + this.flipY = true; + this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml) - } - } + // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap. + // + // Also changing the encoding after already used by a Material will not automatically make the Material + // update. You need to explicitly call Material.needsUpdate to trigger it to recompile. + this.encoding = encoding !== undefined ? encoding : LinearEncoding; - if ( uv.y < 0 || uv.y > 1 ) { + this.version = 0; + this.onUpdate = null; - switch ( this.wrapT ) { + } - case RepeatWrapping: + Texture.DEFAULT_IMAGE = undefined; + Texture.DEFAULT_MAPPING = UVMapping; - uv.y = uv.y - Math.floor( uv.y ); - break; + Texture.prototype = { - case ClampToEdgeWrapping: + constructor: Texture, - uv.y = uv.y < 0 ? 0 : 1; - break; + isTexture: true, - case MirroredRepeatWrapping: + set needsUpdate( value ) { - if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) { + if ( value === true ) this.version ++; - uv.y = Math.ceil( uv.y ) - uv.y; + }, - } else { + clone: function () { - uv.y = uv.y - Math.floor( uv.y ); + return new this.constructor().copy( this ); - } - break; + }, - } + copy: function ( source ) { - } + this.image = source.image; + this.mipmaps = source.mipmaps.slice( 0 ); - if ( this.flipY ) { + this.mapping = source.mapping; - uv.y = 1 - uv.y; + this.wrapS = source.wrapS; + this.wrapT = source.wrapT; - } + this.magFilter = source.magFilter; + this.minFilter = source.minFilter; - } + this.anisotropy = source.anisotropy; - }; + this.format = source.format; + this.type = source.type; - Object.assign( Texture.prototype, EventDispatcher.prototype ); + this.offset.copy( source.offset ); + this.repeat.copy( source.repeat ); - var count = 0; - function TextureIdCount() { return count++; }; + this.generateMipmaps = source.generateMipmaps; + this.premultiplyAlpha = source.premultiplyAlpha; + this.flipY = source.flipY; + this.unpackAlignment = source.unpackAlignment; + this.encoding = source.encoding; - /** - * @author mrdoob / http://mrdoob.com/ - * @author supereggbert / http://www.paulbrunt.co.uk/ - * @author philogb / http://blog.thejit.org/ - * @author jordi_ros / http://plattsoft.com - * @author D1plo1d / http://github.com/D1plo1d - * @author alteredq / http://alteredqualia.com/ - * @author mikael emtinger / http://gomo.se/ - * @author timknip / http://www.floorplanner.com/ - * @author bhouston / http://clara.io - * @author WestLangley / http://github.com/WestLangley - */ + return this; - function Matrix4() { + }, - this.elements = new Float32Array( [ + toJSON: function ( meta ) { - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 + if ( meta.textures[ this.uuid ] !== undefined ) { - ] ); + return meta.textures[ this.uuid ]; - if ( arguments.length > 0 ) { + } - console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' ); + function getDataURL( image ) { - } + var canvas; - }; + if ( image.toDataURL !== undefined ) { - Matrix4.prototype = { + canvas = image; - constructor: Matrix4, + } else { - isMatrix4: true, + canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); + canvas.width = image.width; + canvas.height = image.height; - set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) { + canvas.getContext( '2d' ).drawImage( image, 0, 0, image.width, image.height ); - var te = this.elements; + } - te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14; - te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24; - te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34; - te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44; + if ( canvas.width > 2048 || canvas.height > 2048 ) { - return this; + return canvas.toDataURL( 'image/jpeg', 0.6 ); - }, + } else { - identity: function () { + return canvas.toDataURL( 'image/png' ); - this.set( + } - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 + } - ); + var output = { + metadata: { + version: 4.4, + type: 'Texture', + generator: 'Texture.toJSON' + }, - return this; + uuid: this.uuid, + name: this.name, - }, + mapping: this.mapping, - clone: function () { + repeat: [ this.repeat.x, this.repeat.y ], + offset: [ this.offset.x, this.offset.y ], + wrap: [ this.wrapS, this.wrapT ], - return new Matrix4().fromArray( this.elements ); + minFilter: this.minFilter, + magFilter: this.magFilter, + anisotropy: this.anisotropy, - }, + flipY: this.flipY + }; - copy: function ( m ) { + if ( this.image !== undefined ) { - this.elements.set( m.elements ); + // TODO: Move to THREE.Image - return this; + var image = this.image; - }, + if ( image.uuid === undefined ) { - copyPosition: function ( m ) { + image.uuid = exports.Math.generateUUID(); // UGH - var te = this.elements; - var me = m.elements; + } - te[ 12 ] = me[ 12 ]; - te[ 13 ] = me[ 13 ]; - te[ 14 ] = me[ 14 ]; + if ( meta.images[ image.uuid ] === undefined ) { - return this; + meta.images[ image.uuid ] = { + uuid: image.uuid, + url: getDataURL( image ) + }; - }, + } - extractBasis: function ( xAxis, yAxis, zAxis ) { + output.image = image.uuid; - xAxis.setFromMatrixColumn( this, 0 ); - yAxis.setFromMatrixColumn( this, 1 ); - zAxis.setFromMatrixColumn( this, 2 ); + } - return this; + meta.textures[ this.uuid ] = output; - }, + return output; - makeBasis: function ( xAxis, yAxis, zAxis ) { + }, - this.set( - xAxis.x, yAxis.x, zAxis.x, 0, - xAxis.y, yAxis.y, zAxis.y, 0, - xAxis.z, yAxis.z, zAxis.z, 0, - 0, 0, 0, 1 - ); + dispose: function () { - return this; + this.dispatchEvent( { type: 'dispose' } ); - }, + }, - extractRotation: function () { + transformUv: function ( uv ) { - var v1; + if ( this.mapping !== UVMapping ) return; - return function extractRotation( m ) { + uv.multiply( this.repeat ); + uv.add( this.offset ); - if ( v1 === undefined ) v1 = new Vector3(); + if ( uv.x < 0 || uv.x > 1 ) { - var te = this.elements; - var me = m.elements; + switch ( this.wrapS ) { - var scaleX = 1 / v1.setFromMatrixColumn( m, 0 ).length(); - var scaleY = 1 / v1.setFromMatrixColumn( m, 1 ).length(); - var scaleZ = 1 / v1.setFromMatrixColumn( m, 2 ).length(); + case RepeatWrapping: - te[ 0 ] = me[ 0 ] * scaleX; - te[ 1 ] = me[ 1 ] * scaleX; - te[ 2 ] = me[ 2 ] * scaleX; + uv.x = uv.x - Math.floor( uv.x ); + break; - te[ 4 ] = me[ 4 ] * scaleY; - te[ 5 ] = me[ 5 ] * scaleY; - te[ 6 ] = me[ 6 ] * scaleY; + case ClampToEdgeWrapping: - te[ 8 ] = me[ 8 ] * scaleZ; - te[ 9 ] = me[ 9 ] * scaleZ; - te[ 10 ] = me[ 10 ] * scaleZ; + uv.x = uv.x < 0 ? 0 : 1; + break; - return this; + case MirroredRepeatWrapping: - }; + if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) { - }(), + uv.x = Math.ceil( uv.x ) - uv.x; - makeRotationFromEuler: function ( euler ) { + } else { - if ( (euler && euler.isEuler) === false ) { + uv.x = uv.x - Math.floor( uv.x ); - console.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' ); + } + break; - } + } - var te = this.elements; + } - var x = euler.x, y = euler.y, z = euler.z; - var a = Math.cos( x ), b = Math.sin( x ); - var c = Math.cos( y ), d = Math.sin( y ); - var e = Math.cos( z ), f = Math.sin( z ); + if ( uv.y < 0 || uv.y > 1 ) { - if ( euler.order === 'XYZ' ) { + switch ( this.wrapT ) { - var ae = a * e, af = a * f, be = b * e, bf = b * f; + case RepeatWrapping: - te[ 0 ] = c * e; - te[ 4 ] = - c * f; - te[ 8 ] = d; + uv.y = uv.y - Math.floor( uv.y ); + break; - te[ 1 ] = af + be * d; - te[ 5 ] = ae - bf * d; - te[ 9 ] = - b * c; + case ClampToEdgeWrapping: - te[ 2 ] = bf - ae * d; - te[ 6 ] = be + af * d; - te[ 10 ] = a * c; + uv.y = uv.y < 0 ? 0 : 1; + break; - } else if ( euler.order === 'YXZ' ) { + case MirroredRepeatWrapping: - var ce = c * e, cf = c * f, de = d * e, df = d * f; + if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) { - te[ 0 ] = ce + df * b; - te[ 4 ] = de * b - cf; - te[ 8 ] = a * d; + uv.y = Math.ceil( uv.y ) - uv.y; - te[ 1 ] = a * f; - te[ 5 ] = a * e; - te[ 9 ] = - b; + } else { - te[ 2 ] = cf * b - de; - te[ 6 ] = df + ce * b; - te[ 10 ] = a * c; + uv.y = uv.y - Math.floor( uv.y ); - } else if ( euler.order === 'ZXY' ) { + } + break; - var ce = c * e, cf = c * f, de = d * e, df = d * f; + } - te[ 0 ] = ce - df * b; - te[ 4 ] = - a * f; - te[ 8 ] = de + cf * b; + } - te[ 1 ] = cf + de * b; - te[ 5 ] = a * e; - te[ 9 ] = df - ce * b; + if ( this.flipY ) { - te[ 2 ] = - a * d; - te[ 6 ] = b; - te[ 10 ] = a * c; + uv.y = 1 - uv.y; - } else if ( euler.order === 'ZYX' ) { + } - var ae = a * e, af = a * f, be = b * e, bf = b * f; + } - te[ 0 ] = c * e; - te[ 4 ] = be * d - af; - te[ 8 ] = ae * d + bf; + }; - te[ 1 ] = c * f; - te[ 5 ] = bf * d + ae; - te[ 9 ] = af * d - be; + Object.assign( Texture.prototype, EventDispatcher.prototype ); - te[ 2 ] = - d; - te[ 6 ] = b * c; - te[ 10 ] = a * c; + var count = 0; + function TextureIdCount() { return count++; }; - } else if ( euler.order === 'YZX' ) { + /** + * @author mrdoob / http://mrdoob.com/ + * @author supereggbert / http://www.paulbrunt.co.uk/ + * @author philogb / http://blog.thejit.org/ + * @author jordi_ros / http://plattsoft.com + * @author D1plo1d / http://github.com/D1plo1d + * @author alteredq / http://alteredqualia.com/ + * @author mikael emtinger / http://gomo.se/ + * @author timknip / http://www.floorplanner.com/ + * @author bhouston / http://clara.io + * @author WestLangley / http://github.com/WestLangley + */ - var ac = a * c, ad = a * d, bc = b * c, bd = b * d; + function Matrix4() { - te[ 0 ] = c * e; - te[ 4 ] = bd - ac * f; - te[ 8 ] = bc * f + ad; + this.elements = new Float32Array( [ - te[ 1 ] = f; - te[ 5 ] = a * e; - te[ 9 ] = - b * e; + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 - te[ 2 ] = - d * e; - te[ 6 ] = ad * f + bc; - te[ 10 ] = ac - bd * f; + ] ); - } else if ( euler.order === 'XZY' ) { + if ( arguments.length > 0 ) { - var ac = a * c, ad = a * d, bc = b * c, bd = b * d; + console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' ); - te[ 0 ] = c * e; - te[ 4 ] = - f; - te[ 8 ] = d * e; + } - te[ 1 ] = ac * f + bd; - te[ 5 ] = a * e; - te[ 9 ] = ad * f - bc; + } - te[ 2 ] = bc * f - ad; - te[ 6 ] = b * e; - te[ 10 ] = bd * f + ac; + Matrix4.prototype = { - } + constructor: Matrix4, - // last column - te[ 3 ] = 0; - te[ 7 ] = 0; - te[ 11 ] = 0; + isMatrix4: true, - // bottom row - te[ 12 ] = 0; - te[ 13 ] = 0; - te[ 14 ] = 0; - te[ 15 ] = 1; + set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) { - return this; + var te = this.elements; - }, + te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14; + te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24; + te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34; + te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44; - makeRotationFromQuaternion: function ( q ) { + return this; - var te = this.elements; + }, - var x = q.x, y = q.y, z = q.z, w = q.w; - var x2 = x + x, y2 = y + y, z2 = z + z; - var xx = x * x2, xy = x * y2, xz = x * z2; - var yy = y * y2, yz = y * z2, zz = z * z2; - var wx = w * x2, wy = w * y2, wz = w * z2; + identity: function () { - te[ 0 ] = 1 - ( yy + zz ); - te[ 4 ] = xy - wz; - te[ 8 ] = xz + wy; + this.set( - te[ 1 ] = xy + wz; - te[ 5 ] = 1 - ( xx + zz ); - te[ 9 ] = yz - wx; + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 - te[ 2 ] = xz - wy; - te[ 6 ] = yz + wx; - te[ 10 ] = 1 - ( xx + yy ); + ); - // last column - te[ 3 ] = 0; - te[ 7 ] = 0; - te[ 11 ] = 0; + return this; - // bottom row - te[ 12 ] = 0; - te[ 13 ] = 0; - te[ 14 ] = 0; - te[ 15 ] = 1; + }, - return this; + clone: function () { - }, + return new Matrix4().fromArray( this.elements ); - lookAt: function () { + }, - var x, y, z; + copy: function ( m ) { - return function lookAt( eye, target, up ) { + this.elements.set( m.elements ); - if ( x === undefined ) { + return this; - x = new Vector3(); - y = new Vector3(); - z = new Vector3(); + }, - } + copyPosition: function ( m ) { - var te = this.elements; + var te = this.elements; + var me = m.elements; - z.subVectors( eye, target ).normalize(); + te[ 12 ] = me[ 12 ]; + te[ 13 ] = me[ 13 ]; + te[ 14 ] = me[ 14 ]; - if ( z.lengthSq() === 0 ) { + return this; - z.z = 1; + }, - } + extractBasis: function ( xAxis, yAxis, zAxis ) { - x.crossVectors( up, z ).normalize(); + xAxis.setFromMatrixColumn( this, 0 ); + yAxis.setFromMatrixColumn( this, 1 ); + zAxis.setFromMatrixColumn( this, 2 ); - if ( x.lengthSq() === 0 ) { + return this; - z.z += 0.0001; - x.crossVectors( up, z ).normalize(); + }, - } + makeBasis: function ( xAxis, yAxis, zAxis ) { - y.crossVectors( z, x ); + this.set( + xAxis.x, yAxis.x, zAxis.x, 0, + xAxis.y, yAxis.y, zAxis.y, 0, + xAxis.z, yAxis.z, zAxis.z, 0, + 0, 0, 0, 1 + ); + return this; - te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x; - te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y; - te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z; + }, - return this; + extractRotation: function () { - }; + var v1; - }(), + return function extractRotation( m ) { - multiply: function ( m, n ) { + if ( v1 === undefined ) v1 = new Vector3(); - if ( n !== undefined ) { + var te = this.elements; + var me = m.elements; - console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' ); - return this.multiplyMatrices( m, n ); + var scaleX = 1 / v1.setFromMatrixColumn( m, 0 ).length(); + var scaleY = 1 / v1.setFromMatrixColumn( m, 1 ).length(); + var scaleZ = 1 / v1.setFromMatrixColumn( m, 2 ).length(); - } + te[ 0 ] = me[ 0 ] * scaleX; + te[ 1 ] = me[ 1 ] * scaleX; + te[ 2 ] = me[ 2 ] * scaleX; - return this.multiplyMatrices( this, m ); + te[ 4 ] = me[ 4 ] * scaleY; + te[ 5 ] = me[ 5 ] * scaleY; + te[ 6 ] = me[ 6 ] * scaleY; - }, + te[ 8 ] = me[ 8 ] * scaleZ; + te[ 9 ] = me[ 9 ] * scaleZ; + te[ 10 ] = me[ 10 ] * scaleZ; - premultiply: function ( m ) { + return this; - return this.multiplyMatrices( m, this ); + }; - }, + }(), - multiplyMatrices: function ( a, b ) { + makeRotationFromEuler: function ( euler ) { - var ae = a.elements; - var be = b.elements; - var te = this.elements; + if ( (euler && euler.isEuler) === false ) { - var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ]; - var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ]; - var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ]; - var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ]; + console.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' ); - var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ]; - var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ]; - var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ]; - var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ]; + } - te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41; - te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42; - te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43; - te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44; + var te = this.elements; - te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41; - te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42; - te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43; - te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44; + var x = euler.x, y = euler.y, z = euler.z; + var a = Math.cos( x ), b = Math.sin( x ); + var c = Math.cos( y ), d = Math.sin( y ); + var e = Math.cos( z ), f = Math.sin( z ); - te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41; - te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42; - te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43; - te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44; + if ( euler.order === 'XYZ' ) { - te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41; - te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42; - te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43; - te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44; + var ae = a * e, af = a * f, be = b * e, bf = b * f; - return this; + te[ 0 ] = c * e; + te[ 4 ] = - c * f; + te[ 8 ] = d; - }, + te[ 1 ] = af + be * d; + te[ 5 ] = ae - bf * d; + te[ 9 ] = - b * c; - multiplyToArray: function ( a, b, r ) { + te[ 2 ] = bf - ae * d; + te[ 6 ] = be + af * d; + te[ 10 ] = a * c; - var te = this.elements; + } else if ( euler.order === 'YXZ' ) { - this.multiplyMatrices( a, b ); + var ce = c * e, cf = c * f, de = d * e, df = d * f; - r[ 0 ] = te[ 0 ]; r[ 1 ] = te[ 1 ]; r[ 2 ] = te[ 2 ]; r[ 3 ] = te[ 3 ]; - r[ 4 ] = te[ 4 ]; r[ 5 ] = te[ 5 ]; r[ 6 ] = te[ 6 ]; r[ 7 ] = te[ 7 ]; - r[ 8 ] = te[ 8 ]; r[ 9 ] = te[ 9 ]; r[ 10 ] = te[ 10 ]; r[ 11 ] = te[ 11 ]; - r[ 12 ] = te[ 12 ]; r[ 13 ] = te[ 13 ]; r[ 14 ] = te[ 14 ]; r[ 15 ] = te[ 15 ]; + te[ 0 ] = ce + df * b; + te[ 4 ] = de * b - cf; + te[ 8 ] = a * d; - return this; + te[ 1 ] = a * f; + te[ 5 ] = a * e; + te[ 9 ] = - b; - }, + te[ 2 ] = cf * b - de; + te[ 6 ] = df + ce * b; + te[ 10 ] = a * c; - multiplyScalar: function ( s ) { + } else if ( euler.order === 'ZXY' ) { - var te = this.elements; + var ce = c * e, cf = c * f, de = d * e, df = d * f; - te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s; - te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s; - te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s; - te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s; + te[ 0 ] = ce - df * b; + te[ 4 ] = - a * f; + te[ 8 ] = de + cf * b; - return this; + te[ 1 ] = cf + de * b; + te[ 5 ] = a * e; + te[ 9 ] = df - ce * b; - }, + te[ 2 ] = - a * d; + te[ 6 ] = b; + te[ 10 ] = a * c; - applyToVector3Array: function () { + } else if ( euler.order === 'ZYX' ) { - var v1; + var ae = a * e, af = a * f, be = b * e, bf = b * f; - return function applyToVector3Array( array, offset, length ) { + te[ 0 ] = c * e; + te[ 4 ] = be * d - af; + te[ 8 ] = ae * d + bf; - if ( v1 === undefined ) v1 = new Vector3(); - if ( offset === undefined ) offset = 0; - if ( length === undefined ) length = array.length; + te[ 1 ] = c * f; + te[ 5 ] = bf * d + ae; + te[ 9 ] = af * d - be; - for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) { + te[ 2 ] = - d; + te[ 6 ] = b * c; + te[ 10 ] = a * c; - v1.fromArray( array, j ); - v1.applyMatrix4( this ); - v1.toArray( array, j ); + } else if ( euler.order === 'YZX' ) { - } + var ac = a * c, ad = a * d, bc = b * c, bd = b * d; - return array; + te[ 0 ] = c * e; + te[ 4 ] = bd - ac * f; + te[ 8 ] = bc * f + ad; - }; + te[ 1 ] = f; + te[ 5 ] = a * e; + te[ 9 ] = - b * e; - }(), + te[ 2 ] = - d * e; + te[ 6 ] = ad * f + bc; + te[ 10 ] = ac - bd * f; - applyToBuffer: function () { + } else if ( euler.order === 'XZY' ) { - var v1; + var ac = a * c, ad = a * d, bc = b * c, bd = b * d; - return function applyToBuffer( buffer, offset, length ) { + te[ 0 ] = c * e; + te[ 4 ] = - f; + te[ 8 ] = d * e; - if ( v1 === undefined ) v1 = new Vector3(); - if ( offset === undefined ) offset = 0; - if ( length === undefined ) length = buffer.length / buffer.itemSize; + te[ 1 ] = ac * f + bd; + te[ 5 ] = a * e; + te[ 9 ] = ad * f - bc; - for ( var i = 0, j = offset; i < length; i ++, j ++ ) { + te[ 2 ] = bc * f - ad; + te[ 6 ] = b * e; + te[ 10 ] = bd * f + ac; - v1.x = buffer.getX( j ); - v1.y = buffer.getY( j ); - v1.z = buffer.getZ( j ); + } - v1.applyMatrix4( this ); + // last column + te[ 3 ] = 0; + te[ 7 ] = 0; + te[ 11 ] = 0; - buffer.setXYZ( v1.x, v1.y, v1.z ); + // bottom row + te[ 12 ] = 0; + te[ 13 ] = 0; + te[ 14 ] = 0; + te[ 15 ] = 1; - } + return this; - return buffer; + }, - }; + makeRotationFromQuaternion: function ( q ) { - }(), + var te = this.elements; - determinant: function () { + var x = q.x, y = q.y, z = q.z, w = q.w; + var x2 = x + x, y2 = y + y, z2 = z + z; + var xx = x * x2, xy = x * y2, xz = x * z2; + var yy = y * y2, yz = y * z2, zz = z * z2; + var wx = w * x2, wy = w * y2, wz = w * z2; - var te = this.elements; + te[ 0 ] = 1 - ( yy + zz ); + te[ 4 ] = xy - wz; + te[ 8 ] = xz + wy; - var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ]; - var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ]; - var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ]; - var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ]; + te[ 1 ] = xy + wz; + te[ 5 ] = 1 - ( xx + zz ); + te[ 9 ] = yz - wx; - //TODO: make this more efficient - //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm ) + te[ 2 ] = xz - wy; + te[ 6 ] = yz + wx; + te[ 10 ] = 1 - ( xx + yy ); - return ( - n41 * ( - + n14 * n23 * n32 - - n13 * n24 * n32 - - n14 * n22 * n33 - + n12 * n24 * n33 - + n13 * n22 * n34 - - n12 * n23 * n34 - ) + - n42 * ( - + n11 * n23 * n34 - - n11 * n24 * n33 - + n14 * n21 * n33 - - n13 * n21 * n34 - + n13 * n24 * n31 - - n14 * n23 * n31 - ) + - n43 * ( - + n11 * n24 * n32 - - n11 * n22 * n34 - - n14 * n21 * n32 - + n12 * n21 * n34 - + n14 * n22 * n31 - - n12 * n24 * n31 - ) + - n44 * ( - - n13 * n22 * n31 - - n11 * n23 * n32 - + n11 * n22 * n33 - + n13 * n21 * n32 - - n12 * n21 * n33 - + n12 * n23 * n31 - ) + // last column + te[ 3 ] = 0; + te[ 7 ] = 0; + te[ 11 ] = 0; - ); + // bottom row + te[ 12 ] = 0; + te[ 13 ] = 0; + te[ 14 ] = 0; + te[ 15 ] = 1; - }, + return this; - transpose: function () { + }, - var te = this.elements; - var tmp; + lookAt: function () { - tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp; - tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp; - tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp; + var x, y, z; - tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp; - tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp; - tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp; + return function lookAt( eye, target, up ) { - return this; + if ( x === undefined ) { - }, + x = new Vector3(); + y = new Vector3(); + z = new Vector3(); - flattenToArrayOffset: function ( array, offset ) { + } - console.warn( "THREE.Matrix3: .flattenToArrayOffset is deprecated " + - "- just use .toArray instead." ); + var te = this.elements; - return this.toArray( array, offset ); + z.subVectors( eye, target ).normalize(); - }, + if ( z.lengthSq() === 0 ) { - getPosition: function () { + z.z = 1; - var v1; + } - return function getPosition() { + x.crossVectors( up, z ).normalize(); - if ( v1 === undefined ) v1 = new Vector3(); - console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' ); + if ( x.lengthSq() === 0 ) { - return v1.setFromMatrixColumn( this, 3 ); + z.z += 0.0001; + x.crossVectors( up, z ).normalize(); - }; + } - }(), + y.crossVectors( z, x ); - setPosition: function ( v ) { - var te = this.elements; + te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x; + te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y; + te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z; - te[ 12 ] = v.x; - te[ 13 ] = v.y; - te[ 14 ] = v.z; + return this; - return this; + }; - }, + }(), - getInverse: function ( m, throwOnDegenerate ) { + multiply: function ( m, n ) { - // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm - var te = this.elements, - me = m.elements, + if ( n !== undefined ) { - n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ], - n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ], - n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ], - n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ], + console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' ); + return this.multiplyMatrices( m, n ); - t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44, - t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44, - t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44, - t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + } - var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14; + return this.multiplyMatrices( this, m ); - if ( det === 0 ) { + }, - var msg = "THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0"; + premultiply: function ( m ) { - if ( throwOnDegenerate || false ) {} else { + return this.multiplyMatrices( m, this ); - console.warn( msg ); + }, - } + multiplyMatrices: function ( a, b ) { - return this.identity(); + var ae = a.elements; + var be = b.elements; + var te = this.elements; - } + var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ]; + var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ]; + var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ]; + var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ]; - var detInv = 1 / det; + var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ]; + var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ]; + var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ]; + var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ]; - te[ 0 ] = t11 * detInv; - te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv; - te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv; - te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv; + te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41; + te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42; + te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43; + te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44; - te[ 4 ] = t12 * detInv; - te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv; - te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv; - te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv; + te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41; + te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42; + te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43; + te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44; - te[ 8 ] = t13 * detInv; - te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv; - te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv; - te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv; + te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41; + te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42; + te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43; + te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44; - te[ 12 ] = t14 * detInv; - te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv; - te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv; - te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv; + te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41; + te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42; + te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43; + te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44; - return this; + return this; - }, + }, - scale: function ( v ) { + multiplyToArray: function ( a, b, r ) { - var te = this.elements; - var x = v.x, y = v.y, z = v.z; + var te = this.elements; - te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z; - te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z; - te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z; - te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z; + this.multiplyMatrices( a, b ); - return this; + r[ 0 ] = te[ 0 ]; r[ 1 ] = te[ 1 ]; r[ 2 ] = te[ 2 ]; r[ 3 ] = te[ 3 ]; + r[ 4 ] = te[ 4 ]; r[ 5 ] = te[ 5 ]; r[ 6 ] = te[ 6 ]; r[ 7 ] = te[ 7 ]; + r[ 8 ] = te[ 8 ]; r[ 9 ] = te[ 9 ]; r[ 10 ] = te[ 10 ]; r[ 11 ] = te[ 11 ]; + r[ 12 ] = te[ 12 ]; r[ 13 ] = te[ 13 ]; r[ 14 ] = te[ 14 ]; r[ 15 ] = te[ 15 ]; - }, + return this; - getMaxScaleOnAxis: function () { + }, - var te = this.elements; + multiplyScalar: function ( s ) { - var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ]; - var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ]; - var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ]; + var te = this.elements; - return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) ); + te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s; + te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s; + te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s; + te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s; - }, + return this; - makeTranslation: function ( x, y, z ) { + }, - this.set( + applyToVector3Array: function () { - 1, 0, 0, x, - 0, 1, 0, y, - 0, 0, 1, z, - 0, 0, 0, 1 + var v1; - ); + return function applyToVector3Array( array, offset, length ) { - return this; + if ( v1 === undefined ) v1 = new Vector3(); + if ( offset === undefined ) offset = 0; + if ( length === undefined ) length = array.length; - }, + for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) { - makeRotationX: function ( theta ) { + v1.fromArray( array, j ); + v1.applyMatrix4( this ); + v1.toArray( array, j ); - var c = Math.cos( theta ), s = Math.sin( theta ); + } - this.set( + return array; - 1, 0, 0, 0, - 0, c, - s, 0, - 0, s, c, 0, - 0, 0, 0, 1 + }; - ); + }(), - return this; + applyToBuffer: function () { - }, + var v1; - makeRotationY: function ( theta ) { + return function applyToBuffer( buffer, offset, length ) { - var c = Math.cos( theta ), s = Math.sin( theta ); + if ( v1 === undefined ) v1 = new Vector3(); + if ( offset === undefined ) offset = 0; + if ( length === undefined ) length = buffer.length / buffer.itemSize; - this.set( + for ( var i = 0, j = offset; i < length; i ++, j ++ ) { - c, 0, s, 0, - 0, 1, 0, 0, - - s, 0, c, 0, - 0, 0, 0, 1 + v1.x = buffer.getX( j ); + v1.y = buffer.getY( j ); + v1.z = buffer.getZ( j ); - ); + v1.applyMatrix4( this ); - return this; + buffer.setXYZ( v1.x, v1.y, v1.z ); - }, + } - makeRotationZ: function ( theta ) { + return buffer; - var c = Math.cos( theta ), s = Math.sin( theta ); + }; - this.set( + }(), - c, - s, 0, 0, - s, c, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 + determinant: function () { - ); + var te = this.elements; - return this; + var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ]; + var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ]; + var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ]; + var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ]; - }, + //TODO: make this more efficient + //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm ) - makeRotationAxis: function ( axis, angle ) { + return ( + n41 * ( + + n14 * n23 * n32 + - n13 * n24 * n32 + - n14 * n22 * n33 + + n12 * n24 * n33 + + n13 * n22 * n34 + - n12 * n23 * n34 + ) + + n42 * ( + + n11 * n23 * n34 + - n11 * n24 * n33 + + n14 * n21 * n33 + - n13 * n21 * n34 + + n13 * n24 * n31 + - n14 * n23 * n31 + ) + + n43 * ( + + n11 * n24 * n32 + - n11 * n22 * n34 + - n14 * n21 * n32 + + n12 * n21 * n34 + + n14 * n22 * n31 + - n12 * n24 * n31 + ) + + n44 * ( + - n13 * n22 * n31 + - n11 * n23 * n32 + + n11 * n22 * n33 + + n13 * n21 * n32 + - n12 * n21 * n33 + + n12 * n23 * n31 + ) - // Based on http://www.gamedev.net/reference/articles/article1199.asp + ); - var c = Math.cos( angle ); - var s = Math.sin( angle ); - var t = 1 - c; - var x = axis.x, y = axis.y, z = axis.z; - var tx = t * x, ty = t * y; + }, - this.set( + transpose: function () { - tx * x + c, tx * y - s * z, tx * z + s * y, 0, - tx * y + s * z, ty * y + c, ty * z - s * x, 0, - tx * z - s * y, ty * z + s * x, t * z * z + c, 0, - 0, 0, 0, 1 + var te = this.elements; + var tmp; - ); + tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp; + tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp; + tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp; - return this; + tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp; + tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp; + tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp; - }, + return this; - makeScale: function ( x, y, z ) { + }, - this.set( + flattenToArrayOffset: function ( array, offset ) { - x, 0, 0, 0, - 0, y, 0, 0, - 0, 0, z, 0, - 0, 0, 0, 1 + console.warn( "THREE.Matrix3: .flattenToArrayOffset is deprecated " + + "- just use .toArray instead." ); - ); + return this.toArray( array, offset ); - return this; + }, - }, + getPosition: function () { - compose: function ( position, quaternion, scale ) { + var v1; - this.makeRotationFromQuaternion( quaternion ); - this.scale( scale ); - this.setPosition( position ); + return function getPosition() { - return this; + if ( v1 === undefined ) v1 = new Vector3(); + console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' ); - }, + return v1.setFromMatrixColumn( this, 3 ); - decompose: function () { + }; - var vector, matrix; + }(), - return function decompose( position, quaternion, scale ) { + setPosition: function ( v ) { - if ( vector === undefined ) { + var te = this.elements; - vector = new Vector3(); - matrix = new Matrix4(); + te[ 12 ] = v.x; + te[ 13 ] = v.y; + te[ 14 ] = v.z; - } + return this; - var te = this.elements; + }, - var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length(); - var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length(); - var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length(); + getInverse: function ( m, throwOnDegenerate ) { - // if determine is negative, we need to invert one scale - var det = this.determinant(); - if ( det < 0 ) { + // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm + var te = this.elements, + me = m.elements, - sx = - sx; + n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ], + n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ], + n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ], + n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ], - } + t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44, + t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44, + t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44, + t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; - position.x = te[ 12 ]; - position.y = te[ 13 ]; - position.z = te[ 14 ]; + var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14; - // scale the rotation part + if ( det === 0 ) { - matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy() + var msg = "THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0"; - var invSX = 1 / sx; - var invSY = 1 / sy; - var invSZ = 1 / sz; + if ( throwOnDegenerate === true ) { - matrix.elements[ 0 ] *= invSX; - matrix.elements[ 1 ] *= invSX; - matrix.elements[ 2 ] *= invSX; + throw new Error( msg ); - matrix.elements[ 4 ] *= invSY; - matrix.elements[ 5 ] *= invSY; - matrix.elements[ 6 ] *= invSY; + } else { - matrix.elements[ 8 ] *= invSZ; - matrix.elements[ 9 ] *= invSZ; - matrix.elements[ 10 ] *= invSZ; + console.warn( msg ); - quaternion.setFromRotationMatrix( matrix ); + } - scale.x = sx; - scale.y = sy; - scale.z = sz; + return this.identity(); - return this; + } - }; + var detInv = 1 / det; - }(), + te[ 0 ] = t11 * detInv; + te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv; + te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv; + te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv; - makeFrustum: function ( left, right, bottom, top, near, far ) { + te[ 4 ] = t12 * detInv; + te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv; + te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv; + te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv; - var te = this.elements; - var x = 2 * near / ( right - left ); - var y = 2 * near / ( top - bottom ); + te[ 8 ] = t13 * detInv; + te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv; + te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv; + te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv; - var a = ( right + left ) / ( right - left ); - var b = ( top + bottom ) / ( top - bottom ); - var c = - ( far + near ) / ( far - near ); - var d = - 2 * far * near / ( far - near ); + te[ 12 ] = t14 * detInv; + te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv; + te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv; + te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv; - te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0; - te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0; - te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d; - te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0; + return this; - return this; + }, - }, + scale: function ( v ) { - makePerspective: function ( fov, aspect, near, far ) { + var te = this.elements; + var x = v.x, y = v.y, z = v.z; - var ymax = near * Math.tan( exports.Math.DEG2RAD * fov * 0.5 ); - var ymin = - ymax; - var xmin = ymin * aspect; - var xmax = ymax * aspect; + te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z; + te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z; + te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z; + te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z; - return this.makeFrustum( xmin, xmax, ymin, ymax, near, far ); + return this; - }, + }, - makeOrthographic: function ( left, right, top, bottom, near, far ) { + getMaxScaleOnAxis: function () { - var te = this.elements; - var w = 1.0 / ( right - left ); - var h = 1.0 / ( top - bottom ); - var p = 1.0 / ( far - near ); + var te = this.elements; - var x = ( right + left ) * w; - var y = ( top + bottom ) * h; - var z = ( far + near ) * p; + var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ]; + var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ]; + var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ]; - te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x; - te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y; - te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z; - te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1; + return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) ); - return this; + }, - }, + makeTranslation: function ( x, y, z ) { - equals: function ( matrix ) { + this.set( - var te = this.elements; - var me = matrix.elements; + 1, 0, 0, x, + 0, 1, 0, y, + 0, 0, 1, z, + 0, 0, 0, 1 - for ( var i = 0; i < 16; i ++ ) { + ); - if ( te[ i ] !== me[ i ] ) return false; + return this; - } + }, - return true; + makeRotationX: function ( theta ) { - }, + var c = Math.cos( theta ), s = Math.sin( theta ); - fromArray: function ( array ) { + this.set( - this.elements.set( array ); + 1, 0, 0, 0, + 0, c, - s, 0, + 0, s, c, 0, + 0, 0, 0, 1 - return this; + ); - }, + return this; - toArray: function ( array, offset ) { + }, - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + makeRotationY: function ( theta ) { - var te = this.elements; + var c = Math.cos( theta ), s = Math.sin( theta ); - array[ offset ] = te[ 0 ]; - array[ offset + 1 ] = te[ 1 ]; - array[ offset + 2 ] = te[ 2 ]; - array[ offset + 3 ] = te[ 3 ]; + this.set( - array[ offset + 4 ] = te[ 4 ]; - array[ offset + 5 ] = te[ 5 ]; - array[ offset + 6 ] = te[ 6 ]; - array[ offset + 7 ] = te[ 7 ]; + c, 0, s, 0, + 0, 1, 0, 0, + - s, 0, c, 0, + 0, 0, 0, 1 - array[ offset + 8 ] = te[ 8 ]; - array[ offset + 9 ] = te[ 9 ]; - array[ offset + 10 ] = te[ 10 ]; - array[ offset + 11 ] = te[ 11 ]; + ); - array[ offset + 12 ] = te[ 12 ]; - array[ offset + 13 ] = te[ 13 ]; - array[ offset + 14 ] = te[ 14 ]; - array[ offset + 15 ] = te[ 15 ]; + return this; - return array; + }, - } + makeRotationZ: function ( theta ) { - }; + var c = Math.cos( theta ), s = Math.sin( theta ); - /** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author WestLangley / http://github.com/WestLangley - * @author bhouston / http://clara.io - */ + this.set( - function Quaternion( x, y, z, w ) { + c, - s, 0, 0, + s, c, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 - this._x = x || 0; - this._y = y || 0; - this._z = z || 0; - this._w = ( w !== undefined ) ? w : 1; + ); - }; + return this; - Quaternion.prototype = { + }, - constructor: Quaternion, + makeRotationAxis: function ( axis, angle ) { - get x () { + // Based on http://www.gamedev.net/reference/articles/article1199.asp - return this._x; + var c = Math.cos( angle ); + var s = Math.sin( angle ); + var t = 1 - c; + var x = axis.x, y = axis.y, z = axis.z; + var tx = t * x, ty = t * y; - }, + this.set( - set x ( value ) { + tx * x + c, tx * y - s * z, tx * z + s * y, 0, + tx * y + s * z, ty * y + c, ty * z - s * x, 0, + tx * z - s * y, ty * z + s * x, t * z * z + c, 0, + 0, 0, 0, 1 - this._x = value; - this.onChangeCallback(); + ); - }, + return this; - get y () { + }, - return this._y; + makeScale: function ( x, y, z ) { - }, + this.set( - set y ( value ) { + x, 0, 0, 0, + 0, y, 0, 0, + 0, 0, z, 0, + 0, 0, 0, 1 - this._y = value; - this.onChangeCallback(); + ); - }, + return this; - get z () { + }, - return this._z; + compose: function ( position, quaternion, scale ) { - }, + this.makeRotationFromQuaternion( quaternion ); + this.scale( scale ); + this.setPosition( position ); - set z ( value ) { + return this; - this._z = value; - this.onChangeCallback(); + }, - }, + decompose: function () { - get w () { + var vector, matrix; - return this._w; + return function decompose( position, quaternion, scale ) { - }, + if ( vector === undefined ) { - set w ( value ) { + vector = new Vector3(); + matrix = new Matrix4(); - this._w = value; - this.onChangeCallback(); + } - }, + var te = this.elements; - set: function ( x, y, z, w ) { + var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length(); + var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length(); + var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length(); - this._x = x; - this._y = y; - this._z = z; - this._w = w; + // if determine is negative, we need to invert one scale + var det = this.determinant(); + if ( det < 0 ) { - this.onChangeCallback(); + sx = - sx; - return this; + } - }, + position.x = te[ 12 ]; + position.y = te[ 13 ]; + position.z = te[ 14 ]; - clone: function () { + // scale the rotation part - return new this.constructor( this._x, this._y, this._z, this._w ); + matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy() - }, + var invSX = 1 / sx; + var invSY = 1 / sy; + var invSZ = 1 / sz; - copy: function ( quaternion ) { + matrix.elements[ 0 ] *= invSX; + matrix.elements[ 1 ] *= invSX; + matrix.elements[ 2 ] *= invSX; - this._x = quaternion.x; - this._y = quaternion.y; - this._z = quaternion.z; - this._w = quaternion.w; + matrix.elements[ 4 ] *= invSY; + matrix.elements[ 5 ] *= invSY; + matrix.elements[ 6 ] *= invSY; - this.onChangeCallback(); + matrix.elements[ 8 ] *= invSZ; + matrix.elements[ 9 ] *= invSZ; + matrix.elements[ 10 ] *= invSZ; - return this; + quaternion.setFromRotationMatrix( matrix ); - }, + scale.x = sx; + scale.y = sy; + scale.z = sz; - setFromEuler: function ( euler, update ) { + return this; - if ( (euler && euler.isEuler) === false ) { + }; - throw new Error( 'THREE.Quaternion: .setFromEuler() now expects a Euler rotation rather than a Vector3 and order.' ); + }(), - } + makeFrustum: function ( left, right, bottom, top, near, far ) { - // http://www.mathworks.com/matlabcentral/fileexchange/ - // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/ - // content/SpinCalc.m + var te = this.elements; + var x = 2 * near / ( right - left ); + var y = 2 * near / ( top - bottom ); - var c1 = Math.cos( euler._x / 2 ); - var c2 = Math.cos( euler._y / 2 ); - var c3 = Math.cos( euler._z / 2 ); - var s1 = Math.sin( euler._x / 2 ); - var s2 = Math.sin( euler._y / 2 ); - var s3 = Math.sin( euler._z / 2 ); + var a = ( right + left ) / ( right - left ); + var b = ( top + bottom ) / ( top - bottom ); + var c = - ( far + near ) / ( far - near ); + var d = - 2 * far * near / ( far - near ); - var order = euler.order; + te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0; + te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0; + te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d; + te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0; - if ( order === 'XYZ' ) { + return this; - this._x = s1 * c2 * c3 + c1 * s2 * s3; - this._y = c1 * s2 * c3 - s1 * c2 * s3; - this._z = c1 * c2 * s3 + s1 * s2 * c3; - this._w = c1 * c2 * c3 - s1 * s2 * s3; + }, - } else if ( order === 'YXZ' ) { + makePerspective: function ( fov, aspect, near, far ) { - this._x = s1 * c2 * c3 + c1 * s2 * s3; - this._y = c1 * s2 * c3 - s1 * c2 * s3; - this._z = c1 * c2 * s3 - s1 * s2 * c3; - this._w = c1 * c2 * c3 + s1 * s2 * s3; + var ymax = near * Math.tan( exports.Math.DEG2RAD * fov * 0.5 ); + var ymin = - ymax; + var xmin = ymin * aspect; + var xmax = ymax * aspect; - } else if ( order === 'ZXY' ) { + return this.makeFrustum( xmin, xmax, ymin, ymax, near, far ); - this._x = s1 * c2 * c3 - c1 * s2 * s3; - this._y = c1 * s2 * c3 + s1 * c2 * s3; - this._z = c1 * c2 * s3 + s1 * s2 * c3; - this._w = c1 * c2 * c3 - s1 * s2 * s3; + }, - } else if ( order === 'ZYX' ) { + makeOrthographic: function ( left, right, top, bottom, near, far ) { - this._x = s1 * c2 * c3 - c1 * s2 * s3; - this._y = c1 * s2 * c3 + s1 * c2 * s3; - this._z = c1 * c2 * s3 - s1 * s2 * c3; - this._w = c1 * c2 * c3 + s1 * s2 * s3; + var te = this.elements; + var w = 1.0 / ( right - left ); + var h = 1.0 / ( top - bottom ); + var p = 1.0 / ( far - near ); - } else if ( order === 'YZX' ) { + var x = ( right + left ) * w; + var y = ( top + bottom ) * h; + var z = ( far + near ) * p; - this._x = s1 * c2 * c3 + c1 * s2 * s3; - this._y = c1 * s2 * c3 + s1 * c2 * s3; - this._z = c1 * c2 * s3 - s1 * s2 * c3; - this._w = c1 * c2 * c3 - s1 * s2 * s3; + te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x; + te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y; + te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z; + te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1; - } else if ( order === 'XZY' ) { + return this; - this._x = s1 * c2 * c3 - c1 * s2 * s3; - this._y = c1 * s2 * c3 - s1 * c2 * s3; - this._z = c1 * c2 * s3 + s1 * s2 * c3; - this._w = c1 * c2 * c3 + s1 * s2 * s3; + }, - } + equals: function ( matrix ) { - if ( update !== false ) this.onChangeCallback(); + var te = this.elements; + var me = matrix.elements; - return this; + for ( var i = 0; i < 16; i ++ ) { - }, + if ( te[ i ] !== me[ i ] ) return false; - setFromAxisAngle: function ( axis, angle ) { + } - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm + return true; - // assumes axis is normalized + }, - var halfAngle = angle / 2, s = Math.sin( halfAngle ); + fromArray: function ( array ) { - this._x = axis.x * s; - this._y = axis.y * s; - this._z = axis.z * s; - this._w = Math.cos( halfAngle ); + this.elements.set( array ); - this.onChangeCallback(); + return this; - return this; + }, - }, + toArray: function ( array, offset ) { - setFromRotationMatrix: function ( m ) { + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm + var te = this.elements; - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + array[ offset ] = te[ 0 ]; + array[ offset + 1 ] = te[ 1 ]; + array[ offset + 2 ] = te[ 2 ]; + array[ offset + 3 ] = te[ 3 ]; - var te = m.elements, + array[ offset + 4 ] = te[ 4 ]; + array[ offset + 5 ] = te[ 5 ]; + array[ offset + 6 ] = te[ 6 ]; + array[ offset + 7 ] = te[ 7 ]; - m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ], - m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ], - m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ], + array[ offset + 8 ] = te[ 8 ]; + array[ offset + 9 ] = te[ 9 ]; + array[ offset + 10 ] = te[ 10 ]; + array[ offset + 11 ] = te[ 11 ]; - trace = m11 + m22 + m33, - s; + array[ offset + 12 ] = te[ 12 ]; + array[ offset + 13 ] = te[ 13 ]; + array[ offset + 14 ] = te[ 14 ]; + array[ offset + 15 ] = te[ 15 ]; - if ( trace > 0 ) { + return array; - s = 0.5 / Math.sqrt( trace + 1.0 ); + } - this._w = 0.25 / s; - this._x = ( m32 - m23 ) * s; - this._y = ( m13 - m31 ) * s; - this._z = ( m21 - m12 ) * s; + }; - } else if ( m11 > m22 && m11 > m33 ) { + /** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + * @author WestLangley / http://github.com/WestLangley + * @author bhouston / http://clara.io + */ - s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 ); + function Quaternion( x, y, z, w ) { - this._w = ( m32 - m23 ) / s; - this._x = 0.25 * s; - this._y = ( m12 + m21 ) / s; - this._z = ( m13 + m31 ) / s; + this._x = x || 0; + this._y = y || 0; + this._z = z || 0; + this._w = ( w !== undefined ) ? w : 1; - } else if ( m22 > m33 ) { + } - s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 ); + Quaternion.prototype = { - this._w = ( m13 - m31 ) / s; - this._x = ( m12 + m21 ) / s; - this._y = 0.25 * s; - this._z = ( m23 + m32 ) / s; + constructor: Quaternion, - } else { + get x () { - s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 ); + return this._x; - this._w = ( m21 - m12 ) / s; - this._x = ( m13 + m31 ) / s; - this._y = ( m23 + m32 ) / s; - this._z = 0.25 * s; + }, - } + set x ( value ) { - this.onChangeCallback(); + this._x = value; + this.onChangeCallback(); - return this; + }, - }, + get y () { - setFromUnitVectors: function () { + return this._y; - // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final + }, - // assumes direction vectors vFrom and vTo are normalized + set y ( value ) { - var v1, r; + this._y = value; + this.onChangeCallback(); - var EPS = 0.000001; + }, - return function setFromUnitVectors( vFrom, vTo ) { + get z () { - if ( v1 === undefined ) v1 = new Vector3(); + return this._z; - r = vFrom.dot( vTo ) + 1; + }, - if ( r < EPS ) { + set z ( value ) { - r = 0; + this._z = value; + this.onChangeCallback(); - if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) { + }, - v1.set( - vFrom.y, vFrom.x, 0 ); + get w () { - } else { + return this._w; - v1.set( 0, - vFrom.z, vFrom.y ); + }, - } + set w ( value ) { - } else { + this._w = value; + this.onChangeCallback(); - v1.crossVectors( vFrom, vTo ); + }, - } + set: function ( x, y, z, w ) { - this._x = v1.x; - this._y = v1.y; - this._z = v1.z; - this._w = r; + this._x = x; + this._y = y; + this._z = z; + this._w = w; - return this.normalize(); + this.onChangeCallback(); - }; + return this; - }(), + }, - inverse: function () { + clone: function () { - return this.conjugate().normalize(); + return new this.constructor( this._x, this._y, this._z, this._w ); - }, + }, - conjugate: function () { + copy: function ( quaternion ) { - this._x *= - 1; - this._y *= - 1; - this._z *= - 1; + this._x = quaternion.x; + this._y = quaternion.y; + this._z = quaternion.z; + this._w = quaternion.w; - this.onChangeCallback(); + this.onChangeCallback(); - return this; + return this; - }, + }, - dot: function ( v ) { + setFromEuler: function ( euler, update ) { - return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w; + if ( (euler && euler.isEuler) === false ) { - }, + throw new Error( 'THREE.Quaternion: .setFromEuler() now expects a Euler rotation rather than a Vector3 and order.' ); - lengthSq: function () { + } - return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; + // http://www.mathworks.com/matlabcentral/fileexchange/ + // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/ + // content/SpinCalc.m - }, + var c1 = Math.cos( euler._x / 2 ); + var c2 = Math.cos( euler._y / 2 ); + var c3 = Math.cos( euler._z / 2 ); + var s1 = Math.sin( euler._x / 2 ); + var s2 = Math.sin( euler._y / 2 ); + var s3 = Math.sin( euler._z / 2 ); - length: function () { + var order = euler.order; - return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w ); + if ( order === 'XYZ' ) { - }, + this._x = s1 * c2 * c3 + c1 * s2 * s3; + this._y = c1 * s2 * c3 - s1 * c2 * s3; + this._z = c1 * c2 * s3 + s1 * s2 * c3; + this._w = c1 * c2 * c3 - s1 * s2 * s3; - normalize: function () { + } else if ( order === 'YXZ' ) { - var l = this.length(); + this._x = s1 * c2 * c3 + c1 * s2 * s3; + this._y = c1 * s2 * c3 - s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s2 * c3; + this._w = c1 * c2 * c3 + s1 * s2 * s3; - if ( l === 0 ) { + } else if ( order === 'ZXY' ) { - this._x = 0; - this._y = 0; - this._z = 0; - this._w = 1; + this._x = s1 * c2 * c3 - c1 * s2 * s3; + this._y = c1 * s2 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 + s1 * s2 * c3; + this._w = c1 * c2 * c3 - s1 * s2 * s3; - } else { + } else if ( order === 'ZYX' ) { - l = 1 / l; + this._x = s1 * c2 * c3 - c1 * s2 * s3; + this._y = c1 * s2 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s2 * c3; + this._w = c1 * c2 * c3 + s1 * s2 * s3; - this._x = this._x * l; - this._y = this._y * l; - this._z = this._z * l; - this._w = this._w * l; + } else if ( order === 'YZX' ) { - } + this._x = s1 * c2 * c3 + c1 * s2 * s3; + this._y = c1 * s2 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s2 * c3; + this._w = c1 * c2 * c3 - s1 * s2 * s3; - this.onChangeCallback(); + } else if ( order === 'XZY' ) { - return this; + this._x = s1 * c2 * c3 - c1 * s2 * s3; + this._y = c1 * s2 * c3 - s1 * c2 * s3; + this._z = c1 * c2 * s3 + s1 * s2 * c3; + this._w = c1 * c2 * c3 + s1 * s2 * s3; - }, + } - multiply: function ( q, p ) { + if ( update !== false ) this.onChangeCallback(); - if ( p !== undefined ) { + return this; - console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' ); - return this.multiplyQuaternions( q, p ); + }, - } + setFromAxisAngle: function ( axis, angle ) { - return this.multiplyQuaternions( this, q ); + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm - }, + // assumes axis is normalized - premultiply: function ( q ) { + var halfAngle = angle / 2, s = Math.sin( halfAngle ); - return this.multiplyQuaternions( q, this ); + this._x = axis.x * s; + this._y = axis.y * s; + this._z = axis.z * s; + this._w = Math.cos( halfAngle ); - }, + this.onChangeCallback(); - multiplyQuaternions: function ( a, b ) { + return this; - // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm + }, - var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w; - var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w; + setFromRotationMatrix: function ( m ) { - this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby; - this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz; - this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx; - this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz; + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm - this.onChangeCallback(); + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - return this; + var te = m.elements, - }, + m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ], + m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ], + m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ], - slerp: function ( qb, t ) { + trace = m11 + m22 + m33, + s; - if ( t === 0 ) return this; - if ( t === 1 ) return this.copy( qb ); + if ( trace > 0 ) { - var x = this._x, y = this._y, z = this._z, w = this._w; + s = 0.5 / Math.sqrt( trace + 1.0 ); - // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/ + this._w = 0.25 / s; + this._x = ( m32 - m23 ) * s; + this._y = ( m13 - m31 ) * s; + this._z = ( m21 - m12 ) * s; - var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z; + } else if ( m11 > m22 && m11 > m33 ) { - if ( cosHalfTheta < 0 ) { + s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 ); - this._w = - qb._w; - this._x = - qb._x; - this._y = - qb._y; - this._z = - qb._z; + this._w = ( m32 - m23 ) / s; + this._x = 0.25 * s; + this._y = ( m12 + m21 ) / s; + this._z = ( m13 + m31 ) / s; - cosHalfTheta = - cosHalfTheta; + } else if ( m22 > m33 ) { - } else { + s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 ); - this.copy( qb ); + this._w = ( m13 - m31 ) / s; + this._x = ( m12 + m21 ) / s; + this._y = 0.25 * s; + this._z = ( m23 + m32 ) / s; - } + } else { - if ( cosHalfTheta >= 1.0 ) { + s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 ); - this._w = w; - this._x = x; - this._y = y; - this._z = z; + this._w = ( m21 - m12 ) / s; + this._x = ( m13 + m31 ) / s; + this._y = ( m23 + m32 ) / s; + this._z = 0.25 * s; - return this; + } - } + this.onChangeCallback(); - var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta ); + return this; - if ( Math.abs( sinHalfTheta ) < 0.001 ) { + }, - this._w = 0.5 * ( w + this._w ); - this._x = 0.5 * ( x + this._x ); - this._y = 0.5 * ( y + this._y ); - this._z = 0.5 * ( z + this._z ); + setFromUnitVectors: function () { - return this; + // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final - } + // assumes direction vectors vFrom and vTo are normalized - var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta ); - var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta, - ratioB = Math.sin( t * halfTheta ) / sinHalfTheta; + var v1, r; - this._w = ( w * ratioA + this._w * ratioB ); - this._x = ( x * ratioA + this._x * ratioB ); - this._y = ( y * ratioA + this._y * ratioB ); - this._z = ( z * ratioA + this._z * ratioB ); + var EPS = 0.000001; - this.onChangeCallback(); + return function setFromUnitVectors( vFrom, vTo ) { - return this; + if ( v1 === undefined ) v1 = new Vector3(); - }, + r = vFrom.dot( vTo ) + 1; - equals: function ( quaternion ) { + if ( r < EPS ) { - return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w ); + r = 0; - }, + if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) { - fromArray: function ( array, offset ) { + v1.set( - vFrom.y, vFrom.x, 0 ); - if ( offset === undefined ) offset = 0; + } else { - this._x = array[ offset ]; - this._y = array[ offset + 1 ]; - this._z = array[ offset + 2 ]; - this._w = array[ offset + 3 ]; + v1.set( 0, - vFrom.z, vFrom.y ); - this.onChangeCallback(); + } - return this; + } else { - }, + v1.crossVectors( vFrom, vTo ); - toArray: function ( array, offset ) { + } - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + this._x = v1.x; + this._y = v1.y; + this._z = v1.z; + this._w = r; - array[ offset ] = this._x; - array[ offset + 1 ] = this._y; - array[ offset + 2 ] = this._z; - array[ offset + 3 ] = this._w; + return this.normalize(); - return array; + }; - }, + }(), - onChange: function ( callback ) { + inverse: function () { - this.onChangeCallback = callback; + return this.conjugate().normalize(); - return this; + }, - }, + conjugate: function () { - onChangeCallback: function () {} + this._x *= - 1; + this._y *= - 1; + this._z *= - 1; - }; + this.onChangeCallback(); - Object.assign( Quaternion, { + return this; - slerp: function( qa, qb, qm, t ) { + }, - return qm.copy( qa ).slerp( qb, t ); + dot: function ( v ) { - }, + return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w; - slerpFlat: function( - dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) { + }, - // fuzz-free, array-based Quaternion SLERP operation + lengthSq: function () { - var x0 = src0[ srcOffset0 + 0 ], - y0 = src0[ srcOffset0 + 1 ], - z0 = src0[ srcOffset0 + 2 ], - w0 = src0[ srcOffset0 + 3 ], + return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; - x1 = src1[ srcOffset1 + 0 ], - y1 = src1[ srcOffset1 + 1 ], - z1 = src1[ srcOffset1 + 2 ], - w1 = src1[ srcOffset1 + 3 ]; + }, - if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) { + length: function () { - var s = 1 - t, + return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w ); - cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1, + }, - dir = ( cos >= 0 ? 1 : - 1 ), - sqrSin = 1 - cos * cos; + normalize: function () { - // Skip the Slerp for tiny steps to avoid numeric problems: - if ( sqrSin > Number.EPSILON ) { + var l = this.length(); - var sin = Math.sqrt( sqrSin ), - len = Math.atan2( sin, cos * dir ); + if ( l === 0 ) { - s = Math.sin( s * len ) / sin; - t = Math.sin( t * len ) / sin; + this._x = 0; + this._y = 0; + this._z = 0; + this._w = 1; - } + } else { - var tDir = t * dir; + l = 1 / l; - x0 = x0 * s + x1 * tDir; - y0 = y0 * s + y1 * tDir; - z0 = z0 * s + z1 * tDir; - w0 = w0 * s + w1 * tDir; + this._x = this._x * l; + this._y = this._y * l; + this._z = this._z * l; + this._w = this._w * l; - // Normalize in case we just did a lerp: - if ( s === 1 - t ) { + } - var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 ); + this.onChangeCallback(); - x0 *= f; - y0 *= f; - z0 *= f; - w0 *= f; + return this; - } + }, - } + multiply: function ( q, p ) { - dst[ dstOffset ] = x0; - dst[ dstOffset + 1 ] = y0; - dst[ dstOffset + 2 ] = z0; - dst[ dstOffset + 3 ] = w0; + if ( p !== undefined ) { - } + console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' ); + return this.multiplyQuaternions( q, p ); - } ); + } - /** - * @author mrdoob / http://mrdoob.com/ - * @author *kile / http://kile.stravaganza.org/ - * @author philogb / http://blog.thejit.org/ - * @author mikael emtinger / http://gomo.se/ - * @author egraether / http://egraether.com/ - * @author WestLangley / http://github.com/WestLangley - */ + return this.multiplyQuaternions( this, q ); - function Vector3( x, y, z ) { + }, - this.x = x || 0; - this.y = y || 0; - this.z = z || 0; + premultiply: function ( q ) { - }; + return this.multiplyQuaternions( q, this ); - Vector3.prototype = { + }, - constructor: Vector3, + multiplyQuaternions: function ( a, b ) { - isVector3: true, + // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm - set: function ( x, y, z ) { + var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w; + var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w; - this.x = x; - this.y = y; - this.z = z; + this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby; + this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz; + this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx; + this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz; - return this; + this.onChangeCallback(); - }, + return this; - setScalar: function ( scalar ) { + }, - this.x = scalar; - this.y = scalar; - this.z = scalar; + slerp: function ( qb, t ) { - return this; + if ( t === 0 ) return this; + if ( t === 1 ) return this.copy( qb ); - }, + var x = this._x, y = this._y, z = this._z, w = this._w; - setX: function ( x ) { + // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/ - this.x = x; + var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z; - return this; + if ( cosHalfTheta < 0 ) { - }, + this._w = - qb._w; + this._x = - qb._x; + this._y = - qb._y; + this._z = - qb._z; - setY: function ( y ) { + cosHalfTheta = - cosHalfTheta; - this.y = y; + } else { - return this; + this.copy( qb ); - }, + } - setZ: function ( z ) { + if ( cosHalfTheta >= 1.0 ) { - this.z = z; + this._w = w; + this._x = x; + this._y = y; + this._z = z; - return this; + return this; - }, + } - setComponent: function ( index, value ) { + var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta ); - switch ( index ) { + if ( Math.abs( sinHalfTheta ) < 0.001 ) { - case 0: this.x = value; break; - case 1: this.y = value; break; - case 2: this.z = value; break; - default: throw new Error( 'index is out of range: ' + index ); + this._w = 0.5 * ( w + this._w ); + this._x = 0.5 * ( x + this._x ); + this._y = 0.5 * ( y + this._y ); + this._z = 0.5 * ( z + this._z ); - } + return this; - }, + } - getComponent: function ( index ) { + var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta ); + var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta, + ratioB = Math.sin( t * halfTheta ) / sinHalfTheta; - switch ( index ) { + this._w = ( w * ratioA + this._w * ratioB ); + this._x = ( x * ratioA + this._x * ratioB ); + this._y = ( y * ratioA + this._y * ratioB ); + this._z = ( z * ratioA + this._z * ratioB ); - case 0: return this.x; - case 1: return this.y; - case 2: return this.z; - default: throw new Error( 'index is out of range: ' + index ); + this.onChangeCallback(); - } + return this; - }, + }, - clone: function () { + equals: function ( quaternion ) { - return new this.constructor( this.x, this.y, this.z ); + return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w ); - }, + }, - copy: function ( v ) { + fromArray: function ( array, offset ) { - this.x = v.x; - this.y = v.y; - this.z = v.z; + if ( offset === undefined ) offset = 0; - return this; + this._x = array[ offset ]; + this._y = array[ offset + 1 ]; + this._z = array[ offset + 2 ]; + this._w = array[ offset + 3 ]; - }, + this.onChangeCallback(); - add: function ( v, w ) { + return this; - if ( w !== undefined ) { + }, - console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); - return this.addVectors( v, w ); + toArray: function ( array, offset ) { - } + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - this.x += v.x; - this.y += v.y; - this.z += v.z; + array[ offset ] = this._x; + array[ offset + 1 ] = this._y; + array[ offset + 2 ] = this._z; + array[ offset + 3 ] = this._w; - return this; + return array; - }, + }, - addScalar: function ( s ) { + onChange: function ( callback ) { - this.x += s; - this.y += s; - this.z += s; + this.onChangeCallback = callback; - return this; + return this; - }, + }, - addVectors: function ( a, b ) { + onChangeCallback: function () {} - this.x = a.x + b.x; - this.y = a.y + b.y; - this.z = a.z + b.z; + }; - return this; + Object.assign( Quaternion, { - }, + slerp: function( qa, qb, qm, t ) { - addScaledVector: function ( v, s ) { + return qm.copy( qa ).slerp( qb, t ); - this.x += v.x * s; - this.y += v.y * s; - this.z += v.z * s; + }, - return this; + slerpFlat: function( + dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) { - }, + // fuzz-free, array-based Quaternion SLERP operation - sub: function ( v, w ) { + var x0 = src0[ srcOffset0 + 0 ], + y0 = src0[ srcOffset0 + 1 ], + z0 = src0[ srcOffset0 + 2 ], + w0 = src0[ srcOffset0 + 3 ], - if ( w !== undefined ) { + x1 = src1[ srcOffset1 + 0 ], + y1 = src1[ srcOffset1 + 1 ], + z1 = src1[ srcOffset1 + 2 ], + w1 = src1[ srcOffset1 + 3 ]; - console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); - return this.subVectors( v, w ); + if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) { - } + var s = 1 - t, - this.x -= v.x; - this.y -= v.y; - this.z -= v.z; + cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1, - return this; + dir = ( cos >= 0 ? 1 : - 1 ), + sqrSin = 1 - cos * cos; - }, + // Skip the Slerp for tiny steps to avoid numeric problems: + if ( sqrSin > Number.EPSILON ) { - subScalar: function ( s ) { + var sin = Math.sqrt( sqrSin ), + len = Math.atan2( sin, cos * dir ); - this.x -= s; - this.y -= s; - this.z -= s; + s = Math.sin( s * len ) / sin; + t = Math.sin( t * len ) / sin; - return this; + } - }, + var tDir = t * dir; - subVectors: function ( a, b ) { + x0 = x0 * s + x1 * tDir; + y0 = y0 * s + y1 * tDir; + z0 = z0 * s + z1 * tDir; + w0 = w0 * s + w1 * tDir; - this.x = a.x - b.x; - this.y = a.y - b.y; - this.z = a.z - b.z; + // Normalize in case we just did a lerp: + if ( s === 1 - t ) { - return this; + var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 ); - }, + x0 *= f; + y0 *= f; + z0 *= f; + w0 *= f; - multiply: function ( v, w ) { + } - if ( w !== undefined ) { + } - console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' ); - return this.multiplyVectors( v, w ); + dst[ dstOffset ] = x0; + dst[ dstOffset + 1 ] = y0; + dst[ dstOffset + 2 ] = z0; + dst[ dstOffset + 3 ] = w0; - } + } - this.x *= v.x; - this.y *= v.y; - this.z *= v.z; + } ); - return this; + /** + * @author mrdoob / http://mrdoob.com/ + * @author *kile / http://kile.stravaganza.org/ + * @author philogb / http://blog.thejit.org/ + * @author mikael emtinger / http://gomo.se/ + * @author egraether / http://egraether.com/ + * @author WestLangley / http://github.com/WestLangley + */ - }, + function Vector3( x, y, z ) { - multiplyScalar: function ( scalar ) { + this.x = x || 0; + this.y = y || 0; + this.z = z || 0; - if ( isFinite( scalar ) ) { + } - this.x *= scalar; - this.y *= scalar; - this.z *= scalar; + Vector3.prototype = { - } else { + constructor: Vector3, - this.x = 0; - this.y = 0; - this.z = 0; + isVector3: true, - } + set: function ( x, y, z ) { - return this; + this.x = x; + this.y = y; + this.z = z; - }, + return this; - multiplyVectors: function ( a, b ) { + }, - this.x = a.x * b.x; - this.y = a.y * b.y; - this.z = a.z * b.z; + setScalar: function ( scalar ) { - return this; + this.x = scalar; + this.y = scalar; + this.z = scalar; - }, + return this; - applyEuler: function () { + }, - var quaternion; + setX: function ( x ) { - return function applyEuler( euler ) { + this.x = x; - if ( (euler && euler.isEuler) === false ) { + return this; - console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' ); + }, - } + setY: function ( y ) { - if ( quaternion === undefined ) quaternion = new Quaternion(); + this.y = y; - return this.applyQuaternion( quaternion.setFromEuler( euler ) ); + return this; - }; + }, - }(), + setZ: function ( z ) { - applyAxisAngle: function () { + this.z = z; - var quaternion; + return this; - return function applyAxisAngle( axis, angle ) { + }, - if ( quaternion === undefined ) quaternion = new Quaternion(); + setComponent: function ( index, value ) { - return this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) ); + switch ( index ) { - }; + case 0: this.x = value; break; + case 1: this.y = value; break; + case 2: this.z = value; break; + default: throw new Error( 'index is out of range: ' + index ); - }(), + } - applyMatrix3: function ( m ) { + }, - var x = this.x, y = this.y, z = this.z; - var e = m.elements; + getComponent: function ( index ) { - this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z; - this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z; - this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z; + switch ( index ) { - return this; + case 0: return this.x; + case 1: return this.y; + case 2: return this.z; + default: throw new Error( 'index is out of range: ' + index ); - }, + } - applyMatrix4: function ( m ) { + }, - // input: THREE.Matrix4 affine matrix + clone: function () { - var x = this.x, y = this.y, z = this.z; - var e = m.elements; + return new this.constructor( this.x, this.y, this.z ); - this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ]; - this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ]; - this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ]; + }, - return this; + copy: function ( v ) { - }, + this.x = v.x; + this.y = v.y; + this.z = v.z; - applyProjection: function ( m ) { + return this; - // input: THREE.Matrix4 projection matrix + }, - var x = this.x, y = this.y, z = this.z; - var e = m.elements; - var d = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); // perspective divide + add: function ( v, w ) { - this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * d; - this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * d; - this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * d; + if ( w !== undefined ) { - return this; + console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); + return this.addVectors( v, w ); - }, + } - applyQuaternion: function ( q ) { + this.x += v.x; + this.y += v.y; + this.z += v.z; - var x = this.x, y = this.y, z = this.z; - var qx = q.x, qy = q.y, qz = q.z, qw = q.w; + return this; - // calculate quat * vector + }, - var ix = qw * x + qy * z - qz * y; - var iy = qw * y + qz * x - qx * z; - var iz = qw * z + qx * y - qy * x; - var iw = - qx * x - qy * y - qz * z; + addScalar: function ( s ) { - // calculate result * inverse quat + this.x += s; + this.y += s; + this.z += s; - this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy; - this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz; - this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx; + return this; - return this; + }, - }, + addVectors: function ( a, b ) { - project: function () { + this.x = a.x + b.x; + this.y = a.y + b.y; + this.z = a.z + b.z; - var matrix; + return this; - return function project( camera ) { + }, - if ( matrix === undefined ) matrix = new Matrix4(); + addScaledVector: function ( v, s ) { - matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) ); - return this.applyProjection( matrix ); + this.x += v.x * s; + this.y += v.y * s; + this.z += v.z * s; - }; + return this; - }(), + }, - unproject: function () { + sub: function ( v, w ) { - var matrix; + if ( w !== undefined ) { - return function unproject( camera ) { + console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); + return this.subVectors( v, w ); - if ( matrix === undefined ) matrix = new Matrix4(); + } - matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) ); - return this.applyProjection( matrix ); + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; - }; + return this; - }(), + }, - transformDirection: function ( m ) { + subScalar: function ( s ) { - // input: THREE.Matrix4 affine matrix - // vector interpreted as a direction + this.x -= s; + this.y -= s; + this.z -= s; - var x = this.x, y = this.y, z = this.z; - var e = m.elements; + return this; - this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z; - this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z; - this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z; + }, - return this.normalize(); + subVectors: function ( a, b ) { - }, + this.x = a.x - b.x; + this.y = a.y - b.y; + this.z = a.z - b.z; - divide: function ( v ) { + return this; - this.x /= v.x; - this.y /= v.y; - this.z /= v.z; + }, - return this; + multiply: function ( v, w ) { - }, + if ( w !== undefined ) { - divideScalar: function ( scalar ) { + console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' ); + return this.multiplyVectors( v, w ); - return this.multiplyScalar( 1 / scalar ); + } - }, + this.x *= v.x; + this.y *= v.y; + this.z *= v.z; - min: function ( v ) { + return this; - this.x = Math.min( this.x, v.x ); - this.y = Math.min( this.y, v.y ); - this.z = Math.min( this.z, v.z ); + }, - return this; + multiplyScalar: function ( scalar ) { - }, + if ( isFinite( scalar ) ) { - max: function ( v ) { + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; - this.x = Math.max( this.x, v.x ); - this.y = Math.max( this.y, v.y ); - this.z = Math.max( this.z, v.z ); + } else { - return this; + this.x = 0; + this.y = 0; + this.z = 0; - }, + } - clamp: function ( min, max ) { + return this; - // This function assumes min < max, if this assumption isn't true it will not operate correctly + }, - this.x = Math.max( min.x, Math.min( max.x, this.x ) ); - this.y = Math.max( min.y, Math.min( max.y, this.y ) ); - this.z = Math.max( min.z, Math.min( max.z, this.z ) ); + multiplyVectors: function ( a, b ) { - return this; + this.x = a.x * b.x; + this.y = a.y * b.y; + this.z = a.z * b.z; - }, + return this; - clampScalar: function () { + }, - var min, max; + applyEuler: function () { - return function clampScalar( minVal, maxVal ) { + var quaternion; - if ( min === undefined ) { + return function applyEuler( euler ) { - min = new Vector3(); - max = new Vector3(); + if ( (euler && euler.isEuler) === false ) { - } + console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' ); - min.set( minVal, minVal, minVal ); - max.set( maxVal, maxVal, maxVal ); + } - return this.clamp( min, max ); + if ( quaternion === undefined ) quaternion = new Quaternion(); - }; + return this.applyQuaternion( quaternion.setFromEuler( euler ) ); - }(), + }; - clampLength: function ( min, max ) { + }(), - var length = this.length(); + applyAxisAngle: function () { - return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length ); + var quaternion; - }, + return function applyAxisAngle( axis, angle ) { - floor: function () { + if ( quaternion === undefined ) quaternion = new Quaternion(); - this.x = Math.floor( this.x ); - this.y = Math.floor( this.y ); - this.z = Math.floor( this.z ); + return this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) ); - return this; + }; - }, + }(), - ceil: function () { + applyMatrix3: function ( m ) { - this.x = Math.ceil( this.x ); - this.y = Math.ceil( this.y ); - this.z = Math.ceil( this.z ); + var x = this.x, y = this.y, z = this.z; + var e = m.elements; - return this; + this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z; + this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z; + this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z; - }, + return this; - round: function () { + }, - this.x = Math.round( this.x ); - this.y = Math.round( this.y ); - this.z = Math.round( this.z ); + applyMatrix4: function ( m ) { - return this; + // input: THREE.Matrix4 affine matrix - }, + var x = this.x, y = this.y, z = this.z; + var e = m.elements; - roundToZero: function () { + this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ]; + this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ]; + this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ]; - this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); - this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); - this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z ); + return this; - return this; + }, - }, + applyProjection: function ( m ) { - negate: function () { + // input: THREE.Matrix4 projection matrix - this.x = - this.x; - this.y = - this.y; - this.z = - this.z; + var x = this.x, y = this.y, z = this.z; + var e = m.elements; + var d = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); // perspective divide - return this; + this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * d; + this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * d; + this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * d; - }, + return this; - dot: function ( v ) { + }, - return this.x * v.x + this.y * v.y + this.z * v.z; + applyQuaternion: function ( q ) { - }, + var x = this.x, y = this.y, z = this.z; + var qx = q.x, qy = q.y, qz = q.z, qw = q.w; - lengthSq: function () { + // calculate quat * vector - return this.x * this.x + this.y * this.y + this.z * this.z; + var ix = qw * x + qy * z - qz * y; + var iy = qw * y + qz * x - qx * z; + var iz = qw * z + qx * y - qy * x; + var iw = - qx * x - qy * y - qz * z; - }, + // calculate result * inverse quat - length: function () { + this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy; + this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz; + this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx; - return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z ); + return this; - }, + }, - lengthManhattan: function () { + project: function () { - return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ); + var matrix; - }, + return function project( camera ) { - normalize: function () { + if ( matrix === undefined ) matrix = new Matrix4(); - return this.divideScalar( this.length() ); + matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) ); + return this.applyProjection( matrix ); - }, + }; - setLength: function ( length ) { + }(), - return this.multiplyScalar( length / this.length() ); + unproject: function () { - }, + var matrix; - lerp: function ( v, alpha ) { + return function unproject( camera ) { - this.x += ( v.x - this.x ) * alpha; - this.y += ( v.y - this.y ) * alpha; - this.z += ( v.z - this.z ) * alpha; + if ( matrix === undefined ) matrix = new Matrix4(); - return this; + matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) ); + return this.applyProjection( matrix ); - }, + }; - lerpVectors: function ( v1, v2, alpha ) { + }(), - return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); + transformDirection: function ( m ) { - }, + // input: THREE.Matrix4 affine matrix + // vector interpreted as a direction - cross: function ( v, w ) { + var x = this.x, y = this.y, z = this.z; + var e = m.elements; - if ( w !== undefined ) { + this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z; + this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z; + this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z; - console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' ); - return this.crossVectors( v, w ); + return this.normalize(); - } + }, - var x = this.x, y = this.y, z = this.z; + divide: function ( v ) { - this.x = y * v.z - z * v.y; - this.y = z * v.x - x * v.z; - this.z = x * v.y - y * v.x; + this.x /= v.x; + this.y /= v.y; + this.z /= v.z; - return this; + return this; - }, + }, - crossVectors: function ( a, b ) { + divideScalar: function ( scalar ) { - var ax = a.x, ay = a.y, az = a.z; - var bx = b.x, by = b.y, bz = b.z; + return this.multiplyScalar( 1 / scalar ); - this.x = ay * bz - az * by; - this.y = az * bx - ax * bz; - this.z = ax * by - ay * bx; + }, - return this; + min: function ( v ) { - }, + this.x = Math.min( this.x, v.x ); + this.y = Math.min( this.y, v.y ); + this.z = Math.min( this.z, v.z ); - projectOnVector: function ( vector ) { + return this; - var scalar = vector.dot( this ) / vector.lengthSq(); + }, - return this.copy( vector ).multiplyScalar( scalar ); + max: function ( v ) { - }, + this.x = Math.max( this.x, v.x ); + this.y = Math.max( this.y, v.y ); + this.z = Math.max( this.z, v.z ); - projectOnPlane: function () { + return this; - var v1; + }, - return function projectOnPlane( planeNormal ) { + clamp: function ( min, max ) { - if ( v1 === undefined ) v1 = new Vector3(); + // This function assumes min < max, if this assumption isn't true it will not operate correctly - v1.copy( this ).projectOnVector( planeNormal ); + this.x = Math.max( min.x, Math.min( max.x, this.x ) ); + this.y = Math.max( min.y, Math.min( max.y, this.y ) ); + this.z = Math.max( min.z, Math.min( max.z, this.z ) ); - return this.sub( v1 ); + return this; - }; + }, - }(), + clampScalar: function () { - reflect: function () { + var min, max; - // reflect incident vector off plane orthogonal to normal - // normal is assumed to have unit length + return function clampScalar( minVal, maxVal ) { - var v1; + if ( min === undefined ) { - return function reflect( normal ) { + min = new Vector3(); + max = new Vector3(); - if ( v1 === undefined ) v1 = new Vector3(); + } - return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) ); + min.set( minVal, minVal, minVal ); + max.set( maxVal, maxVal, maxVal ); - }; + return this.clamp( min, max ); - }(), + }; - angleTo: function ( v ) { + }(), - var theta = this.dot( v ) / ( Math.sqrt( this.lengthSq() * v.lengthSq() ) ); + clampLength: function ( min, max ) { - // clamp, to handle numerical problems + var length = this.length(); - return Math.acos( exports.Math.clamp( theta, - 1, 1 ) ); + return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length ); - }, + }, - distanceTo: function ( v ) { + floor: function () { - return Math.sqrt( this.distanceToSquared( v ) ); + this.x = Math.floor( this.x ); + this.y = Math.floor( this.y ); + this.z = Math.floor( this.z ); - }, + return this; - distanceToSquared: function ( v ) { + }, - var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z; + ceil: function () { - return dx * dx + dy * dy + dz * dz; + this.x = Math.ceil( this.x ); + this.y = Math.ceil( this.y ); + this.z = Math.ceil( this.z ); - }, + return this; - distanceToManhattan: function ( v ) { + }, - return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z ); + round: function () { - }, + this.x = Math.round( this.x ); + this.y = Math.round( this.y ); + this.z = Math.round( this.z ); - setFromSpherical: function( s ) { + return this; - var sinPhiRadius = Math.sin( s.phi ) * s.radius; + }, - this.x = sinPhiRadius * Math.sin( s.theta ); - this.y = Math.cos( s.phi ) * s.radius; - this.z = sinPhiRadius * Math.cos( s.theta ); + roundToZero: function () { - return this; + this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); + this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); + this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z ); - }, + return this; - setFromMatrixPosition: function ( m ) { + }, - return this.setFromMatrixColumn( m, 3 ); + negate: function () { - }, + this.x = - this.x; + this.y = - this.y; + this.z = - this.z; - setFromMatrixScale: function ( m ) { + return this; - var sx = this.setFromMatrixColumn( m, 0 ).length(); - var sy = this.setFromMatrixColumn( m, 1 ).length(); - var sz = this.setFromMatrixColumn( m, 2 ).length(); + }, - this.x = sx; - this.y = sy; - this.z = sz; + dot: function ( v ) { - return this; + return this.x * v.x + this.y * v.y + this.z * v.z; - }, + }, - setFromMatrixColumn: function ( m, index ) { + lengthSq: function () { - if ( typeof m === 'number' ) { + return this.x * this.x + this.y * this.y + this.z * this.z; - console.warn( 'THREE.Vector3: setFromMatrixColumn now expects ( matrix, index ).' ); - var temp = m - m = index; - index = temp; + }, - } + length: function () { - return this.fromArray( m.elements, index * 4 ); + return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z ); - }, + }, - equals: function ( v ) { + lengthManhattan: function () { - return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) ); + return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ); - }, + }, - fromArray: function ( array, offset ) { + normalize: function () { - if ( offset === undefined ) offset = 0; + return this.divideScalar( this.length() ); - this.x = array[ offset ]; - this.y = array[ offset + 1 ]; - this.z = array[ offset + 2 ]; + }, - return this; + setLength: function ( length ) { - }, + return this.multiplyScalar( length / this.length() ); - toArray: function ( array, offset ) { + }, - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + lerp: function ( v, alpha ) { - array[ offset ] = this.x; - array[ offset + 1 ] = this.y; - array[ offset + 2 ] = this.z; + this.x += ( v.x - this.x ) * alpha; + this.y += ( v.y - this.y ) * alpha; + this.z += ( v.z - this.z ) * alpha; - return array; + return this; - }, + }, - fromAttribute: function ( attribute, index, offset ) { + lerpVectors: function ( v1, v2, alpha ) { - if ( offset === undefined ) offset = 0; + return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); - index = index * attribute.itemSize + offset; + }, - this.x = attribute.array[ index ]; - this.y = attribute.array[ index + 1 ]; - this.z = attribute.array[ index + 2 ]; + cross: function ( v, w ) { - return this; + if ( w !== undefined ) { - } + console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' ); + return this.crossVectors( v, w ); - }; + } - /** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - */ + var x = this.x, y = this.y, z = this.z; - function SpritePlugin( renderer, sprites ) { + this.x = y * v.z - z * v.y; + this.y = z * v.x - x * v.z; + this.z = x * v.y - y * v.x; - var gl = renderer.context; - var state = renderer.state; + return this; - var vertexBuffer, elementBuffer; - var program, attributes, uniforms; + }, - var texture; + crossVectors: function ( a, b ) { - // decompose matrixWorld + var ax = a.x, ay = a.y, az = a.z; + var bx = b.x, by = b.y, bz = b.z; - var spritePosition = new Vector3(); - var spriteRotation = new Quaternion(); - var spriteScale = new Vector3(); + this.x = ay * bz - az * by; + this.y = az * bx - ax * bz; + this.z = ax * by - ay * bx; - function init() { + return this; - var vertices = new Float32Array( [ - - 0.5, - 0.5, 0, 0, - 0.5, - 0.5, 1, 0, - 0.5, 0.5, 1, 1, - - 0.5, 0.5, 0, 1 - ] ); + }, - var faces = new Uint16Array( [ - 0, 1, 2, - 0, 2, 3 - ] ); + projectOnVector: function ( vector ) { - vertexBuffer = gl.createBuffer(); - elementBuffer = gl.createBuffer(); + var scalar = vector.dot( this ) / vector.lengthSq(); - gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer ); - gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW ); + return this.copy( vector ).multiplyScalar( scalar ); - gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); - gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW ); + }, - program = createProgram(); + projectOnPlane: function () { - attributes = { - position: gl.getAttribLocation ( program, 'position' ), - uv: gl.getAttribLocation ( program, 'uv' ) - }; + var v1; - uniforms = { - uvOffset: gl.getUniformLocation( program, 'uvOffset' ), - uvScale: gl.getUniformLocation( program, 'uvScale' ), + return function projectOnPlane( planeNormal ) { - rotation: gl.getUniformLocation( program, 'rotation' ), - scale: gl.getUniformLocation( program, 'scale' ), + if ( v1 === undefined ) v1 = new Vector3(); - color: gl.getUniformLocation( program, 'color' ), - map: gl.getUniformLocation( program, 'map' ), - opacity: gl.getUniformLocation( program, 'opacity' ), + v1.copy( this ).projectOnVector( planeNormal ); - modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ), - projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ), + return this.sub( v1 ); - fogType: gl.getUniformLocation( program, 'fogType' ), - fogDensity: gl.getUniformLocation( program, 'fogDensity' ), - fogNear: gl.getUniformLocation( program, 'fogNear' ), - fogFar: gl.getUniformLocation( program, 'fogFar' ), - fogColor: gl.getUniformLocation( program, 'fogColor' ), + }; - alphaTest: gl.getUniformLocation( program, 'alphaTest' ) - }; + }(), - var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); - canvas.width = 8; - canvas.height = 8; + reflect: function () { - var context = canvas.getContext( '2d' ); - context.fillStyle = 'white'; - context.fillRect( 0, 0, 8, 8 ); + // reflect incident vector off plane orthogonal to normal + // normal is assumed to have unit length - texture = new Texture( canvas ); - texture.needsUpdate = true; + var v1; - } + return function reflect( normal ) { - this.render = function ( scene, camera ) { + if ( v1 === undefined ) v1 = new Vector3(); - if ( sprites.length === 0 ) return; + return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) ); - // setup gl + }; - if ( program === undefined ) { + }(), - init(); + angleTo: function ( v ) { - } + var theta = this.dot( v ) / ( Math.sqrt( this.lengthSq() * v.lengthSq() ) ); - gl.useProgram( program ); + // clamp, to handle numerical problems - state.initAttributes(); - state.enableAttribute( attributes.position ); - state.enableAttribute( attributes.uv ); - state.disableUnusedAttributes(); + return Math.acos( exports.Math.clamp( theta, - 1, 1 ) ); - state.disable( gl.CULL_FACE ); - state.enable( gl.BLEND ); + }, - gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer ); - gl.vertexAttribPointer( attributes.position, 2, gl.FLOAT, false, 2 * 8, 0 ); - gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 ); + distanceTo: function ( v ) { - gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); + return Math.sqrt( this.distanceToSquared( v ) ); - gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements ); + }, - state.activeTexture( gl.TEXTURE0 ); - gl.uniform1i( uniforms.map, 0 ); + distanceToSquared: function ( v ) { - var oldFogType = 0; - var sceneFogType = 0; - var fog = scene.fog; + var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z; - if ( fog ) { + return dx * dx + dy * dy + dz * dz; - gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b ); + }, - if ( (fog && fog.isFog) ) { + distanceToManhattan: function ( v ) { - gl.uniform1f( uniforms.fogNear, fog.near ); - gl.uniform1f( uniforms.fogFar, fog.far ); + return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z ); - gl.uniform1i( uniforms.fogType, 1 ); - oldFogType = 1; - sceneFogType = 1; + }, - } else if ( (fog && fog.isFogExp2) ) { + setFromSpherical: function( s ) { - gl.uniform1f( uniforms.fogDensity, fog.density ); + var sinPhiRadius = Math.sin( s.phi ) * s.radius; - gl.uniform1i( uniforms.fogType, 2 ); - oldFogType = 2; - sceneFogType = 2; + this.x = sinPhiRadius * Math.sin( s.theta ); + this.y = Math.cos( s.phi ) * s.radius; + this.z = sinPhiRadius * Math.cos( s.theta ); - } + return this; - } else { + }, - gl.uniform1i( uniforms.fogType, 0 ); - oldFogType = 0; - sceneFogType = 0; + setFromMatrixPosition: function ( m ) { - } + return this.setFromMatrixColumn( m, 3 ); + }, - // update positions and sort + setFromMatrixScale: function ( m ) { - for ( var i = 0, l = sprites.length; i < l; i ++ ) { + var sx = this.setFromMatrixColumn( m, 0 ).length(); + var sy = this.setFromMatrixColumn( m, 1 ).length(); + var sz = this.setFromMatrixColumn( m, 2 ).length(); - var sprite = sprites[ i ]; + this.x = sx; + this.y = sy; + this.z = sz; - sprite.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld ); - sprite.z = - sprite.modelViewMatrix.elements[ 14 ]; + return this; - } + }, - sprites.sort( painterSortStable ); + setFromMatrixColumn: function ( m, index ) { - // render all sprites + if ( typeof m === 'number' ) { - var scale = []; + console.warn( 'THREE.Vector3: setFromMatrixColumn now expects ( matrix, index ).' ); + var temp = m + m = index; + index = temp; - for ( var i = 0, l = sprites.length; i < l; i ++ ) { + } - var sprite = sprites[ i ]; - var material = sprite.material; + return this.fromArray( m.elements, index * 4 ); - if ( material.visible === false ) continue; + }, - gl.uniform1f( uniforms.alphaTest, material.alphaTest ); - gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite.modelViewMatrix.elements ); + equals: function ( v ) { - sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale ); + return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) ); - scale[ 0 ] = spriteScale.x; - scale[ 1 ] = spriteScale.y; + }, - var fogType = 0; + fromArray: function ( array, offset ) { - if ( scene.fog && material.fog ) { + if ( offset === undefined ) offset = 0; - fogType = sceneFogType; + this.x = array[ offset ]; + this.y = array[ offset + 1 ]; + this.z = array[ offset + 2 ]; - } + return this; - if ( oldFogType !== fogType ) { + }, - gl.uniform1i( uniforms.fogType, fogType ); - oldFogType = fogType; + toArray: function ( array, offset ) { - } + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - if ( material.map !== null ) { + array[ offset ] = this.x; + array[ offset + 1 ] = this.y; + array[ offset + 2 ] = this.z; - gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y ); - gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y ); + return array; - } else { + }, - gl.uniform2f( uniforms.uvOffset, 0, 0 ); - gl.uniform2f( uniforms.uvScale, 1, 1 ); + fromAttribute: function ( attribute, index, offset ) { - } + if ( offset === undefined ) offset = 0; - gl.uniform1f( uniforms.opacity, material.opacity ); - gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b ); + index = index * attribute.itemSize + offset; - gl.uniform1f( uniforms.rotation, material.rotation ); - gl.uniform2fv( uniforms.scale, scale ); + this.x = attribute.array[ index ]; + this.y = attribute.array[ index + 1 ]; + this.z = attribute.array[ index + 2 ]; - state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst ); - state.setDepthTest( material.depthTest ); - state.setDepthWrite( material.depthWrite ); + return this; - if ( material.map ) { + } - renderer.setTexture2D( material.map, 0 ); + }; - } else { + /** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + */ - renderer.setTexture2D( texture, 0 ); + function SpritePlugin( renderer, sprites ) { - } + var gl = renderer.context; + var state = renderer.state; - gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); + var vertexBuffer, elementBuffer; + var program, attributes, uniforms; - } + var texture; - // restore gl + // decompose matrixWorld - state.enable( gl.CULL_FACE ); + var spritePosition = new Vector3(); + var spriteRotation = new Quaternion(); + var spriteScale = new Vector3(); - renderer.resetGLState(); + function init() { - }; + var vertices = new Float32Array( [ + - 0.5, - 0.5, 0, 0, + 0.5, - 0.5, 1, 0, + 0.5, 0.5, 1, 1, + - 0.5, 0.5, 0, 1 + ] ); - function createProgram() { + var faces = new Uint16Array( [ + 0, 1, 2, + 0, 2, 3 + ] ); - var program = gl.createProgram(); + vertexBuffer = gl.createBuffer(); + elementBuffer = gl.createBuffer(); - var vertexShader = gl.createShader( gl.VERTEX_SHADER ); - var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER ); + gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer ); + gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW ); - gl.shaderSource( vertexShader, [ + gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); + gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW ); - 'precision ' + renderer.getPrecision() + ' float;', + program = createProgram(); - 'uniform mat4 modelViewMatrix;', - 'uniform mat4 projectionMatrix;', - 'uniform float rotation;', - 'uniform vec2 scale;', - 'uniform vec2 uvOffset;', - 'uniform vec2 uvScale;', + attributes = { + position: gl.getAttribLocation ( program, 'position' ), + uv: gl.getAttribLocation ( program, 'uv' ) + }; - 'attribute vec2 position;', - 'attribute vec2 uv;', + uniforms = { + uvOffset: gl.getUniformLocation( program, 'uvOffset' ), + uvScale: gl.getUniformLocation( program, 'uvScale' ), - 'varying vec2 vUV;', + rotation: gl.getUniformLocation( program, 'rotation' ), + scale: gl.getUniformLocation( program, 'scale' ), - 'void main() {', + color: gl.getUniformLocation( program, 'color' ), + map: gl.getUniformLocation( program, 'map' ), + opacity: gl.getUniformLocation( program, 'opacity' ), - 'vUV = uvOffset + uv * uvScale;', + modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ), + projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ), - 'vec2 alignedPosition = position * scale;', + fogType: gl.getUniformLocation( program, 'fogType' ), + fogDensity: gl.getUniformLocation( program, 'fogDensity' ), + fogNear: gl.getUniformLocation( program, 'fogNear' ), + fogFar: gl.getUniformLocation( program, 'fogFar' ), + fogColor: gl.getUniformLocation( program, 'fogColor' ), - 'vec2 rotatedPosition;', - 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;', - 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;', + alphaTest: gl.getUniformLocation( program, 'alphaTest' ) + }; - 'vec4 finalPosition;', + var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); + canvas.width = 8; + canvas.height = 8; - 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );', - 'finalPosition.xy += rotatedPosition;', - 'finalPosition = projectionMatrix * finalPosition;', + var context = canvas.getContext( '2d' ); + context.fillStyle = 'white'; + context.fillRect( 0, 0, 8, 8 ); - 'gl_Position = finalPosition;', + texture = new Texture( canvas ); + texture.needsUpdate = true; - '}' + } - ].join( '\n' ) ); + this.render = function ( scene, camera ) { - gl.shaderSource( fragmentShader, [ + if ( sprites.length === 0 ) return; - 'precision ' + renderer.getPrecision() + ' float;', + // setup gl - 'uniform vec3 color;', - 'uniform sampler2D map;', - 'uniform float opacity;', + if ( program === undefined ) { - 'uniform int fogType;', - 'uniform vec3 fogColor;', - 'uniform float fogDensity;', - 'uniform float fogNear;', - 'uniform float fogFar;', - 'uniform float alphaTest;', + init(); - 'varying vec2 vUV;', + } - 'void main() {', + gl.useProgram( program ); - 'vec4 texture = texture2D( map, vUV );', + state.initAttributes(); + state.enableAttribute( attributes.position ); + state.enableAttribute( attributes.uv ); + state.disableUnusedAttributes(); - 'if ( texture.a < alphaTest ) discard;', + state.disable( gl.CULL_FACE ); + state.enable( gl.BLEND ); - 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );', + gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer ); + gl.vertexAttribPointer( attributes.position, 2, gl.FLOAT, false, 2 * 8, 0 ); + gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 ); - 'if ( fogType > 0 ) {', + gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); - 'float depth = gl_FragCoord.z / gl_FragCoord.w;', - 'float fogFactor = 0.0;', + gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements ); - 'if ( fogType == 1 ) {', + state.activeTexture( gl.TEXTURE0 ); + gl.uniform1i( uniforms.map, 0 ); - 'fogFactor = smoothstep( fogNear, fogFar, depth );', + var oldFogType = 0; + var sceneFogType = 0; + var fog = scene.fog; - '} else {', + if ( fog ) { - 'const float LOG2 = 1.442695;', - 'fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );', - 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );', + gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b ); - '}', + if ( (fog && fog.isFog) ) { - 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );', + gl.uniform1f( uniforms.fogNear, fog.near ); + gl.uniform1f( uniforms.fogFar, fog.far ); - '}', + gl.uniform1i( uniforms.fogType, 1 ); + oldFogType = 1; + sceneFogType = 1; - '}' + } else if ( (fog && fog.isFogExp2) ) { - ].join( '\n' ) ); + gl.uniform1f( uniforms.fogDensity, fog.density ); - gl.compileShader( vertexShader ); - gl.compileShader( fragmentShader ); + gl.uniform1i( uniforms.fogType, 2 ); + oldFogType = 2; + sceneFogType = 2; - gl.attachShader( program, vertexShader ); - gl.attachShader( program, fragmentShader ); + } - gl.linkProgram( program ); + } else { - return program; + gl.uniform1i( uniforms.fogType, 0 ); + oldFogType = 0; + sceneFogType = 0; - } + } - function painterSortStable( a, b ) { - if ( a.renderOrder !== b.renderOrder ) { + // update positions and sort - return a.renderOrder - b.renderOrder; + for ( var i = 0, l = sprites.length; i < l; i ++ ) { - } else if ( a.z !== b.z ) { + var sprite = sprites[ i ]; - return b.z - a.z; + sprite.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld ); + sprite.z = - sprite.modelViewMatrix.elements[ 14 ]; - } else { + } - return b.id - a.id; + sprites.sort( painterSortStable ); - } + // render all sprites - } + var scale = []; - }; + for ( var i = 0, l = sprites.length; i < l; i ++ ) { - /** - * @author bhouston / http://clara.io - */ + var sprite = sprites[ i ]; + var material = sprite.material; - function Box2( min, max ) { + if ( material.visible === false ) continue; - this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity ); - this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity ); + gl.uniform1f( uniforms.alphaTest, material.alphaTest ); + gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite.modelViewMatrix.elements ); - }; + sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale ); - Box2.prototype = { + scale[ 0 ] = spriteScale.x; + scale[ 1 ] = spriteScale.y; - constructor: Box2, + var fogType = 0; - set: function ( min, max ) { + if ( scene.fog && material.fog ) { - this.min.copy( min ); - this.max.copy( max ); + fogType = sceneFogType; - return this; + } - }, + if ( oldFogType !== fogType ) { - setFromPoints: function ( points ) { + gl.uniform1i( uniforms.fogType, fogType ); + oldFogType = fogType; - this.makeEmpty(); + } - for ( var i = 0, il = points.length; i < il; i ++ ) { + if ( material.map !== null ) { - this.expandByPoint( points[ i ] ); + gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y ); + gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y ); - } + } else { - return this; + gl.uniform2f( uniforms.uvOffset, 0, 0 ); + gl.uniform2f( uniforms.uvScale, 1, 1 ); - }, + } - setFromCenterAndSize: function () { + gl.uniform1f( uniforms.opacity, material.opacity ); + gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b ); - var v1 = new Vector2(); + gl.uniform1f( uniforms.rotation, material.rotation ); + gl.uniform2fv( uniforms.scale, scale ); - return function setFromCenterAndSize( center, size ) { + state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst ); + state.setDepthTest( material.depthTest ); + state.setDepthWrite( material.depthWrite ); - var halfSize = v1.copy( size ).multiplyScalar( 0.5 ); - this.min.copy( center ).sub( halfSize ); - this.max.copy( center ).add( halfSize ); + if ( material.map ) { - return this; + renderer.setTexture2D( material.map, 0 ); - }; + } else { - }(), + renderer.setTexture2D( texture, 0 ); - clone: function () { + } - return new this.constructor().copy( this ); + gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); - }, + } - copy: function ( box ) { + // restore gl - this.min.copy( box.min ); - this.max.copy( box.max ); + state.enable( gl.CULL_FACE ); - return this; + renderer.resetGLState(); - }, + }; - makeEmpty: function () { + function createProgram() { - this.min.x = this.min.y = + Infinity; - this.max.x = this.max.y = - Infinity; + var program = gl.createProgram(); - return this; + var vertexShader = gl.createShader( gl.VERTEX_SHADER ); + var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER ); - }, + gl.shaderSource( vertexShader, [ - isEmpty: function () { + 'precision ' + renderer.getPrecision() + ' float;', - // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes + 'uniform mat4 modelViewMatrix;', + 'uniform mat4 projectionMatrix;', + 'uniform float rotation;', + 'uniform vec2 scale;', + 'uniform vec2 uvOffset;', + 'uniform vec2 uvScale;', - return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ); + 'attribute vec2 position;', + 'attribute vec2 uv;', - }, + 'varying vec2 vUV;', - center: function ( optionalTarget ) { + 'void main() {', - var result = optionalTarget || new Vector2(); - return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); + 'vUV = uvOffset + uv * uvScale;', - }, + 'vec2 alignedPosition = position * scale;', - size: function ( optionalTarget ) { + 'vec2 rotatedPosition;', + 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;', + 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;', - var result = optionalTarget || new Vector2(); - return result.subVectors( this.max, this.min ); + 'vec4 finalPosition;', - }, + 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );', + 'finalPosition.xy += rotatedPosition;', + 'finalPosition = projectionMatrix * finalPosition;', - expandByPoint: function ( point ) { + 'gl_Position = finalPosition;', - this.min.min( point ); - this.max.max( point ); + '}' - return this; + ].join( '\n' ) ); - }, + gl.shaderSource( fragmentShader, [ - expandByVector: function ( vector ) { + 'precision ' + renderer.getPrecision() + ' float;', - this.min.sub( vector ); - this.max.add( vector ); + 'uniform vec3 color;', + 'uniform sampler2D map;', + 'uniform float opacity;', - return this; + 'uniform int fogType;', + 'uniform vec3 fogColor;', + 'uniform float fogDensity;', + 'uniform float fogNear;', + 'uniform float fogFar;', + 'uniform float alphaTest;', - }, + 'varying vec2 vUV;', - expandByScalar: function ( scalar ) { + 'void main() {', - this.min.addScalar( - scalar ); - this.max.addScalar( scalar ); + 'vec4 texture = texture2D( map, vUV );', - return this; + 'if ( texture.a < alphaTest ) discard;', - }, + 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );', - containsPoint: function ( point ) { + 'if ( fogType > 0 ) {', - if ( point.x < this.min.x || point.x > this.max.x || - point.y < this.min.y || point.y > this.max.y ) { + 'float depth = gl_FragCoord.z / gl_FragCoord.w;', + 'float fogFactor = 0.0;', - return false; + 'if ( fogType == 1 ) {', - } + 'fogFactor = smoothstep( fogNear, fogFar, depth );', - return true; + '} else {', - }, + 'const float LOG2 = 1.442695;', + 'fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );', + 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );', - containsBox: function ( box ) { + '}', - if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) && - ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) { + 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );', - return true; + '}', - } + '}' - return false; + ].join( '\n' ) ); - }, + gl.compileShader( vertexShader ); + gl.compileShader( fragmentShader ); - getParameter: function ( point, optionalTarget ) { + gl.attachShader( program, vertexShader ); + gl.attachShader( program, fragmentShader ); - // This can potentially have a divide by zero if the box - // has a size dimension of 0. + gl.linkProgram( program ); - var result = optionalTarget || new Vector2(); + return program; - return result.set( - ( point.x - this.min.x ) / ( this.max.x - this.min.x ), - ( point.y - this.min.y ) / ( this.max.y - this.min.y ) - ); + } - }, + function painterSortStable( a, b ) { - intersectsBox: function ( box ) { + if ( a.renderOrder !== b.renderOrder ) { - // using 6 splitting planes to rule out intersections. + return a.renderOrder - b.renderOrder; - if ( box.max.x < this.min.x || box.min.x > this.max.x || - box.max.y < this.min.y || box.min.y > this.max.y ) { + } else if ( a.z !== b.z ) { - return false; + return b.z - a.z; - } + } else { - return true; + return b.id - a.id; - }, + } - clampPoint: function ( point, optionalTarget ) { + } - var result = optionalTarget || new Vector2(); - return result.copy( point ).clamp( this.min, this.max ); + } - }, + /** + * @author bhouston / http://clara.io + */ - distanceToPoint: function () { + function Box2( min, max ) { - var v1 = new Vector2(); + this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity ); + this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity ); - return function distanceToPoint( point ) { + } - var clampedPoint = v1.copy( point ).clamp( this.min, this.max ); - return clampedPoint.sub( point ).length(); + Box2.prototype = { - }; + constructor: Box2, - }(), + set: function ( min, max ) { - intersect: function ( box ) { + this.min.copy( min ); + this.max.copy( max ); - this.min.max( box.min ); - this.max.min( box.max ); + return this; - return this; + }, - }, + setFromPoints: function ( points ) { - union: function ( box ) { + this.makeEmpty(); - this.min.min( box.min ); - this.max.max( box.max ); + for ( var i = 0, il = points.length; i < il; i ++ ) { - return this; + this.expandByPoint( points[ i ] ); - }, + } - translate: function ( offset ) { + return this; - this.min.add( offset ); - this.max.add( offset ); + }, - return this; + setFromCenterAndSize: function () { - }, + var v1 = new Vector2(); - equals: function ( box ) { + return function setFromCenterAndSize( center, size ) { - return box.min.equals( this.min ) && box.max.equals( this.max ); + var halfSize = v1.copy( size ).multiplyScalar( 0.5 ); + this.min.copy( center ).sub( halfSize ); + this.max.copy( center ).add( halfSize ); - } + return this; - }; + }; - /** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - */ + }(), - function LensFlarePlugin( renderer, flares ) { + clone: function () { - var gl = renderer.context; - var state = renderer.state; + return new this.constructor().copy( this ); - var vertexBuffer, elementBuffer; - var shader, program, attributes, uniforms; + }, - var tempTexture, occlusionTexture; + copy: function ( box ) { - function init() { + this.min.copy( box.min ); + this.max.copy( box.max ); - var vertices = new Float32Array( [ - - 1, - 1, 0, 0, - 1, - 1, 1, 0, - 1, 1, 1, 1, - - 1, 1, 0, 1 - ] ); + return this; - var faces = new Uint16Array( [ - 0, 1, 2, - 0, 2, 3 - ] ); + }, - // buffers + makeEmpty: function () { - vertexBuffer = gl.createBuffer(); - elementBuffer = gl.createBuffer(); + this.min.x = this.min.y = + Infinity; + this.max.x = this.max.y = - Infinity; - gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer ); - gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW ); + return this; - gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); - gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW ); + }, - // textures + isEmpty: function () { - tempTexture = gl.createTexture(); - occlusionTexture = gl.createTexture(); + // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes - state.bindTexture( gl.TEXTURE_2D, tempTexture ); - gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 16, 16, 0, gl.RGB, gl.UNSIGNED_BYTE, null ); - gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE ); - gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE ); - gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST ); - gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST ); + return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ); - state.bindTexture( gl.TEXTURE_2D, occlusionTexture ); - gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 16, 16, 0, gl.RGBA, gl.UNSIGNED_BYTE, null ); - gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE ); - gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE ); - gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST ); - gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST ); + }, - shader = { + center: function ( optionalTarget ) { - vertexShader: [ + var result = optionalTarget || new Vector2(); + return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); - "uniform lowp int renderType;", + }, - "uniform vec3 screenPosition;", - "uniform vec2 scale;", - "uniform float rotation;", + size: function ( optionalTarget ) { - "uniform sampler2D occlusionMap;", + var result = optionalTarget || new Vector2(); + return result.subVectors( this.max, this.min ); - "attribute vec2 position;", - "attribute vec2 uv;", + }, - "varying vec2 vUV;", - "varying float vVisibility;", + expandByPoint: function ( point ) { - "void main() {", + this.min.min( point ); + this.max.max( point ); - "vUV = uv;", + return this; - "vec2 pos = position;", + }, - "if ( renderType == 2 ) {", + expandByVector: function ( vector ) { - "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );", - "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );", - "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );", - "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );", - "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );", - "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );", - "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );", - "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );", - "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );", + this.min.sub( vector ); + this.max.add( vector ); - "vVisibility = visibility.r / 9.0;", - "vVisibility *= 1.0 - visibility.g / 9.0;", - "vVisibility *= visibility.b / 9.0;", - "vVisibility *= 1.0 - visibility.a / 9.0;", + return this; - "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;", - "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;", + }, - "}", + expandByScalar: function ( scalar ) { - "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );", + this.min.addScalar( - scalar ); + this.max.addScalar( scalar ); - "}" + return this; - ].join( "\n" ), + }, - fragmentShader: [ + containsPoint: function ( point ) { - "uniform lowp int renderType;", + if ( point.x < this.min.x || point.x > this.max.x || + point.y < this.min.y || point.y > this.max.y ) { - "uniform sampler2D map;", - "uniform float opacity;", - "uniform vec3 color;", + return false; - "varying vec2 vUV;", - "varying float vVisibility;", + } - "void main() {", + return true; - // pink square + }, - "if ( renderType == 0 ) {", + containsBox: function ( box ) { - "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );", + if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) && + ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) { - // restore + return true; - "} else if ( renderType == 1 ) {", + } - "gl_FragColor = texture2D( map, vUV );", + return false; - // flare + }, - "} else {", + getParameter: function ( point, optionalTarget ) { - "vec4 texture = texture2D( map, vUV );", - "texture.a *= opacity * vVisibility;", - "gl_FragColor = texture;", - "gl_FragColor.rgb *= color;", + // This can potentially have a divide by zero if the box + // has a size dimension of 0. - "}", + var result = optionalTarget || new Vector2(); - "}" + return result.set( + ( point.x - this.min.x ) / ( this.max.x - this.min.x ), + ( point.y - this.min.y ) / ( this.max.y - this.min.y ) + ); - ].join( "\n" ) + }, - }; + intersectsBox: function ( box ) { - program = createProgram( shader ); + // using 6 splitting planes to rule out intersections. - attributes = { - vertex: gl.getAttribLocation ( program, "position" ), - uv: gl.getAttribLocation ( program, "uv" ) - }; + if ( box.max.x < this.min.x || box.min.x > this.max.x || + box.max.y < this.min.y || box.min.y > this.max.y ) { - uniforms = { - renderType: gl.getUniformLocation( program, "renderType" ), - map: gl.getUniformLocation( program, "map" ), - occlusionMap: gl.getUniformLocation( program, "occlusionMap" ), - opacity: gl.getUniformLocation( program, "opacity" ), - color: gl.getUniformLocation( program, "color" ), - scale: gl.getUniformLocation( program, "scale" ), - rotation: gl.getUniformLocation( program, "rotation" ), - screenPosition: gl.getUniformLocation( program, "screenPosition" ) - }; + return false; - } + } - /* - * Render lens flares - * Method: renders 16x16 0xff00ff-colored points scattered over the light source area, - * reads these back and calculates occlusion. - */ + return true; - this.render = function ( scene, camera, viewport ) { + }, - if ( flares.length === 0 ) return; + clampPoint: function ( point, optionalTarget ) { - var tempPosition = new Vector3(); + var result = optionalTarget || new Vector2(); + return result.copy( point ).clamp( this.min, this.max ); - var invAspect = viewport.w / viewport.z, - halfViewportWidth = viewport.z * 0.5, - halfViewportHeight = viewport.w * 0.5; + }, - var size = 16 / viewport.w, - scale = new Vector2( size * invAspect, size ); + distanceToPoint: function () { - var screenPosition = new Vector3( 1, 1, 0 ), - screenPositionPixels = new Vector2( 1, 1 ); + var v1 = new Vector2(); - var validArea = new Box2(); + return function distanceToPoint( point ) { - validArea.min.set( 0, 0 ); - validArea.max.set( viewport.z - 16, viewport.w - 16 ); + var clampedPoint = v1.copy( point ).clamp( this.min, this.max ); + return clampedPoint.sub( point ).length(); - if ( program === undefined ) { + }; - init(); + }(), - } + intersect: function ( box ) { - gl.useProgram( program ); + this.min.max( box.min ); + this.max.min( box.max ); - state.initAttributes(); - state.enableAttribute( attributes.vertex ); - state.enableAttribute( attributes.uv ); - state.disableUnusedAttributes(); + return this; - // loop through all lens flares to update their occlusion and positions - // setup gl and common used attribs/uniforms + }, - gl.uniform1i( uniforms.occlusionMap, 0 ); - gl.uniform1i( uniforms.map, 1 ); + union: function ( box ) { - gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer ); - gl.vertexAttribPointer( attributes.vertex, 2, gl.FLOAT, false, 2 * 8, 0 ); - gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 ); + this.min.min( box.min ); + this.max.max( box.max ); - gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); + return this; - state.disable( gl.CULL_FACE ); - state.setDepthWrite( false ); + }, - for ( var i = 0, l = flares.length; i < l; i ++ ) { + translate: function ( offset ) { - size = 16 / viewport.w; - scale.set( size * invAspect, size ); + this.min.add( offset ); + this.max.add( offset ); - // calc object screen position + return this; - var flare = flares[ i ]; + }, - tempPosition.set( flare.matrixWorld.elements[ 12 ], flare.matrixWorld.elements[ 13 ], flare.matrixWorld.elements[ 14 ] ); + equals: function ( box ) { - tempPosition.applyMatrix4( camera.matrixWorldInverse ); - tempPosition.applyProjection( camera.projectionMatrix ); + return box.min.equals( this.min ) && box.max.equals( this.max ); - // setup arrays for gl programs + } - screenPosition.copy( tempPosition ); + }; - // horizontal and vertical coordinate of the lower left corner of the pixels to copy + /** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + */ - screenPositionPixels.x = viewport.x + ( screenPosition.x * halfViewportWidth ) + halfViewportWidth - 8; - screenPositionPixels.y = viewport.y + ( screenPosition.y * halfViewportHeight ) + halfViewportHeight - 8; + function LensFlarePlugin( renderer, flares ) { - // screen cull + var gl = renderer.context; + var state = renderer.state; - if ( validArea.containsPoint( screenPositionPixels ) === true ) { + var vertexBuffer, elementBuffer; + var shader, program, attributes, uniforms; - // save current RGB to temp texture + var tempTexture, occlusionTexture; - state.activeTexture( gl.TEXTURE0 ); - state.bindTexture( gl.TEXTURE_2D, null ); - state.activeTexture( gl.TEXTURE1 ); - state.bindTexture( gl.TEXTURE_2D, tempTexture ); - gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 ); + function init() { + var vertices = new Float32Array( [ + - 1, - 1, 0, 0, + 1, - 1, 1, 0, + 1, 1, 1, 1, + - 1, 1, 0, 1 + ] ); - // render pink quad + var faces = new Uint16Array( [ + 0, 1, 2, + 0, 2, 3 + ] ); - gl.uniform1i( uniforms.renderType, 0 ); - gl.uniform2f( uniforms.scale, scale.x, scale.y ); - gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z ); + // buffers - state.disable( gl.BLEND ); - state.enable( gl.DEPTH_TEST ); + vertexBuffer = gl.createBuffer(); + elementBuffer = gl.createBuffer(); - gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); + gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer ); + gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW ); + gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); + gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW ); - // copy result to occlusionMap + // textures - state.activeTexture( gl.TEXTURE0 ); - state.bindTexture( gl.TEXTURE_2D, occlusionTexture ); - gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 ); + tempTexture = gl.createTexture(); + occlusionTexture = gl.createTexture(); + state.bindTexture( gl.TEXTURE_2D, tempTexture ); + gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 16, 16, 0, gl.RGB, gl.UNSIGNED_BYTE, null ); + gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE ); + gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE ); + gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST ); + gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST ); - // restore graphics + state.bindTexture( gl.TEXTURE_2D, occlusionTexture ); + gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 16, 16, 0, gl.RGBA, gl.UNSIGNED_BYTE, null ); + gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE ); + gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE ); + gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST ); + gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST ); - gl.uniform1i( uniforms.renderType, 1 ); - state.disable( gl.DEPTH_TEST ); + shader = { - state.activeTexture( gl.TEXTURE1 ); - state.bindTexture( gl.TEXTURE_2D, tempTexture ); - gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); + vertexShader: [ + "uniform lowp int renderType;", - // update object positions + "uniform vec3 screenPosition;", + "uniform vec2 scale;", + "uniform float rotation;", - flare.positionScreen.copy( screenPosition ); + "uniform sampler2D occlusionMap;", - if ( flare.customUpdateCallback ) { + "attribute vec2 position;", + "attribute vec2 uv;", - flare.customUpdateCallback( flare ); + "varying vec2 vUV;", + "varying float vVisibility;", - } else { + "void main() {", - flare.updateLensFlares(); + "vUV = uv;", - } + "vec2 pos = position;", - // render flares + "if ( renderType == 2 ) {", - gl.uniform1i( uniforms.renderType, 2 ); - state.enable( gl.BLEND ); + "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );", + "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );", + "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );", + "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );", + "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );", + "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );", + "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );", + "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );", + "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );", - for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) { + "vVisibility = visibility.r / 9.0;", + "vVisibility *= 1.0 - visibility.g / 9.0;", + "vVisibility *= visibility.b / 9.0;", + "vVisibility *= 1.0 - visibility.a / 9.0;", - var sprite = flare.lensFlares[ j ]; + "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;", + "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;", - if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) { + "}", - screenPosition.x = sprite.x; - screenPosition.y = sprite.y; - screenPosition.z = sprite.z; + "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );", - size = sprite.size * sprite.scale / viewport.w; + "}" - scale.x = size * invAspect; - scale.y = size; + ].join( "\n" ), - gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z ); - gl.uniform2f( uniforms.scale, scale.x, scale.y ); - gl.uniform1f( uniforms.rotation, sprite.rotation ); + fragmentShader: [ - gl.uniform1f( uniforms.opacity, sprite.opacity ); - gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b ); + "uniform lowp int renderType;", - state.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst ); - renderer.setTexture2D( sprite.texture, 1 ); + "uniform sampler2D map;", + "uniform float opacity;", + "uniform vec3 color;", - gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); + "varying vec2 vUV;", + "varying float vVisibility;", - } + "void main() {", - } + // pink square - } + "if ( renderType == 0 ) {", - } + "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );", - // restore gl + // restore - state.enable( gl.CULL_FACE ); - state.enable( gl.DEPTH_TEST ); - state.setDepthWrite( true ); + "} else if ( renderType == 1 ) {", - renderer.resetGLState(); + "gl_FragColor = texture2D( map, vUV );", - }; + // flare - function createProgram( shader ) { + "} else {", - var program = gl.createProgram(); + "vec4 texture = texture2D( map, vUV );", + "texture.a *= opacity * vVisibility;", + "gl_FragColor = texture;", + "gl_FragColor.rgb *= color;", - var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER ); - var vertexShader = gl.createShader( gl.VERTEX_SHADER ); + "}", - var prefix = "precision " + renderer.getPrecision() + " float;\n"; + "}" - gl.shaderSource( fragmentShader, prefix + shader.fragmentShader ); - gl.shaderSource( vertexShader, prefix + shader.vertexShader ); + ].join( "\n" ) - gl.compileShader( fragmentShader ); - gl.compileShader( vertexShader ); + }; - gl.attachShader( program, fragmentShader ); - gl.attachShader( program, vertexShader ); + program = createProgram( shader ); - gl.linkProgram( program ); + attributes = { + vertex: gl.getAttribLocation ( program, "position" ), + uv: gl.getAttribLocation ( program, "uv" ) + }; - return program; + uniforms = { + renderType: gl.getUniformLocation( program, "renderType" ), + map: gl.getUniformLocation( program, "map" ), + occlusionMap: gl.getUniformLocation( program, "occlusionMap" ), + opacity: gl.getUniformLocation( program, "opacity" ), + color: gl.getUniformLocation( program, "color" ), + scale: gl.getUniformLocation( program, "scale" ), + rotation: gl.getUniformLocation( program, "rotation" ), + screenPosition: gl.getUniformLocation( program, "screenPosition" ) + }; - } + } - }; + /* + * Render lens flares + * Method: renders 16x16 0xff00ff-colored points scattered over the light source area, + * reads these back and calculates occlusion. + */ - /** - * @author mrdoob / http://mrdoob.com/ - */ + this.render = function ( scene, camera, viewport ) { - function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) { + if ( flares.length === 0 ) return; - images = images !== undefined ? images : []; - mapping = mapping !== undefined ? mapping : CubeReflectionMapping; + var tempPosition = new Vector3(); - Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); + var invAspect = viewport.w / viewport.z, + halfViewportWidth = viewport.z * 0.5, + halfViewportHeight = viewport.w * 0.5; - this.flipY = false; + var size = 16 / viewport.w, + scale = new Vector2( size * invAspect, size ); - }; + var screenPosition = new Vector3( 1, 1, 0 ), + screenPositionPixels = new Vector2( 1, 1 ); - CubeTexture.prototype = Object.create( Texture.prototype ); - CubeTexture.prototype.constructor = CubeTexture; + var validArea = new Box2(); - CubeTexture.prototype.isCubeTexture = true; + validArea.min.set( 0, 0 ); + validArea.max.set( viewport.z - 16, viewport.w - 16 ); - Object.defineProperty( CubeTexture.prototype, 'images', { + if ( program === undefined ) { - get: function () { + init(); - return this.image; + } - }, + gl.useProgram( program ); - set: function ( value ) { + state.initAttributes(); + state.enableAttribute( attributes.vertex ); + state.enableAttribute( attributes.uv ); + state.disableUnusedAttributes(); - this.image = value; + // loop through all lens flares to update their occlusion and positions + // setup gl and common used attribs/uniforms - } + gl.uniform1i( uniforms.occlusionMap, 0 ); + gl.uniform1i( uniforms.map, 1 ); - } ); + gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer ); + gl.vertexAttribPointer( attributes.vertex, 2, gl.FLOAT, false, 2 * 8, 0 ); + gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 ); - /** - * - * Uniforms of a program. - * Those form a tree structure with a special top-level container for the root, - * which you get by calling 'new WebGLUniforms( gl, program, renderer )'. - * - * - * Properties of inner nodes including the top-level container: - * - * .seq - array of nested uniforms - * .map - nested uniforms by name - * - * - * Methods of all nodes except the top-level container: - * - * .setValue( gl, value, [renderer] ) - * - * uploads a uniform value(s) - * the 'renderer' parameter is needed for sampler uniforms - * - * - * Static methods of the top-level container (renderer factorizations): - * - * .upload( gl, seq, values, renderer ) - * - * sets uniforms in 'seq' to 'values[id].value' - * - * .seqWithValue( seq, values ) : filteredSeq - * - * filters 'seq' entries with corresponding entry in values - * - * .splitDynamic( seq, values ) : filteredSeq - * - * filters 'seq' entries with dynamic entry and removes them from 'seq' - * - * - * Methods of the top-level container (renderer factorizations): - * - * .setValue( gl, name, value ) - * - * sets uniform with name 'name' to 'value' - * - * .set( gl, obj, prop ) - * - * sets uniform from object and property with same name than uniform - * - * .setOptional( gl, obj, prop ) - * - * like .set for an optional property of the object - * - * - * @author tschw - * - */ + gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); - exports.WebGLUniforms = ( function() { // scope + state.disable( gl.CULL_FACE ); + state.setDepthWrite( false ); - var emptyTexture = new Texture(); - var emptyCubeTexture = new CubeTexture(); + for ( var i = 0, l = flares.length; i < l; i ++ ) { - // --- Base for inner nodes (including the root) --- + size = 16 / viewport.w; + scale.set( size * invAspect, size ); - var UniformContainer = function() { + // calc object screen position - this.seq = []; - this.map = {}; + var flare = flares[ i ]; - }, + tempPosition.set( flare.matrixWorld.elements[ 12 ], flare.matrixWorld.elements[ 13 ], flare.matrixWorld.elements[ 14 ] ); - // --- Utilities --- + tempPosition.applyMatrix4( camera.matrixWorldInverse ); + tempPosition.applyProjection( camera.projectionMatrix ); - // Array Caches (provide typed arrays for temporary by size) + // setup arrays for gl programs - arrayCacheF32 = [], - arrayCacheI32 = [], + screenPosition.copy( tempPosition ); - // Flattening for arrays of vectors and matrices + // horizontal and vertical coordinate of the lower left corner of the pixels to copy - flatten = function( array, nBlocks, blockSize ) { + screenPositionPixels.x = viewport.x + ( screenPosition.x * halfViewportWidth ) + halfViewportWidth - 8; + screenPositionPixels.y = viewport.y + ( screenPosition.y * halfViewportHeight ) + halfViewportHeight - 8; - var firstElem = array[ 0 ]; + // screen cull - if ( firstElem <= 0 || firstElem > 0 ) return array; - // unoptimized: ! isNaN( firstElem ) - // see http://jacksondunstan.com/articles/983 + if ( validArea.containsPoint( screenPositionPixels ) === true ) { - var n = nBlocks * blockSize, - r = arrayCacheF32[ n ]; + // save current RGB to temp texture - if ( r === undefined ) { + state.activeTexture( gl.TEXTURE0 ); + state.bindTexture( gl.TEXTURE_2D, null ); + state.activeTexture( gl.TEXTURE1 ); + state.bindTexture( gl.TEXTURE_2D, tempTexture ); + gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 ); - r = new Float32Array( n ); - arrayCacheF32[ n ] = r; - } + // render pink quad - if ( nBlocks !== 0 ) { + gl.uniform1i( uniforms.renderType, 0 ); + gl.uniform2f( uniforms.scale, scale.x, scale.y ); + gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z ); - firstElem.toArray( r, 0 ); + state.disable( gl.BLEND ); + state.enable( gl.DEPTH_TEST ); - for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) { + gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); - offset += blockSize; - array[ i ].toArray( r, offset ); - } + // copy result to occlusionMap - } + state.activeTexture( gl.TEXTURE0 ); + state.bindTexture( gl.TEXTURE_2D, occlusionTexture ); + gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 ); - return r; - }, + // restore graphics - // Texture unit allocation + gl.uniform1i( uniforms.renderType, 1 ); + state.disable( gl.DEPTH_TEST ); - allocTexUnits = function( renderer, n ) { + state.activeTexture( gl.TEXTURE1 ); + state.bindTexture( gl.TEXTURE_2D, tempTexture ); + gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); - var r = arrayCacheI32[ n ]; - if ( r === undefined ) { + // update object positions - r = new Int32Array( n ); - arrayCacheI32[ n ] = r; + flare.positionScreen.copy( screenPosition ); - } + if ( flare.customUpdateCallback ) { - for ( var i = 0; i !== n; ++ i ) - r[ i ] = renderer.allocTextureUnit(); + flare.customUpdateCallback( flare ); - return r; + } else { - }, + flare.updateLensFlares(); - // --- Setters --- + } - // Note: Defining these methods externally, because they come in a bunch - // and this way their names minify. + // render flares - // Single scalar + gl.uniform1i( uniforms.renderType, 2 ); + state.enable( gl.BLEND ); - setValue1f = function( gl, v ) { gl.uniform1f( this.addr, v ); }, - setValue1i = function( gl, v ) { gl.uniform1i( this.addr, v ); }, + for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) { - // Single float vector (from flat array or THREE.VectorN) + var sprite = flare.lensFlares[ j ]; - setValue2fv = function( gl, v ) { + if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) { - if ( v.x === undefined ) gl.uniform2fv( this.addr, v ); - else gl.uniform2f( this.addr, v.x, v.y ); + screenPosition.x = sprite.x; + screenPosition.y = sprite.y; + screenPosition.z = sprite.z; - }, + size = sprite.size * sprite.scale / viewport.w; - setValue3fv = function( gl, v ) { + scale.x = size * invAspect; + scale.y = size; - if ( v.x !== undefined ) - gl.uniform3f( this.addr, v.x, v.y, v.z ); - else if ( v.r !== undefined ) - gl.uniform3f( this.addr, v.r, v.g, v.b ); - else - gl.uniform3fv( this.addr, v ); + gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z ); + gl.uniform2f( uniforms.scale, scale.x, scale.y ); + gl.uniform1f( uniforms.rotation, sprite.rotation ); - }, + gl.uniform1f( uniforms.opacity, sprite.opacity ); + gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b ); - setValue4fv = function( gl, v ) { + state.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst ); + renderer.setTexture2D( sprite.texture, 1 ); - if ( v.x === undefined ) gl.uniform4fv( this.addr, v ); - else gl.uniform4f( this.addr, v.x, v.y, v.z, v.w ); + gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); - }, + } - // Single matrix (from flat array or MatrixN) + } - setValue2fm = function( gl, v ) { + } - gl.uniformMatrix2fv( this.addr, false, v.elements || v ); + } - }, + // restore gl - setValue3fm = function( gl, v ) { + state.enable( gl.CULL_FACE ); + state.enable( gl.DEPTH_TEST ); + state.setDepthWrite( true ); - gl.uniformMatrix3fv( this.addr, false, v.elements || v ); + renderer.resetGLState(); - }, + }; - setValue4fm = function( gl, v ) { + function createProgram( shader ) { - gl.uniformMatrix4fv( this.addr, false, v.elements || v ); + var program = gl.createProgram(); - }, + var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER ); + var vertexShader = gl.createShader( gl.VERTEX_SHADER ); - // Single texture (2D / Cube) + var prefix = "precision " + renderer.getPrecision() + " float;\n"; - setValueT1 = function( gl, v, renderer ) { + gl.shaderSource( fragmentShader, prefix + shader.fragmentShader ); + gl.shaderSource( vertexShader, prefix + shader.vertexShader ); - var unit = renderer.allocTextureUnit(); - gl.uniform1i( this.addr, unit ); - renderer.setTexture2D( v || emptyTexture, unit ); + gl.compileShader( fragmentShader ); + gl.compileShader( vertexShader ); - }, + gl.attachShader( program, fragmentShader ); + gl.attachShader( program, vertexShader ); - setValueT6 = function( gl, v, renderer ) { + gl.linkProgram( program ); - var unit = renderer.allocTextureUnit(); - gl.uniform1i( this.addr, unit ); - renderer.setTextureCube( v || emptyCubeTexture, unit ); + return program; - }, + } - // Integer / Boolean vectors or arrays thereof (always flat arrays) + } - setValue2iv = function( gl, v ) { gl.uniform2iv( this.addr, v ); }, - setValue3iv = function( gl, v ) { gl.uniform3iv( this.addr, v ); }, - setValue4iv = function( gl, v ) { gl.uniform4iv( this.addr, v ); }, + /** + * @author mrdoob / http://mrdoob.com/ + */ - // Helper to pick the right setter for the singular case + function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) { - getSingularSetter = function( type ) { + images = images !== undefined ? images : []; + mapping = mapping !== undefined ? mapping : CubeReflectionMapping; - switch ( type ) { + Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); - case 0x1406: return setValue1f; // FLOAT - case 0x8b50: return setValue2fv; // _VEC2 - case 0x8b51: return setValue3fv; // _VEC3 - case 0x8b52: return setValue4fv; // _VEC4 + this.flipY = false; - case 0x8b5a: return setValue2fm; // _MAT2 - case 0x8b5b: return setValue3fm; // _MAT3 - case 0x8b5c: return setValue4fm; // _MAT4 + } - case 0x8b5e: return setValueT1; // SAMPLER_2D - case 0x8b60: return setValueT6; // SAMPLER_CUBE + CubeTexture.prototype = Object.create( Texture.prototype ); + CubeTexture.prototype.constructor = CubeTexture; - case 0x1404: case 0x8b56: return setValue1i; // INT, BOOL - case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2 - case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3 - case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4 + CubeTexture.prototype.isCubeTexture = true; - } + Object.defineProperty( CubeTexture.prototype, 'images', { - }, + get: function () { - // Array of scalars + return this.image; - setValue1fv = function( gl, v ) { gl.uniform1fv( this.addr, v ); }, - setValue1iv = function( gl, v ) { gl.uniform1iv( this.addr, v ); }, + }, - // Array of vectors (flat or from THREE classes) + set: function ( value ) { - setValueV2a = function( gl, v ) { + this.image = value; - gl.uniform2fv( this.addr, flatten( v, this.size, 2 ) ); + } - }, + } ); + + /** + * + * Uniforms of a program. + * Those form a tree structure with a special top-level container for the root, + * which you get by calling 'new WebGLUniforms( gl, program, renderer )'. + * + * + * Properties of inner nodes including the top-level container: + * + * .seq - array of nested uniforms + * .map - nested uniforms by name + * + * + * Methods of all nodes except the top-level container: + * + * .setValue( gl, value, [renderer] ) + * + * uploads a uniform value(s) + * the 'renderer' parameter is needed for sampler uniforms + * + * + * Static methods of the top-level container (renderer factorizations): + * + * .upload( gl, seq, values, renderer ) + * + * sets uniforms in 'seq' to 'values[id].value' + * + * .seqWithValue( seq, values ) : filteredSeq + * + * filters 'seq' entries with corresponding entry in values + * + * .splitDynamic( seq, values ) : filteredSeq + * + * filters 'seq' entries with dynamic entry and removes them from 'seq' + * + * + * Methods of the top-level container (renderer factorizations): + * + * .setValue( gl, name, value ) + * + * sets uniform with name 'name' to 'value' + * + * .set( gl, obj, prop ) + * + * sets uniform from object and property with same name than uniform + * + * .setOptional( gl, obj, prop ) + * + * like .set for an optional property of the object + * + * + * @author tschw + * + */ - setValueV3a = function( gl, v ) { + exports.WebGLUniforms = ( function() { // scope - gl.uniform3fv( this.addr, flatten( v, this.size, 3 ) ); + var emptyTexture = new Texture(); + var emptyCubeTexture = new CubeTexture(); - }, + // --- Base for inner nodes (including the root) --- - setValueV4a = function( gl, v ) { + var UniformContainer = function() { - gl.uniform4fv( this.addr, flatten( v, this.size, 4 ) ); + this.seq = []; + this.map = {}; - }, + }, - // Array of matrices (flat or from THREE clases) + // --- Utilities --- - setValueM2a = function( gl, v ) { + // Array Caches (provide typed arrays for temporary by size) - gl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) ); + arrayCacheF32 = [], + arrayCacheI32 = [], - }, + // Flattening for arrays of vectors and matrices - setValueM3a = function( gl, v ) { + flatten = function( array, nBlocks, blockSize ) { - gl.uniformMatrix3fv( this.addr, false, flatten( v, this.size, 9 ) ); + var firstElem = array[ 0 ]; - }, + if ( firstElem <= 0 || firstElem > 0 ) return array; + // unoptimized: ! isNaN( firstElem ) + // see http://jacksondunstan.com/articles/983 - setValueM4a = function( gl, v ) { + var n = nBlocks * blockSize, + r = arrayCacheF32[ n ]; - gl.uniformMatrix4fv( this.addr, false, flatten( v, this.size, 16 ) ); + if ( r === undefined ) { - }, + r = new Float32Array( n ); + arrayCacheF32[ n ] = r; - // Array of textures (2D / Cube) + } - setValueT1a = function( gl, v, renderer ) { + if ( nBlocks !== 0 ) { - var n = v.length, - units = allocTexUnits( renderer, n ); + firstElem.toArray( r, 0 ); - gl.uniform1iv( this.addr, units ); + for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) { - for ( var i = 0; i !== n; ++ i ) { + offset += blockSize; + array[ i ].toArray( r, offset ); - renderer.setTexture2D( v[ i ] || emptyTexture, units[ i ] ); + } - } + } - }, + return r; - setValueT6a = function( gl, v, renderer ) { + }, - var n = v.length, - units = allocTexUnits( renderer, n ); + // Texture unit allocation - gl.uniform1iv( this.addr, units ); + allocTexUnits = function( renderer, n ) { - for ( var i = 0; i !== n; ++ i ) { + var r = arrayCacheI32[ n ]; - renderer.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] ); + if ( r === undefined ) { - } + r = new Int32Array( n ); + arrayCacheI32[ n ] = r; - }, + } + for ( var i = 0; i !== n; ++ i ) + r[ i ] = renderer.allocTextureUnit(); - // Helper to pick the right setter for a pure (bottom-level) array + return r; - getPureArraySetter = function( type ) { + }, - switch ( type ) { + // --- Setters --- - case 0x1406: return setValue1fv; // FLOAT - case 0x8b50: return setValueV2a; // _VEC2 - case 0x8b51: return setValueV3a; // _VEC3 - case 0x8b52: return setValueV4a; // _VEC4 + // Note: Defining these methods externally, because they come in a bunch + // and this way their names minify. - case 0x8b5a: return setValueM2a; // _MAT2 - case 0x8b5b: return setValueM3a; // _MAT3 - case 0x8b5c: return setValueM4a; // _MAT4 + // Single scalar - case 0x8b5e: return setValueT1a; // SAMPLER_2D - case 0x8b60: return setValueT6a; // SAMPLER_CUBE + setValue1f = function( gl, v ) { gl.uniform1f( this.addr, v ); }, + setValue1i = function( gl, v ) { gl.uniform1i( this.addr, v ); }, - case 0x1404: case 0x8b56: return setValue1iv; // INT, BOOL - case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2 - case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3 - case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4 + // Single float vector (from flat array or THREE.VectorN) - } + setValue2fv = function( gl, v ) { - }, + if ( v.x === undefined ) gl.uniform2fv( this.addr, v ); + else gl.uniform2f( this.addr, v.x, v.y ); - // --- Uniform Classes --- + }, - SingleUniform = function SingleUniform( id, activeInfo, addr ) { + setValue3fv = function( gl, v ) { - this.id = id; - this.addr = addr; - this.setValue = getSingularSetter( activeInfo.type ); + if ( v.x !== undefined ) + gl.uniform3f( this.addr, v.x, v.y, v.z ); + else if ( v.r !== undefined ) + gl.uniform3f( this.addr, v.r, v.g, v.b ); + else + gl.uniform3fv( this.addr, v ); - // this.path = activeInfo.name; // DEBUG + }, - }, + setValue4fv = function( gl, v ) { - PureArrayUniform = function( id, activeInfo, addr ) { + if ( v.x === undefined ) gl.uniform4fv( this.addr, v ); + else gl.uniform4f( this.addr, v.x, v.y, v.z, v.w ); - this.id = id; - this.addr = addr; - this.size = activeInfo.size; - this.setValue = getPureArraySetter( activeInfo.type ); + }, - // this.path = activeInfo.name; // DEBUG + // Single matrix (from flat array or MatrixN) - }, + setValue2fm = function( gl, v ) { - StructuredUniform = function( id ) { + gl.uniformMatrix2fv( this.addr, false, v.elements || v ); - this.id = id; + }, - UniformContainer.call( this ); // mix-in + setValue3fm = function( gl, v ) { - }; + gl.uniformMatrix3fv( this.addr, false, v.elements || v ); - StructuredUniform.prototype.setValue = function( gl, value ) { + }, - // Note: Don't need an extra 'renderer' parameter, since samplers - // are not allowed in structured uniforms. + setValue4fm = function( gl, v ) { - var seq = this.seq; + gl.uniformMatrix4fv( this.addr, false, v.elements || v ); - for ( var i = 0, n = seq.length; i !== n; ++ i ) { + }, - var u = seq[ i ]; - u.setValue( gl, value[ u.id ] ); + // Single texture (2D / Cube) - } + setValueT1 = function( gl, v, renderer ) { - }; + var unit = renderer.allocTextureUnit(); + gl.uniform1i( this.addr, unit ); + renderer.setTexture2D( v || emptyTexture, unit ); - // --- Top-level --- + }, - // Parser - builds up the property tree from the path strings + setValueT6 = function( gl, v, renderer ) { - var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g, - // extracts - // - the identifier (member name or array index) - // - followed by an optional right bracket (found when array index) - // - followed by an optional left bracket or dot (type of subscript) - // - // Note: These portions can be read in a non-overlapping fashion and - // allow straightforward parsing of the hierarchy that WebGL encodes - // in the uniform names. + var unit = renderer.allocTextureUnit(); + gl.uniform1i( this.addr, unit ); + renderer.setTextureCube( v || emptyCubeTexture, unit ); - addUniform = function( container, uniformObject ) { + }, - container.seq.push( uniformObject ); - container.map[ uniformObject.id ] = uniformObject; + // Integer / Boolean vectors or arrays thereof (always flat arrays) - }, + setValue2iv = function( gl, v ) { gl.uniform2iv( this.addr, v ); }, + setValue3iv = function( gl, v ) { gl.uniform3iv( this.addr, v ); }, + setValue4iv = function( gl, v ) { gl.uniform4iv( this.addr, v ); }, - parseUniform = function( activeInfo, addr, container ) { + // Helper to pick the right setter for the singular case - var path = activeInfo.name, - pathLength = path.length; + getSingularSetter = function( type ) { - // reset RegExp object, because of the early exit of a previous run - RePathPart.lastIndex = 0; + switch ( type ) { - for (; ;) { + case 0x1406: return setValue1f; // FLOAT + case 0x8b50: return setValue2fv; // _VEC2 + case 0x8b51: return setValue3fv; // _VEC3 + case 0x8b52: return setValue4fv; // _VEC4 - var match = RePathPart.exec( path ), - matchEnd = RePathPart.lastIndex, + case 0x8b5a: return setValue2fm; // _MAT2 + case 0x8b5b: return setValue3fm; // _MAT3 + case 0x8b5c: return setValue4fm; // _MAT4 - id = match[ 1 ], - idIsIndex = match[ 2 ] === ']', - subscript = match[ 3 ]; + case 0x8b5e: return setValueT1; // SAMPLER_2D + case 0x8b60: return setValueT6; // SAMPLER_CUBE - if ( idIsIndex ) id = id | 0; // convert to integer + case 0x1404: case 0x8b56: return setValue1i; // INT, BOOL + case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2 + case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3 + case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4 - if ( subscript === undefined || - subscript === '[' && matchEnd + 2 === pathLength ) { - // bare name or "pure" bottom-level array "[0]" suffix + } - addUniform( container, subscript === undefined ? - new SingleUniform( id, activeInfo, addr ) : - new PureArrayUniform( id, activeInfo, addr ) ); + }, - break; + // Array of scalars - } else { - // step into inner node / create it in case it doesn't exist + setValue1fv = function( gl, v ) { gl.uniform1fv( this.addr, v ); }, + setValue1iv = function( gl, v ) { gl.uniform1iv( this.addr, v ); }, - var map = container.map, - next = map[ id ]; + // Array of vectors (flat or from THREE classes) - if ( next === undefined ) { + setValueV2a = function( gl, v ) { - next = new StructuredUniform( id ); - addUniform( container, next ); + gl.uniform2fv( this.addr, flatten( v, this.size, 2 ) ); - } + }, - container = next; + setValueV3a = function( gl, v ) { - } + gl.uniform3fv( this.addr, flatten( v, this.size, 3 ) ); - } + }, - }, + setValueV4a = function( gl, v ) { - // Root Container + gl.uniform4fv( this.addr, flatten( v, this.size, 4 ) ); - WebGLUniforms = function WebGLUniforms( gl, program, renderer ) { + }, - UniformContainer.call( this ); + // Array of matrices (flat or from THREE clases) - this.renderer = renderer; + setValueM2a = function( gl, v ) { - var n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS ); + gl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) ); - for ( var i = 0; i !== n; ++ i ) { + }, - var info = gl.getActiveUniform( program, i ), - path = info.name, - addr = gl.getUniformLocation( program, path ); + setValueM3a = function( gl, v ) { - parseUniform( info, addr, this ); + gl.uniformMatrix3fv( this.addr, false, flatten( v, this.size, 9 ) ); - } + }, - }; + setValueM4a = function( gl, v ) { + gl.uniformMatrix4fv( this.addr, false, flatten( v, this.size, 16 ) ); - WebGLUniforms.prototype.setValue = function( gl, name, value ) { + }, - var u = this.map[ name ]; + // Array of textures (2D / Cube) - if ( u !== undefined ) u.setValue( gl, value, this.renderer ); + setValueT1a = function( gl, v, renderer ) { - }; + var n = v.length, + units = allocTexUnits( renderer, n ); - WebGLUniforms.prototype.set = function( gl, object, name ) { + gl.uniform1iv( this.addr, units ); - var u = this.map[ name ]; + for ( var i = 0; i !== n; ++ i ) { - if ( u !== undefined ) u.setValue( gl, object[ name ], this.renderer ); + renderer.setTexture2D( v[ i ] || emptyTexture, units[ i ] ); - }; + } - WebGLUniforms.prototype.setOptional = function( gl, object, name ) { + }, - var v = object[ name ]; + setValueT6a = function( gl, v, renderer ) { - if ( v !== undefined ) this.setValue( gl, name, v ); + var n = v.length, + units = allocTexUnits( renderer, n ); - }; + gl.uniform1iv( this.addr, units ); + for ( var i = 0; i !== n; ++ i ) { - // Static interface + renderer.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] ); - WebGLUniforms.upload = function( gl, seq, values, renderer ) { + } - for ( var i = 0, n = seq.length; i !== n; ++ i ) { + }, - var u = seq[ i ], - v = values[ u.id ]; - if ( v.needsUpdate !== false ) { - // note: always updating when .needsUpdate is undefined + // Helper to pick the right setter for a pure (bottom-level) array - u.setValue( gl, v.value, renderer ); + getPureArraySetter = function( type ) { - } + switch ( type ) { - } + case 0x1406: return setValue1fv; // FLOAT + case 0x8b50: return setValueV2a; // _VEC2 + case 0x8b51: return setValueV3a; // _VEC3 + case 0x8b52: return setValueV4a; // _VEC4 - }; + case 0x8b5a: return setValueM2a; // _MAT2 + case 0x8b5b: return setValueM3a; // _MAT3 + case 0x8b5c: return setValueM4a; // _MAT4 - WebGLUniforms.seqWithValue = function( seq, values ) { + case 0x8b5e: return setValueT1a; // SAMPLER_2D + case 0x8b60: return setValueT6a; // SAMPLER_CUBE - var r = []; + case 0x1404: case 0x8b56: return setValue1iv; // INT, BOOL + case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2 + case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3 + case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4 - for ( var i = 0, n = seq.length; i !== n; ++ i ) { + } - var u = seq[ i ]; - if ( u.id in values ) r.push( u ); + }, - } + // --- Uniform Classes --- - return r; + SingleUniform = function SingleUniform( id, activeInfo, addr ) { - }; + this.id = id; + this.addr = addr; + this.setValue = getSingularSetter( activeInfo.type ); - WebGLUniforms.splitDynamic = function( seq, values ) { + // this.path = activeInfo.name; // DEBUG - var r = null, - n = seq.length, - w = 0; + }, - for ( var i = 0; i !== n; ++ i ) { + PureArrayUniform = function( id, activeInfo, addr ) { - var u = seq[ i ], - v = values[ u.id ]; + this.id = id; + this.addr = addr; + this.size = activeInfo.size; + this.setValue = getPureArraySetter( activeInfo.type ); - if ( v && v.dynamic === true ) { + // this.path = activeInfo.name; // DEBUG - if ( r === null ) r = []; - r.push( u ); + }, - } else { + StructuredUniform = function( id ) { - // in-place compact 'seq', removing the matches - if ( w < i ) seq[ w ] = u; - ++ w; + this.id = id; - } + UniformContainer.call( this ); // mix-in - } + }; - if ( w < n ) seq.length = w; + StructuredUniform.prototype.setValue = function( gl, value ) { - return r; + // Note: Don't need an extra 'renderer' parameter, since samplers + // are not allowed in structured uniforms. - }; + var seq = this.seq; - WebGLUniforms.evalDynamic = function( seq, values, object, camera ) { + for ( var i = 0, n = seq.length; i !== n; ++ i ) { - for ( var i = 0, n = seq.length; i !== n; ++ i ) { + var u = seq[ i ]; + u.setValue( gl, value[ u.id ] ); - var v = values[ seq[ i ].id ], - f = v.onUpdateCallback; + } - if ( f !== undefined ) f.call( v, object, camera ); + }; - } + // --- Top-level --- - }; + // Parser - builds up the property tree from the path strings - return WebGLUniforms; + var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g, + // extracts + // - the identifier (member name or array index) + // - followed by an optional right bracket (found when array index) + // - followed by an optional left bracket or dot (type of subscript) + // + // Note: These portions can be read in a non-overlapping fashion and + // allow straightforward parsing of the hierarchy that WebGL encodes + // in the uniform names. - } )(); + addUniform = function( container, uniformObject ) { - /** - * @author mrdoob / http://mrdoob.com/ - */ + container.seq.push( uniformObject ); + container.map[ uniformObject.id ] = uniformObject; - function WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, info ) { + }, - var _infoMemory = info.memory; - var _isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && _gl instanceof WebGL2RenderingContext ); + parseUniform = function( activeInfo, addr, container ) { - // + var path = activeInfo.name, + pathLength = path.length; - function clampToMaxSize( image, maxSize ) { + // reset RegExp object, because of the early exit of a previous run + RePathPart.lastIndex = 0; - if ( image.width > maxSize || image.height > maxSize ) { + for (; ;) { - // Warning: Scaling through the canvas will only work with images that use - // premultiplied alpha. + var match = RePathPart.exec( path ), + matchEnd = RePathPart.lastIndex, - var scale = maxSize / Math.max( image.width, image.height ); + id = match[ 1 ], + idIsIndex = match[ 2 ] === ']', + subscript = match[ 3 ]; - var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); - canvas.width = Math.floor( image.width * scale ); - canvas.height = Math.floor( image.height * scale ); + if ( idIsIndex ) id = id | 0; // convert to integer - var context = canvas.getContext( '2d' ); - context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height ); + if ( subscript === undefined || + subscript === '[' && matchEnd + 2 === pathLength ) { + // bare name or "pure" bottom-level array "[0]" suffix - console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image ); + addUniform( container, subscript === undefined ? + new SingleUniform( id, activeInfo, addr ) : + new PureArrayUniform( id, activeInfo, addr ) ); - return canvas; + break; - } + } else { + // step into inner node / create it in case it doesn't exist - return image; + var map = container.map, + next = map[ id ]; - } + if ( next === undefined ) { - function isPowerOfTwo( image ) { + next = new StructuredUniform( id ); + addUniform( container, next ); - return exports.Math.isPowerOfTwo( image.width ) && exports.Math.isPowerOfTwo( image.height ); + } - } + container = next; - function makePowerOfTwo( image ) { + } - if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement ) { + } - var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); - canvas.width = exports.Math.nearestPowerOfTwo( image.width ); - canvas.height = exports.Math.nearestPowerOfTwo( image.height ); + }, - var context = canvas.getContext( '2d' ); - context.drawImage( image, 0, 0, canvas.width, canvas.height ); + // Root Container - console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image ); + WebGLUniforms = function WebGLUniforms( gl, program, renderer ) { - return canvas; + UniformContainer.call( this ); - } + this.renderer = renderer; - return image; + var n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS ); - } + for ( var i = 0; i !== n; ++ i ) { - function textureNeedsPowerOfTwo( texture ) { + var info = gl.getActiveUniform( program, i ), + path = info.name, + addr = gl.getUniformLocation( program, path ); - if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) return true; - if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) return true; + parseUniform( info, addr, this ); - return false; + } - } + }; - // Fallback filters for non-power-of-2 textures - function filterFallback( f ) { + WebGLUniforms.prototype.setValue = function( gl, name, value ) { - if ( f === NearestFilter || f === NearestMipMapNearestFilter || f === NearestMipMapLinearFilter ) { + var u = this.map[ name ]; - return _gl.NEAREST; + if ( u !== undefined ) u.setValue( gl, value, this.renderer ); - } + }; - return _gl.LINEAR; + WebGLUniforms.prototype.set = function( gl, object, name ) { - } + var u = this.map[ name ]; - // + if ( u !== undefined ) u.setValue( gl, object[ name ], this.renderer ); - function onTextureDispose( event ) { + }; - var texture = event.target; + WebGLUniforms.prototype.setOptional = function( gl, object, name ) { - texture.removeEventListener( 'dispose', onTextureDispose ); + var v = object[ name ]; - deallocateTexture( texture ); + if ( v !== undefined ) this.setValue( gl, name, v ); - _infoMemory.textures --; + }; - } + // Static interface - function onRenderTargetDispose( event ) { + WebGLUniforms.upload = function( gl, seq, values, renderer ) { - var renderTarget = event.target; + for ( var i = 0, n = seq.length; i !== n; ++ i ) { - renderTarget.removeEventListener( 'dispose', onRenderTargetDispose ); + var u = seq[ i ], + v = values[ u.id ]; - deallocateRenderTarget( renderTarget ); + if ( v.needsUpdate !== false ) { + // note: always updating when .needsUpdate is undefined - _infoMemory.textures --; + u.setValue( gl, v.value, renderer ); - } + } - // + } - function deallocateTexture( texture ) { + }; - var textureProperties = properties.get( texture ); + WebGLUniforms.seqWithValue = function( seq, values ) { - if ( texture.image && textureProperties.__image__webglTextureCube ) { + var r = []; - // cube texture + for ( var i = 0, n = seq.length; i !== n; ++ i ) { - _gl.deleteTexture( textureProperties.__image__webglTextureCube ); + var u = seq[ i ]; + if ( u.id in values ) r.push( u ); - } else { + } - // 2D texture + return r; - if ( textureProperties.__webglInit === undefined ) return; + }; - _gl.deleteTexture( textureProperties.__webglTexture ); + WebGLUniforms.splitDynamic = function( seq, values ) { - } + var r = null, + n = seq.length, + w = 0; - // remove all webgl properties - properties.delete( texture ); + for ( var i = 0; i !== n; ++ i ) { - } + var u = seq[ i ], + v = values[ u.id ]; - function deallocateRenderTarget( renderTarget ) { + if ( v && v.dynamic === true ) { - var renderTargetProperties = properties.get( renderTarget ); - var textureProperties = properties.get( renderTarget.texture ); + if ( r === null ) r = []; + r.push( u ); - if ( ! renderTarget ) return; + } else { - if ( textureProperties.__webglTexture !== undefined ) { + // in-place compact 'seq', removing the matches + if ( w < i ) seq[ w ] = u; + ++ w; - _gl.deleteTexture( textureProperties.__webglTexture ); + } - } + } - if ( renderTarget.depthTexture ) { + if ( w < n ) seq.length = w; - renderTarget.depthTexture.dispose(); + return r; - } + }; - if ( (renderTarget && renderTarget.isWebGLRenderTargetCube) ) { + WebGLUniforms.evalDynamic = function( seq, values, object, camera ) { - for ( var i = 0; i < 6; i ++ ) { + for ( var i = 0, n = seq.length; i !== n; ++ i ) { - _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] ); - if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] ); + var v = values[ seq[ i ].id ], + f = v.onUpdateCallback; - } + if ( f !== undefined ) f.call( v, object, camera ); - } else { + } - _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer ); - if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer ); + }; - } + return WebGLUniforms; - properties.delete( renderTarget.texture ); - properties.delete( renderTarget ); + } )(); - } + /** + * @author mrdoob / http://mrdoob.com/ + */ - // + function WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, info ) { + var _infoMemory = info.memory; + var _isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && _gl instanceof WebGL2RenderingContext ); + // - function setTexture2D( texture, slot ) { + function clampToMaxSize( image, maxSize ) { - var textureProperties = properties.get( texture ); + if ( image.width > maxSize || image.height > maxSize ) { - if ( texture.version > 0 && textureProperties.__version !== texture.version ) { + // Warning: Scaling through the canvas will only work with images that use + // premultiplied alpha. - var image = texture.image; + var scale = maxSize / Math.max( image.width, image.height ); - if ( image === undefined ) { + var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); + canvas.width = Math.floor( image.width * scale ); + canvas.height = Math.floor( image.height * scale ); - console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture ); + var context = canvas.getContext( '2d' ); + context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height ); - } else if ( image.complete === false ) { + console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image ); - console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture ); + return canvas; - } else { + } - uploadTexture( textureProperties, texture, slot ); - return; + return image; - } + } - } + function isPowerOfTwo( image ) { - state.activeTexture( _gl.TEXTURE0 + slot ); - state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture ); + return exports.Math.isPowerOfTwo( image.width ) && exports.Math.isPowerOfTwo( image.height ); - } + } - function setTextureCube( texture, slot ) { + function makePowerOfTwo( image ) { - var textureProperties = properties.get( texture ); + if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement ) { - if ( texture.image.length === 6 ) { + var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); + canvas.width = exports.Math.nearestPowerOfTwo( image.width ); + canvas.height = exports.Math.nearestPowerOfTwo( image.height ); - if ( texture.version > 0 && textureProperties.__version !== texture.version ) { + var context = canvas.getContext( '2d' ); + context.drawImage( image, 0, 0, canvas.width, canvas.height ); - if ( ! textureProperties.__image__webglTextureCube ) { + console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image ); - texture.addEventListener( 'dispose', onTextureDispose ); + return canvas; - textureProperties.__image__webglTextureCube = _gl.createTexture(); + } - _infoMemory.textures ++; + return image; - } + } - state.activeTexture( _gl.TEXTURE0 + slot ); - state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube ); + function textureNeedsPowerOfTwo( texture ) { - _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY ); + if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) return true; + if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) return true; - var isCompressed = (texture && texture.isCompressedTexture); - var isDataTexture = (texture.image[ 0 ] && texture.image[ 0 ].isDataTexture); + return false; - var cubeImage = []; + } - for ( var i = 0; i < 6; i ++ ) { + // Fallback filters for non-power-of-2 textures - if ( ! isCompressed && ! isDataTexture ) { + function filterFallback( f ) { - cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize ); + if ( f === NearestFilter || f === NearestMipMapNearestFilter || f === NearestMipMapLinearFilter ) { - } else { + return _gl.NEAREST; - cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ]; + } - } + return _gl.LINEAR; - } + } - var image = cubeImage[ 0 ], - isPowerOfTwoImage = isPowerOfTwo( image ), - glFormat = paramThreeToGL( texture.format ), - glType = paramThreeToGL( texture.type ); + // - setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isPowerOfTwoImage ); + function onTextureDispose( event ) { - for ( var i = 0; i < 6; i ++ ) { + var texture = event.target; - if ( ! isCompressed ) { + texture.removeEventListener( 'dispose', onTextureDispose ); - if ( isDataTexture ) { + deallocateTexture( texture ); - state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data ); + _infoMemory.textures --; - } else { - state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] ); + } - } + function onRenderTargetDispose( event ) { - } else { + var renderTarget = event.target; - var mipmap, mipmaps = cubeImage[ i ].mipmaps; + renderTarget.removeEventListener( 'dispose', onRenderTargetDispose ); - for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) { + deallocateRenderTarget( renderTarget ); - mipmap = mipmaps[ j ]; + _infoMemory.textures --; - if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) { + } - if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) { + // - state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data ); + function deallocateTexture( texture ) { - } else { + var textureProperties = properties.get( texture ); - console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()" ); + if ( texture.image && textureProperties.__image__webglTextureCube ) { - } + // cube texture - } else { + _gl.deleteTexture( textureProperties.__image__webglTextureCube ); - state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + } else { - } + // 2D texture - } + if ( textureProperties.__webglInit === undefined ) return; - } + _gl.deleteTexture( textureProperties.__webglTexture ); - } + } - if ( texture.generateMipmaps && isPowerOfTwoImage ) { + // remove all webgl properties + properties.delete( texture ); - _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP ); + } - } + function deallocateRenderTarget( renderTarget ) { - textureProperties.__version = texture.version; + var renderTargetProperties = properties.get( renderTarget ); + var textureProperties = properties.get( renderTarget.texture ); - if ( texture.onUpdate ) texture.onUpdate( texture ); + if ( ! renderTarget ) return; - } else { + if ( textureProperties.__webglTexture !== undefined ) { - state.activeTexture( _gl.TEXTURE0 + slot ); - state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube ); + _gl.deleteTexture( textureProperties.__webglTexture ); - } + } - } + if ( renderTarget.depthTexture ) { - } + renderTarget.depthTexture.dispose(); - function setTextureCubeDynamic( texture, slot ) { + } - state.activeTexture( _gl.TEXTURE0 + slot ); - state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture ); + if ( (renderTarget && renderTarget.isWebGLRenderTargetCube) ) { - } + for ( var i = 0; i < 6; i ++ ) { - function setTextureParameters( textureType, texture, isPowerOfTwoImage ) { + _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] ); + if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] ); - var extension; + } - if ( isPowerOfTwoImage ) { + } else { - _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) ); - _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) ); + _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer ); + if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer ); - _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) ); - _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) ); + } - } else { + properties.delete( renderTarget.texture ); + properties.delete( renderTarget ); - _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE ); - _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE ); + } - if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) { + // - console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture ); - } - _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) ); - _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) ); + function setTexture2D( texture, slot ) { - if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) { + var textureProperties = properties.get( texture ); - console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture ); + if ( texture.version > 0 && textureProperties.__version !== texture.version ) { - } + var image = texture.image; - } + if ( image === undefined ) { - extension = extensions.get( 'EXT_texture_filter_anisotropic' ); + console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture ); - if ( extension ) { + } else if ( image.complete === false ) { - if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return; - if ( texture.type === HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return; + console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture ); - if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) { + } else { - _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) ); - properties.get( texture ).__currentAnisotropy = texture.anisotropy; + uploadTexture( textureProperties, texture, slot ); + return; - } + } - } + } - } + state.activeTexture( _gl.TEXTURE0 + slot ); + state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture ); - function uploadTexture( textureProperties, texture, slot ) { + } - if ( textureProperties.__webglInit === undefined ) { + function setTextureCube( texture, slot ) { - textureProperties.__webglInit = true; + var textureProperties = properties.get( texture ); - texture.addEventListener( 'dispose', onTextureDispose ); + if ( texture.image.length === 6 ) { - textureProperties.__webglTexture = _gl.createTexture(); + if ( texture.version > 0 && textureProperties.__version !== texture.version ) { - _infoMemory.textures ++; + if ( ! textureProperties.__image__webglTextureCube ) { - } + texture.addEventListener( 'dispose', onTextureDispose ); - state.activeTexture( _gl.TEXTURE0 + slot ); - state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture ); + textureProperties.__image__webglTextureCube = _gl.createTexture(); - _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY ); - _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha ); - _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment ); + _infoMemory.textures ++; - var image = clampToMaxSize( texture.image, capabilities.maxTextureSize ); + } - if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( image ) === false ) { + state.activeTexture( _gl.TEXTURE0 + slot ); + state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube ); - image = makePowerOfTwo( image ); + _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY ); - } + var isCompressed = (texture && texture.isCompressedTexture); + var isDataTexture = (texture.image[ 0 ] && texture.image[ 0 ].isDataTexture); - var isPowerOfTwoImage = isPowerOfTwo( image ), - glFormat = paramThreeToGL( texture.format ), - glType = paramThreeToGL( texture.type ); + var cubeImage = []; - setTextureParameters( _gl.TEXTURE_2D, texture, isPowerOfTwoImage ); + for ( var i = 0; i < 6; i ++ ) { - var mipmap, mipmaps = texture.mipmaps; + if ( ! isCompressed && ! isDataTexture ) { - if ( (texture && texture.isDepthTexture) ) { + cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize ); - // populate depth texture with dummy data + } else { - var internalFormat = _gl.DEPTH_COMPONENT; + cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ]; - if ( texture.type === FloatType ) { + } - if ( !_isWebGL2 ) throw new Error('Float Depth Texture only supported in WebGL2.0'); - internalFormat = _gl.DEPTH_COMPONENT32F; + } - } else if ( _isWebGL2 ) { + var image = cubeImage[ 0 ], + isPowerOfTwoImage = isPowerOfTwo( image ), + glFormat = paramThreeToGL( texture.format ), + glType = paramThreeToGL( texture.type ); - // WebGL 2.0 requires signed internalformat for glTexImage2D - internalFormat = _gl.DEPTH_COMPONENT16; + setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isPowerOfTwoImage ); - } + for ( var i = 0; i < 6; i ++ ) { - // Depth stencil textures need the DEPTH_STENCIL internal format - // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) - if ( texture.format === DepthStencilFormat ) { + if ( ! isCompressed ) { - internalFormat = _gl.DEPTH_STENCIL; + if ( isDataTexture ) { - } + state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data ); - state.texImage2D( _gl.TEXTURE_2D, 0, internalFormat, image.width, image.height, 0, glFormat, glType, null ); + } else { - } else if ( (texture && texture.isDataTexture) ) { + state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] ); - // use manually created mipmaps if available - // if there are no manual mipmaps - // set 0 level mipmap and then use GL to generate other mipmap levels + } - if ( mipmaps.length > 0 && isPowerOfTwoImage ) { + } else { - for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { + var mipmap, mipmaps = cubeImage[ i ].mipmaps; - mipmap = mipmaps[ i ]; - state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) { - } + mipmap = mipmaps[ j ]; - texture.generateMipmaps = false; + if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) { - } else { + if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) { - state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data ); + state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data ); - } + } else { - } else if ( (texture && texture.isCompressedTexture) ) { + console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()" ); - for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { + } - mipmap = mipmaps[ i ]; + } else { - if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) { + state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); - if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) { + } - state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data ); + } - } else { + } - console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" ); + } - } + if ( texture.generateMipmaps && isPowerOfTwoImage ) { - } else { + _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP ); - state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + } - } + textureProperties.__version = texture.version; - } + if ( texture.onUpdate ) texture.onUpdate( texture ); - } else { + } else { - // regular Texture (image, video, canvas) + state.activeTexture( _gl.TEXTURE0 + slot ); + state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube ); - // use manually created mipmaps if available - // if there are no manual mipmaps - // set 0 level mipmap and then use GL to generate other mipmap levels + } - if ( mipmaps.length > 0 && isPowerOfTwoImage ) { + } - for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { + } - mipmap = mipmaps[ i ]; - state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap ); + function setTextureCubeDynamic( texture, slot ) { - } + state.activeTexture( _gl.TEXTURE0 + slot ); + state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture ); - texture.generateMipmaps = false; + } - } else { + function setTextureParameters( textureType, texture, isPowerOfTwoImage ) { - state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, image ); + var extension; - } + if ( isPowerOfTwoImage ) { - } + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) ); + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) ); - if ( texture.generateMipmaps && isPowerOfTwoImage ) _gl.generateMipmap( _gl.TEXTURE_2D ); + _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) ); + _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) ); - textureProperties.__version = texture.version; + } else { - if ( texture.onUpdate ) texture.onUpdate( texture ); + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE ); + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE ); - } + if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) { - // Render targets + console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture ); - // Setup storage for target texture and bind it to correct framebuffer - function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) { + } - var glFormat = paramThreeToGL( renderTarget.texture.format ); - var glType = paramThreeToGL( renderTarget.texture.type ); - state.texImage2D( textureTarget, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null ); - _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); - _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 ); - _gl.bindFramebuffer( _gl.FRAMEBUFFER, null ); + _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) ); + _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) ); - } + if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) { - // Setup storage for internal depth/stencil buffers and bind to correct framebuffer - function setupRenderBufferStorage( renderbuffer, renderTarget ) { + console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture ); - _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer ); + } - if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) { + } - _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height ); - _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); + extension = extensions.get( 'EXT_texture_filter_anisotropic' ); - } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) { + if ( extension ) { - _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height ); - _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); + if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return; + if ( texture.type === HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return; - } else { + if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) { - // FIXME: We don't support !depth !stencil - _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height ); + _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) ); + properties.get( texture ).__currentAnisotropy = texture.anisotropy; - } + } - _gl.bindRenderbuffer( _gl.RENDERBUFFER, null ); + } - } + } - // Setup resources for a Depth Texture for a FBO (needs an extension) - function setupDepthTexture( framebuffer, renderTarget ) { + function uploadTexture( textureProperties, texture, slot ) { - var isCube = ( (renderTarget && renderTarget.isWebGLRenderTargetCube) ); - if ( isCube ) throw new Error('Depth Texture with cube render targets is not supported!'); + if ( textureProperties.__webglInit === undefined ) { - _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + textureProperties.__webglInit = true; - if ( !( (renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture) ) ) { + texture.addEventListener( 'dispose', onTextureDispose ); - throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture'); + textureProperties.__webglTexture = _gl.createTexture(); - } + _infoMemory.textures ++; - // upload an empty depth texture with framebuffer size - if ( !properties.get( renderTarget.depthTexture ).__webglTexture || - renderTarget.depthTexture.image.width !== renderTarget.width || - renderTarget.depthTexture.image.height !== renderTarget.height ) { - renderTarget.depthTexture.image.width = renderTarget.width; - renderTarget.depthTexture.image.height = renderTarget.height; - renderTarget.depthTexture.needsUpdate = true; - } + } - setTexture2D( renderTarget.depthTexture, 0 ); + state.activeTexture( _gl.TEXTURE0 + slot ); + state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture ); - var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture; + _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY ); + _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha ); + _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment ); - if ( renderTarget.depthTexture.format === DepthFormat ) { + var image = clampToMaxSize( texture.image, capabilities.maxTextureSize ); - _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 ); + if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( image ) === false ) { - } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) { + image = makePowerOfTwo( image ); - _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 ); + } - } else { + var isPowerOfTwoImage = isPowerOfTwo( image ), + glFormat = paramThreeToGL( texture.format ), + glType = paramThreeToGL( texture.type ); - throw new Error('Unknown depthTexture format') + setTextureParameters( _gl.TEXTURE_2D, texture, isPowerOfTwoImage ); - } + var mipmap, mipmaps = texture.mipmaps; - } + if ( (texture && texture.isDepthTexture) ) { - // Setup GL resources for a non-texture depth buffer - function setupDepthRenderbuffer( renderTarget ) { + // populate depth texture with dummy data - var renderTargetProperties = properties.get( renderTarget ); + var internalFormat = _gl.DEPTH_COMPONENT; - var isCube = ( (renderTarget && renderTarget.isWebGLRenderTargetCube) ); + if ( texture.type === FloatType ) { - if ( renderTarget.depthTexture ) { + if ( !_isWebGL2 ) throw new Error('Float Depth Texture only supported in WebGL2.0'); + internalFormat = _gl.DEPTH_COMPONENT32F; - if ( isCube ) throw new Error('target.depthTexture not supported in Cube render targets'); + } else if ( _isWebGL2 ) { - setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget ); + // WebGL 2.0 requires signed internalformat for glTexImage2D + internalFormat = _gl.DEPTH_COMPONENT16; - } else { + } - if ( isCube ) { + // Depth stencil textures need the DEPTH_STENCIL internal format + // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) + if ( texture.format === DepthStencilFormat ) { - renderTargetProperties.__webglDepthbuffer = []; + internalFormat = _gl.DEPTH_STENCIL; - for ( var i = 0; i < 6; i ++ ) { + } - _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] ); - renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer(); - setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget ); + state.texImage2D( _gl.TEXTURE_2D, 0, internalFormat, image.width, image.height, 0, glFormat, glType, null ); - } + } else if ( (texture && texture.isDataTexture) ) { - } else { + // use manually created mipmaps if available + // if there are no manual mipmaps + // set 0 level mipmap and then use GL to generate other mipmap levels - _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer ); - renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer(); - setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget ); + if ( mipmaps.length > 0 && isPowerOfTwoImage ) { - } + for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { - } + mipmap = mipmaps[ i ]; + state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); - _gl.bindFramebuffer( _gl.FRAMEBUFFER, null ); + } - } + texture.generateMipmaps = false; - // Set up GL resources for the render target - function setupRenderTarget( renderTarget ) { + } else { - var renderTargetProperties = properties.get( renderTarget ); - var textureProperties = properties.get( renderTarget.texture ); + state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data ); - renderTarget.addEventListener( 'dispose', onRenderTargetDispose ); + } - textureProperties.__webglTexture = _gl.createTexture(); + } else if ( (texture && texture.isCompressedTexture) ) { - _infoMemory.textures ++; + for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { - var isCube = ( (renderTarget && renderTarget.isWebGLRenderTargetCube) ); - var isTargetPowerOfTwo = isPowerOfTwo( renderTarget ); + mipmap = mipmaps[ i ]; - // Setup framebuffer + if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) { - if ( isCube ) { + if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) { - renderTargetProperties.__webglFramebuffer = []; + state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data ); - for ( var i = 0; i < 6; i ++ ) { + } else { - renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer(); + console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" ); - } + } - } else { + } else { - renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer(); + state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); - } + } - // Setup color buffer + } - if ( isCube ) { + } else { - state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture ); - setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo ); + // regular Texture (image, video, canvas) - for ( var i = 0; i < 6; i ++ ) { + // use manually created mipmaps if available + // if there are no manual mipmaps + // set 0 level mipmap and then use GL to generate other mipmap levels - setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i ); + if ( mipmaps.length > 0 && isPowerOfTwoImage ) { - } + for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { - if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP ); - state.bindTexture( _gl.TEXTURE_CUBE_MAP, null ); + mipmap = mipmaps[ i ]; + state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap ); - } else { + } - state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture ); - setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo ); - setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D ); + texture.generateMipmaps = false; - if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D ); - state.bindTexture( _gl.TEXTURE_2D, null ); + } else { - } + state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, image ); - // Setup depth and stencil buffers + } - if ( renderTarget.depthBuffer ) { + } - setupDepthRenderbuffer( renderTarget ); + if ( texture.generateMipmaps && isPowerOfTwoImage ) _gl.generateMipmap( _gl.TEXTURE_2D ); - } + textureProperties.__version = texture.version; - } + if ( texture.onUpdate ) texture.onUpdate( texture ); - function updateRenderTargetMipmap( renderTarget ) { + } - var texture = renderTarget.texture; + // Render targets - if ( texture.generateMipmaps && isPowerOfTwo( renderTarget ) && - texture.minFilter !== NearestFilter && - texture.minFilter !== LinearFilter ) { + // Setup storage for target texture and bind it to correct framebuffer + function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) { - var target = (renderTarget && renderTarget.isWebGLRenderTargetCube) ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D; - var webglTexture = properties.get( texture ).__webglTexture; + var glFormat = paramThreeToGL( renderTarget.texture.format ); + var glType = paramThreeToGL( renderTarget.texture.type ); + state.texImage2D( textureTarget, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null ); + _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 ); + _gl.bindFramebuffer( _gl.FRAMEBUFFER, null ); - state.bindTexture( target, webglTexture ); - _gl.generateMipmap( target ); - state.bindTexture( target, null ); + } - } + // Setup storage for internal depth/stencil buffers and bind to correct framebuffer + function setupRenderBufferStorage( renderbuffer, renderTarget ) { - } + _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer ); - this.setTexture2D = setTexture2D; - this.setTextureCube = setTextureCube; - this.setTextureCubeDynamic = setTextureCubeDynamic; - this.setupRenderTarget = setupRenderTarget; - this.updateRenderTargetMipmap = updateRenderTargetMipmap; + if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) { - }; + _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height ); + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); - /** - * @author supereggbert / http://www.paulbrunt.co.uk/ - * @author philogb / http://blog.thejit.org/ - * @author mikael emtinger / http://gomo.se/ - * @author egraether / http://egraether.com/ - * @author WestLangley / http://github.com/WestLangley - */ + } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) { - function Vector4( x, y, z, w ) { + _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height ); + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); - this.x = x || 0; - this.y = y || 0; - this.z = z || 0; - this.w = ( w !== undefined ) ? w : 1; + } else { - }; + // FIXME: We don't support !depth !stencil + _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height ); - Vector4.prototype = { + } - constructor: Vector4, + _gl.bindRenderbuffer( _gl.RENDERBUFFER, null ); - isVector4: true, + } - set: function ( x, y, z, w ) { + // Setup resources for a Depth Texture for a FBO (needs an extension) + function setupDepthTexture( framebuffer, renderTarget ) { - this.x = x; - this.y = y; - this.z = z; - this.w = w; + var isCube = ( (renderTarget && renderTarget.isWebGLRenderTargetCube) ); + if ( isCube ) throw new Error('Depth Texture with cube render targets is not supported!'); - return this; + _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); - }, + if ( !( (renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture) ) ) { - setScalar: function ( scalar ) { + throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture'); - this.x = scalar; - this.y = scalar; - this.z = scalar; - this.w = scalar; + } - return this; + // upload an empty depth texture with framebuffer size + if ( !properties.get( renderTarget.depthTexture ).__webglTexture || + renderTarget.depthTexture.image.width !== renderTarget.width || + renderTarget.depthTexture.image.height !== renderTarget.height ) { + renderTarget.depthTexture.image.width = renderTarget.width; + renderTarget.depthTexture.image.height = renderTarget.height; + renderTarget.depthTexture.needsUpdate = true; + } - }, + setTexture2D( renderTarget.depthTexture, 0 ); - setX: function ( x ) { + var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture; - this.x = x; + if ( renderTarget.depthTexture.format === DepthFormat ) { - return this; + _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 ); - }, + } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) { - setY: function ( y ) { + _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 ); - this.y = y; + } else { - return this; + throw new Error('Unknown depthTexture format') - }, + } - setZ: function ( z ) { + } - this.z = z; + // Setup GL resources for a non-texture depth buffer + function setupDepthRenderbuffer( renderTarget ) { - return this; + var renderTargetProperties = properties.get( renderTarget ); - }, + var isCube = ( (renderTarget && renderTarget.isWebGLRenderTargetCube) ); - setW: function ( w ) { + if ( renderTarget.depthTexture ) { - this.w = w; + if ( isCube ) throw new Error('target.depthTexture not supported in Cube render targets'); - return this; + setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget ); - }, + } else { - setComponent: function ( index, value ) { + if ( isCube ) { - switch ( index ) { + renderTargetProperties.__webglDepthbuffer = []; - case 0: this.x = value; break; - case 1: this.y = value; break; - case 2: this.z = value; break; - case 3: this.w = value; break; - default: throw new Error( 'index is out of range: ' + index ); + for ( var i = 0; i < 6; i ++ ) { - } + _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] ); + renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer(); + setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget ); - }, + } - getComponent: function ( index ) { + } else { - switch ( index ) { + _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer ); + renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer(); + setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget ); - case 0: return this.x; - case 1: return this.y; - case 2: return this.z; - case 3: return this.w; - default: throw new Error( 'index is out of range: ' + index ); + } - } + } - }, + _gl.bindFramebuffer( _gl.FRAMEBUFFER, null ); - clone: function () { + } - return new this.constructor( this.x, this.y, this.z, this.w ); + // Set up GL resources for the render target + function setupRenderTarget( renderTarget ) { - }, + var renderTargetProperties = properties.get( renderTarget ); + var textureProperties = properties.get( renderTarget.texture ); - copy: function ( v ) { + renderTarget.addEventListener( 'dispose', onRenderTargetDispose ); - this.x = v.x; - this.y = v.y; - this.z = v.z; - this.w = ( v.w !== undefined ) ? v.w : 1; + textureProperties.__webglTexture = _gl.createTexture(); - return this; + _infoMemory.textures ++; - }, + var isCube = ( (renderTarget && renderTarget.isWebGLRenderTargetCube) ); + var isTargetPowerOfTwo = isPowerOfTwo( renderTarget ); - add: function ( v, w ) { + // Setup framebuffer - if ( w !== undefined ) { + if ( isCube ) { - console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); - return this.addVectors( v, w ); + renderTargetProperties.__webglFramebuffer = []; - } + for ( var i = 0; i < 6; i ++ ) { - this.x += v.x; - this.y += v.y; - this.z += v.z; - this.w += v.w; + renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer(); - return this; + } - }, + } else { - addScalar: function ( s ) { + renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer(); - this.x += s; - this.y += s; - this.z += s; - this.w += s; + } - return this; + // Setup color buffer - }, + if ( isCube ) { - addVectors: function ( a, b ) { + state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture ); + setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo ); - this.x = a.x + b.x; - this.y = a.y + b.y; - this.z = a.z + b.z; - this.w = a.w + b.w; + for ( var i = 0; i < 6; i ++ ) { - return this; + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i ); - }, + } - addScaledVector: function ( v, s ) { + if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP ); + state.bindTexture( _gl.TEXTURE_CUBE_MAP, null ); - this.x += v.x * s; - this.y += v.y * s; - this.z += v.z * s; - this.w += v.w * s; + } else { - return this; + state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture ); + setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo ); + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D ); - }, + if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D ); + state.bindTexture( _gl.TEXTURE_2D, null ); - sub: function ( v, w ) { + } - if ( w !== undefined ) { + // Setup depth and stencil buffers - console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); - return this.subVectors( v, w ); + if ( renderTarget.depthBuffer ) { - } + setupDepthRenderbuffer( renderTarget ); - this.x -= v.x; - this.y -= v.y; - this.z -= v.z; - this.w -= v.w; + } - return this; + } - }, + function updateRenderTargetMipmap( renderTarget ) { - subScalar: function ( s ) { + var texture = renderTarget.texture; - this.x -= s; - this.y -= s; - this.z -= s; - this.w -= s; + if ( texture.generateMipmaps && isPowerOfTwo( renderTarget ) && + texture.minFilter !== NearestFilter && + texture.minFilter !== LinearFilter ) { - return this; + var target = (renderTarget && renderTarget.isWebGLRenderTargetCube) ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D; + var webglTexture = properties.get( texture ).__webglTexture; - }, + state.bindTexture( target, webglTexture ); + _gl.generateMipmap( target ); + state.bindTexture( target, null ); - subVectors: function ( a, b ) { + } - this.x = a.x - b.x; - this.y = a.y - b.y; - this.z = a.z - b.z; - this.w = a.w - b.w; + } - return this; + this.setTexture2D = setTexture2D; + this.setTextureCube = setTextureCube; + this.setTextureCubeDynamic = setTextureCubeDynamic; + this.setupRenderTarget = setupRenderTarget; + this.updateRenderTargetMipmap = updateRenderTargetMipmap; - }, + } - multiplyScalar: function ( scalar ) { + /** + * @author supereggbert / http://www.paulbrunt.co.uk/ + * @author philogb / http://blog.thejit.org/ + * @author mikael emtinger / http://gomo.se/ + * @author egraether / http://egraether.com/ + * @author WestLangley / http://github.com/WestLangley + */ - if ( isFinite( scalar ) ) { + function Vector4( x, y, z, w ) { - this.x *= scalar; - this.y *= scalar; - this.z *= scalar; - this.w *= scalar; + this.x = x || 0; + this.y = y || 0; + this.z = z || 0; + this.w = ( w !== undefined ) ? w : 1; - } else { + } - this.x = 0; - this.y = 0; - this.z = 0; - this.w = 0; + Vector4.prototype = { - } + constructor: Vector4, - return this; + isVector4: true, - }, + set: function ( x, y, z, w ) { - applyMatrix4: function ( m ) { + this.x = x; + this.y = y; + this.z = z; + this.w = w; - var x = this.x, y = this.y, z = this.z, w = this.w; - var e = m.elements; + return this; - this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w; - this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w; - this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w; - this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w; + }, - return this; + setScalar: function ( scalar ) { - }, + this.x = scalar; + this.y = scalar; + this.z = scalar; + this.w = scalar; - divideScalar: function ( scalar ) { + return this; - return this.multiplyScalar( 1 / scalar ); + }, - }, + setX: function ( x ) { - setAxisAngleFromQuaternion: function ( q ) { + this.x = x; - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm + return this; - // q is assumed to be normalized + }, - this.w = 2 * Math.acos( q.w ); + setY: function ( y ) { - var s = Math.sqrt( 1 - q.w * q.w ); + this.y = y; - if ( s < 0.0001 ) { + return this; - this.x = 1; - this.y = 0; - this.z = 0; + }, - } else { + setZ: function ( z ) { - this.x = q.x / s; - this.y = q.y / s; - this.z = q.z / s; + this.z = z; - } + return this; - return this; + }, - }, + setW: function ( w ) { - setAxisAngleFromRotationMatrix: function ( m ) { + this.w = w; - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm + return this; - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + }, - var angle, x, y, z, // variables for result - epsilon = 0.01, // margin to allow for rounding errors - epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees + setComponent: function ( index, value ) { - te = m.elements, + switch ( index ) { - m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ], - m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ], - m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ]; + case 0: this.x = value; break; + case 1: this.y = value; break; + case 2: this.z = value; break; + case 3: this.w = value; break; + default: throw new Error( 'index is out of range: ' + index ); - if ( ( Math.abs( m12 - m21 ) < epsilon ) && - ( Math.abs( m13 - m31 ) < epsilon ) && - ( Math.abs( m23 - m32 ) < epsilon ) ) { + } - // singularity found - // first check for identity matrix which must have +1 for all terms - // in leading diagonal and zero in other terms + }, - if ( ( Math.abs( m12 + m21 ) < epsilon2 ) && - ( Math.abs( m13 + m31 ) < epsilon2 ) && - ( Math.abs( m23 + m32 ) < epsilon2 ) && - ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) { + getComponent: function ( index ) { - // this singularity is identity matrix so angle = 0 + switch ( index ) { - this.set( 1, 0, 0, 0 ); + case 0: return this.x; + case 1: return this.y; + case 2: return this.z; + case 3: return this.w; + default: throw new Error( 'index is out of range: ' + index ); - return this; // zero angle, arbitrary axis + } - } + }, - // otherwise this singularity is angle = 180 + clone: function () { - angle = Math.PI; + return new this.constructor( this.x, this.y, this.z, this.w ); - var xx = ( m11 + 1 ) / 2; - var yy = ( m22 + 1 ) / 2; - var zz = ( m33 + 1 ) / 2; - var xy = ( m12 + m21 ) / 4; - var xz = ( m13 + m31 ) / 4; - var yz = ( m23 + m32 ) / 4; + }, - if ( ( xx > yy ) && ( xx > zz ) ) { + copy: function ( v ) { - // m11 is the largest diagonal term + this.x = v.x; + this.y = v.y; + this.z = v.z; + this.w = ( v.w !== undefined ) ? v.w : 1; - if ( xx < epsilon ) { + return this; - x = 0; - y = 0.707106781; - z = 0.707106781; + }, - } else { + add: function ( v, w ) { - x = Math.sqrt( xx ); - y = xy / x; - z = xz / x; + if ( w !== undefined ) { - } + console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); + return this.addVectors( v, w ); - } else if ( yy > zz ) { + } - // m22 is the largest diagonal term + this.x += v.x; + this.y += v.y; + this.z += v.z; + this.w += v.w; - if ( yy < epsilon ) { + return this; - x = 0.707106781; - y = 0; - z = 0.707106781; + }, - } else { + addScalar: function ( s ) { - y = Math.sqrt( yy ); - x = xy / y; - z = yz / y; + this.x += s; + this.y += s; + this.z += s; + this.w += s; - } + return this; - } else { + }, - // m33 is the largest diagonal term so base result on this + addVectors: function ( a, b ) { - if ( zz < epsilon ) { + this.x = a.x + b.x; + this.y = a.y + b.y; + this.z = a.z + b.z; + this.w = a.w + b.w; - x = 0.707106781; - y = 0.707106781; - z = 0; + return this; - } else { + }, - z = Math.sqrt( zz ); - x = xz / z; - y = yz / z; + addScaledVector: function ( v, s ) { - } + this.x += v.x * s; + this.y += v.y * s; + this.z += v.z * s; + this.w += v.w * s; - } + return this; - this.set( x, y, z, angle ); + }, - return this; // return 180 deg rotation + sub: function ( v, w ) { - } + if ( w !== undefined ) { - // as we have reached here there are no singularities so we can handle normally + console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); + return this.subVectors( v, w ); - var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) + - ( m13 - m31 ) * ( m13 - m31 ) + - ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize + } - if ( Math.abs( s ) < 0.001 ) s = 1; + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; + this.w -= v.w; - // prevent divide by zero, should not happen if matrix is orthogonal and should be - // caught by singularity test above, but I've left it in just in case + return this; - this.x = ( m32 - m23 ) / s; - this.y = ( m13 - m31 ) / s; - this.z = ( m21 - m12 ) / s; - this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 ); + }, - return this; + subScalar: function ( s ) { - }, + this.x -= s; + this.y -= s; + this.z -= s; + this.w -= s; - min: function ( v ) { + return this; - this.x = Math.min( this.x, v.x ); - this.y = Math.min( this.y, v.y ); - this.z = Math.min( this.z, v.z ); - this.w = Math.min( this.w, v.w ); + }, - return this; + subVectors: function ( a, b ) { - }, + this.x = a.x - b.x; + this.y = a.y - b.y; + this.z = a.z - b.z; + this.w = a.w - b.w; - max: function ( v ) { + return this; - this.x = Math.max( this.x, v.x ); - this.y = Math.max( this.y, v.y ); - this.z = Math.max( this.z, v.z ); - this.w = Math.max( this.w, v.w ); + }, - return this; + multiplyScalar: function ( scalar ) { - }, + if ( isFinite( scalar ) ) { - clamp: function ( min, max ) { + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; + this.w *= scalar; - // This function assumes min < max, if this assumption isn't true it will not operate correctly + } else { - this.x = Math.max( min.x, Math.min( max.x, this.x ) ); - this.y = Math.max( min.y, Math.min( max.y, this.y ) ); - this.z = Math.max( min.z, Math.min( max.z, this.z ) ); - this.w = Math.max( min.w, Math.min( max.w, this.w ) ); + this.x = 0; + this.y = 0; + this.z = 0; + this.w = 0; - return this; + } - }, + return this; - clampScalar: function () { + }, - var min, max; + applyMatrix4: function ( m ) { - return function clampScalar( minVal, maxVal ) { + var x = this.x, y = this.y, z = this.z, w = this.w; + var e = m.elements; - if ( min === undefined ) { + this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w; + this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w; + this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w; + this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w; - min = new Vector4(); - max = new Vector4(); + return this; - } + }, - min.set( minVal, minVal, minVal, minVal ); - max.set( maxVal, maxVal, maxVal, maxVal ); + divideScalar: function ( scalar ) { - return this.clamp( min, max ); + return this.multiplyScalar( 1 / scalar ); - }; + }, - }(), + setAxisAngleFromQuaternion: function ( q ) { - floor: function () { + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm - this.x = Math.floor( this.x ); - this.y = Math.floor( this.y ); - this.z = Math.floor( this.z ); - this.w = Math.floor( this.w ); + // q is assumed to be normalized - return this; + this.w = 2 * Math.acos( q.w ); - }, + var s = Math.sqrt( 1 - q.w * q.w ); - ceil: function () { + if ( s < 0.0001 ) { - this.x = Math.ceil( this.x ); - this.y = Math.ceil( this.y ); - this.z = Math.ceil( this.z ); - this.w = Math.ceil( this.w ); + this.x = 1; + this.y = 0; + this.z = 0; - return this; + } else { - }, + this.x = q.x / s; + this.y = q.y / s; + this.z = q.z / s; - round: function () { + } - this.x = Math.round( this.x ); - this.y = Math.round( this.y ); - this.z = Math.round( this.z ); - this.w = Math.round( this.w ); + return this; - return this; + }, - }, + setAxisAngleFromRotationMatrix: function ( m ) { - roundToZero: function () { + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm - this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); - this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); - this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z ); - this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w ); + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - return this; + var angle, x, y, z, // variables for result + epsilon = 0.01, // margin to allow for rounding errors + epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees - }, + te = m.elements, - negate: function () { + m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ], + m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ], + m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ]; - this.x = - this.x; - this.y = - this.y; - this.z = - this.z; - this.w = - this.w; + if ( ( Math.abs( m12 - m21 ) < epsilon ) && + ( Math.abs( m13 - m31 ) < epsilon ) && + ( Math.abs( m23 - m32 ) < epsilon ) ) { - return this; + // singularity found + // first check for identity matrix which must have +1 for all terms + // in leading diagonal and zero in other terms - }, + if ( ( Math.abs( m12 + m21 ) < epsilon2 ) && + ( Math.abs( m13 + m31 ) < epsilon2 ) && + ( Math.abs( m23 + m32 ) < epsilon2 ) && + ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) { - dot: function ( v ) { + // this singularity is identity matrix so angle = 0 - return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; + this.set( 1, 0, 0, 0 ); - }, + return this; // zero angle, arbitrary axis - lengthSq: function () { + } - return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; + // otherwise this singularity is angle = 180 - }, + angle = Math.PI; - length: function () { + var xx = ( m11 + 1 ) / 2; + var yy = ( m22 + 1 ) / 2; + var zz = ( m33 + 1 ) / 2; + var xy = ( m12 + m21 ) / 4; + var xz = ( m13 + m31 ) / 4; + var yz = ( m23 + m32 ) / 4; - return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w ); + if ( ( xx > yy ) && ( xx > zz ) ) { - }, + // m11 is the largest diagonal term - lengthManhattan: function () { + if ( xx < epsilon ) { - return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w ); + x = 0; + y = 0.707106781; + z = 0.707106781; - }, + } else { - normalize: function () { + x = Math.sqrt( xx ); + y = xy / x; + z = xz / x; - return this.divideScalar( this.length() ); + } - }, + } else if ( yy > zz ) { - setLength: function ( length ) { + // m22 is the largest diagonal term - return this.multiplyScalar( length / this.length() ); + if ( yy < epsilon ) { - }, + x = 0.707106781; + y = 0; + z = 0.707106781; - lerp: function ( v, alpha ) { + } else { - this.x += ( v.x - this.x ) * alpha; - this.y += ( v.y - this.y ) * alpha; - this.z += ( v.z - this.z ) * alpha; - this.w += ( v.w - this.w ) * alpha; + y = Math.sqrt( yy ); + x = xy / y; + z = yz / y; - return this; + } - }, + } else { - lerpVectors: function ( v1, v2, alpha ) { + // m33 is the largest diagonal term so base result on this - return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); + if ( zz < epsilon ) { - }, + x = 0.707106781; + y = 0.707106781; + z = 0; - equals: function ( v ) { + } else { - return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) ); + z = Math.sqrt( zz ); + x = xz / z; + y = yz / z; - }, + } - fromArray: function ( array, offset ) { + } - if ( offset === undefined ) offset = 0; + this.set( x, y, z, angle ); - this.x = array[ offset ]; - this.y = array[ offset + 1 ]; - this.z = array[ offset + 2 ]; - this.w = array[ offset + 3 ]; + return this; // return 180 deg rotation - return this; + } - }, + // as we have reached here there are no singularities so we can handle normally - toArray: function ( array, offset ) { + var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) + + ( m13 - m31 ) * ( m13 - m31 ) + + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + if ( Math.abs( s ) < 0.001 ) s = 1; - array[ offset ] = this.x; - array[ offset + 1 ] = this.y; - array[ offset + 2 ] = this.z; - array[ offset + 3 ] = this.w; + // prevent divide by zero, should not happen if matrix is orthogonal and should be + // caught by singularity test above, but I've left it in just in case - return array; + this.x = ( m32 - m23 ) / s; + this.y = ( m13 - m31 ) / s; + this.z = ( m21 - m12 ) / s; + this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 ); - }, + return this; - fromAttribute: function ( attribute, index, offset ) { + }, - if ( offset === undefined ) offset = 0; + min: function ( v ) { - index = index * attribute.itemSize + offset; + this.x = Math.min( this.x, v.x ); + this.y = Math.min( this.y, v.y ); + this.z = Math.min( this.z, v.z ); + this.w = Math.min( this.w, v.w ); - this.x = attribute.array[ index ]; - this.y = attribute.array[ index + 1 ]; - this.z = attribute.array[ index + 2 ]; - this.w = attribute.array[ index + 3 ]; + return this; - return this; + }, - } + max: function ( v ) { - }; + this.x = Math.max( this.x, v.x ); + this.y = Math.max( this.y, v.y ); + this.z = Math.max( this.z, v.z ); + this.w = Math.max( this.w, v.w ); - /** - * @author mrdoob / http://mrdoob.com/ - */ + return this; - function WebGLState( gl, extensions, paramThreeToGL ) { + }, - var _this = this; + clamp: function ( min, max ) { - this.buffers = { - color: new WebGLColorBuffer( gl, this ), - depth: new WebGLDepthBuffer( gl, this ), - stencil: new WebGLStencilBuffer( gl, this ) - }; + // This function assumes min < max, if this assumption isn't true it will not operate correctly - var maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS ); - var newAttributes = new Uint8Array( maxVertexAttributes ); - var enabledAttributes = new Uint8Array( maxVertexAttributes ); - var attributeDivisors = new Uint8Array( maxVertexAttributes ); + this.x = Math.max( min.x, Math.min( max.x, this.x ) ); + this.y = Math.max( min.y, Math.min( max.y, this.y ) ); + this.z = Math.max( min.z, Math.min( max.z, this.z ) ); + this.w = Math.max( min.w, Math.min( max.w, this.w ) ); - var capabilities = {}; + return this; - var compressedTextureFormats = null; + }, - var currentBlending = null; - var currentBlendEquation = null; - var currentBlendSrc = null; - var currentBlendDst = null; - var currentBlendEquationAlpha = null; - var currentBlendSrcAlpha = null; - var currentBlendDstAlpha = null; - var currentPremultipledAlpha = false; + clampScalar: function () { - var currentFlipSided = null; - var currentCullFace = null; + var min, max; - var currentLineWidth = null; + return function clampScalar( minVal, maxVal ) { - var currentPolygonOffsetFactor = null; - var currentPolygonOffsetUnits = null; + if ( min === undefined ) { - var currentScissorTest = null; + min = new Vector4(); + max = new Vector4(); - var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS ); + } - var currentTextureSlot = null; - var currentBoundTextures = {}; + min.set( minVal, minVal, minVal, minVal ); + max.set( maxVal, maxVal, maxVal, maxVal ); - var currentScissor = new Vector4(); - var currentViewport = new Vector4(); + return this.clamp( min, max ); - function createTexture( type, target, count ) { + }; - var data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4. - var texture = gl.createTexture(); + }(), - gl.bindTexture( type, texture ); - gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST ); - gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST ); + floor: function () { - for ( var i = 0; i < count; i ++ ) { + this.x = Math.floor( this.x ); + this.y = Math.floor( this.y ); + this.z = Math.floor( this.z ); + this.w = Math.floor( this.w ); - gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data ); + return this; - } + }, - return texture; + ceil: function () { - } + this.x = Math.ceil( this.x ); + this.y = Math.ceil( this.y ); + this.z = Math.ceil( this.z ); + this.w = Math.ceil( this.w ); - var emptyTextures = {}; - emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 ); - emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 ); + return this; - // + }, - this.init = function () { + round: function () { - this.clearColor( 0, 0, 0, 1 ); - this.clearDepth( 1 ); - this.clearStencil( 0 ); + this.x = Math.round( this.x ); + this.y = Math.round( this.y ); + this.z = Math.round( this.z ); + this.w = Math.round( this.w ); - this.enable( gl.DEPTH_TEST ); - this.setDepthFunc( LessEqualDepth ); + return this; - this.setFlipSided( false ); - this.setCullFace( CullFaceBack ); - this.enable( gl.CULL_FACE ); + }, - this.enable( gl.BLEND ); - this.setBlending( NormalBlending ); + roundToZero: function () { - }; + this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); + this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); + this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z ); + this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w ); - this.initAttributes = function () { + return this; - for ( var i = 0, l = newAttributes.length; i < l; i ++ ) { + }, - newAttributes[ i ] = 0; + negate: function () { - } + this.x = - this.x; + this.y = - this.y; + this.z = - this.z; + this.w = - this.w; - }; + return this; - this.enableAttribute = function ( attribute ) { + }, - newAttributes[ attribute ] = 1; + dot: function ( v ) { - if ( enabledAttributes[ attribute ] === 0 ) { + return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; - gl.enableVertexAttribArray( attribute ); - enabledAttributes[ attribute ] = 1; + }, - } + lengthSq: function () { - if ( attributeDivisors[ attribute ] !== 0 ) { + return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; - var extension = extensions.get( 'ANGLE_instanced_arrays' ); + }, - extension.vertexAttribDivisorANGLE( attribute, 0 ); - attributeDivisors[ attribute ] = 0; + length: function () { - } + return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w ); - }; + }, - this.enableAttributeAndDivisor = function ( attribute, meshPerAttribute, extension ) { + lengthManhattan: function () { - newAttributes[ attribute ] = 1; + return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w ); - if ( enabledAttributes[ attribute ] === 0 ) { + }, - gl.enableVertexAttribArray( attribute ); - enabledAttributes[ attribute ] = 1; + normalize: function () { - } + return this.divideScalar( this.length() ); - if ( attributeDivisors[ attribute ] !== meshPerAttribute ) { + }, - extension.vertexAttribDivisorANGLE( attribute, meshPerAttribute ); - attributeDivisors[ attribute ] = meshPerAttribute; + setLength: function ( length ) { - } + return this.multiplyScalar( length / this.length() ); - }; + }, - this.disableUnusedAttributes = function () { + lerp: function ( v, alpha ) { - for ( var i = 0, l = enabledAttributes.length; i !== l; ++ i ) { + this.x += ( v.x - this.x ) * alpha; + this.y += ( v.y - this.y ) * alpha; + this.z += ( v.z - this.z ) * alpha; + this.w += ( v.w - this.w ) * alpha; - if ( enabledAttributes[ i ] !== newAttributes[ i ] ) { + return this; - gl.disableVertexAttribArray( i ); - enabledAttributes[ i ] = 0; + }, - } + lerpVectors: function ( v1, v2, alpha ) { - } + return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); - }; + }, - this.enable = function ( id ) { + equals: function ( v ) { - if ( capabilities[ id ] !== true ) { + return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) ); - gl.enable( id ); - capabilities[ id ] = true; + }, - } + fromArray: function ( array, offset ) { - }; + if ( offset === undefined ) offset = 0; - this.disable = function ( id ) { + this.x = array[ offset ]; + this.y = array[ offset + 1 ]; + this.z = array[ offset + 2 ]; + this.w = array[ offset + 3 ]; - if ( capabilities[ id ] !== false ) { + return this; - gl.disable( id ); - capabilities[ id ] = false; + }, - } + toArray: function ( array, offset ) { - }; + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - this.getCompressedTextureFormats = function () { + array[ offset ] = this.x; + array[ offset + 1 ] = this.y; + array[ offset + 2 ] = this.z; + array[ offset + 3 ] = this.w; - if ( compressedTextureFormats === null ) { + return array; - compressedTextureFormats = []; + }, - if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) || - extensions.get( 'WEBGL_compressed_texture_s3tc' ) || - extensions.get( 'WEBGL_compressed_texture_etc1' ) ) { + fromAttribute: function ( attribute, index, offset ) { - var formats = gl.getParameter( gl.COMPRESSED_TEXTURE_FORMATS ); + if ( offset === undefined ) offset = 0; - for ( var i = 0; i < formats.length; i ++ ) { + index = index * attribute.itemSize + offset; - compressedTextureFormats.push( formats[ i ] ); + this.x = attribute.array[ index ]; + this.y = attribute.array[ index + 1 ]; + this.z = attribute.array[ index + 2 ]; + this.w = attribute.array[ index + 3 ]; - } + return this; - } + } - } + }; - return compressedTextureFormats; + /** + * @author mrdoob / http://mrdoob.com/ + */ - }; + function WebGLState( gl, extensions, paramThreeToGL ) { - this.setBlending = function ( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) { + var _this = this; - if ( blending !== NoBlending ) { + this.buffers = { + color: new WebGLColorBuffer( gl, this ), + depth: new WebGLDepthBuffer( gl, this ), + stencil: new WebGLStencilBuffer( gl, this ) + }; - this.enable( gl.BLEND ); + var maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS ); + var newAttributes = new Uint8Array( maxVertexAttributes ); + var enabledAttributes = new Uint8Array( maxVertexAttributes ); + var attributeDivisors = new Uint8Array( maxVertexAttributes ); - } else { + var capabilities = {}; - this.disable( gl.BLEND ); - currentBlending = blending; // no blending, that is - return; + var compressedTextureFormats = null; - } + var currentBlending = null; + var currentBlendEquation = null; + var currentBlendSrc = null; + var currentBlendDst = null; + var currentBlendEquationAlpha = null; + var currentBlendSrcAlpha = null; + var currentBlendDstAlpha = null; + var currentPremultipledAlpha = false; - if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) { + var currentFlipSided = null; + var currentCullFace = null; - if ( blending === AdditiveBlending ) { + var currentLineWidth = null; - if ( premultipliedAlpha ) { + var currentPolygonOffsetFactor = null; + var currentPolygonOffsetUnits = null; - gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); - gl.blendFuncSeparate( gl.ONE, gl.ONE, gl.ONE, gl.ONE ); + var currentScissorTest = null; - } else { + var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS ); - gl.blendEquation( gl.FUNC_ADD ); - gl.blendFunc( gl.SRC_ALPHA, gl.ONE ); + var currentTextureSlot = null; + var currentBoundTextures = {}; - } + var currentScissor = new Vector4(); + var currentViewport = new Vector4(); - } else if ( blending === SubtractiveBlending ) { + function createTexture( type, target, count ) { - if ( premultipliedAlpha ) { + var data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4. + var texture = gl.createTexture(); - gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); - gl.blendFuncSeparate( gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA ); + gl.bindTexture( type, texture ); + gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST ); + gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST ); - } else { + for ( var i = 0; i < count; i ++ ) { - gl.blendEquation( gl.FUNC_ADD ); - gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR ); + gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data ); - } + } - } else if ( blending === MultiplyBlending ) { + return texture; - if ( premultipliedAlpha ) { + } - gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); - gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA ); + var emptyTextures = {}; + emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 ); + emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 ); - } else { + // - gl.blendEquation( gl.FUNC_ADD ); - gl.blendFunc( gl.ZERO, gl.SRC_COLOR ); + this.init = function () { - } + this.clearColor( 0, 0, 0, 1 ); + this.clearDepth( 1 ); + this.clearStencil( 0 ); - } else { + this.enable( gl.DEPTH_TEST ); + this.setDepthFunc( LessEqualDepth ); - if ( premultipliedAlpha ) { + this.setFlipSided( false ); + this.setCullFace( CullFaceBack ); + this.enable( gl.CULL_FACE ); - gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); - gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA ); + this.enable( gl.BLEND ); + this.setBlending( NormalBlending ); - } else { + }; - gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); - gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA ); + this.initAttributes = function () { - } + for ( var i = 0, l = newAttributes.length; i < l; i ++ ) { - } + newAttributes[ i ] = 0; - currentBlending = blending; - currentPremultipledAlpha = premultipliedAlpha; + } - } + }; - if ( blending === CustomBlending ) { + this.enableAttribute = function ( attribute ) { - blendEquationAlpha = blendEquationAlpha || blendEquation; - blendSrcAlpha = blendSrcAlpha || blendSrc; - blendDstAlpha = blendDstAlpha || blendDst; + newAttributes[ attribute ] = 1; - if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) { + if ( enabledAttributes[ attribute ] === 0 ) { - gl.blendEquationSeparate( paramThreeToGL( blendEquation ), paramThreeToGL( blendEquationAlpha ) ); + gl.enableVertexAttribArray( attribute ); + enabledAttributes[ attribute ] = 1; - currentBlendEquation = blendEquation; - currentBlendEquationAlpha = blendEquationAlpha; + } - } + if ( attributeDivisors[ attribute ] !== 0 ) { - if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) { + var extension = extensions.get( 'ANGLE_instanced_arrays' ); - gl.blendFuncSeparate( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ), paramThreeToGL( blendSrcAlpha ), paramThreeToGL( blendDstAlpha ) ); + extension.vertexAttribDivisorANGLE( attribute, 0 ); + attributeDivisors[ attribute ] = 0; - currentBlendSrc = blendSrc; - currentBlendDst = blendDst; - currentBlendSrcAlpha = blendSrcAlpha; - currentBlendDstAlpha = blendDstAlpha; + } - } + }; - } else { + this.enableAttributeAndDivisor = function ( attribute, meshPerAttribute, extension ) { - currentBlendEquation = null; - currentBlendSrc = null; - currentBlendDst = null; - currentBlendEquationAlpha = null; - currentBlendSrcAlpha = null; - currentBlendDstAlpha = null; + newAttributes[ attribute ] = 1; - } + if ( enabledAttributes[ attribute ] === 0 ) { - }; + gl.enableVertexAttribArray( attribute ); + enabledAttributes[ attribute ] = 1; - // TODO Deprecate + } - this.setColorWrite = function ( colorWrite ) { + if ( attributeDivisors[ attribute ] !== meshPerAttribute ) { - this.buffers.color.setMask( colorWrite ); + extension.vertexAttribDivisorANGLE( attribute, meshPerAttribute ); + attributeDivisors[ attribute ] = meshPerAttribute; - }; + } - this.setDepthTest = function ( depthTest ) { + }; - this.buffers.depth.setTest( depthTest ); + this.disableUnusedAttributes = function () { - }; + for ( var i = 0, l = enabledAttributes.length; i !== l; ++ i ) { - this.setDepthWrite = function ( depthWrite ) { + if ( enabledAttributes[ i ] !== newAttributes[ i ] ) { - this.buffers.depth.setMask( depthWrite ); + gl.disableVertexAttribArray( i ); + enabledAttributes[ i ] = 0; - }; + } - this.setDepthFunc = function ( depthFunc ) { + } - this.buffers.depth.setFunc( depthFunc ); + }; - }; + this.enable = function ( id ) { - this.setStencilTest = function ( stencilTest ) { + if ( capabilities[ id ] !== true ) { - this.buffers.stencil.setTest( stencilTest ); + gl.enable( id ); + capabilities[ id ] = true; - }; + } - this.setStencilWrite = function ( stencilWrite ) { + }; - this.buffers.stencil.setMask( stencilWrite ); + this.disable = function ( id ) { - }; + if ( capabilities[ id ] !== false ) { - this.setStencilFunc = function ( stencilFunc, stencilRef, stencilMask ) { + gl.disable( id ); + capabilities[ id ] = false; - this.buffers.stencil.setFunc( stencilFunc, stencilRef, stencilMask ); + } - }; + }; - this.setStencilOp = function ( stencilFail, stencilZFail, stencilZPass ) { + this.getCompressedTextureFormats = function () { - this.buffers.stencil.setOp( stencilFail, stencilZFail, stencilZPass ); + if ( compressedTextureFormats === null ) { - }; + compressedTextureFormats = []; - // + if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) || + extensions.get( 'WEBGL_compressed_texture_s3tc' ) || + extensions.get( 'WEBGL_compressed_texture_etc1' ) ) { - this.setFlipSided = function ( flipSided ) { + var formats = gl.getParameter( gl.COMPRESSED_TEXTURE_FORMATS ); - if ( currentFlipSided !== flipSided ) { + for ( var i = 0; i < formats.length; i ++ ) { - if ( flipSided ) { + compressedTextureFormats.push( formats[ i ] ); - gl.frontFace( gl.CW ); + } - } else { + } - gl.frontFace( gl.CCW ); + } - } + return compressedTextureFormats; - currentFlipSided = flipSided; + }; - } + this.setBlending = function ( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) { - }; + if ( blending !== NoBlending ) { - this.setCullFace = function ( cullFace ) { + this.enable( gl.BLEND ); - if ( cullFace !== CullFaceNone ) { + } else { - this.enable( gl.CULL_FACE ); + this.disable( gl.BLEND ); + currentBlending = blending; // no blending, that is + return; - if ( cullFace !== currentCullFace ) { + } - if ( cullFace === CullFaceBack ) { + if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) { - gl.cullFace( gl.BACK ); + if ( blending === AdditiveBlending ) { - } else if ( cullFace === CullFaceFront ) { + if ( premultipliedAlpha ) { - gl.cullFace( gl.FRONT ); + gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); + gl.blendFuncSeparate( gl.ONE, gl.ONE, gl.ONE, gl.ONE ); - } else { + } else { - gl.cullFace( gl.FRONT_AND_BACK ); + gl.blendEquation( gl.FUNC_ADD ); + gl.blendFunc( gl.SRC_ALPHA, gl.ONE ); - } + } - } + } else if ( blending === SubtractiveBlending ) { - } else { + if ( premultipliedAlpha ) { - this.disable( gl.CULL_FACE ); + gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); + gl.blendFuncSeparate( gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA ); - } + } else { - currentCullFace = cullFace; + gl.blendEquation( gl.FUNC_ADD ); + gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR ); - }; + } - this.setLineWidth = function ( width ) { + } else if ( blending === MultiplyBlending ) { - if ( width !== currentLineWidth ) { + if ( premultipliedAlpha ) { - gl.lineWidth( width ); + gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); + gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA ); - currentLineWidth = width; + } else { - } + gl.blendEquation( gl.FUNC_ADD ); + gl.blendFunc( gl.ZERO, gl.SRC_COLOR ); - }; + } - this.setPolygonOffset = function ( polygonOffset, factor, units ) { + } else { - if ( polygonOffset ) { + if ( premultipliedAlpha ) { - this.enable( gl.POLYGON_OFFSET_FILL ); + gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); + gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA ); - if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) { + } else { - gl.polygonOffset( factor, units ); + gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); + gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA ); - currentPolygonOffsetFactor = factor; - currentPolygonOffsetUnits = units; + } - } + } - } else { + currentBlending = blending; + currentPremultipledAlpha = premultipliedAlpha; - this.disable( gl.POLYGON_OFFSET_FILL ); + } - } + if ( blending === CustomBlending ) { - }; + blendEquationAlpha = blendEquationAlpha || blendEquation; + blendSrcAlpha = blendSrcAlpha || blendSrc; + blendDstAlpha = blendDstAlpha || blendDst; - this.getScissorTest = function () { + if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) { - return currentScissorTest; + gl.blendEquationSeparate( paramThreeToGL( blendEquation ), paramThreeToGL( blendEquationAlpha ) ); - }; + currentBlendEquation = blendEquation; + currentBlendEquationAlpha = blendEquationAlpha; - this.setScissorTest = function ( scissorTest ) { + } - currentScissorTest = scissorTest; + if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) { - if ( scissorTest ) { + gl.blendFuncSeparate( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ), paramThreeToGL( blendSrcAlpha ), paramThreeToGL( blendDstAlpha ) ); - this.enable( gl.SCISSOR_TEST ); + currentBlendSrc = blendSrc; + currentBlendDst = blendDst; + currentBlendSrcAlpha = blendSrcAlpha; + currentBlendDstAlpha = blendDstAlpha; - } else { + } - this.disable( gl.SCISSOR_TEST ); + } else { - } + currentBlendEquation = null; + currentBlendSrc = null; + currentBlendDst = null; + currentBlendEquationAlpha = null; + currentBlendSrcAlpha = null; + currentBlendDstAlpha = null; - }; + } - // texture + }; - this.activeTexture = function ( webglSlot ) { + // TODO Deprecate - if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1; + this.setColorWrite = function ( colorWrite ) { - if ( currentTextureSlot !== webglSlot ) { + this.buffers.color.setMask( colorWrite ); - gl.activeTexture( webglSlot ); - currentTextureSlot = webglSlot; + }; - } + this.setDepthTest = function ( depthTest ) { - }; + this.buffers.depth.setTest( depthTest ); - this.bindTexture = function ( webglType, webglTexture ) { + }; - if ( currentTextureSlot === null ) { + this.setDepthWrite = function ( depthWrite ) { - _this.activeTexture(); + this.buffers.depth.setMask( depthWrite ); - } + }; - var boundTexture = currentBoundTextures[ currentTextureSlot ]; + this.setDepthFunc = function ( depthFunc ) { - if ( boundTexture === undefined ) { + this.buffers.depth.setFunc( depthFunc ); - boundTexture = { type: undefined, texture: undefined }; - currentBoundTextures[ currentTextureSlot ] = boundTexture; + }; - } + this.setStencilTest = function ( stencilTest ) { - if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) { + this.buffers.stencil.setTest( stencilTest ); - gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] ); + }; - boundTexture.type = webglType; - boundTexture.texture = webglTexture; + this.setStencilWrite = function ( stencilWrite ) { - } + this.buffers.stencil.setMask( stencilWrite ); - }; + }; - this.compressedTexImage2D = function () { + this.setStencilFunc = function ( stencilFunc, stencilRef, stencilMask ) { - try { + this.buffers.stencil.setFunc( stencilFunc, stencilRef, stencilMask ); - gl.compressedTexImage2D.apply( gl, arguments ); + }; - } catch ( error ) { + this.setStencilOp = function ( stencilFail, stencilZFail, stencilZPass ) { - console.error( error ); + this.buffers.stencil.setOp( stencilFail, stencilZFail, stencilZPass ); - } + }; - }; + // - this.texImage2D = function () { + this.setFlipSided = function ( flipSided ) { - try { + if ( currentFlipSided !== flipSided ) { - gl.texImage2D.apply( gl, arguments ); + if ( flipSided ) { - } catch ( error ) { + gl.frontFace( gl.CW ); - console.error( error ); + } else { - } + gl.frontFace( gl.CCW ); - }; + } - // TODO Deprecate + currentFlipSided = flipSided; - this.clearColor = function ( r, g, b, a ) { + } - this.buffers.color.setClear( r, g, b, a ); + }; - }; + this.setCullFace = function ( cullFace ) { - this.clearDepth = function ( depth ) { + if ( cullFace !== CullFaceNone ) { - this.buffers.depth.setClear( depth ); + this.enable( gl.CULL_FACE ); - }; + if ( cullFace !== currentCullFace ) { - this.clearStencil = function ( stencil ) { + if ( cullFace === CullFaceBack ) { - this.buffers.stencil.setClear( stencil ); + gl.cullFace( gl.BACK ); - }; + } else if ( cullFace === CullFaceFront ) { - // + gl.cullFace( gl.FRONT ); - this.scissor = function ( scissor ) { + } else { - if ( currentScissor.equals( scissor ) === false ) { + gl.cullFace( gl.FRONT_AND_BACK ); - gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w ); - currentScissor.copy( scissor ); + } - } + } - }; + } else { - this.viewport = function ( viewport ) { + this.disable( gl.CULL_FACE ); - if ( currentViewport.equals( viewport ) === false ) { + } - gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w ); - currentViewport.copy( viewport ); + currentCullFace = cullFace; - } + }; - }; + this.setLineWidth = function ( width ) { - // + if ( width !== currentLineWidth ) { - this.reset = function () { + gl.lineWidth( width ); - for ( var i = 0; i < enabledAttributes.length; i ++ ) { + currentLineWidth = width; - if ( enabledAttributes[ i ] === 1 ) { + } - gl.disableVertexAttribArray( i ); - enabledAttributes[ i ] = 0; + }; - } + this.setPolygonOffset = function ( polygonOffset, factor, units ) { - } + if ( polygonOffset ) { - capabilities = {}; + this.enable( gl.POLYGON_OFFSET_FILL ); - compressedTextureFormats = null; + if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) { - currentTextureSlot = null; - currentBoundTextures = {}; + gl.polygonOffset( factor, units ); - currentBlending = null; + currentPolygonOffsetFactor = factor; + currentPolygonOffsetUnits = units; - currentFlipSided = null; - currentCullFace = null; + } - this.buffers.color.reset(); - this.buffers.depth.reset(); - this.buffers.stencil.reset(); + } else { - }; + this.disable( gl.POLYGON_OFFSET_FILL ); - }; + } - function WebGLColorBuffer( gl, state ) { + }; - var locked = false; + this.getScissorTest = function () { - var color = new Vector4(); - var currentColorMask = null; - var currentColorClear = new Vector4(); + return currentScissorTest; - this.setMask = function ( colorMask ) { + }; - if ( currentColorMask !== colorMask && ! locked ) { + this.setScissorTest = function ( scissorTest ) { - gl.colorMask( colorMask, colorMask, colorMask, colorMask ); - currentColorMask = colorMask; + currentScissorTest = scissorTest; - } + if ( scissorTest ) { - }; + this.enable( gl.SCISSOR_TEST ); - this.setLocked = function ( lock ) { + } else { - locked = lock; + this.disable( gl.SCISSOR_TEST ); - }; + } - this.setClear = function ( r, g, b, a ) { + }; - color.set( r, g, b, a ); + // texture - if ( currentColorClear.equals( color ) === false ) { + this.activeTexture = function ( webglSlot ) { - gl.clearColor( r, g, b, a ); - currentColorClear.copy( color ); + if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1; - } + if ( currentTextureSlot !== webglSlot ) { - }; + gl.activeTexture( webglSlot ); + currentTextureSlot = webglSlot; - this.reset = function () { + } - locked = false; + }; - currentColorMask = null; - currentColorClear = new Vector4(); + this.bindTexture = function ( webglType, webglTexture ) { - }; + if ( currentTextureSlot === null ) { - }; + _this.activeTexture(); - function WebGLDepthBuffer( gl, state ) { + } - var locked = false; + var boundTexture = currentBoundTextures[ currentTextureSlot ]; - var currentDepthMask = null; - var currentDepthFunc = null; - var currentDepthClear = null; + if ( boundTexture === undefined ) { - this.setTest = function ( depthTest ) { + boundTexture = { type: undefined, texture: undefined }; + currentBoundTextures[ currentTextureSlot ] = boundTexture; - if ( depthTest ) { + } - state.enable( gl.DEPTH_TEST ); + if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) { - } else { + gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] ); - state.disable( gl.DEPTH_TEST ); + boundTexture.type = webglType; + boundTexture.texture = webglTexture; - } + } - }; + }; - this.setMask = function( depthMask ){ + this.compressedTexImage2D = function () { - if ( currentDepthMask !== depthMask && ! locked ) { + try { - gl.depthMask( depthMask ); - currentDepthMask = depthMask; + gl.compressedTexImage2D.apply( gl, arguments ); - } + } catch ( error ) { - }; + console.error( error ); - this.setFunc = function ( depthFunc ) { + } - if ( currentDepthFunc !== depthFunc ) { + }; - if ( depthFunc ) { + this.texImage2D = function () { - switch ( depthFunc ) { + try { - case NeverDepth: + gl.texImage2D.apply( gl, arguments ); - gl.depthFunc( gl.NEVER ); - break; + } catch ( error ) { - case AlwaysDepth: + console.error( error ); - gl.depthFunc( gl.ALWAYS ); - break; + } - case LessDepth: + }; - gl.depthFunc( gl.LESS ); - break; + // TODO Deprecate - case LessEqualDepth: + this.clearColor = function ( r, g, b, a ) { - gl.depthFunc( gl.LEQUAL ); - break; + this.buffers.color.setClear( r, g, b, a ); - case EqualDepth: + }; - gl.depthFunc( gl.EQUAL ); - break; + this.clearDepth = function ( depth ) { - case GreaterEqualDepth: + this.buffers.depth.setClear( depth ); - gl.depthFunc( gl.GEQUAL ); - break; + }; - case GreaterDepth: + this.clearStencil = function ( stencil ) { - gl.depthFunc( gl.GREATER ); - break; + this.buffers.stencil.setClear( stencil ); - case NotEqualDepth: + }; - gl.depthFunc( gl.NOTEQUAL ); - break; + // - default: + this.scissor = function ( scissor ) { - gl.depthFunc( gl.LEQUAL ); + if ( currentScissor.equals( scissor ) === false ) { - } + gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w ); + currentScissor.copy( scissor ); - } else { + } - gl.depthFunc( gl.LEQUAL ); + }; - } + this.viewport = function ( viewport ) { - currentDepthFunc = depthFunc; + if ( currentViewport.equals( viewport ) === false ) { - } + gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w ); + currentViewport.copy( viewport ); - }; + } - this.setLocked = function ( lock ) { + }; - locked = lock; + // - }; + this.reset = function () { - this.setClear = function ( depth ) { + for ( var i = 0; i < enabledAttributes.length; i ++ ) { - if ( currentDepthClear !== depth ) { + if ( enabledAttributes[ i ] === 1 ) { - gl.clearDepth( depth ); - currentDepthClear = depth; + gl.disableVertexAttribArray( i ); + enabledAttributes[ i ] = 0; - } + } - }; + } - this.reset = function () { + capabilities = {}; - locked = false; + compressedTextureFormats = null; - currentDepthMask = null; - currentDepthFunc = null; - currentDepthClear = null; + currentTextureSlot = null; + currentBoundTextures = {}; - }; + currentBlending = null; - }; + currentFlipSided = null; + currentCullFace = null; - function WebGLStencilBuffer( gl, state ) { + this.buffers.color.reset(); + this.buffers.depth.reset(); + this.buffers.stencil.reset(); - var locked = false; + }; - var currentStencilMask = null; - var currentStencilFunc = null; - var currentStencilRef = null; - var currentStencilFuncMask = null; - var currentStencilFail = null; - var currentStencilZFail = null; - var currentStencilZPass = null; - var currentStencilClear = null; + }; - this.setTest = function ( stencilTest ) { + function WebGLColorBuffer( gl, state ) { - if ( stencilTest ) { + var locked = false; - state.enable( gl.STENCIL_TEST ); + var color = new Vector4(); + var currentColorMask = null; + var currentColorClear = new Vector4(); - } else { + this.setMask = function ( colorMask ) { - state.disable( gl.STENCIL_TEST ); + if ( currentColorMask !== colorMask && ! locked ) { - } + gl.colorMask( colorMask, colorMask, colorMask, colorMask ); + currentColorMask = colorMask; - }; + } - this.setMask = function ( stencilMask ) { + }; - if ( currentStencilMask !== stencilMask && ! locked ) { + this.setLocked = function ( lock ) { - gl.stencilMask( stencilMask ); - currentStencilMask = stencilMask; + locked = lock; - } + }; - }; + this.setClear = function ( r, g, b, a ) { - this.setFunc = function ( stencilFunc, stencilRef, stencilMask ) { + color.set( r, g, b, a ); - if ( currentStencilFunc !== stencilFunc || - currentStencilRef !== stencilRef || - currentStencilFuncMask !== stencilMask ) { + if ( currentColorClear.equals( color ) === false ) { - gl.stencilFunc( stencilFunc, stencilRef, stencilMask ); + gl.clearColor( r, g, b, a ); + currentColorClear.copy( color ); - currentStencilFunc = stencilFunc; - currentStencilRef = stencilRef; - currentStencilFuncMask = stencilMask; + } - } + }; - }; + this.reset = function () { - this.setOp = function ( stencilFail, stencilZFail, stencilZPass ) { + locked = false; - if ( currentStencilFail !== stencilFail || - currentStencilZFail !== stencilZFail || - currentStencilZPass !== stencilZPass ) { + currentColorMask = null; + currentColorClear = new Vector4(); - gl.stencilOp( stencilFail, stencilZFail, stencilZPass ); + }; - currentStencilFail = stencilFail; - currentStencilZFail = stencilZFail; - currentStencilZPass = stencilZPass; + }; - } + function WebGLDepthBuffer( gl, state ) { - }; + var locked = false; - this.setLocked = function ( lock ) { + var currentDepthMask = null; + var currentDepthFunc = null; + var currentDepthClear = null; - locked = lock; + this.setTest = function ( depthTest ) { - }; + if ( depthTest ) { - this.setClear = function ( stencil ) { + state.enable( gl.DEPTH_TEST ); - if ( currentStencilClear !== stencil ) { + } else { - gl.clearStencil( stencil ); - currentStencilClear = stencil; + state.disable( gl.DEPTH_TEST ); - } + } - }; + }; - this.reset = function () { + this.setMask = function( depthMask ){ - locked = false; + if ( currentDepthMask !== depthMask && ! locked ) { - currentStencilMask = null; - currentStencilFunc = null; - currentStencilRef = null; - currentStencilFuncMask = null; - currentStencilFail = null; - currentStencilZFail = null; - currentStencilZPass = null; - currentStencilClear = null; + gl.depthMask( depthMask ); + currentDepthMask = depthMask; - }; + } - }; + }; - /** - * @author szimek / https://github.com/szimek/ - * @author alteredq / http://alteredqualia.com/ - * @author Marius Kintel / https://github.com/kintel - */ + this.setFunc = function ( depthFunc ) { - /* - In options, we can specify: - * Texture parameters for an auto-generated target texture - * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers - */ - function WebGLRenderTarget( width, height, options ) { + if ( currentDepthFunc !== depthFunc ) { - this.uuid = exports.Math.generateUUID(); + if ( depthFunc ) { - this.width = width; - this.height = height; + switch ( depthFunc ) { - this.scissor = new Vector4( 0, 0, width, height ); - this.scissorTest = false; + case NeverDepth: - this.viewport = new Vector4( 0, 0, width, height ); + gl.depthFunc( gl.NEVER ); + break; - options = options || {}; + case AlwaysDepth: - if ( options.minFilter === undefined ) options.minFilter = LinearFilter; + gl.depthFunc( gl.ALWAYS ); + break; - this.texture = new Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding ); + case LessDepth: - this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true; - this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true; - this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null; + gl.depthFunc( gl.LESS ); + break; - }; + case LessEqualDepth: - Object.assign( WebGLRenderTarget.prototype, EventDispatcher.prototype, { + gl.depthFunc( gl.LEQUAL ); + break; - isWebGLRenderTarget: true, + case EqualDepth: - setSize: function ( width, height ) { + gl.depthFunc( gl.EQUAL ); + break; - if ( this.width !== width || this.height !== height ) { + case GreaterEqualDepth: - this.width = width; - this.height = height; + gl.depthFunc( gl.GEQUAL ); + break; - this.dispose(); + case GreaterDepth: - } + gl.depthFunc( gl.GREATER ); + break; - this.viewport.set( 0, 0, width, height ); - this.scissor.set( 0, 0, width, height ); + case NotEqualDepth: - }, + gl.depthFunc( gl.NOTEQUAL ); + break; - clone: function () { + default: - return new this.constructor().copy( this ); + gl.depthFunc( gl.LEQUAL ); - }, + } - copy: function ( source ) { + } else { - this.width = source.width; - this.height = source.height; + gl.depthFunc( gl.LEQUAL ); - this.viewport.copy( source.viewport ); + } - this.texture = source.texture.clone(); + currentDepthFunc = depthFunc; - this.depthBuffer = source.depthBuffer; - this.stencilBuffer = source.stencilBuffer; - this.depthTexture = source.depthTexture; + } - return this; + }; - }, + this.setLocked = function ( lock ) { - dispose: function () { + locked = lock; - this.dispatchEvent( { type: 'dispose' } ); + }; - } + this.setClear = function ( depth ) { - } ); + if ( currentDepthClear !== depth ) { - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + gl.clearDepth( depth ); + currentDepthClear = depth; - function Material() { + } - Object.defineProperty( this, 'id', { value: MaterialIdCount() } ); + }; - this.uuid = exports.Math.generateUUID(); + this.reset = function () { - this.name = ''; - this.type = 'Material'; + locked = false; - this.fog = true; - this.lights = true; + currentDepthMask = null; + currentDepthFunc = null; + currentDepthClear = null; - this.blending = NormalBlending; - this.side = FrontSide; - this.shading = SmoothShading; // THREE.FlatShading, THREE.SmoothShading - this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors + }; - this.opacity = 1; - this.transparent = false; + }; - this.blendSrc = SrcAlphaFactor; - this.blendDst = OneMinusSrcAlphaFactor; - this.blendEquation = AddEquation; - this.blendSrcAlpha = null; - this.blendDstAlpha = null; - this.blendEquationAlpha = null; + function WebGLStencilBuffer( gl, state ) { - this.depthFunc = LessEqualDepth; - this.depthTest = true; - this.depthWrite = true; + var locked = false; - this.clippingPlanes = null; - this.clipShadows = false; + var currentStencilMask = null; + var currentStencilFunc = null; + var currentStencilRef = null; + var currentStencilFuncMask = null; + var currentStencilFail = null; + var currentStencilZFail = null; + var currentStencilZPass = null; + var currentStencilClear = null; - this.colorWrite = true; + this.setTest = function ( stencilTest ) { - this.precision = null; // override the renderer's default precision for this material + if ( stencilTest ) { - this.polygonOffset = false; - this.polygonOffsetFactor = 0; - this.polygonOffsetUnits = 0; + state.enable( gl.STENCIL_TEST ); - this.alphaTest = 0; - this.premultipliedAlpha = false; + } else { - this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer + state.disable( gl.STENCIL_TEST ); - this.visible = true; + } - this._needsUpdate = true; + }; - }; + this.setMask = function ( stencilMask ) { - Material.prototype = { + if ( currentStencilMask !== stencilMask && ! locked ) { - constructor: Material, + gl.stencilMask( stencilMask ); + currentStencilMask = stencilMask; - isMaterial: true, + } - get needsUpdate() { + }; - return this._needsUpdate; + this.setFunc = function ( stencilFunc, stencilRef, stencilMask ) { - }, + if ( currentStencilFunc !== stencilFunc || + currentStencilRef !== stencilRef || + currentStencilFuncMask !== stencilMask ) { - set needsUpdate( value ) { + gl.stencilFunc( stencilFunc, stencilRef, stencilMask ); - if ( value === true ) this.update(); - this._needsUpdate = value; + currentStencilFunc = stencilFunc; + currentStencilRef = stencilRef; + currentStencilFuncMask = stencilMask; - }, + } - setValues: function ( values ) { + }; - if ( values === undefined ) return; + this.setOp = function ( stencilFail, stencilZFail, stencilZPass ) { - for ( var key in values ) { + if ( currentStencilFail !== stencilFail || + currentStencilZFail !== stencilZFail || + currentStencilZPass !== stencilZPass ) { - var newValue = values[ key ]; + gl.stencilOp( stencilFail, stencilZFail, stencilZPass ); - if ( newValue === undefined ) { + currentStencilFail = stencilFail; + currentStencilZFail = stencilZFail; + currentStencilZPass = stencilZPass; - console.warn( "THREE.Material: '" + key + "' parameter is undefined." ); - continue; + } - } + }; - var currentValue = this[ key ]; + this.setLocked = function ( lock ) { - if ( currentValue === undefined ) { + locked = lock; - console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." ); - continue; + }; - } + this.setClear = function ( stencil ) { - if ( (currentValue && currentValue.isColor) ) { + if ( currentStencilClear !== stencil ) { - currentValue.set( newValue ); + gl.clearStencil( stencil ); + currentStencilClear = stencil; - } else if ( (currentValue && currentValue.isVector3) && (newValue && newValue.isVector3) ) { + } - currentValue.copy( newValue ); + }; - } else if ( key === 'overdraw' ) { + this.reset = function () { - // ensure overdraw is backwards-compatible with legacy boolean type - this[ key ] = Number( newValue ); + locked = false; - } else { + currentStencilMask = null; + currentStencilFunc = null; + currentStencilRef = null; + currentStencilFuncMask = null; + currentStencilFail = null; + currentStencilZFail = null; + currentStencilZPass = null; + currentStencilClear = null; - this[ key ] = newValue; + }; - } + } - } + /** + * @author szimek / https://github.com/szimek/ + * @author alteredq / http://alteredqualia.com/ + * @author Marius Kintel / https://github.com/kintel + */ - }, + /* + In options, we can specify: + * Texture parameters for an auto-generated target texture + * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers + */ + function WebGLRenderTarget( width, height, options ) { - toJSON: function ( meta ) { + this.uuid = exports.Math.generateUUID(); - var isRoot = meta === undefined; + this.width = width; + this.height = height; - if ( isRoot ) { + this.scissor = new Vector4( 0, 0, width, height ); + this.scissorTest = false; - meta = { - textures: {}, - images: {} - }; + this.viewport = new Vector4( 0, 0, width, height ); - } + options = options || {}; - var data = { - metadata: { - version: 4.4, - type: 'Material', - generator: 'Material.toJSON' - } - }; + if ( options.minFilter === undefined ) options.minFilter = LinearFilter; - // standard Material serialization - data.uuid = this.uuid; - data.type = this.type; + this.texture = new Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding ); - if ( this.name !== '' ) data.name = this.name; + this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true; + this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true; + this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null; - if ( (this.color && this.color.isColor) ) data.color = this.color.getHex(); + } - if ( this.roughness !== undefined ) data.roughness = this.roughness; - if ( this.metalness !== undefined ) data.metalness = this.metalness; + Object.assign( WebGLRenderTarget.prototype, EventDispatcher.prototype, { - if ( (this.emissive && this.emissive.isColor) ) data.emissive = this.emissive.getHex(); - if ( (this.specular && this.specular.isColor) ) data.specular = this.specular.getHex(); - if ( this.shininess !== undefined ) data.shininess = this.shininess; + isWebGLRenderTarget: true, - if ( (this.map && this.map.isTexture) ) data.map = this.map.toJSON( meta ).uuid; - if ( (this.alphaMap && this.alphaMap.isTexture) ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid; - if ( (this.lightMap && this.lightMap.isTexture) ) data.lightMap = this.lightMap.toJSON( meta ).uuid; - if ( (this.bumpMap && this.bumpMap.isTexture) ) { + setSize: function ( width, height ) { - data.bumpMap = this.bumpMap.toJSON( meta ).uuid; - data.bumpScale = this.bumpScale; + if ( this.width !== width || this.height !== height ) { - } - if ( (this.normalMap && this.normalMap.isTexture) ) { + this.width = width; + this.height = height; - data.normalMap = this.normalMap.toJSON( meta ).uuid; - data.normalScale = this.normalScale.toArray(); + this.dispose(); - } - if ( (this.displacementMap && this.displacementMap.isTexture) ) { + } - data.displacementMap = this.displacementMap.toJSON( meta ).uuid; - data.displacementScale = this.displacementScale; - data.displacementBias = this.displacementBias; + this.viewport.set( 0, 0, width, height ); + this.scissor.set( 0, 0, width, height ); - } - if ( (this.roughnessMap && this.roughnessMap.isTexture) ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid; - if ( (this.metalnessMap && this.metalnessMap.isTexture) ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid; + }, - if ( (this.emissiveMap && this.emissiveMap.isTexture) ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid; - if ( (this.specularMap && this.specularMap.isTexture) ) data.specularMap = this.specularMap.toJSON( meta ).uuid; + clone: function () { - if ( (this.envMap && this.envMap.isTexture) ) { + return new this.constructor().copy( this ); - data.envMap = this.envMap.toJSON( meta ).uuid; - data.reflectivity = this.reflectivity; // Scale behind envMap + }, - } + copy: function ( source ) { - if ( this.size !== undefined ) data.size = this.size; - if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation; + this.width = source.width; + this.height = source.height; - if ( this.blending !== NormalBlending ) data.blending = this.blending; - if ( this.shading !== SmoothShading ) data.shading = this.shading; - if ( this.side !== FrontSide ) data.side = this.side; - if ( this.vertexColors !== NoColors ) data.vertexColors = this.vertexColors; + this.viewport.copy( source.viewport ); - if ( this.opacity < 1 ) data.opacity = this.opacity; - if ( this.transparent === true ) data.transparent = this.transparent; - if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest; - if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha; - if ( this.wireframe === true ) data.wireframe = this.wireframe; - if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth; + this.texture = source.texture.clone(); - // TODO: Copied from Object3D.toJSON + this.depthBuffer = source.depthBuffer; + this.stencilBuffer = source.stencilBuffer; + this.depthTexture = source.depthTexture; - function extractFromCache( cache ) { + return this; - var values = []; + }, - for ( var key in cache ) { + dispose: function () { - var data = cache[ key ]; - delete data.metadata; - values.push( data ); + this.dispatchEvent( { type: 'dispose' } ); - } + } - return values; + } ); - } + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - if ( isRoot ) { + function Material() { - var textures = extractFromCache( meta.textures ); - var images = extractFromCache( meta.images ); + Object.defineProperty( this, 'id', { value: MaterialIdCount() } ); - if ( textures.length > 0 ) data.textures = textures; - if ( images.length > 0 ) data.images = images; + this.uuid = exports.Math.generateUUID(); - } + this.name = ''; + this.type = 'Material'; - return data; + this.fog = true; + this.lights = true; - }, + this.blending = NormalBlending; + this.side = FrontSide; + this.shading = SmoothShading; // THREE.FlatShading, THREE.SmoothShading + this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors - clone: function () { + this.opacity = 1; + this.transparent = false; - return new this.constructor().copy( this ); + this.blendSrc = SrcAlphaFactor; + this.blendDst = OneMinusSrcAlphaFactor; + this.blendEquation = AddEquation; + this.blendSrcAlpha = null; + this.blendDstAlpha = null; + this.blendEquationAlpha = null; - }, + this.depthFunc = LessEqualDepth; + this.depthTest = true; + this.depthWrite = true; - copy: function ( source ) { + this.clippingPlanes = null; + this.clipShadows = false; - this.name = source.name; + this.colorWrite = true; - this.fog = source.fog; - this.lights = source.lights; + this.precision = null; // override the renderer's default precision for this material - this.blending = source.blending; - this.side = source.side; - this.shading = source.shading; - this.vertexColors = source.vertexColors; + this.polygonOffset = false; + this.polygonOffsetFactor = 0; + this.polygonOffsetUnits = 0; - this.opacity = source.opacity; - this.transparent = source.transparent; + this.alphaTest = 0; + this.premultipliedAlpha = false; - this.blendSrc = source.blendSrc; - this.blendDst = source.blendDst; - this.blendEquation = source.blendEquation; - this.blendSrcAlpha = source.blendSrcAlpha; - this.blendDstAlpha = source.blendDstAlpha; - this.blendEquationAlpha = source.blendEquationAlpha; + this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer - this.depthFunc = source.depthFunc; - this.depthTest = source.depthTest; - this.depthWrite = source.depthWrite; + this.visible = true; - this.colorWrite = source.colorWrite; + this._needsUpdate = true; - this.precision = source.precision; + } - this.polygonOffset = source.polygonOffset; - this.polygonOffsetFactor = source.polygonOffsetFactor; - this.polygonOffsetUnits = source.polygonOffsetUnits; + Material.prototype = { - this.alphaTest = source.alphaTest; + constructor: Material, - this.premultipliedAlpha = source.premultipliedAlpha; + isMaterial: true, - this.overdraw = source.overdraw; + get needsUpdate() { - this.visible = source.visible; - this.clipShadows = source.clipShadows; + return this._needsUpdate; - var srcPlanes = source.clippingPlanes, - dstPlanes = null; + }, - if ( srcPlanes !== null ) { + set needsUpdate( value ) { - var n = srcPlanes.length; - dstPlanes = new Array( n ); + if ( value === true ) this.update(); + this._needsUpdate = value; - for ( var i = 0; i !== n; ++ i ) - dstPlanes[ i ] = srcPlanes[ i ].clone(); + }, - } + setValues: function ( values ) { - this.clippingPlanes = dstPlanes; + if ( values === undefined ) return; - return this; + for ( var key in values ) { - }, + var newValue = values[ key ]; - update: function () { + if ( newValue === undefined ) { - this.dispatchEvent( { type: 'update' } ); + console.warn( "THREE.Material: '" + key + "' parameter is undefined." ); + continue; - }, + } - dispose: function () { + var currentValue = this[ key ]; - this.dispatchEvent( { type: 'dispose' } ); + if ( currentValue === undefined ) { - } + console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." ); + continue; - }; + } - Object.assign( Material.prototype, EventDispatcher.prototype ); + if ( (currentValue && currentValue.isColor) ) { - var count$1 = 0; - function MaterialIdCount() { return count$1++; }; + currentValue.set( newValue ); - /** - * Uniform Utilities - */ + } else if ( (currentValue && currentValue.isVector3) && (newValue && newValue.isVector3) ) { - exports.UniformsUtils = { + currentValue.copy( newValue ); - merge: function ( uniforms ) { + } else if ( key === 'overdraw' ) { - var merged = {}; + // ensure overdraw is backwards-compatible with legacy boolean type + this[ key ] = Number( newValue ); - for ( var u = 0; u < uniforms.length; u ++ ) { + } else { - var tmp = this.clone( uniforms[ u ] ); + this[ key ] = newValue; - for ( var p in tmp ) { + } - merged[ p ] = tmp[ p ]; + } - } + }, - } + toJSON: function ( meta ) { - return merged; + var isRoot = meta === undefined; - }, + if ( isRoot ) { - clone: function ( uniforms_src ) { + meta = { + textures: {}, + images: {} + }; - var uniforms_dst = {}; + } - for ( var u in uniforms_src ) { + var data = { + metadata: { + version: 4.4, + type: 'Material', + generator: 'Material.toJSON' + } + }; - uniforms_dst[ u ] = {}; + // standard Material serialization + data.uuid = this.uuid; + data.type = this.type; - for ( var p in uniforms_src[ u ] ) { + if ( this.name !== '' ) data.name = this.name; - var parameter_src = uniforms_src[ u ][ p ]; + if ( (this.color && this.color.isColor) ) data.color = this.color.getHex(); - if ( (parameter_src && parameter_src.isColor) || - (parameter_src && parameter_src.isVector2) || - (parameter_src && parameter_src.isVector3) || - (parameter_src && parameter_src.isVector4) || - (parameter_src && parameter_src.isMatrix3) || - (parameter_src && parameter_src.isMatrix4) || - (parameter_src && parameter_src.isTexture) ) { + if ( this.roughness !== undefined ) data.roughness = this.roughness; + if ( this.metalness !== undefined ) data.metalness = this.metalness; - uniforms_dst[ u ][ p ] = parameter_src.clone(); + if ( (this.emissive && this.emissive.isColor) ) data.emissive = this.emissive.getHex(); + if ( (this.specular && this.specular.isColor) ) data.specular = this.specular.getHex(); + if ( this.shininess !== undefined ) data.shininess = this.shininess; - } else if ( Array.isArray( parameter_src ) ) { + if ( (this.map && this.map.isTexture) ) data.map = this.map.toJSON( meta ).uuid; + if ( (this.alphaMap && this.alphaMap.isTexture) ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid; + if ( (this.lightMap && this.lightMap.isTexture) ) data.lightMap = this.lightMap.toJSON( meta ).uuid; + if ( (this.bumpMap && this.bumpMap.isTexture) ) { - uniforms_dst[ u ][ p ] = parameter_src.slice(); + data.bumpMap = this.bumpMap.toJSON( meta ).uuid; + data.bumpScale = this.bumpScale; - } else { + } + if ( (this.normalMap && this.normalMap.isTexture) ) { - uniforms_dst[ u ][ p ] = parameter_src; + data.normalMap = this.normalMap.toJSON( meta ).uuid; + data.normalScale = this.normalScale.toArray(); - } + } + if ( (this.displacementMap && this.displacementMap.isTexture) ) { - } + data.displacementMap = this.displacementMap.toJSON( meta ).uuid; + data.displacementScale = this.displacementScale; + data.displacementBias = this.displacementBias; - } + } + if ( (this.roughnessMap && this.roughnessMap.isTexture) ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid; + if ( (this.metalnessMap && this.metalnessMap.isTexture) ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid; - return uniforms_dst; + if ( (this.emissiveMap && this.emissiveMap.isTexture) ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid; + if ( (this.specularMap && this.specularMap.isTexture) ) data.specularMap = this.specularMap.toJSON( meta ).uuid; - } + if ( (this.envMap && this.envMap.isTexture) ) { - }; + data.envMap = this.envMap.toJSON( meta ).uuid; + data.reflectivity = this.reflectivity; // Scale behind envMap - /** - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * defines: { "label" : "value" }, - * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } }, - * - * fragmentShader: , - * vertexShader: , - * - * wireframe: , - * wireframeLinewidth: , - * - * lights: , - * - * skinning: , - * morphTargets: , - * morphNormals: - * } - */ + } - function ShaderMaterial( parameters ) { + if ( this.size !== undefined ) data.size = this.size; + if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation; - Material.call( this ); + if ( this.blending !== NormalBlending ) data.blending = this.blending; + if ( this.shading !== SmoothShading ) data.shading = this.shading; + if ( this.side !== FrontSide ) data.side = this.side; + if ( this.vertexColors !== NoColors ) data.vertexColors = this.vertexColors; - this.type = 'ShaderMaterial'; + if ( this.opacity < 1 ) data.opacity = this.opacity; + if ( this.transparent === true ) data.transparent = this.transparent; - this.defines = {}; - this.uniforms = {}; + data.depthFunc = this.depthFunc; + data.depthTest = this.depthTest; + data.depthWrite = this.depthWrite; - this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}'; - this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}'; + if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest; + if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha; + if ( this.wireframe === true ) data.wireframe = this.wireframe; + if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth; + if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap; + if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin; - this.linewidth = 1; + data.skinning = this.skinning; + data.morphTargets = this.morphTargets; - this.wireframe = false; - this.wireframeLinewidth = 1; + // TODO: Copied from Object3D.toJSON - this.fog = false; // set to use scene fog - this.lights = false; // set to use scene lights - this.clipping = false; // set to use user-defined clipping planes + function extractFromCache( cache ) { - this.skinning = false; // set to use skinning attribute streams - this.morphTargets = false; // set to use morph targets - this.morphNormals = false; // set to use morph normals + var values = []; - this.extensions = { - derivatives: false, // set to use derivatives - fragDepth: false, // set to use fragment depth values - drawBuffers: false, // set to use draw buffers - shaderTextureLOD: false // set to use shader texture LOD - }; + for ( var key in cache ) { - // When rendered geometry doesn't include these attributes but the material does, - // use these default values in WebGL. This avoids errors when buffer data is missing. - this.defaultAttributeValues = { - 'color': [ 1, 1, 1 ], - 'uv': [ 0, 0 ], - 'uv2': [ 0, 0 ] - }; + var data = cache[ key ]; + delete data.metadata; + values.push( data ); - this.index0AttributeName = undefined; + } - if ( parameters !== undefined ) { + return values; - if ( parameters.attributes !== undefined ) { + } - console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' ); + if ( isRoot ) { - } + var textures = extractFromCache( meta.textures ); + var images = extractFromCache( meta.images ); - this.setValues( parameters ); + if ( textures.length > 0 ) data.textures = textures; + if ( images.length > 0 ) data.images = images; - } + } - }; + return data; - ShaderMaterial.prototype = Object.create( Material.prototype ); - ShaderMaterial.prototype.constructor = ShaderMaterial; + }, - ShaderMaterial.prototype.isShaderMaterial = true; + clone: function () { - ShaderMaterial.prototype.copy = function ( source ) { + return new this.constructor().copy( this ); - Material.prototype.copy.call( this, source ); + }, - this.fragmentShader = source.fragmentShader; - this.vertexShader = source.vertexShader; + copy: function ( source ) { - this.uniforms = exports.UniformsUtils.clone( source.uniforms ); + this.name = source.name; - this.defines = source.defines; + this.fog = source.fog; + this.lights = source.lights; - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; + this.blending = source.blending; + this.side = source.side; + this.shading = source.shading; + this.vertexColors = source.vertexColors; - this.lights = source.lights; - this.clipping = source.clipping; + this.opacity = source.opacity; + this.transparent = source.transparent; - this.skinning = source.skinning; + this.blendSrc = source.blendSrc; + this.blendDst = source.blendDst; + this.blendEquation = source.blendEquation; + this.blendSrcAlpha = source.blendSrcAlpha; + this.blendDstAlpha = source.blendDstAlpha; + this.blendEquationAlpha = source.blendEquationAlpha; - this.morphTargets = source.morphTargets; - this.morphNormals = source.morphNormals; + this.depthFunc = source.depthFunc; + this.depthTest = source.depthTest; + this.depthWrite = source.depthWrite; - this.extensions = source.extensions; + this.colorWrite = source.colorWrite; - return this; + this.precision = source.precision; - }; + this.polygonOffset = source.polygonOffset; + this.polygonOffsetFactor = source.polygonOffsetFactor; + this.polygonOffsetUnits = source.polygonOffsetUnits; - ShaderMaterial.prototype.toJSON = function ( meta ) { + this.alphaTest = source.alphaTest; - var data = Material.prototype.toJSON.call( this, meta ); + this.premultipliedAlpha = source.premultipliedAlpha; - data.uniforms = this.uniforms; - data.vertexShader = this.vertexShader; - data.fragmentShader = this.fragmentShader; + this.overdraw = source.overdraw; - return data; + this.visible = source.visible; + this.clipShadows = source.clipShadows; - }; + var srcPlanes = source.clippingPlanes, + dstPlanes = null; - var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n"; + if ( srcPlanes !== null ) { - var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif\n"; + var n = srcPlanes.length; + dstPlanes = new Array( n ); - var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif\n"; + for ( var i = 0; i !== n; ++ i ) + dstPlanes[ i ] = srcPlanes[ i ].clone(); - var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\t#endif\n#endif\n"; + } - var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif"; + this.clippingPlanes = dstPlanes; - var begin_vertex = "\nvec3 transformed = vec3( position );\n"; + return this; - var beginnormal_vertex = "\nvec3 objectNormal = vec3( normal );\n"; + }, - var bsdfs = "bool testLightInRange( const in float lightDistance, const in float cutoffDistance ) {\n\treturn any( bvec2( cutoffDistance == 0.0, lightDistance < cutoffDistance ) );\n}\nfloat punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t\tif( decayExponent > 0.0 ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\t\tfloat maxDistanceCutoffFactor = pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t\treturn distanceFalloff * maxDistanceCutoffFactor;\n#else\n\t\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n#endif\n\t\t}\n\t\treturn 1.0;\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_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}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec3 BRDF_Specular_GGX_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n\treturn specularColor * AB.x + AB.y;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n"; + update: function () { - var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\t\tvec3 vSigmaX = dFdx( surf_pos );\n\t\tvec3 vSigmaY = dFdy( surf_pos );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 );\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif\n"; + this.dispatchEvent( { type: 'update' } ); - var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tfor ( int i = 0; i < NUM_CLIPPING_PLANES; ++ i ) {\n\t\tvec4 plane = clippingPlanes[ i ];\n\t\tif ( dot( vViewPosition, plane.xyz ) > plane.w ) discard;\n\t}\n#endif\n"; + }, - var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\t#if ! defined( PHYSICAL ) && ! defined( PHONG )\n\t\tvarying vec3 vViewPosition;\n\t#endif\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif\n"; + dispose: function () { - var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvarying vec3 vViewPosition;\n#endif\n"; + this.dispatchEvent( { type: 'dispose' } ); - var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n"; + } - var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif"; + }; - var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif\n"; + Object.assign( Material.prototype, EventDispatcher.prototype ); - var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif"; + var count$1 = 0; + function MaterialIdCount() { return count$1++; }; - var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif"; + /** + * Uniform Utilities + */ - var common = "#define PI 3.14159265359\n#define PI2 6.28318530718\n#define RECIPROCAL_PI 0.31830988618\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define whiteCompliment(a) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\n"; + exports.UniformsUtils = { - var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n#define cubeUV_textureSize (1024.0)\nint getFaceFromDirection(vec3 direction) {\n\tvec3 absDirection = abs(direction);\n\tint face = -1;\n\tif( absDirection.x > absDirection.z ) {\n\t\tif(absDirection.x > absDirection.y )\n\t\t\tface = direction.x > 0.0 ? 0 : 3;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\telse {\n\t\tif(absDirection.z > absDirection.y )\n\t\t\tface = direction.z > 0.0 ? 2 : 5;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\treturn face;\n}\n#define cubeUV_maxLods1 (log2(cubeUV_textureSize*0.25) - 1.0)\n#define cubeUV_rangeClamp (exp2((6.0 - 1.0) * 2.0))\nvec2 MipLevelInfo( vec3 vec, float roughnessLevel, float roughness ) {\n\tfloat scale = exp2(cubeUV_maxLods1 - roughnessLevel);\n\tfloat dxRoughness = dFdx(roughness);\n\tfloat dyRoughness = dFdy(roughness);\n\tvec3 dx = dFdx( vec * scale * dxRoughness );\n\tvec3 dy = dFdy( vec * scale * dyRoughness );\n\tfloat d = max( dot( dx, dx ), dot( dy, dy ) );\n\td = clamp(d, 1.0, cubeUV_rangeClamp);\n\tfloat mipLevel = 0.5 * log2(d);\n\treturn vec2(floor(mipLevel), fract(mipLevel));\n}\n#define cubeUV_maxLods2 (log2(cubeUV_textureSize*0.25) - 2.0)\n#define cubeUV_rcpTextureSize (1.0 / cubeUV_textureSize)\nvec2 getCubeUV(vec3 direction, float roughnessLevel, float mipLevel) {\n\tmipLevel = roughnessLevel > cubeUV_maxLods2 - 3.0 ? 0.0 : mipLevel;\n\tfloat a = 16.0 * cubeUV_rcpTextureSize;\n\tvec2 exp2_packed = exp2( vec2( roughnessLevel, mipLevel ) );\n\tvec2 rcp_exp2_packed = vec2( 1.0 ) / exp2_packed;\n\tfloat powScale = exp2_packed.x * exp2_packed.y;\n\tfloat scale = rcp_exp2_packed.x * rcp_exp2_packed.y * 0.25;\n\tfloat mipOffset = 0.75*(1.0 - rcp_exp2_packed.y) * rcp_exp2_packed.x;\n\tbool bRes = mipLevel == 0.0;\n\tscale = bRes && (scale < a) ? a : scale;\n\tvec3 r;\n\tvec2 offset;\n\tint face = getFaceFromDirection(direction);\n\tfloat rcpPowScale = 1.0 / powScale;\n\tif( face == 0) {\n\t\tr = vec3(direction.x, -direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 1) {\n\t\tr = vec3(direction.y, direction.x, direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 2) {\n\t\tr = vec3(direction.z, direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 3) {\n\t\tr = vec3(direction.x, direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse if( face == 4) {\n\t\tr = vec3(direction.y, direction.x, -direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse {\n\t\tr = vec3(direction.z, -direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\tr = normalize(r);\n\tfloat texelOffset = 0.5 * cubeUV_rcpTextureSize;\n\tvec2 s = ( r.yz / abs( r.x ) + vec2( 1.0 ) ) * 0.5;\n\tvec2 base = offset + vec2( texelOffset );\n\treturn base + s * ( scale - 2.0 * texelOffset );\n}\n#define cubeUV_maxLods3 (log2(cubeUV_textureSize*0.25) - 3.0)\nvec4 textureCubeUV(vec3 reflectedDirection, float roughness ) {\n\tfloat roughnessVal = roughness* cubeUV_maxLods3;\n\tfloat r1 = floor(roughnessVal);\n\tfloat r2 = r1 + 1.0;\n\tfloat t = fract(roughnessVal);\n\tvec2 mipInfo = MipLevelInfo(reflectedDirection, r1, roughness);\n\tfloat s = mipInfo.y;\n\tfloat level0 = mipInfo.x;\n\tfloat level1 = level0 + 1.0;\n\tlevel1 = level1 > 5.0 ? 5.0 : level1;\n\tlevel0 += min( floor( s + 0.5 ), 5.0 );\n\tvec2 uv_10 = getCubeUV(reflectedDirection, r1, level0);\n\tvec4 color10 = envMapTexelToLinear(texture2D(envMap, uv_10));\n\tvec2 uv_20 = getCubeUV(reflectedDirection, r2, level0);\n\tvec4 color20 = envMapTexelToLinear(texture2D(envMap, uv_20));\n\tvec4 result = mix(color10, color20, t);\n\treturn vec4(result.rgb, 1.0);\n}\n#endif\n"; + merge: function ( uniforms ) { - var defaultnormal_vertex = "#ifdef FLIP_SIDED\n\tobjectNormal = -objectNormal;\n#endif\nvec3 transformedNormal = normalMatrix * objectNormal;\n"; + var merged = {}; - var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif\n"; + for ( var u = 0; u < uniforms.length; u ++ ) { - var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normal * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n"; + var tmp = this.clone( uniforms[ u ] ); - var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif\n"; + for ( var p in tmp ) { - var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif\n"; + merged[ p ] = tmp[ p ]; - var encodings_fragment = " gl_FragColor = linearToOutputTexel( gl_FragColor );\n"; + } - var encodings_pars_fragment = "\nvec4 LinearToLinear( in vec4 value ) {\n return value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.w );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n return vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n float maxComponent = max( max( value.r, value.g ), value.b );\n float fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n return vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n return vec4( value.xyz * value.w * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n float maxRGB = max( value.x, max( value.g, value.b ) );\n float M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n M = ceil( M * 255.0 ) / 255.0;\n return vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n return vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n float maxRGB = max( value.x, max( value.g, value.b ) );\n float D = max( maxRange / maxRGB, 1.0 );\n D = min( floor( D ) / 255.0, 1.0 );\n return vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n vec3 Xp_Y_XYZp = value.rgb * cLogLuvM;\n Xp_Y_XYZp = max(Xp_Y_XYZp, vec3(1e-6, 1e-6, 1e-6));\n vec4 vResult;\n vResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n float Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n vResult.w = fract(Le);\n vResult.z = (Le - (floor(vResult.w*255.0))/255.0)/255.0;\n return vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n float Le = value.z * 255.0 + value.w;\n vec3 Xp_Y_XYZp;\n Xp_Y_XYZp.y = exp2((Le - 127.0) / 2.0);\n Xp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n Xp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n vec3 vRGB = Xp_Y_XYZp.rgb * cLogLuvInverseM;\n return vec4( max(vRGB, 0.0), 1.0 );\n}\n"; + } - var envmap_fragment = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\tvec2 sampleUV;\n\t\tsampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n\t\tsampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\tvec3 reflectView = flipNormal * normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\n\t\tvec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n\t#endif\n\tenvColor = envMapTexelToLinear( envColor );\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif\n"; + return merged; - var envmap_pars_fragment = "#if defined( USE_ENVMAP ) || defined( PHYSICAL )\n\tuniform float reflectivity;\n\tuniform float envMapIntenstiy;\n#endif\n#ifdef USE_ENVMAP\n\t#if ! defined( PHYSICAL ) && ( defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) )\n\t\tvarying vec3 vWorldPosition;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\tuniform float flipEnvMap;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( PHYSICAL )\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif\n"; + }, - var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif\n"; + clone: function ( uniforms_src ) { - var envmap_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif\n"; + var uniforms_dst = {}; - var fog_fragment = "#ifdef USE_FOG\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tfloat depth = gl_FragDepthEXT / gl_FragCoord.w;\n\t#else\n\t\tfloat depth = gl_FragCoord.z / gl_FragCoord.w;\n\t#endif\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * depth * depth * LOG2 ) );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, depth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif\n"; + for ( var u in uniforms_src ) { - var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif"; + uniforms_dst[ u ] = {}; - var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif\n"; + for ( var p in uniforms_src[ u ] ) { - var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif"; + var parameter_src = uniforms_src[ u ][ p ]; - var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\n#if NUM_POINT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_DIR_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvLightFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n#endif\n"; + if ( (parameter_src && parameter_src.isColor) || + (parameter_src && parameter_src.isVector2) || + (parameter_src && parameter_src.isVector3) || + (parameter_src && parameter_src.isVector4) || + (parameter_src && parameter_src.isMatrix3) || + (parameter_src && parameter_src.isMatrix4) || + (parameter_src && parameter_src.isTexture) ) { - var lights_pars = "uniform vec3 ambientLightColor;\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.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\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tif ( testLightInRange( lightDistance, pointLight.distance ) ) {\n\t\t\tdirectLight.color = pointLight.color;\n\t\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\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\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( all( bvec2( angleCos > spotLight.coneCos, testLightInRange( lightDistance, spotLight.distance ) ) ) ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\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 GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif\n#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\t#include \n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = flipNormal * vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryVec = flipNormal * vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\tvec4 envMapColor = textureCubeUV( queryVec, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in GeometricContext geometry, const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( -geometry.viewDir, geometry.normal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( -geometry.viewDir, geometry.normal, refractionRatio );\n\t\t#endif\n\t\t#include \n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( blinnShininessExponent, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryReflectVec = flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\tvec4 envMapColor = textureCubeUV(queryReflectVec, BlinnExponentToGGXRoughness(blinnShininessExponent));\n\t\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\t\tvec2 sampleUV;\n\t\t\tsampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n\t\t\tsampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\t\tvec3 reflectView = flipNormal * normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif\n"; + uniforms_dst[ u ][ p ] = parameter_src.clone(); - var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n"; + } else if ( Array.isArray( parameter_src ) ) { - var lights_phong_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)\n"; + uniforms_dst[ u ][ p ] = parameter_src.slice(); - var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.specularRoughness = clamp( roughnessFactor, 0.04, 1.0 );\n#ifdef STANDARD\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.clearCoat = saturate( clearCoat );\tmaterial.clearCoatRoughness = clamp( clearCoatRoughness, 0.04, 1.0 );\n#endif\n"; + } else { - var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3\tdiffuseColor;\n\tfloat\tspecularRoughness;\n\tvec3\tspecularColor;\n\t#ifndef STANDARD\n\t\tfloat clearCoat;\n\t\tfloat clearCoatRoughness;\n\t#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearCoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifndef STANDARD\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.directSpecular += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry, material.specularColor, material.specularRoughness );\n\treflectedLight.directDiffuse += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\t#ifndef STANDARD\n\t\treflectedLight.directSpecular += irradiance * material.clearCoat * BRDF_Specular_GGX( directLight, geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 clearCoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifndef STANDARD\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\tfloat dotNL = dotNV;\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.indirectSpecular += ( 1.0 - clearCoatDHR ) * radiance * BRDF_Specular_GGX_Environment( geometry, material.specularColor, material.specularRoughness );\n\t#ifndef STANDARD\n\t\treflectedLight.indirectSpecular += clearCoatRadiance * material.clearCoat * BRDF_Specular_GGX_Environment( geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\n#define Material_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.specularRoughness )\n#define Material_ClearCoat_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.clearCoatRoughness )\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}\n"; + uniforms_dst[ u ][ p ] = parameter_src; - var lights_template = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = normalize( vViewPosition );\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( pointLight.shadow, directLight.visible ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( spotLight.shadow, directLight.visible ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( directionalLight.shadow, directLight.visible ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#ifdef USE_LIGHTMAP\n\t\tvec3 lightMapIrradiance = texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t \tirradiance += getLightProbeIndirectIrradiance( geometry, 8 );\n\t#endif\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tvec3 radiance = getLightProbeIndirectRadiance( geometry, Material_BlinnShininessExponent( material ), 8 );\n\t#ifndef STANDARD\n\t\tvec3 clearCoatRadiance = getLightProbeIndirectRadiance( geometry, Material_ClearCoat_BlinnShininessExponent( material ), 8 );\n\t#else\n\t\tvec3 clearCoatRadiance = vec3( 0.0 );\n\t#endif\n\t\t\n\tRE_IndirectSpecular( radiance, clearCoatRadiance, geometry, material, reflectedLight );\n#endif\n"; + } - var logdepthbuf_fragment = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\tgl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n#endif"; + } - var logdepthbuf_pars_fragment = "#ifdef USE_LOGDEPTHBUF\n\tuniform float logDepthBufFC;\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n#endif\n"; + } - var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n\tuniform float logDepthBufFC;\n#endif"; + return uniforms_dst; - var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\tgl_Position.z = log2(max( EPSILON, gl_Position.w + 1.0 )) * logDepthBufFC;\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t#else\n\t\tgl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;\n\t#endif\n#endif\n"; + } - var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif\n"; + }; - var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n"; + /** + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * defines: { "label" : "value" }, + * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } }, + * + * fragmentShader: , + * vertexShader: , + * + * wireframe: , + * wireframeLinewidth: , + * + * lights: , + * + * skinning: , + * morphTargets: , + * morphNormals: + * } + */ - var map_particle_fragment = "#ifdef USE_MAP\n\tvec4 mapTexel = texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) * offsetRepeat.zw + offsetRepeat.xy );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n"; + function ShaderMaterial( parameters ) { - var map_particle_pars_fragment = "#ifdef USE_MAP\n\tuniform vec4 offsetRepeat;\n\tuniform sampler2D map;\n#endif\n"; + Material.call( this ); - var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.r;\n#endif\n"; + this.type = 'ShaderMaterial'; - var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif"; + this.defines = {}; + this.uniforms = {}; - var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n\tobjectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n\tobjectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n\tobjectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n#endif\n"; + this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}'; + this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}'; - var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\t#ifndef USE_MORPHNORMALS\n\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif"; + this.linewidth = 1; - var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n\ttransformed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n\ttransformed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n\ttransformed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\ttransformed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n\ttransformed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n\ttransformed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n\ttransformed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n\t#endif\n#endif\n"; + this.wireframe = false; + this.wireframeLinewidth = 1; - var normal_flip = "#ifdef DOUBLE_SIDED\n\tfloat flipNormal = ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n#else\n\tfloat flipNormal = 1.0;\n#endif\n"; + this.fog = false; // set to use scene fog + this.lights = false; // set to use scene lights + this.clipping = false; // set to use user-defined clipping planes - var normal_fragment = "#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal ) * flipNormal;\n#endif\n#ifdef USE_NORMALMAP\n\tnormal = perturbNormal2Arb( -vViewPosition, normal );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif\n"; + this.skinning = false; // set to use skinning attribute streams + this.morphTargets = false; // set to use morph targets + this.morphNormals = false; // set to use morph normals - var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tvec3 S = normalize( q0 * st1.t - q1 * st0.t );\n\t\tvec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n\t\tvec3 N = normalize( surf_norm );\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy = normalScale * mapN.xy;\n\t\tmat3 tsn = mat3( S, T, N );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif\n"; + this.extensions = { + derivatives: false, // set to use derivatives + fragDepth: false, // set to use fragment depth values + drawBuffers: false, // set to use draw buffers + shaderTextureLOD: false // set to use shader texture LOD + }; - var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 1.0 - 2.0 * rgb.xyz;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n return ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n return (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n}\n"; + // When rendered geometry doesn't include these attributes but the material does, + // use these default values in WebGL. This avoids errors when buffer data is missing. + this.defaultAttributeValues = { + 'color': [ 1, 1, 1 ], + 'uv': [ 0, 0 ], + 'uv2': [ 0, 0 ] + }; - var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif\n"; + this.index0AttributeName = undefined; - var project_vertex = "#ifdef USE_SKINNING\n\tvec4 mvPosition = modelViewMatrix * skinned;\n#else\n\tvec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\n#endif\ngl_Position = projectionMatrix * mvPosition;\n"; + if ( parameters !== undefined ) { - var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.r;\n#endif\n"; + if ( parameters.attributes !== undefined ) { - var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif"; + console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' ); - var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tfloat texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\n\t\tconst vec2 offset = vec2( 0.0, 1.0 );\n\t\tvec2 texelSize = vec2( 1.0 ) / size;\n\t\tvec2 centroidUV = floor( uv * size + 0.5 ) / size;\n\t\tfloat lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\n\t\tfloat lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\n\t\tfloat rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\n\t\tfloat rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\n\t\tvec2 f = fract( uv * size + 0.5 );\n\t\tfloat a = mix( lb, lt, f.y );\n\t\tfloat b = mix( rb, rt, f.y );\n\t\tfloat c = mix( a, b, f.x );\n\t\treturn c;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\treturn (\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn 1.0;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\tfloat dp = ( length( lightToPosition ) - shadowBias ) / 1000.0;\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif\n"; + } - var shadowmap_pars_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n#endif\n"; + this.setValues( parameters ); - var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n#endif\n"; + } - var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tshadow *= bool( directionalLight.shadow ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tshadow *= bool( spotLight.shadow ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tshadow *= bool( pointLight.shadow ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#endif\n\treturn shadow;\n}\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"; + ShaderMaterial.prototype = Object.create( Material.prototype ); + ShaderMaterial.prototype.constructor = ShaderMaterial; - var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform sampler2D boneTexture;\n\t\tuniform int boneTextureWidth;\n\t\tuniform int boneTextureHeight;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureWidth ) );\n\t\t\tfloat y = floor( j / float( boneTextureWidth ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureWidth );\n\t\t\tfloat dy = 1.0 / float( boneTextureHeight );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif\n"; + ShaderMaterial.prototype.isShaderMaterial = true; - var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\tskinned = bindMatrixInverse * skinned;\n#endif\n"; + ShaderMaterial.prototype.copy = function ( source ) { - var skinnormal_vertex = "#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n#endif\n"; + Material.prototype.copy.call( this, source ); - var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif"; + this.fragmentShader = source.fragmentShader; + this.vertexShader = source.vertexShader; - var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif"; + this.uniforms = exports.UniformsUtils.clone( source.uniforms ); - var tonemapping_fragment = "#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif\n"; + this.defines = source.defines; - var tonemapping_pars_fragment = "#define saturate(a) clamp( a, 0.0, 1.0 )\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\nvec3 LinearToneMapping( vec3 color ) {\n return toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n return saturate( color / ( vec3( 1.0 ) + color ) );\n}\n#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )\nvec3 Uncharted2ToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n return saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n color = max( vec3( 0.0 ), color - 0.004 );\n return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\n"; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; - var uv_pars_fragment = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n#endif"; + this.lights = source.lights; + this.clipping = source.clipping; - var uv_pars_vertex = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n\tuniform vec4 offsetRepeat;\n#endif\n"; + this.skinning = source.skinning; - var uv_vertex = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvUv = uv * offsetRepeat.zw + offsetRepeat.xy;\n#endif"; + this.morphTargets = source.morphTargets; + this.morphNormals = source.morphNormals; - var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif"; + this.extensions = source.extensions; - var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif"; + return this; - var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif"; + }; - var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( PHYSICAL ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )\n\t#ifdef USE_SKINNING\n\t\tvec4 worldPosition = modelMatrix * skinned;\n\t#else\n\t\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n\t#endif\n#endif\n"; + ShaderMaterial.prototype.toJSON = function ( meta ) { - var cube_frag = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldPosition;\n#include \nvoid main() {\n\tgl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\n\tgl_FragColor.a *= opacity;\n}\n"; + var data = Material.prototype.toJSON.call( this, meta ); - var cube_vert = "varying vec3 vWorldPosition;\n#include \nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}\n"; + data.uniforms = this.uniforms; + data.vertexShader = this.vertexShader; + data.fragmentShader = this.fragmentShader; - var depth_frag = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( gl_FragCoord.z ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( gl_FragCoord.z );\n\t#endif\n}\n"; + return data; - var depth_vert = "#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; + }; - var distanceRGBA_frag = "uniform vec3 lightPos;\nvarying vec4 vWorldPosition;\n#include \n#include \n#include \nvoid main () {\n\t#include \n\tgl_FragColor = packDepthToRGBA( length( vWorldPosition.xyz - lightPos.xyz ) / 1000.0 );\n}\n"; + var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n"; - var distanceRGBA_vert = "varying vec4 vWorldPosition;\n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvWorldPosition = worldPosition;\n}\n"; + var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif\n"; - var equirect_frag = "uniform sampler2D tEquirect;\nuniform float tFlip;\nvarying vec3 vWorldPosition;\n#include \nvoid main() {\n\tvec3 direction = normalize( vWorldPosition );\n\tvec2 sampleUV;\n\tsampleUV.y = saturate( tFlip * direction.y * -0.5 + 0.5 );\n\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n}\n"; + var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif\n"; - var equirect_vert = "varying vec3 vWorldPosition;\n#include \nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}\n"; + var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\t#endif\n#endif\n"; - var linedashed_frag = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; + var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif"; - var linedashed_vert = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvLineDistance = scale * lineDistance;\n\tvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include \n\t#include \n}\n"; + var begin_vertex = "\nvec3 transformed = vec3( position );\n"; - var meshbasic_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tReflectedLight reflectedLight;\n\treflectedLight.directDiffuse = vec3( 0.0 );\n\treflectedLight.directSpecular = vec3( 0.0 );\n\treflectedLight.indirectDiffuse = diffuseColor.rgb;\n\treflectedLight.indirectSpecular = vec3( 0.0 );\n\t#include \n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include \n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; + var beginnormal_vertex = "\nvec3 objectNormal = vec3( normal );\n"; - var meshbasic_vert = "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_ENVMAP\n\t#include \n\t#include \n\t#include \n\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; + var bsdfs = "bool testLightInRange( const in float lightDistance, const in float cutoffDistance ) {\n\treturn any( bvec2( cutoffDistance == 0.0, lightDistance < cutoffDistance ) );\n}\nfloat punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t\tif( decayExponent > 0.0 ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\t\tfloat maxDistanceCutoffFactor = pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t\treturn distanceFalloff * maxDistanceCutoffFactor;\n#else\n\t\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n#endif\n\t\t}\n\t\treturn 1.0;\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_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}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec3 BRDF_Specular_GGX_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n\treturn specularColor * AB.x + AB.y;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n"; - var meshlambert_frag = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\treflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\n\t#include \n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; + var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\t\tvec3 vSigmaX = dFdx( surf_pos );\n\t\tvec3 vSigmaY = dFdy( surf_pos );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 );\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif\n"; - var meshlambert_vert = "#define LAMBERT\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; + var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tfor ( int i = 0; i < NUM_CLIPPING_PLANES; ++ i ) {\n\t\tvec4 plane = clippingPlanes[ i ];\n\t\tif ( dot( vViewPosition, plane.xyz ) > plane.w ) discard;\n\t}\n#endif\n"; - var meshphong_frag = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; + var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\t#if ! defined( PHYSICAL ) && ! defined( PHONG )\n\t\tvarying vec3 vViewPosition;\n\t#endif\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif\n"; - var meshphong_vert = "#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n}\n"; + var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvarying vec3 vViewPosition;\n#endif\n"; - var meshphysical_frag = "#define PHYSICAL\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifndef STANDARD\n\tuniform float clearCoat;\n\tuniform float clearCoatRoughness;\n#endif\nuniform float envMapIntensity;\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; + var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n"; - var meshphysical_vert = "#define PHYSICAL\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n}\n"; + var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif"; - var normal_frag = "uniform float opacity;\nvarying vec3 vNormal;\n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tgl_FragColor = vec4( packNormalToRGB( vNormal ), opacity );\n\t#include \n}\n"; + var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif\n"; - var normal_vert = "varying vec3 vNormal;\n#include \n#include \n#include \n#include \nvoid main() {\n\tvNormal = normalize( normalMatrix * normal );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; + var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif"; - var points_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; + var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif"; - var points_vert = "uniform float size;\nuniform float scale;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#ifdef USE_SIZEATTENUATION\n\t\tgl_PointSize = size * ( scale / - mvPosition.z );\n\t#else\n\t\tgl_PointSize = size;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; + var common = "#define PI 3.14159265359\n#define PI2 6.28318530718\n#define RECIPROCAL_PI 0.31830988618\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define whiteCompliment(a) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\n"; - var shadow_frag = "uniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tgl_FragColor = vec4( 0.0, 0.0, 0.0, opacity * ( 1.0 - getShadowMask() ) );\n}\n"; + var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n#define cubeUV_textureSize (1024.0)\nint getFaceFromDirection(vec3 direction) {\n\tvec3 absDirection = abs(direction);\n\tint face = -1;\n\tif( absDirection.x > absDirection.z ) {\n\t\tif(absDirection.x > absDirection.y )\n\t\t\tface = direction.x > 0.0 ? 0 : 3;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\telse {\n\t\tif(absDirection.z > absDirection.y )\n\t\t\tface = direction.z > 0.0 ? 2 : 5;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\treturn face;\n}\n#define cubeUV_maxLods1 (log2(cubeUV_textureSize*0.25) - 1.0)\n#define cubeUV_rangeClamp (exp2((6.0 - 1.0) * 2.0))\nvec2 MipLevelInfo( vec3 vec, float roughnessLevel, float roughness ) {\n\tfloat scale = exp2(cubeUV_maxLods1 - roughnessLevel);\n\tfloat dxRoughness = dFdx(roughness);\n\tfloat dyRoughness = dFdy(roughness);\n\tvec3 dx = dFdx( vec * scale * dxRoughness );\n\tvec3 dy = dFdy( vec * scale * dyRoughness );\n\tfloat d = max( dot( dx, dx ), dot( dy, dy ) );\n\td = clamp(d, 1.0, cubeUV_rangeClamp);\n\tfloat mipLevel = 0.5 * log2(d);\n\treturn vec2(floor(mipLevel), fract(mipLevel));\n}\n#define cubeUV_maxLods2 (log2(cubeUV_textureSize*0.25) - 2.0)\n#define cubeUV_rcpTextureSize (1.0 / cubeUV_textureSize)\nvec2 getCubeUV(vec3 direction, float roughnessLevel, float mipLevel) {\n\tmipLevel = roughnessLevel > cubeUV_maxLods2 - 3.0 ? 0.0 : mipLevel;\n\tfloat a = 16.0 * cubeUV_rcpTextureSize;\n\tvec2 exp2_packed = exp2( vec2( roughnessLevel, mipLevel ) );\n\tvec2 rcp_exp2_packed = vec2( 1.0 ) / exp2_packed;\n\tfloat powScale = exp2_packed.x * exp2_packed.y;\n\tfloat scale = rcp_exp2_packed.x * rcp_exp2_packed.y * 0.25;\n\tfloat mipOffset = 0.75*(1.0 - rcp_exp2_packed.y) * rcp_exp2_packed.x;\n\tbool bRes = mipLevel == 0.0;\n\tscale = bRes && (scale < a) ? a : scale;\n\tvec3 r;\n\tvec2 offset;\n\tint face = getFaceFromDirection(direction);\n\tfloat rcpPowScale = 1.0 / powScale;\n\tif( face == 0) {\n\t\tr = vec3(direction.x, -direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 1) {\n\t\tr = vec3(direction.y, direction.x, direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 2) {\n\t\tr = vec3(direction.z, direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 3) {\n\t\tr = vec3(direction.x, direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse if( face == 4) {\n\t\tr = vec3(direction.y, direction.x, -direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse {\n\t\tr = vec3(direction.z, -direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\tr = normalize(r);\n\tfloat texelOffset = 0.5 * cubeUV_rcpTextureSize;\n\tvec2 s = ( r.yz / abs( r.x ) + vec2( 1.0 ) ) * 0.5;\n\tvec2 base = offset + vec2( texelOffset );\n\treturn base + s * ( scale - 2.0 * texelOffset );\n}\n#define cubeUV_maxLods3 (log2(cubeUV_textureSize*0.25) - 3.0)\nvec4 textureCubeUV(vec3 reflectedDirection, float roughness ) {\n\tfloat roughnessVal = roughness* cubeUV_maxLods3;\n\tfloat r1 = floor(roughnessVal);\n\tfloat r2 = r1 + 1.0;\n\tfloat t = fract(roughnessVal);\n\tvec2 mipInfo = MipLevelInfo(reflectedDirection, r1, roughness);\n\tfloat s = mipInfo.y;\n\tfloat level0 = mipInfo.x;\n\tfloat level1 = level0 + 1.0;\n\tlevel1 = level1 > 5.0 ? 5.0 : level1;\n\tlevel0 += min( floor( s + 0.5 ), 5.0 );\n\tvec2 uv_10 = getCubeUV(reflectedDirection, r1, level0);\n\tvec4 color10 = envMapTexelToLinear(texture2D(envMap, uv_10));\n\tvec2 uv_20 = getCubeUV(reflectedDirection, r2, level0);\n\tvec4 color20 = envMapTexelToLinear(texture2D(envMap, uv_20));\n\tvec4 result = mix(color10, color20, t);\n\treturn vec4(result.rgb, 1.0);\n}\n#endif\n"; - var shadow_vert = "#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; + var defaultnormal_vertex = "#ifdef FLIP_SIDED\n\tobjectNormal = -objectNormal;\n#endif\nvec3 transformedNormal = normalMatrix * objectNormal;\n"; - var ShaderChunk = { - alphamap_fragment: alphamap_fragment, - alphamap_pars_fragment: alphamap_pars_fragment, - alphatest_fragment: alphatest_fragment, - aomap_fragment: aomap_fragment, - aomap_pars_fragment: aomap_pars_fragment, - begin_vertex: begin_vertex, - beginnormal_vertex: beginnormal_vertex, - bsdfs: bsdfs, - bumpmap_pars_fragment: bumpmap_pars_fragment, - clipping_planes_fragment: clipping_planes_fragment, - clipping_planes_pars_fragment: clipping_planes_pars_fragment, - clipping_planes_pars_vertex: clipping_planes_pars_vertex, - clipping_planes_vertex: clipping_planes_vertex, - color_fragment: color_fragment, - color_pars_fragment: color_pars_fragment, - color_pars_vertex: color_pars_vertex, - color_vertex: color_vertex, - common: common, - cube_uv_reflection_fragment: cube_uv_reflection_fragment, - defaultnormal_vertex: defaultnormal_vertex, - displacementmap_pars_vertex: displacementmap_pars_vertex, - displacementmap_vertex: displacementmap_vertex, - emissivemap_fragment: emissivemap_fragment, - emissivemap_pars_fragment: emissivemap_pars_fragment, - encodings_fragment: encodings_fragment, - encodings_pars_fragment: encodings_pars_fragment, - envmap_fragment: envmap_fragment, - envmap_pars_fragment: envmap_pars_fragment, - envmap_pars_vertex: envmap_pars_vertex, - envmap_vertex: envmap_vertex, - fog_fragment: fog_fragment, - fog_pars_fragment: fog_pars_fragment, - lightmap_fragment: lightmap_fragment, - lightmap_pars_fragment: lightmap_pars_fragment, - lights_lambert_vertex: lights_lambert_vertex, - lights_pars: lights_pars, - lights_phong_fragment: lights_phong_fragment, - lights_phong_pars_fragment: lights_phong_pars_fragment, - lights_physical_fragment: lights_physical_fragment, - lights_physical_pars_fragment: lights_physical_pars_fragment, - lights_template: lights_template, - logdepthbuf_fragment: logdepthbuf_fragment, - logdepthbuf_pars_fragment: logdepthbuf_pars_fragment, - logdepthbuf_pars_vertex: logdepthbuf_pars_vertex, - logdepthbuf_vertex: logdepthbuf_vertex, - map_fragment: map_fragment, - map_pars_fragment: map_pars_fragment, - map_particle_fragment: map_particle_fragment, - map_particle_pars_fragment: map_particle_pars_fragment, - metalnessmap_fragment: metalnessmap_fragment, - metalnessmap_pars_fragment: metalnessmap_pars_fragment, - morphnormal_vertex: morphnormal_vertex, - morphtarget_pars_vertex: morphtarget_pars_vertex, - morphtarget_vertex: morphtarget_vertex, - normal_flip: normal_flip, - normal_fragment: normal_fragment, - normalmap_pars_fragment: normalmap_pars_fragment, - packing: packing, - premultiplied_alpha_fragment: premultiplied_alpha_fragment, - project_vertex: project_vertex, - roughnessmap_fragment: roughnessmap_fragment, - roughnessmap_pars_fragment: roughnessmap_pars_fragment, - shadowmap_pars_fragment: shadowmap_pars_fragment, - shadowmap_pars_vertex: shadowmap_pars_vertex, - shadowmap_vertex: shadowmap_vertex, - shadowmask_pars_fragment: shadowmask_pars_fragment, - skinbase_vertex: skinbase_vertex, - skinning_pars_vertex: skinning_pars_vertex, - skinning_vertex: skinning_vertex, - skinnormal_vertex: skinnormal_vertex, - specularmap_fragment: specularmap_fragment, - specularmap_pars_fragment: specularmap_pars_fragment, - tonemapping_fragment: tonemapping_fragment, - tonemapping_pars_fragment: tonemapping_pars_fragment, - uv_pars_fragment: uv_pars_fragment, - uv_pars_vertex: uv_pars_vertex, - uv_vertex: uv_vertex, - uv2_pars_fragment: uv2_pars_fragment, - uv2_pars_vertex: uv2_pars_vertex, - uv2_vertex: uv2_vertex, - worldpos_vertex: worldpos_vertex, - - cube_frag: cube_frag, - cube_vert: cube_vert, - depth_frag: depth_frag, - depth_vert: depth_vert, - distanceRGBA_frag: distanceRGBA_frag, - distanceRGBA_vert: distanceRGBA_vert, - equirect_frag: equirect_frag, - equirect_vert: equirect_vert, - linedashed_frag: linedashed_frag, - linedashed_vert: linedashed_vert, - meshbasic_frag: meshbasic_frag, - meshbasic_vert: meshbasic_vert, - meshlambert_frag: meshlambert_frag, - meshlambert_vert: meshlambert_vert, - meshphong_frag: meshphong_frag, - meshphong_vert: meshphong_vert, - meshphysical_frag: meshphysical_frag, - meshphysical_vert: meshphysical_vert, - normal_frag: normal_frag, - normal_vert: normal_vert, - points_frag: points_frag, - points_vert: points_vert, - shadow_frag: shadow_frag, - shadow_vert: shadow_vert - }; - - /** - * @author mrdoob / http://mrdoob.com/ - */ - - function Color( r, g, b ) { - - if ( g === undefined && b === undefined ) { - - // r is THREE.Color, hex or string - return this.set( r ); - - } - - return this.setRGB( r, g, b ); - - }; + var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif\n"; - Color.prototype = { + var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normal * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n"; - constructor: Color, + var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif\n"; - isColor: true, + var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif\n"; - r: 1, g: 1, b: 1, + var encodings_fragment = " gl_FragColor = linearToOutputTexel( gl_FragColor );\n"; - set: function ( value ) { + var encodings_pars_fragment = "\nvec4 LinearToLinear( in vec4 value ) {\n return value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.w );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n return vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n float maxComponent = max( max( value.r, value.g ), value.b );\n float fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n return vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n return vec4( value.xyz * value.w * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n float maxRGB = max( value.x, max( value.g, value.b ) );\n float M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n M = ceil( M * 255.0 ) / 255.0;\n return vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n return vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n float maxRGB = max( value.x, max( value.g, value.b ) );\n float D = max( maxRange / maxRGB, 1.0 );\n D = min( floor( D ) / 255.0, 1.0 );\n return vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n vec3 Xp_Y_XYZp = value.rgb * cLogLuvM;\n Xp_Y_XYZp = max(Xp_Y_XYZp, vec3(1e-6, 1e-6, 1e-6));\n vec4 vResult;\n vResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n float Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n vResult.w = fract(Le);\n vResult.z = (Le - (floor(vResult.w*255.0))/255.0)/255.0;\n return vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n float Le = value.z * 255.0 + value.w;\n vec3 Xp_Y_XYZp;\n Xp_Y_XYZp.y = exp2((Le - 127.0) / 2.0);\n Xp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n Xp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n vec3 vRGB = Xp_Y_XYZp.rgb * cLogLuvInverseM;\n return vec4( max(vRGB, 0.0), 1.0 );\n}\n"; - if ( (value && value.isColor) ) { + var envmap_fragment = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\tvec2 sampleUV;\n\t\tsampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n\t\tsampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\tvec3 reflectView = flipNormal * normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\n\t\tvec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n\t#endif\n\tenvColor = envMapTexelToLinear( envColor );\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif\n"; - this.copy( value ); + var envmap_pars_fragment = "#if defined( USE_ENVMAP ) || defined( PHYSICAL )\n\tuniform float reflectivity;\n\tuniform float envMapIntenstiy;\n#endif\n#ifdef USE_ENVMAP\n\t#if ! defined( PHYSICAL ) && ( defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) )\n\t\tvarying vec3 vWorldPosition;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\tuniform float flipEnvMap;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( PHYSICAL )\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif\n"; - } else if ( typeof value === 'number' ) { + var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif\n"; - this.setHex( value ); + var envmap_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif\n"; - } else if ( typeof value === 'string' ) { + var fog_fragment = "#ifdef USE_FOG\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tfloat depth = gl_FragDepthEXT / gl_FragCoord.w;\n\t#else\n\t\tfloat depth = gl_FragCoord.z / gl_FragCoord.w;\n\t#endif\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * depth * depth * LOG2 ) );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, depth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif\n"; - this.setStyle( value ); + var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif"; - } + var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif\n"; - return this; + var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif"; - }, + var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\n#if NUM_POINT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_DIR_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvLightFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n#endif\n"; - setScalar: function ( scalar ) { + var lights_pars = "uniform vec3 ambientLightColor;\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.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\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tif ( testLightInRange( lightDistance, pointLight.distance ) ) {\n\t\t\tdirectLight.color = pointLight.color;\n\t\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\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\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( all( bvec2( angleCos > spotLight.coneCos, testLightInRange( lightDistance, spotLight.distance ) ) ) ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\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 GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif\n#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\t#include \n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = flipNormal * vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryVec = flipNormal * vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\tvec4 envMapColor = textureCubeUV( queryVec, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in GeometricContext geometry, const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( -geometry.viewDir, geometry.normal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( -geometry.viewDir, geometry.normal, refractionRatio );\n\t\t#endif\n\t\t#include \n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( blinnShininessExponent, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryReflectVec = flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\tvec4 envMapColor = textureCubeUV(queryReflectVec, BlinnExponentToGGXRoughness(blinnShininessExponent));\n\t\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\t\tvec2 sampleUV;\n\t\t\tsampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n\t\t\tsampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\t\tvec3 reflectView = flipNormal * normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif\n"; - this.r = scalar; - this.g = scalar; - this.b = scalar; + var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n"; - }, + var lights_phong_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)\n"; - setHex: function ( hex ) { + var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.specularRoughness = clamp( roughnessFactor, 0.04, 1.0 );\n#ifdef STANDARD\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.clearCoat = saturate( clearCoat );\tmaterial.clearCoatRoughness = clamp( clearCoatRoughness, 0.04, 1.0 );\n#endif\n"; - hex = Math.floor( hex ); + var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3\tdiffuseColor;\n\tfloat\tspecularRoughness;\n\tvec3\tspecularColor;\n\t#ifndef STANDARD\n\t\tfloat clearCoat;\n\t\tfloat clearCoatRoughness;\n\t#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearCoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifndef STANDARD\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.directSpecular += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry, material.specularColor, material.specularRoughness );\n\treflectedLight.directDiffuse += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\t#ifndef STANDARD\n\t\treflectedLight.directSpecular += irradiance * material.clearCoat * BRDF_Specular_GGX( directLight, geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 clearCoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifndef STANDARD\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\tfloat dotNL = dotNV;\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.indirectSpecular += ( 1.0 - clearCoatDHR ) * radiance * BRDF_Specular_GGX_Environment( geometry, material.specularColor, material.specularRoughness );\n\t#ifndef STANDARD\n\t\treflectedLight.indirectSpecular += clearCoatRadiance * material.clearCoat * BRDF_Specular_GGX_Environment( geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\n#define Material_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.specularRoughness )\n#define Material_ClearCoat_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.clearCoatRoughness )\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}\n"; - this.r = ( hex >> 16 & 255 ) / 255; - this.g = ( hex >> 8 & 255 ) / 255; - this.b = ( hex & 255 ) / 255; + var lights_template = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = normalize( vViewPosition );\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( pointLight.shadow, directLight.visible ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( spotLight.shadow, directLight.visible ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( directionalLight.shadow, directLight.visible ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#ifdef USE_LIGHTMAP\n\t\tvec3 lightMapIrradiance = texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t \tirradiance += getLightProbeIndirectIrradiance( geometry, 8 );\n\t#endif\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tvec3 radiance = getLightProbeIndirectRadiance( geometry, Material_BlinnShininessExponent( material ), 8 );\n\t#ifndef STANDARD\n\t\tvec3 clearCoatRadiance = getLightProbeIndirectRadiance( geometry, Material_ClearCoat_BlinnShininessExponent( material ), 8 );\n\t#else\n\t\tvec3 clearCoatRadiance = vec3( 0.0 );\n\t#endif\n\t\t\n\tRE_IndirectSpecular( radiance, clearCoatRadiance, geometry, material, reflectedLight );\n#endif\n"; - return this; + var logdepthbuf_fragment = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\tgl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n#endif"; - }, + var logdepthbuf_pars_fragment = "#ifdef USE_LOGDEPTHBUF\n\tuniform float logDepthBufFC;\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n#endif\n"; - setRGB: function ( r, g, b ) { + var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n\tuniform float logDepthBufFC;\n#endif"; - this.r = r; - this.g = g; - this.b = b; + var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\tgl_Position.z = log2(max( EPSILON, gl_Position.w + 1.0 )) * logDepthBufFC;\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t#else\n\t\tgl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;\n\t#endif\n#endif\n"; - return this; + var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif\n"; - }, + var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n"; - setHSL: function () { + var map_particle_fragment = "#ifdef USE_MAP\n\tvec4 mapTexel = texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) * offsetRepeat.zw + offsetRepeat.xy );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n"; - function hue2rgb( p, q, t ) { + var map_particle_pars_fragment = "#ifdef USE_MAP\n\tuniform vec4 offsetRepeat;\n\tuniform sampler2D map;\n#endif\n"; - if ( t < 0 ) t += 1; - if ( t > 1 ) t -= 1; - if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t; - if ( t < 1 / 2 ) return q; - if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t ); - return p; + var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.r;\n#endif\n"; - } + var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif"; - return function setHSL( h, s, l ) { + var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n\tobjectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n\tobjectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n\tobjectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n#endif\n"; - // h,s,l ranges are in 0.0 - 1.0 - h = exports.Math.euclideanModulo( h, 1 ); - s = exports.Math.clamp( s, 0, 1 ); - l = exports.Math.clamp( l, 0, 1 ); + var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\t#ifndef USE_MORPHNORMALS\n\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif"; - if ( s === 0 ) { + var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n\ttransformed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n\ttransformed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n\ttransformed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\ttransformed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n\ttransformed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n\ttransformed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n\ttransformed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n\t#endif\n#endif\n"; - this.r = this.g = this.b = l; + var normal_flip = "#ifdef DOUBLE_SIDED\n\tfloat flipNormal = ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n#else\n\tfloat flipNormal = 1.0;\n#endif\n"; - } else { + var normal_fragment = "#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal ) * flipNormal;\n#endif\n#ifdef USE_NORMALMAP\n\tnormal = perturbNormal2Arb( -vViewPosition, normal );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif\n"; - var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s ); - var q = ( 2 * l ) - p; + var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tvec3 S = normalize( q0 * st1.t - q1 * st0.t );\n\t\tvec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n\t\tvec3 N = normalize( surf_norm );\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy = normalScale * mapN.xy;\n\t\tmat3 tsn = mat3( S, T, N );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif\n"; - this.r = hue2rgb( q, p, h + 1 / 3 ); - this.g = hue2rgb( q, p, h ); - this.b = hue2rgb( q, p, h - 1 / 3 ); + var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 1.0 - 2.0 * rgb.xyz;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n return ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n return (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n}\n"; - } + var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif\n"; - return this; + var project_vertex = "#ifdef USE_SKINNING\n\tvec4 mvPosition = modelViewMatrix * skinned;\n#else\n\tvec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\n#endif\ngl_Position = projectionMatrix * mvPosition;\n"; - }; + var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.r;\n#endif\n"; - }(), + var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif"; - setStyle: function ( style ) { + var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tfloat texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\n\t\tconst vec2 offset = vec2( 0.0, 1.0 );\n\t\tvec2 texelSize = vec2( 1.0 ) / size;\n\t\tvec2 centroidUV = floor( uv * size + 0.5 ) / size;\n\t\tfloat lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\n\t\tfloat lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\n\t\tfloat rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\n\t\tfloat rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\n\t\tvec2 f = fract( uv * size + 0.5 );\n\t\tfloat a = mix( lb, lt, f.y );\n\t\tfloat b = mix( rb, rt, f.y );\n\t\tfloat c = mix( a, b, f.x );\n\t\treturn c;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\treturn (\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn 1.0;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\tfloat dp = ( length( lightToPosition ) - shadowBias ) / 1000.0;\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif\n"; - function handleAlpha( string ) { + var shadowmap_pars_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n#endif\n"; - if ( string === undefined ) return; + var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n#endif\n"; - if ( parseFloat( string ) < 1 ) { + var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tshadow *= bool( directionalLight.shadow ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tshadow *= bool( spotLight.shadow ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tshadow *= bool( pointLight.shadow ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#endif\n\treturn shadow;\n}\n"; - console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' ); + 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"; - } + var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform sampler2D boneTexture;\n\t\tuniform int boneTextureWidth;\n\t\tuniform int boneTextureHeight;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureWidth ) );\n\t\t\tfloat y = floor( j / float( boneTextureWidth ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureWidth );\n\t\t\tfloat dy = 1.0 / float( boneTextureHeight );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif\n"; - } + var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\tskinned = bindMatrixInverse * skinned;\n#endif\n"; + var skinnormal_vertex = "#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n#endif\n"; - var m; + var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif"; - if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) { + var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif"; - // rgb / hsl + var tonemapping_fragment = "#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif\n"; - var color; - var name = m[ 1 ]; - var components = m[ 2 ]; + var tonemapping_pars_fragment = "#define saturate(a) clamp( a, 0.0, 1.0 )\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\nvec3 LinearToneMapping( vec3 color ) {\n return toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n return saturate( color / ( vec3( 1.0 ) + color ) );\n}\n#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )\nvec3 Uncharted2ToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n return saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n color = max( vec3( 0.0 ), color - 0.004 );\n return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\n"; - switch ( name ) { + var uv_pars_fragment = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n#endif"; - case 'rgb': - case 'rgba': + var uv_pars_vertex = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n\tuniform vec4 offsetRepeat;\n#endif\n"; - if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) { + var uv_vertex = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvUv = uv * offsetRepeat.zw + offsetRepeat.xy;\n#endif"; - // rgb(255,0,0) rgba(255,0,0,0.5) - this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255; - this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255; - this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255; + var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif"; - handleAlpha( color[ 5 ] ); + var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif"; - return this; + var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif"; - } + var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( PHYSICAL ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )\n\t#ifdef USE_SKINNING\n\t\tvec4 worldPosition = modelMatrix * skinned;\n\t#else\n\t\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n\t#endif\n#endif\n"; - if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) { + var cube_frag = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldPosition;\n#include \nvoid main() {\n\tgl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\n\tgl_FragColor.a *= opacity;\n}\n"; - // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5) - this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100; - this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100; - this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100; + var cube_vert = "varying vec3 vWorldPosition;\n#include \nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}\n"; - handleAlpha( color[ 5 ] ); + var depth_frag = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( gl_FragCoord.z ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( gl_FragCoord.z );\n\t#endif\n}\n"; - return this; + var depth_vert = "#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; - } + var distanceRGBA_frag = "uniform vec3 lightPos;\nvarying vec4 vWorldPosition;\n#include \n#include \n#include \nvoid main () {\n\t#include \n\tgl_FragColor = packDepthToRGBA( length( vWorldPosition.xyz - lightPos.xyz ) / 1000.0 );\n}\n"; - break; + var distanceRGBA_vert = "varying vec4 vWorldPosition;\n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvWorldPosition = worldPosition;\n}\n"; - case 'hsl': - case 'hsla': + var equirect_frag = "uniform sampler2D tEquirect;\nuniform float tFlip;\nvarying vec3 vWorldPosition;\n#include \nvoid main() {\n\tvec3 direction = normalize( vWorldPosition );\n\tvec2 sampleUV;\n\tsampleUV.y = saturate( tFlip * direction.y * -0.5 + 0.5 );\n\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n}\n"; - if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) { + var equirect_vert = "varying vec3 vWorldPosition;\n#include \nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}\n"; - // hsl(120,50%,50%) hsla(120,50%,50%,0.5) - var h = parseFloat( color[ 1 ] ) / 360; - var s = parseInt( color[ 2 ], 10 ) / 100; - var l = parseInt( color[ 3 ], 10 ) / 100; + var linedashed_frag = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; - handleAlpha( color[ 5 ] ); + var linedashed_vert = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvLineDistance = scale * lineDistance;\n\tvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include \n\t#include \n}\n"; - return this.setHSL( h, s, l ); + var meshbasic_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tReflectedLight reflectedLight;\n\treflectedLight.directDiffuse = vec3( 0.0 );\n\treflectedLight.directSpecular = vec3( 0.0 );\n\treflectedLight.indirectDiffuse = diffuseColor.rgb;\n\treflectedLight.indirectSpecular = vec3( 0.0 );\n\t#include \n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include \n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; - } + var meshbasic_vert = "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_ENVMAP\n\t#include \n\t#include \n\t#include \n\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; - break; + var meshlambert_frag = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\treflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\n\t#include \n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; - } + var meshlambert_vert = "#define LAMBERT\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; - } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) { + var meshphong_frag = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; - // hex color + var meshphong_vert = "#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n}\n"; - var hex = m[ 1 ]; - var size = hex.length; + var meshphysical_frag = "#define PHYSICAL\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifndef STANDARD\n\tuniform float clearCoat;\n\tuniform float clearCoatRoughness;\n#endif\nuniform float envMapIntensity;\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; - if ( size === 3 ) { + var meshphysical_vert = "#define PHYSICAL\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n}\n"; - // #ff0 - this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255; - this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255; - this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255; + var normal_frag = "uniform float opacity;\nvarying vec3 vNormal;\n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tgl_FragColor = vec4( packNormalToRGB( vNormal ), opacity );\n\t#include \n}\n"; - return this; + var normal_vert = "varying vec3 vNormal;\n#include \n#include \n#include \n#include \nvoid main() {\n\tvNormal = normalize( normalMatrix * normal );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; - } else if ( size === 6 ) { + var points_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; - // #ff0000 - this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255; - this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255; - this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255; + var points_vert = "uniform float size;\nuniform float scale;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#ifdef USE_SIZEATTENUATION\n\t\tgl_PointSize = size * ( scale / - mvPosition.z );\n\t#else\n\t\tgl_PointSize = size;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; - return this; + var shadow_frag = "uniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tgl_FragColor = vec4( 0.0, 0.0, 0.0, opacity * ( 1.0 - getShadowMask() ) );\n}\n"; - } + var shadow_vert = "#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; - } + var ShaderChunk = { + alphamap_fragment: alphamap_fragment, + alphamap_pars_fragment: alphamap_pars_fragment, + alphatest_fragment: alphatest_fragment, + aomap_fragment: aomap_fragment, + aomap_pars_fragment: aomap_pars_fragment, + begin_vertex: begin_vertex, + beginnormal_vertex: beginnormal_vertex, + bsdfs: bsdfs, + bumpmap_pars_fragment: bumpmap_pars_fragment, + clipping_planes_fragment: clipping_planes_fragment, + clipping_planes_pars_fragment: clipping_planes_pars_fragment, + clipping_planes_pars_vertex: clipping_planes_pars_vertex, + clipping_planes_vertex: clipping_planes_vertex, + color_fragment: color_fragment, + color_pars_fragment: color_pars_fragment, + color_pars_vertex: color_pars_vertex, + color_vertex: color_vertex, + common: common, + cube_uv_reflection_fragment: cube_uv_reflection_fragment, + defaultnormal_vertex: defaultnormal_vertex, + displacementmap_pars_vertex: displacementmap_pars_vertex, + displacementmap_vertex: displacementmap_vertex, + emissivemap_fragment: emissivemap_fragment, + emissivemap_pars_fragment: emissivemap_pars_fragment, + encodings_fragment: encodings_fragment, + encodings_pars_fragment: encodings_pars_fragment, + envmap_fragment: envmap_fragment, + envmap_pars_fragment: envmap_pars_fragment, + envmap_pars_vertex: envmap_pars_vertex, + envmap_vertex: envmap_vertex, + fog_fragment: fog_fragment, + fog_pars_fragment: fog_pars_fragment, + lightmap_fragment: lightmap_fragment, + lightmap_pars_fragment: lightmap_pars_fragment, + lights_lambert_vertex: lights_lambert_vertex, + lights_pars: lights_pars, + lights_phong_fragment: lights_phong_fragment, + lights_phong_pars_fragment: lights_phong_pars_fragment, + lights_physical_fragment: lights_physical_fragment, + lights_physical_pars_fragment: lights_physical_pars_fragment, + lights_template: lights_template, + logdepthbuf_fragment: logdepthbuf_fragment, + logdepthbuf_pars_fragment: logdepthbuf_pars_fragment, + logdepthbuf_pars_vertex: logdepthbuf_pars_vertex, + logdepthbuf_vertex: logdepthbuf_vertex, + map_fragment: map_fragment, + map_pars_fragment: map_pars_fragment, + map_particle_fragment: map_particle_fragment, + map_particle_pars_fragment: map_particle_pars_fragment, + metalnessmap_fragment: metalnessmap_fragment, + metalnessmap_pars_fragment: metalnessmap_pars_fragment, + morphnormal_vertex: morphnormal_vertex, + morphtarget_pars_vertex: morphtarget_pars_vertex, + morphtarget_vertex: morphtarget_vertex, + normal_flip: normal_flip, + normal_fragment: normal_fragment, + normalmap_pars_fragment: normalmap_pars_fragment, + packing: packing, + premultiplied_alpha_fragment: premultiplied_alpha_fragment, + project_vertex: project_vertex, + roughnessmap_fragment: roughnessmap_fragment, + roughnessmap_pars_fragment: roughnessmap_pars_fragment, + shadowmap_pars_fragment: shadowmap_pars_fragment, + shadowmap_pars_vertex: shadowmap_pars_vertex, + shadowmap_vertex: shadowmap_vertex, + shadowmask_pars_fragment: shadowmask_pars_fragment, + skinbase_vertex: skinbase_vertex, + skinning_pars_vertex: skinning_pars_vertex, + skinning_vertex: skinning_vertex, + skinnormal_vertex: skinnormal_vertex, + specularmap_fragment: specularmap_fragment, + specularmap_pars_fragment: specularmap_pars_fragment, + tonemapping_fragment: tonemapping_fragment, + tonemapping_pars_fragment: tonemapping_pars_fragment, + uv_pars_fragment: uv_pars_fragment, + uv_pars_vertex: uv_pars_vertex, + uv_vertex: uv_vertex, + uv2_pars_fragment: uv2_pars_fragment, + uv2_pars_vertex: uv2_pars_vertex, + uv2_vertex: uv2_vertex, + worldpos_vertex: worldpos_vertex, + + cube_frag: cube_frag, + cube_vert: cube_vert, + depth_frag: depth_frag, + depth_vert: depth_vert, + distanceRGBA_frag: distanceRGBA_frag, + distanceRGBA_vert: distanceRGBA_vert, + equirect_frag: equirect_frag, + equirect_vert: equirect_vert, + linedashed_frag: linedashed_frag, + linedashed_vert: linedashed_vert, + meshbasic_frag: meshbasic_frag, + meshbasic_vert: meshbasic_vert, + meshlambert_frag: meshlambert_frag, + meshlambert_vert: meshlambert_vert, + meshphong_frag: meshphong_frag, + meshphong_vert: meshphong_vert, + meshphysical_frag: meshphysical_frag, + meshphysical_vert: meshphysical_vert, + normal_frag: normal_frag, + normal_vert: normal_vert, + points_frag: points_frag, + points_vert: points_vert, + shadow_frag: shadow_frag, + shadow_vert: shadow_vert + }; - if ( style && style.length > 0 ) { + /** + * @author mrdoob / http://mrdoob.com/ + */ - // color keywords - var hex = exports.ColorKeywords[ style ]; + function Color( r, g, b ) { - if ( hex !== undefined ) { + if ( g === undefined && b === undefined ) { - // red - this.setHex( hex ); + // r is THREE.Color, hex or string + return this.set( r ); - } else { + } - // unknown color - console.warn( 'THREE.Color: Unknown color ' + style ); + return this.setRGB( r, g, b ); - } + } - } + Color.prototype = { - return this; + constructor: Color, - }, + isColor: true, - clone: function () { + r: 1, g: 1, b: 1, - return new this.constructor( this.r, this.g, this.b ); + set: function ( value ) { - }, + if ( (value && value.isColor) ) { - copy: function ( color ) { + this.copy( value ); - this.r = color.r; - this.g = color.g; - this.b = color.b; + } else if ( typeof value === 'number' ) { - return this; + this.setHex( value ); - }, + } else if ( typeof value === 'string' ) { - copyGammaToLinear: function ( color, gammaFactor ) { + this.setStyle( value ); - if ( gammaFactor === undefined ) gammaFactor = 2.0; + } - this.r = Math.pow( color.r, gammaFactor ); - this.g = Math.pow( color.g, gammaFactor ); - this.b = Math.pow( color.b, gammaFactor ); + return this; - return this; + }, - }, + setScalar: function ( scalar ) { - copyLinearToGamma: function ( color, gammaFactor ) { + this.r = scalar; + this.g = scalar; + this.b = scalar; - if ( gammaFactor === undefined ) gammaFactor = 2.0; + }, - var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0; + setHex: function ( hex ) { - this.r = Math.pow( color.r, safeInverse ); - this.g = Math.pow( color.g, safeInverse ); - this.b = Math.pow( color.b, safeInverse ); + hex = Math.floor( hex ); - return this; + this.r = ( hex >> 16 & 255 ) / 255; + this.g = ( hex >> 8 & 255 ) / 255; + this.b = ( hex & 255 ) / 255; - }, + return this; - convertGammaToLinear: function () { + }, - var r = this.r, g = this.g, b = this.b; + setRGB: function ( r, g, b ) { - this.r = r * r; - this.g = g * g; - this.b = b * b; + this.r = r; + this.g = g; + this.b = b; - return this; + return this; - }, + }, - convertLinearToGamma: function () { + setHSL: function () { - this.r = Math.sqrt( this.r ); - this.g = Math.sqrt( this.g ); - this.b = Math.sqrt( this.b ); + function hue2rgb( p, q, t ) { - return this; + if ( t < 0 ) t += 1; + if ( t > 1 ) t -= 1; + if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t; + if ( t < 1 / 2 ) return q; + if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t ); + return p; - }, + } - getHex: function () { + return function setHSL( h, s, l ) { - return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0; + // h,s,l ranges are in 0.0 - 1.0 + h = exports.Math.euclideanModulo( h, 1 ); + s = exports.Math.clamp( s, 0, 1 ); + l = exports.Math.clamp( l, 0, 1 ); - }, + if ( s === 0 ) { - getHexString: function () { + this.r = this.g = this.b = l; - return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 ); + } else { - }, + var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s ); + var q = ( 2 * l ) - p; - getHSL: function ( optionalTarget ) { + this.r = hue2rgb( q, p, h + 1 / 3 ); + this.g = hue2rgb( q, p, h ); + this.b = hue2rgb( q, p, h - 1 / 3 ); - // h,s,l ranges are in 0.0 - 1.0 + } - var hsl = optionalTarget || { h: 0, s: 0, l: 0 }; + return this; - var r = this.r, g = this.g, b = this.b; + }; - var max = Math.max( r, g, b ); - var min = Math.min( r, g, b ); + }(), - var hue, saturation; - var lightness = ( min + max ) / 2.0; + setStyle: function ( style ) { - if ( min === max ) { + function handleAlpha( string ) { - hue = 0; - saturation = 0; + if ( string === undefined ) return; - } else { + if ( parseFloat( string ) < 1 ) { - var delta = max - min; + console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' ); - saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min ); + } - switch ( max ) { + } - case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break; - case g: hue = ( b - r ) / delta + 2; break; - case b: hue = ( r - g ) / delta + 4; break; - } + var m; - hue /= 6; + if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) { - } + // rgb / hsl - hsl.h = hue; - hsl.s = saturation; - hsl.l = lightness; + var color; + var name = m[ 1 ]; + var components = m[ 2 ]; - return hsl; + switch ( name ) { - }, + case 'rgb': + case 'rgba': - getStyle: function () { + if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) { - return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')'; + // rgb(255,0,0) rgba(255,0,0,0.5) + this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255; + this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255; + this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255; - }, + handleAlpha( color[ 5 ] ); - offsetHSL: function ( h, s, l ) { + return this; - var hsl = this.getHSL(); + } - hsl.h += h; hsl.s += s; hsl.l += l; + if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) { - this.setHSL( hsl.h, hsl.s, hsl.l ); + // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5) + this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100; + this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100; + this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100; - return this; + handleAlpha( color[ 5 ] ); - }, + return this; - add: function ( color ) { + } - this.r += color.r; - this.g += color.g; - this.b += color.b; + break; - return this; + case 'hsl': + case 'hsla': - }, + if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) { - addColors: function ( color1, color2 ) { + // hsl(120,50%,50%) hsla(120,50%,50%,0.5) + var h = parseFloat( color[ 1 ] ) / 360; + var s = parseInt( color[ 2 ], 10 ) / 100; + var l = parseInt( color[ 3 ], 10 ) / 100; - this.r = color1.r + color2.r; - this.g = color1.g + color2.g; - this.b = color1.b + color2.b; + handleAlpha( color[ 5 ] ); - return this; + return this.setHSL( h, s, l ); - }, + } - addScalar: function ( s ) { + break; - this.r += s; - this.g += s; - this.b += s; + } - return this; + } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) { - }, + // hex color - sub: function( color ) { + var hex = m[ 1 ]; + var size = hex.length; - this.r = Math.max( 0, this.r - color.r ); - this.g = Math.max( 0, this.g - color.g ); - this.b = Math.max( 0, this.b - color.b ); + if ( size === 3 ) { - return this; + // #ff0 + this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255; + this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255; + this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255; - }, + return this; - multiply: function ( color ) { + } else if ( size === 6 ) { - this.r *= color.r; - this.g *= color.g; - this.b *= color.b; + // #ff0000 + this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255; + this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255; + this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255; - return this; + return this; - }, + } - multiplyScalar: function ( s ) { + } - this.r *= s; - this.g *= s; - this.b *= s; + if ( style && style.length > 0 ) { - return this; + // color keywords + var hex = exports.ColorKeywords[ style ]; - }, + if ( hex !== undefined ) { - lerp: function ( color, alpha ) { + // red + this.setHex( hex ); - this.r += ( color.r - this.r ) * alpha; - this.g += ( color.g - this.g ) * alpha; - this.b += ( color.b - this.b ) * alpha; + } else { - return this; + // unknown color + console.warn( 'THREE.Color: Unknown color ' + style ); - }, + } - equals: function ( c ) { + } - return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b ); + return this; - }, + }, - fromArray: function ( array, offset ) { + clone: function () { - if ( offset === undefined ) offset = 0; + return new this.constructor( this.r, this.g, this.b ); - this.r = array[ offset ]; - this.g = array[ offset + 1 ]; - this.b = array[ offset + 2 ]; + }, - return this; + copy: function ( color ) { - }, + this.r = color.r; + this.g = color.g; + this.b = color.b; - toArray: function ( array, offset ) { + return this; - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + }, - array[ offset ] = this.r; - array[ offset + 1 ] = this.g; - array[ offset + 2 ] = this.b; + copyGammaToLinear: function ( color, gammaFactor ) { - return array; + if ( gammaFactor === undefined ) gammaFactor = 2.0; - } + this.r = Math.pow( color.r, gammaFactor ); + this.g = Math.pow( color.g, gammaFactor ); + this.b = Math.pow( color.b, gammaFactor ); - }; + return this; - exports.ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF, - 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2, - 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50, - 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B, - 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B, - 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F, - 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3, - 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222, - 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700, - 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4, - 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00, - 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3, - 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA, - 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32, - 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3, - 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC, - 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD, - 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6, - 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9, - 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F, - 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE, - 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA, - 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0, - 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 }; + }, - /** - * Uniforms library for shared webgl shaders - */ + copyLinearToGamma: function ( color, gammaFactor ) { - exports.UniformsLib = { + if ( gammaFactor === undefined ) gammaFactor = 2.0; - common: { + var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0; - "diffuse": { value: new Color( 0xeeeeee ) }, - "opacity": { value: 1.0 }, + this.r = Math.pow( color.r, safeInverse ); + this.g = Math.pow( color.g, safeInverse ); + this.b = Math.pow( color.b, safeInverse ); - "map": { value: null }, - "offsetRepeat": { value: new Vector4( 0, 0, 1, 1 ) }, + return this; - "specularMap": { value: null }, - "alphaMap": { value: null }, + }, - "envMap": { value: null }, - "flipEnvMap": { value: - 1 }, - "reflectivity": { value: 1.0 }, - "refractionRatio": { value: 0.98 } + convertGammaToLinear: function () { - }, + var r = this.r, g = this.g, b = this.b; - aomap: { + this.r = r * r; + this.g = g * g; + this.b = b * b; - "aoMap": { value: null }, - "aoMapIntensity": { value: 1 } + return this; - }, + }, - lightmap: { + convertLinearToGamma: function () { - "lightMap": { value: null }, - "lightMapIntensity": { value: 1 } + this.r = Math.sqrt( this.r ); + this.g = Math.sqrt( this.g ); + this.b = Math.sqrt( this.b ); - }, + return this; - emissivemap: { + }, - "emissiveMap": { value: null } + getHex: function () { - }, + return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0; - bumpmap: { + }, - "bumpMap": { value: null }, - "bumpScale": { value: 1 } + getHexString: function () { - }, + return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 ); - normalmap: { + }, - "normalMap": { value: null }, - "normalScale": { value: new Vector2( 1, 1 ) } + getHSL: function ( optionalTarget ) { - }, + // h,s,l ranges are in 0.0 - 1.0 - displacementmap: { + var hsl = optionalTarget || { h: 0, s: 0, l: 0 }; - "displacementMap": { value: null }, - "displacementScale": { value: 1 }, - "displacementBias": { value: 0 } + var r = this.r, g = this.g, b = this.b; - }, + var max = Math.max( r, g, b ); + var min = Math.min( r, g, b ); - roughnessmap: { + var hue, saturation; + var lightness = ( min + max ) / 2.0; - "roughnessMap": { value: null } + if ( min === max ) { - }, + hue = 0; + saturation = 0; - metalnessmap: { + } else { - "metalnessMap": { value: null } + var delta = max - min; - }, + saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min ); - fog: { + switch ( max ) { - "fogDensity": { value: 0.00025 }, - "fogNear": { value: 1 }, - "fogFar": { value: 2000 }, - "fogColor": { value: new Color( 0xffffff ) } + case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break; + case g: hue = ( b - r ) / delta + 2; break; + case b: hue = ( r - g ) / delta + 4; break; - }, + } - lights: { + hue /= 6; - "ambientLightColor": { value: [] }, + } - "directionalLights": { value: [], properties: { - "direction": {}, - "color": {}, + hsl.h = hue; + hsl.s = saturation; + hsl.l = lightness; - "shadow": {}, - "shadowBias": {}, - "shadowRadius": {}, - "shadowMapSize": {} - } }, + return hsl; - "directionalShadowMap": { value: [] }, - "directionalShadowMatrix": { value: [] }, + }, - "spotLights": { value: [], properties: { - "color": {}, - "position": {}, - "direction": {}, - "distance": {}, - "coneCos": {}, - "penumbraCos": {}, - "decay": {}, + getStyle: function () { - "shadow": {}, - "shadowBias": {}, - "shadowRadius": {}, - "shadowMapSize": {} - } }, + return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')'; - "spotShadowMap": { value: [] }, - "spotShadowMatrix": { value: [] }, + }, - "pointLights": { value: [], properties: { - "color": {}, - "position": {}, - "decay": {}, - "distance": {}, + offsetHSL: function ( h, s, l ) { - "shadow": {}, - "shadowBias": {}, - "shadowRadius": {}, - "shadowMapSize": {} - } }, + var hsl = this.getHSL(); - "pointShadowMap": { value: [] }, - "pointShadowMatrix": { value: [] }, + hsl.h += h; hsl.s += s; hsl.l += l; - "hemisphereLights": { value: [], properties: { - "direction": {}, - "skyColor": {}, - "groundColor": {} - } } + this.setHSL( hsl.h, hsl.s, hsl.l ); - }, + return this; - points: { + }, - "diffuse": { value: new Color( 0xeeeeee ) }, - "opacity": { value: 1.0 }, - "size": { value: 1.0 }, - "scale": { value: 1.0 }, - "map": { value: null }, - "offsetRepeat": { value: new Vector4( 0, 0, 1, 1 ) } + add: function ( color ) { - } + this.r += color.r; + this.g += color.g; + this.b += color.b; - }; + return this; - /** - * Webgl Shader Library for three.js - * - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - * @author mikael emtinger / http://gomo.se/ - */ + }, + addColors: function ( color1, color2 ) { - exports.ShaderLib = { + this.r = color1.r + color2.r; + this.g = color1.g + color2.g; + this.b = color1.b + color2.b; - 'basic': { + return this; - uniforms: exports.UniformsUtils.merge( [ + }, - exports.UniformsLib[ 'common' ], - exports.UniformsLib[ 'aomap' ], - exports.UniformsLib[ 'fog' ] + addScalar: function ( s ) { - ] ), + this.r += s; + this.g += s; + this.b += s; - vertexShader: ShaderChunk[ 'meshbasic_vert' ], - fragmentShader: ShaderChunk[ 'meshbasic_frag' ] + return this; - }, + }, - 'lambert': { + sub: function( color ) { - uniforms: exports.UniformsUtils.merge( [ + this.r = Math.max( 0, this.r - color.r ); + this.g = Math.max( 0, this.g - color.g ); + this.b = Math.max( 0, this.b - color.b ); - exports.UniformsLib[ 'common' ], - exports.UniformsLib[ 'aomap' ], - exports.UniformsLib[ 'lightmap' ], - exports.UniformsLib[ 'emissivemap' ], - exports.UniformsLib[ 'fog' ], - exports.UniformsLib[ 'lights' ], + return this; - { - "emissive" : { value: new Color( 0x000000 ) } - } + }, - ] ), + multiply: function ( color ) { - vertexShader: ShaderChunk[ 'meshlambert_vert' ], - fragmentShader: ShaderChunk[ 'meshlambert_frag' ] + this.r *= color.r; + this.g *= color.g; + this.b *= color.b; - }, + return this; - 'phong': { + }, - uniforms: exports.UniformsUtils.merge( [ + multiplyScalar: function ( s ) { - exports.UniformsLib[ 'common' ], - exports.UniformsLib[ 'aomap' ], - exports.UniformsLib[ 'lightmap' ], - exports.UniformsLib[ 'emissivemap' ], - exports.UniformsLib[ 'bumpmap' ], - exports.UniformsLib[ 'normalmap' ], - exports.UniformsLib[ 'displacementmap' ], - exports.UniformsLib[ 'fog' ], - exports.UniformsLib[ 'lights' ], + this.r *= s; + this.g *= s; + this.b *= s; - { - "emissive" : { value: new Color( 0x000000 ) }, - "specular" : { value: new Color( 0x111111 ) }, - "shininess": { value: 30 } - } + return this; - ] ), + }, - vertexShader: ShaderChunk[ 'meshphong_vert' ], - fragmentShader: ShaderChunk[ 'meshphong_frag' ] + lerp: function ( color, alpha ) { - }, + this.r += ( color.r - this.r ) * alpha; + this.g += ( color.g - this.g ) * alpha; + this.b += ( color.b - this.b ) * alpha; - 'standard': { + return this; - uniforms: exports.UniformsUtils.merge( [ + }, - exports.UniformsLib[ 'common' ], - exports.UniformsLib[ 'aomap' ], - exports.UniformsLib[ 'lightmap' ], - exports.UniformsLib[ 'emissivemap' ], - exports.UniformsLib[ 'bumpmap' ], - exports.UniformsLib[ 'normalmap' ], - exports.UniformsLib[ 'displacementmap' ], - exports.UniformsLib[ 'roughnessmap' ], - exports.UniformsLib[ 'metalnessmap' ], - exports.UniformsLib[ 'fog' ], - exports.UniformsLib[ 'lights' ], + equals: function ( c ) { - { - "emissive" : { value: new Color( 0x000000 ) }, - "roughness": { value: 0.5 }, - "metalness": { value: 0 }, - "envMapIntensity" : { value: 1 }, // temporary - } + return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b ); - ] ), + }, - vertexShader: ShaderChunk[ 'meshphysical_vert' ], - fragmentShader: ShaderChunk[ 'meshphysical_frag' ] + fromArray: function ( array, offset ) { - }, + if ( offset === undefined ) offset = 0; - 'points': { + this.r = array[ offset ]; + this.g = array[ offset + 1 ]; + this.b = array[ offset + 2 ]; - uniforms: exports.UniformsUtils.merge( [ + return this; - exports.UniformsLib[ 'points' ], - exports.UniformsLib[ 'fog' ] + }, - ] ), + toArray: function ( array, offset ) { - vertexShader: ShaderChunk[ 'points_vert' ], - fragmentShader: ShaderChunk[ 'points_frag' ] + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - }, + array[ offset ] = this.r; + array[ offset + 1 ] = this.g; + array[ offset + 2 ] = this.b; - 'dashed': { + return array; - uniforms: exports.UniformsUtils.merge( [ + }, - exports.UniformsLib[ 'common' ], - exports.UniformsLib[ 'fog' ], + toJSON: function () { - { - "scale" : { value: 1 }, - "dashSize" : { value: 1 }, - "totalSize": { value: 2 } - } + return this.getHex(); - ] ), + } - vertexShader: ShaderChunk[ 'linedashed_vert' ], - fragmentShader: ShaderChunk[ 'linedashed_frag' ] + }; - }, + exports.ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF, + 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2, + 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50, + 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B, + 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B, + 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F, + 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3, + 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222, + 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700, + 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4, + 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00, + 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3, + 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA, + 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32, + 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3, + 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC, + 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD, + 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6, + 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9, + 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F, + 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE, + 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA, + 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0, + 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 }; + + /** + * Uniforms library for shared webgl shaders + */ + + exports.UniformsLib = { + + common: { + + "diffuse": { value: new Color( 0xeeeeee ) }, + "opacity": { value: 1.0 }, + + "map": { value: null }, + "offsetRepeat": { value: new Vector4( 0, 0, 1, 1 ) }, + + "specularMap": { value: null }, + "alphaMap": { value: null }, + + "envMap": { value: null }, + "flipEnvMap": { value: - 1 }, + "reflectivity": { value: 1.0 }, + "refractionRatio": { value: 0.98 } - 'depth': { + }, - uniforms: exports.UniformsUtils.merge( [ + aomap: { - exports.UniformsLib[ 'common' ], - exports.UniformsLib[ 'displacementmap' ] + "aoMap": { value: null }, + "aoMapIntensity": { value: 1 } - ] ), + }, - vertexShader: ShaderChunk[ 'depth_vert' ], - fragmentShader: ShaderChunk[ 'depth_frag' ] + lightmap: { - }, + "lightMap": { value: null }, + "lightMapIntensity": { value: 1 } - 'normal': { + }, - uniforms: { + emissivemap: { - "opacity" : { value: 1.0 } + "emissiveMap": { value: null } - }, + }, - vertexShader: ShaderChunk[ 'normal_vert' ], - fragmentShader: ShaderChunk[ 'normal_frag' ] + bumpmap: { - }, + "bumpMap": { value: null }, + "bumpScale": { value: 1 } - /* ------------------------------------------------------------------------- - // Cube map shader - ------------------------------------------------------------------------- */ + }, - 'cube': { + normalmap: { - uniforms: { - "tCube": { value: null }, - "tFlip": { value: - 1 }, - "opacity": { value: 1.0 } - }, + "normalMap": { value: null }, + "normalScale": { value: new Vector2( 1, 1 ) } - vertexShader: ShaderChunk[ 'cube_vert' ], - fragmentShader: ShaderChunk[ 'cube_frag' ] + }, - }, + displacementmap: { - /* ------------------------------------------------------------------------- - // Cube map shader - ------------------------------------------------------------------------- */ + "displacementMap": { value: null }, + "displacementScale": { value: 1 }, + "displacementBias": { value: 0 } - 'equirect': { + }, - uniforms: { - "tEquirect": { value: null }, - "tFlip": { value: - 1 } - }, + roughnessmap: { - vertexShader: ShaderChunk[ 'equirect_vert' ], - fragmentShader: ShaderChunk[ 'equirect_frag' ] + "roughnessMap": { value: null } - }, + }, - 'distanceRGBA': { + metalnessmap: { - uniforms: { + "metalnessMap": { value: null } - "lightPos": { value: new Vector3() } + }, - }, + fog: { - vertexShader: ShaderChunk[ 'distanceRGBA_vert' ], - fragmentShader: ShaderChunk[ 'distanceRGBA_frag' ] + "fogDensity": { value: 0.00025 }, + "fogNear": { value: 1 }, + "fogFar": { value: 2000 }, + "fogColor": { value: new Color( 0xffffff ) } - } + }, - }; + lights: { + + "ambientLightColor": { value: [] }, + + "directionalLights": { value: [], properties: { + "direction": {}, + "color": {}, + + "shadow": {}, + "shadowBias": {}, + "shadowRadius": {}, + "shadowMapSize": {} + } }, + + "directionalShadowMap": { value: [] }, + "directionalShadowMatrix": { value: [] }, + + "spotLights": { value: [], properties: { + "color": {}, + "position": {}, + "direction": {}, + "distance": {}, + "coneCos": {}, + "penumbraCos": {}, + "decay": {}, + + "shadow": {}, + "shadowBias": {}, + "shadowRadius": {}, + "shadowMapSize": {} + } }, + + "spotShadowMap": { value: [] }, + "spotShadowMatrix": { value: [] }, + + "pointLights": { value: [], properties: { + "color": {}, + "position": {}, + "decay": {}, + "distance": {}, + + "shadow": {}, + "shadowBias": {}, + "shadowRadius": {}, + "shadowMapSize": {} + } }, + + "pointShadowMap": { value: [] }, + "pointShadowMatrix": { value: [] }, + + "hemisphereLights": { value: [], properties: { + "direction": {}, + "skyColor": {}, + "groundColor": {} + } } - exports.ShaderLib[ 'physical' ] = { + }, - uniforms: exports.UniformsUtils.merge( [ + points: { - exports.ShaderLib[ 'standard' ].uniforms, + "diffuse": { value: new Color( 0xeeeeee ) }, + "opacity": { value: 1.0 }, + "size": { value: 1.0 }, + "scale": { value: 1.0 }, + "map": { value: null }, + "offsetRepeat": { value: new Vector4( 0, 0, 1, 1 ) } - { - "clearCoat": { value: 0 }, - "clearCoatRoughness": { value: 0 } - } + } - ] ), + }; - vertexShader: ShaderChunk[ 'meshphysical_vert' ], - fragmentShader: ShaderChunk[ 'meshphysical_frag' ] + /** + * Webgl Shader Library for three.js + * + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + * @author mikael emtinger / http://gomo.se/ + */ - }; - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * @author bhouston / https://clara.io - * @author WestLangley / http://github.com/WestLangley - * - * parameters = { - * - * opacity: , - * - * map: new THREE.Texture( ), - * - * alphaMap: new THREE.Texture( ), - * - * displacementMap: new THREE.Texture( ), - * displacementScale: , - * displacementBias: , - * - * wireframe: , - * wireframeLinewidth: - * } - */ + exports.ShaderLib = { - function MeshDepthMaterial( parameters ) { + 'basic': { - Material.call( this ); + uniforms: exports.UniformsUtils.merge( [ - this.type = 'MeshDepthMaterial'; + exports.UniformsLib[ 'common' ], + exports.UniformsLib[ 'aomap' ], + exports.UniformsLib[ 'fog' ] - this.depthPacking = BasicDepthPacking; + ] ), - this.skinning = false; - this.morphTargets = false; + vertexShader: ShaderChunk[ 'meshbasic_vert' ], + fragmentShader: ShaderChunk[ 'meshbasic_frag' ] - this.map = null; + }, - this.alphaMap = null; + 'lambert': { - this.displacementMap = null; - this.displacementScale = 1; - this.displacementBias = 0; + uniforms: exports.UniformsUtils.merge( [ - this.wireframe = false; - this.wireframeLinewidth = 1; + exports.UniformsLib[ 'common' ], + exports.UniformsLib[ 'aomap' ], + exports.UniformsLib[ 'lightmap' ], + exports.UniformsLib[ 'emissivemap' ], + exports.UniformsLib[ 'fog' ], + exports.UniformsLib[ 'lights' ], - this.fog = false; - this.lights = false; + { + "emissive" : { value: new Color( 0x000000 ) } + } - this.setValues( parameters ); + ] ), - }; + vertexShader: ShaderChunk[ 'meshlambert_vert' ], + fragmentShader: ShaderChunk[ 'meshlambert_frag' ] - MeshDepthMaterial.prototype = Object.create( Material.prototype ); - MeshDepthMaterial.prototype.constructor = MeshDepthMaterial; + }, - MeshDepthMaterial.prototype.isMeshDepthMaterial = true; + 'phong': { - MeshDepthMaterial.prototype.copy = function ( source ) { + uniforms: exports.UniformsUtils.merge( [ - Material.prototype.copy.call( this, source ); + exports.UniformsLib[ 'common' ], + exports.UniformsLib[ 'aomap' ], + exports.UniformsLib[ 'lightmap' ], + exports.UniformsLib[ 'emissivemap' ], + exports.UniformsLib[ 'bumpmap' ], + exports.UniformsLib[ 'normalmap' ], + exports.UniformsLib[ 'displacementmap' ], + exports.UniformsLib[ 'fog' ], + exports.UniformsLib[ 'lights' ], - this.depthPacking = source.depthPacking; + { + "emissive" : { value: new Color( 0x000000 ) }, + "specular" : { value: new Color( 0x111111 ) }, + "shininess": { value: 30 } + } - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; + ] ), - this.map = source.map; + vertexShader: ShaderChunk[ 'meshphong_vert' ], + fragmentShader: ShaderChunk[ 'meshphong_frag' ] - this.alphaMap = source.alphaMap; + }, - this.displacementMap = source.displacementMap; - this.displacementScale = source.displacementScale; - this.displacementBias = source.displacementBias; + 'standard': { - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; + uniforms: exports.UniformsUtils.merge( [ - return this; + exports.UniformsLib[ 'common' ], + exports.UniformsLib[ 'aomap' ], + exports.UniformsLib[ 'lightmap' ], + exports.UniformsLib[ 'emissivemap' ], + exports.UniformsLib[ 'bumpmap' ], + exports.UniformsLib[ 'normalmap' ], + exports.UniformsLib[ 'displacementmap' ], + exports.UniformsLib[ 'roughnessmap' ], + exports.UniformsLib[ 'metalnessmap' ], + exports.UniformsLib[ 'fog' ], + exports.UniformsLib[ 'lights' ], - }; + { + "emissive" : { value: new Color( 0x000000 ) }, + "roughness": { value: 0.5 }, + "metalness": { value: 0 }, + "envMapIntensity" : { value: 1 }, // temporary + } - /** - * @author bhouston / http://clara.io - * @author WestLangley / http://github.com/WestLangley - */ + ] ), - function Box3( min, max ) { + vertexShader: ShaderChunk[ 'meshphysical_vert' ], + fragmentShader: ShaderChunk[ 'meshphysical_frag' ] - this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity ); - this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity ); + }, - }; + 'points': { - Box3.prototype = { + uniforms: exports.UniformsUtils.merge( [ - constructor: Box3, + exports.UniformsLib[ 'points' ], + exports.UniformsLib[ 'fog' ] - isBox3: true, + ] ), - set: function ( min, max ) { + vertexShader: ShaderChunk[ 'points_vert' ], + fragmentShader: ShaderChunk[ 'points_frag' ] - this.min.copy( min ); - this.max.copy( max ); + }, - return this; + 'dashed': { - }, + uniforms: exports.UniformsUtils.merge( [ - setFromArray: function ( array ) { + exports.UniformsLib[ 'common' ], + exports.UniformsLib[ 'fog' ], - var minX = + Infinity; - var minY = + Infinity; - var minZ = + Infinity; + { + "scale" : { value: 1 }, + "dashSize" : { value: 1 }, + "totalSize": { value: 2 } + } - var maxX = - Infinity; - var maxY = - Infinity; - var maxZ = - Infinity; + ] ), - for ( var i = 0, l = array.length; i < l; i += 3 ) { + vertexShader: ShaderChunk[ 'linedashed_vert' ], + fragmentShader: ShaderChunk[ 'linedashed_frag' ] - var x = array[ i ]; - var y = array[ i + 1 ]; - var z = array[ i + 2 ]; + }, - if ( x < minX ) minX = x; - if ( y < minY ) minY = y; - if ( z < minZ ) minZ = z; + 'depth': { - if ( x > maxX ) maxX = x; - if ( y > maxY ) maxY = y; - if ( z > maxZ ) maxZ = z; + uniforms: exports.UniformsUtils.merge( [ - } + exports.UniformsLib[ 'common' ], + exports.UniformsLib[ 'displacementmap' ] - this.min.set( minX, minY, minZ ); - this.max.set( maxX, maxY, maxZ ); + ] ), - }, + vertexShader: ShaderChunk[ 'depth_vert' ], + fragmentShader: ShaderChunk[ 'depth_frag' ] - setFromPoints: function ( points ) { + }, - this.makeEmpty(); + 'normal': { - for ( var i = 0, il = points.length; i < il; i ++ ) { + uniforms: { - this.expandByPoint( points[ i ] ); + "opacity" : { value: 1.0 } - } + }, - return this; + vertexShader: ShaderChunk[ 'normal_vert' ], + fragmentShader: ShaderChunk[ 'normal_frag' ] - }, + }, - setFromCenterAndSize: function () { + /* ------------------------------------------------------------------------- + // Cube map shader + ------------------------------------------------------------------------- */ - var v1 = new Vector3(); + 'cube': { - return function setFromCenterAndSize( center, size ) { + uniforms: { + "tCube": { value: null }, + "tFlip": { value: - 1 }, + "opacity": { value: 1.0 } + }, - var halfSize = v1.copy( size ).multiplyScalar( 0.5 ); + vertexShader: ShaderChunk[ 'cube_vert' ], + fragmentShader: ShaderChunk[ 'cube_frag' ] - this.min.copy( center ).sub( halfSize ); - this.max.copy( center ).add( halfSize ); + }, - return this; + /* ------------------------------------------------------------------------- + // Cube map shader + ------------------------------------------------------------------------- */ - }; + 'equirect': { - }(), + uniforms: { + "tEquirect": { value: null }, + "tFlip": { value: - 1 } + }, - setFromObject: function () { + vertexShader: ShaderChunk[ 'equirect_vert' ], + fragmentShader: ShaderChunk[ 'equirect_frag' ] - // Computes the world-axis-aligned bounding box of an object (including its children), - // accounting for both the object's, and children's, world transforms + }, - var v1 = new Vector3(); + 'distanceRGBA': { - return function setFromObject( object ) { + uniforms: { - var scope = this; + "lightPos": { value: new Vector3() } - object.updateMatrixWorld( true ); + }, - this.makeEmpty(); + vertexShader: ShaderChunk[ 'distanceRGBA_vert' ], + fragmentShader: ShaderChunk[ 'distanceRGBA_frag' ] - object.traverse( function ( node ) { + } - var geometry = node.geometry; + }; - if ( geometry !== undefined ) { + exports.ShaderLib[ 'physical' ] = { - if ( (geometry && geometry.isGeometry) ) { + uniforms: exports.UniformsUtils.merge( [ - var vertices = geometry.vertices; + exports.ShaderLib[ 'standard' ].uniforms, - for ( var i = 0, il = vertices.length; i < il; i ++ ) { + { + "clearCoat": { value: 0 }, + "clearCoatRoughness": { value: 0 } + } - v1.copy( vertices[ i ] ); - v1.applyMatrix4( node.matrixWorld ); + ] ), - scope.expandByPoint( v1 ); + vertexShader: ShaderChunk[ 'meshphysical_vert' ], + fragmentShader: ShaderChunk[ 'meshphysical_frag' ] - } + }; - } else if ( (geometry && geometry.isBufferGeometry) ) { + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * @author bhouston / https://clara.io + * @author WestLangley / http://github.com/WestLangley + * + * parameters = { + * + * opacity: , + * + * map: new THREE.Texture( ), + * + * alphaMap: new THREE.Texture( ), + * + * displacementMap: new THREE.Texture( ), + * displacementScale: , + * displacementBias: , + * + * wireframe: , + * wireframeLinewidth: + * } + */ - var attribute = geometry.attributes.position; + function MeshDepthMaterial( parameters ) { - if ( attribute !== undefined ) { + Material.call( this ); - var array, offset, stride; + this.type = 'MeshDepthMaterial'; - if ( (attribute && attribute.isInterleavedBufferAttribute) ) { + this.depthPacking = BasicDepthPacking; - array = attribute.data.array; - offset = attribute.offset; - stride = attribute.data.stride; + this.skinning = false; + this.morphTargets = false; - } else { + this.map = null; - array = attribute.array; - offset = 0; - stride = 3; + this.alphaMap = null; - } + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; - for ( var i = offset, il = array.length; i < il; i += stride ) { + this.wireframe = false; + this.wireframeLinewidth = 1; - v1.fromArray( array, i ); - v1.applyMatrix4( node.matrixWorld ); + this.fog = false; + this.lights = false; - scope.expandByPoint( v1 ); + this.setValues( parameters ); - } + } - } + MeshDepthMaterial.prototype = Object.create( Material.prototype ); + MeshDepthMaterial.prototype.constructor = MeshDepthMaterial; - } + MeshDepthMaterial.prototype.isMeshDepthMaterial = true; - } + MeshDepthMaterial.prototype.copy = function ( source ) { - } ); + Material.prototype.copy.call( this, source ); - return this; + this.depthPacking = source.depthPacking; - }; + this.skinning = source.skinning; + this.morphTargets = source.morphTargets; - }(), + this.map = source.map; - clone: function () { + this.alphaMap = source.alphaMap; - return new this.constructor().copy( this ); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; - }, + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; - copy: function ( box ) { + return this; - this.min.copy( box.min ); - this.max.copy( box.max ); + }; - return this; + /** + * @author bhouston / http://clara.io + * @author WestLangley / http://github.com/WestLangley + */ - }, + function Box3( min, max ) { - makeEmpty: function () { + this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity ); + this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity ); - this.min.x = this.min.y = this.min.z = + Infinity; - this.max.x = this.max.y = this.max.z = - Infinity; + } - return this; + Box3.prototype = { - }, + constructor: Box3, - isEmpty: function () { + isBox3: true, - // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes + set: function ( min, max ) { - return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z ); + this.min.copy( min ); + this.max.copy( max ); - }, + return this; - center: function ( optionalTarget ) { + }, - var result = optionalTarget || new Vector3(); - return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); + setFromArray: function ( array ) { - }, + var minX = + Infinity; + var minY = + Infinity; + var minZ = + Infinity; - size: function ( optionalTarget ) { + var maxX = - Infinity; + var maxY = - Infinity; + var maxZ = - Infinity; - var result = optionalTarget || new Vector3(); - return result.subVectors( this.max, this.min ); + for ( var i = 0, l = array.length; i < l; i += 3 ) { - }, + var x = array[ i ]; + var y = array[ i + 1 ]; + var z = array[ i + 2 ]; - expandByPoint: function ( point ) { + if ( x < minX ) minX = x; + if ( y < minY ) minY = y; + if ( z < minZ ) minZ = z; - this.min.min( point ); - this.max.max( point ); + if ( x > maxX ) maxX = x; + if ( y > maxY ) maxY = y; + if ( z > maxZ ) maxZ = z; - return this; + } - }, + this.min.set( minX, minY, minZ ); + this.max.set( maxX, maxY, maxZ ); - expandByVector: function ( vector ) { + }, - this.min.sub( vector ); - this.max.add( vector ); + setFromPoints: function ( points ) { - return this; + this.makeEmpty(); - }, + for ( var i = 0, il = points.length; i < il; i ++ ) { - expandByScalar: function ( scalar ) { + this.expandByPoint( points[ i ] ); - this.min.addScalar( - scalar ); - this.max.addScalar( scalar ); + } - return this; + return this; - }, + }, - containsPoint: function ( point ) { + setFromCenterAndSize: function () { - if ( point.x < this.min.x || point.x > this.max.x || - point.y < this.min.y || point.y > this.max.y || - point.z < this.min.z || point.z > this.max.z ) { + var v1 = new Vector3(); - return false; + return function setFromCenterAndSize( center, size ) { - } + var halfSize = v1.copy( size ).multiplyScalar( 0.5 ); - return true; + this.min.copy( center ).sub( halfSize ); + this.max.copy( center ).add( halfSize ); - }, + return this; - containsBox: function ( box ) { + }; - if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) && - ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) && - ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) { + }(), - return true; + setFromObject: function () { - } + // Computes the world-axis-aligned bounding box of an object (including its children), + // accounting for both the object's, and children's, world transforms - return false; + var v1 = new Vector3(); - }, + return function setFromObject( object ) { - getParameter: function ( point, optionalTarget ) { + var scope = this; - // This can potentially have a divide by zero if the box - // has a size dimension of 0. + object.updateMatrixWorld( true ); - var result = optionalTarget || new Vector3(); + this.makeEmpty(); - return result.set( - ( point.x - this.min.x ) / ( this.max.x - this.min.x ), - ( point.y - this.min.y ) / ( this.max.y - this.min.y ), - ( point.z - this.min.z ) / ( this.max.z - this.min.z ) - ); + object.traverse( function ( node ) { - }, + var geometry = node.geometry; - intersectsBox: function ( box ) { + if ( geometry !== undefined ) { - // using 6 splitting planes to rule out intersections. + if ( (geometry && geometry.isGeometry) ) { - if ( box.max.x < this.min.x || box.min.x > this.max.x || - box.max.y < this.min.y || box.min.y > this.max.y || - box.max.z < this.min.z || box.min.z > this.max.z ) { + var vertices = geometry.vertices; - return false; + for ( var i = 0, il = vertices.length; i < il; i ++ ) { - } + v1.copy( vertices[ i ] ); + v1.applyMatrix4( node.matrixWorld ); - return true; + scope.expandByPoint( v1 ); - }, + } - intersectsSphere: ( function () { + } else if ( (geometry && geometry.isBufferGeometry) ) { - var closestPoint; + var attribute = geometry.attributes.position; - return function intersectsSphere( sphere ) { + if ( attribute !== undefined ) { - if ( closestPoint === undefined ) closestPoint = new Vector3(); + var array, offset, stride; - // Find the point on the AABB closest to the sphere center. - this.clampPoint( sphere.center, closestPoint ); + if ( (attribute && attribute.isInterleavedBufferAttribute) ) { - // If that point is inside the sphere, the AABB and sphere intersect. - return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius ); + array = attribute.data.array; + offset = attribute.offset; + stride = attribute.data.stride; - }; + } else { - } )(), + array = attribute.array; + offset = 0; + stride = 3; - intersectsPlane: function ( plane ) { + } - // We compute the minimum and maximum dot product values. If those values - // are on the same side (back or front) of the plane, then there is no intersection. + for ( var i = offset, il = array.length; i < il; i += stride ) { - var min, max; + v1.fromArray( array, i ); + v1.applyMatrix4( node.matrixWorld ); - if ( plane.normal.x > 0 ) { + scope.expandByPoint( v1 ); - min = plane.normal.x * this.min.x; - max = plane.normal.x * this.max.x; + } - } else { + } - min = plane.normal.x * this.max.x; - max = plane.normal.x * this.min.x; + } - } + } - if ( plane.normal.y > 0 ) { + } ); - min += plane.normal.y * this.min.y; - max += plane.normal.y * this.max.y; + return this; - } else { + }; - min += plane.normal.y * this.max.y; - max += plane.normal.y * this.min.y; + }(), - } + clone: function () { - if ( plane.normal.z > 0 ) { + return new this.constructor().copy( this ); - min += plane.normal.z * this.min.z; - max += plane.normal.z * this.max.z; + }, - } else { + copy: function ( box ) { - min += plane.normal.z * this.max.z; - max += plane.normal.z * this.min.z; + this.min.copy( box.min ); + this.max.copy( box.max ); - } + return this; - return ( min <= plane.constant && max >= plane.constant ); + }, - }, + makeEmpty: function () { - clampPoint: function ( point, optionalTarget ) { + this.min.x = this.min.y = this.min.z = + Infinity; + this.max.x = this.max.y = this.max.z = - Infinity; - var result = optionalTarget || new Vector3(); - return result.copy( point ).clamp( this.min, this.max ); + return this; - }, + }, - distanceToPoint: function () { + isEmpty: function () { - var v1 = new Vector3(); + // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes - return function distanceToPoint( point ) { + return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z ); - var clampedPoint = v1.copy( point ).clamp( this.min, this.max ); - return clampedPoint.sub( point ).length(); + }, - }; + center: function ( optionalTarget ) { - }(), + var result = optionalTarget || new Vector3(); + return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); - getBoundingSphere: function () { + }, - var v1 = new Vector3(); + size: function ( optionalTarget ) { - return function getBoundingSphere( optionalTarget ) { + var result = optionalTarget || new Vector3(); + return result.subVectors( this.max, this.min ); - var result = optionalTarget || new Sphere(); + }, - result.center = this.center(); - result.radius = this.size( v1 ).length() * 0.5; + expandByPoint: function ( point ) { - return result; + this.min.min( point ); + this.max.max( point ); - }; + return this; - }(), + }, - intersect: function ( box ) { + expandByVector: function ( vector ) { - this.min.max( box.min ); - this.max.min( box.max ); + this.min.sub( vector ); + this.max.add( vector ); - // ensure that if there is no overlap, the result is fully empty, not slightly empty with non-inf/+inf values that will cause subsequence intersects to erroneously return valid values. - if( this.isEmpty() ) this.makeEmpty(); + return this; - return this; + }, - }, + expandByScalar: function ( scalar ) { - union: function ( box ) { + this.min.addScalar( - scalar ); + this.max.addScalar( scalar ); - this.min.min( box.min ); - this.max.max( box.max ); + return this; - return this; + }, - }, + containsPoint: function ( point ) { - applyMatrix4: function () { + if ( point.x < this.min.x || point.x > this.max.x || + point.y < this.min.y || point.y > this.max.y || + point.z < this.min.z || point.z > this.max.z ) { - var points = [ - new Vector3(), - new Vector3(), - new Vector3(), - new Vector3(), - new Vector3(), - new Vector3(), - new Vector3(), - new Vector3() - ]; + return false; - return function applyMatrix4( matrix ) { + } - // transform of empty box is an empty box. - if( this.isEmpty() ) return this; + return true; - // NOTE: I am using a binary pattern to specify all 2^3 combinations below - points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000 - points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001 - points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010 - points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011 - points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100 - points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101 - points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110 - points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111 + }, - this.setFromPoints( points ); + containsBox: function ( box ) { - return this; + if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) && + ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) && + ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) { - }; + return true; - }(), + } - translate: function ( offset ) { + return false; - this.min.add( offset ); - this.max.add( offset ); + }, - return this; + getParameter: function ( point, optionalTarget ) { - }, + // This can potentially have a divide by zero if the box + // has a size dimension of 0. - equals: function ( box ) { + var result = optionalTarget || new Vector3(); - return box.min.equals( this.min ) && box.max.equals( this.max ); + return result.set( + ( point.x - this.min.x ) / ( this.max.x - this.min.x ), + ( point.y - this.min.y ) / ( this.max.y - this.min.y ), + ( point.z - this.min.z ) / ( this.max.z - this.min.z ) + ); - } + }, - }; + intersectsBox: function ( box ) { - /** - * @author bhouston / http://clara.io - * @author mrdoob / http://mrdoob.com/ - */ + // using 6 splitting planes to rule out intersections. - function Sphere( center, radius ) { + if ( box.max.x < this.min.x || box.min.x > this.max.x || + box.max.y < this.min.y || box.min.y > this.max.y || + box.max.z < this.min.z || box.min.z > this.max.z ) { - this.center = ( center !== undefined ) ? center : new Vector3(); - this.radius = ( radius !== undefined ) ? radius : 0; + return false; - }; + } - Sphere.prototype = { + return true; - constructor: Sphere, + }, - set: function ( center, radius ) { + intersectsSphere: ( function () { - this.center.copy( center ); - this.radius = radius; + var closestPoint; - return this; + return function intersectsSphere( sphere ) { - }, + if ( closestPoint === undefined ) closestPoint = new Vector3(); - setFromPoints: function () { + // Find the point on the AABB closest to the sphere center. + this.clampPoint( sphere.center, closestPoint ); - var box = new Box3(); + // If that point is inside the sphere, the AABB and sphere intersect. + return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius ); - return function setFromPoints( points, optionalCenter ) { + }; - var center = this.center; + } )(), - if ( optionalCenter !== undefined ) { + intersectsPlane: function ( plane ) { - center.copy( optionalCenter ); + // We compute the minimum and maximum dot product values. If those values + // are on the same side (back or front) of the plane, then there is no intersection. - } else { + var min, max; - box.setFromPoints( points ).center( center ); + if ( plane.normal.x > 0 ) { - } + min = plane.normal.x * this.min.x; + max = plane.normal.x * this.max.x; - var maxRadiusSq = 0; + } else { - for ( var i = 0, il = points.length; i < il; i ++ ) { + min = plane.normal.x * this.max.x; + max = plane.normal.x * this.min.x; - maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) ); + } - } + if ( plane.normal.y > 0 ) { - this.radius = Math.sqrt( maxRadiusSq ); + min += plane.normal.y * this.min.y; + max += plane.normal.y * this.max.y; - return this; + } else { - }; + min += plane.normal.y * this.max.y; + max += plane.normal.y * this.min.y; - }(), + } - clone: function () { + if ( plane.normal.z > 0 ) { - return new this.constructor().copy( this ); + min += plane.normal.z * this.min.z; + max += plane.normal.z * this.max.z; - }, + } else { - copy: function ( sphere ) { + min += plane.normal.z * this.max.z; + max += plane.normal.z * this.min.z; - this.center.copy( sphere.center ); - this.radius = sphere.radius; + } - return this; + return ( min <= plane.constant && max >= plane.constant ); - }, + }, - empty: function () { + clampPoint: function ( point, optionalTarget ) { - return ( this.radius <= 0 ); + var result = optionalTarget || new Vector3(); + return result.copy( point ).clamp( this.min, this.max ); - }, + }, - containsPoint: function ( point ) { + distanceToPoint: function () { - return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) ); + var v1 = new Vector3(); - }, + return function distanceToPoint( point ) { - distanceToPoint: function ( point ) { + var clampedPoint = v1.copy( point ).clamp( this.min, this.max ); + return clampedPoint.sub( point ).length(); - return ( point.distanceTo( this.center ) - this.radius ); + }; - }, + }(), - intersectsSphere: function ( sphere ) { + getBoundingSphere: function () { - var radiusSum = this.radius + sphere.radius; + var v1 = new Vector3(); - return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum ); + return function getBoundingSphere( optionalTarget ) { - }, + var result = optionalTarget || new Sphere(); - intersectsBox: function ( box ) { + result.center = this.center(); + result.radius = this.size( v1 ).length() * 0.5; - return box.intersectsSphere( this ); + return result; - }, + }; - intersectsPlane: function ( plane ) { + }(), - // We use the following equation to compute the signed distance from - // the center of the sphere to the plane. - // - // distance = q * n - d - // - // If this distance is greater than the radius of the sphere, - // then there is no intersection. + intersect: function ( box ) { - return Math.abs( this.center.dot( plane.normal ) - plane.constant ) <= this.radius; + this.min.max( box.min ); + this.max.min( box.max ); - }, + // ensure that if there is no overlap, the result is fully empty, not slightly empty with non-inf/+inf values that will cause subsequence intersects to erroneously return valid values. + if( this.isEmpty() ) this.makeEmpty(); - clampPoint: function ( point, optionalTarget ) { + return this; - var deltaLengthSq = this.center.distanceToSquared( point ); + }, - var result = optionalTarget || new Vector3(); + union: function ( box ) { - result.copy( point ); + this.min.min( box.min ); + this.max.max( box.max ); - if ( deltaLengthSq > ( this.radius * this.radius ) ) { + return this; - result.sub( this.center ).normalize(); - result.multiplyScalar( this.radius ).add( this.center ); + }, - } + applyMatrix4: function () { - return result; + var points = [ + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3() + ]; - }, + return function applyMatrix4( matrix ) { - getBoundingBox: function ( optionalTarget ) { + // transform of empty box is an empty box. + if( this.isEmpty() ) return this; - var box = optionalTarget || new Box3(); + // NOTE: I am using a binary pattern to specify all 2^3 combinations below + points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000 + points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001 + points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010 + points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011 + points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100 + points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101 + points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110 + points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111 - box.set( this.center, this.center ); - box.expandByScalar( this.radius ); + this.setFromPoints( points ); - return box; + return this; - }, + }; - applyMatrix4: function ( matrix ) { + }(), - this.center.applyMatrix4( matrix ); - this.radius = this.radius * matrix.getMaxScaleOnAxis(); + translate: function ( offset ) { - return this; + this.min.add( offset ); + this.max.add( offset ); - }, + return this; - translate: function ( offset ) { + }, - this.center.add( offset ); + equals: function ( box ) { - return this; + return box.min.equals( this.min ) && box.max.equals( this.max ); - }, + } - equals: function ( sphere ) { + }; - return sphere.center.equals( this.center ) && ( sphere.radius === this.radius ); + /** + * @author bhouston / http://clara.io + * @author mrdoob / http://mrdoob.com/ + */ - } + function Sphere( center, radius ) { - }; + this.center = ( center !== undefined ) ? center : new Vector3(); + this.radius = ( radius !== undefined ) ? radius : 0; - /** - * @author alteredq / http://alteredqualia.com/ - * @author WestLangley / http://github.com/WestLangley - * @author bhouston / http://clara.io - * @author tschw - */ + } - function Matrix3() { + Sphere.prototype = { - this.elements = new Float32Array( [ + constructor: Sphere, - 1, 0, 0, - 0, 1, 0, - 0, 0, 1 + set: function ( center, radius ) { - ] ); + this.center.copy( center ); + this.radius = radius; - if ( arguments.length > 0 ) { + return this; - console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' ); + }, - } + setFromPoints: function () { - }; + var box = new Box3(); - Matrix3.prototype = { + return function setFromPoints( points, optionalCenter ) { - constructor: Matrix3, + var center = this.center; - isMatrix3: true, + if ( optionalCenter !== undefined ) { - set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) { + center.copy( optionalCenter ); - var te = this.elements; + } else { - te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31; - te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32; - te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33; + box.setFromPoints( points ).center( center ); - return this; + } - }, + var maxRadiusSq = 0; - identity: function () { + for ( var i = 0, il = points.length; i < il; i ++ ) { - this.set( + maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) ); - 1, 0, 0, - 0, 1, 0, - 0, 0, 1 + } - ); + this.radius = Math.sqrt( maxRadiusSq ); - return this; + return this; - }, + }; - clone: function () { + }(), - return new this.constructor().fromArray( this.elements ); + clone: function () { - }, + return new this.constructor().copy( this ); - copy: function ( m ) { + }, - var me = m.elements; + copy: function ( sphere ) { - this.set( + this.center.copy( sphere.center ); + this.radius = sphere.radius; - me[ 0 ], me[ 3 ], me[ 6 ], - me[ 1 ], me[ 4 ], me[ 7 ], - me[ 2 ], me[ 5 ], me[ 8 ] + return this; - ); + }, - return this; + empty: function () { - }, + return ( this.radius <= 0 ); - setFromMatrix4: function( m ) { + }, - var me = m.elements; + containsPoint: function ( point ) { - this.set( + return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) ); - me[ 0 ], me[ 4 ], me[ 8 ], - me[ 1 ], me[ 5 ], me[ 9 ], - me[ 2 ], me[ 6 ], me[ 10 ] + }, - ); + distanceToPoint: function ( point ) { - return this; + return ( point.distanceTo( this.center ) - this.radius ); - }, + }, - applyToVector3Array: function () { + intersectsSphere: function ( sphere ) { - var v1; + var radiusSum = this.radius + sphere.radius; - return function applyToVector3Array( array, offset, length ) { + return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum ); - if ( v1 === undefined ) v1 = new Vector3(); - if ( offset === undefined ) offset = 0; - if ( length === undefined ) length = array.length; + }, - for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) { + intersectsBox: function ( box ) { - v1.fromArray( array, j ); - v1.applyMatrix3( this ); - v1.toArray( array, j ); + return box.intersectsSphere( this ); - } + }, - return array; + intersectsPlane: function ( plane ) { - }; + // We use the following equation to compute the signed distance from + // the center of the sphere to the plane. + // + // distance = q * n - d + // + // If this distance is greater than the radius of the sphere, + // then there is no intersection. - }(), + return Math.abs( this.center.dot( plane.normal ) - plane.constant ) <= this.radius; - applyToBuffer: function () { + }, - var v1; + clampPoint: function ( point, optionalTarget ) { - return function applyToBuffer( buffer, offset, length ) { + var deltaLengthSq = this.center.distanceToSquared( point ); - if ( v1 === undefined ) v1 = new Vector3(); - if ( offset === undefined ) offset = 0; - if ( length === undefined ) length = buffer.length / buffer.itemSize; + var result = optionalTarget || new Vector3(); - for ( var i = 0, j = offset; i < length; i ++, j ++ ) { + result.copy( point ); - v1.x = buffer.getX( j ); - v1.y = buffer.getY( j ); - v1.z = buffer.getZ( j ); + if ( deltaLengthSq > ( this.radius * this.radius ) ) { - v1.applyMatrix3( this ); + result.sub( this.center ).normalize(); + result.multiplyScalar( this.radius ).add( this.center ); - buffer.setXYZ( v1.x, v1.y, v1.z ); + } - } + return result; - return buffer; + }, - }; + getBoundingBox: function ( optionalTarget ) { - }(), + var box = optionalTarget || new Box3(); - multiplyScalar: function ( s ) { + box.set( this.center, this.center ); + box.expandByScalar( this.radius ); - var te = this.elements; + return box; - te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s; - te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s; - te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s; + }, - return this; + applyMatrix4: function ( matrix ) { - }, + this.center.applyMatrix4( matrix ); + this.radius = this.radius * matrix.getMaxScaleOnAxis(); - determinant: function () { + return this; - var te = this.elements; + }, - var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ], - d = te[ 3 ], e = te[ 4 ], f = te[ 5 ], - g = te[ 6 ], h = te[ 7 ], i = te[ 8 ]; + translate: function ( offset ) { - return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g; + this.center.add( offset ); - }, + return this; - getInverse: function ( matrix, throwOnDegenerate ) { + }, - if ( (matrix && matrix.isMatrix4) ) { + equals: function ( sphere ) { - console.error( "THREE.Matrix3.getInverse no longer takes a Matrix4 argument." ); + return sphere.center.equals( this.center ) && ( sphere.radius === this.radius ); - } + } - var me = matrix.elements, - te = this.elements, + }; - n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], - n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ], - n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ], + /** + * @author alteredq / http://alteredqualia.com/ + * @author WestLangley / http://github.com/WestLangley + * @author bhouston / http://clara.io + * @author tschw + */ - t11 = n33 * n22 - n32 * n23, - t12 = n32 * n13 - n33 * n12, - t13 = n23 * n12 - n22 * n13, + function Matrix3() { - det = n11 * t11 + n21 * t12 + n31 * t13; + this.elements = new Float32Array( [ - if ( det === 0 ) { + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 - var msg = "THREE.Matrix3.getInverse(): can't invert matrix, determinant is 0"; + ] ); - if ( throwOnDegenerate || false ) {} else { + if ( arguments.length > 0 ) { - console.warn( msg ); + console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' ); - } + } - return this.identity(); - } + } - var detInv = 1 / det; + Matrix3.prototype = { - te[ 0 ] = t11 * detInv; - te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv; - te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv; + constructor: Matrix3, - te[ 3 ] = t12 * detInv; - te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv; - te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv; + isMatrix3: true, - te[ 6 ] = t13 * detInv; - te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv; - te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv; + set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) { - return this; + var te = this.elements; - }, + te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31; + te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32; + te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33; - transpose: function () { + return this; - var tmp, m = this.elements; + }, - tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp; - tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp; - tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp; + identity: function () { - return this; + this.set( - }, + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 - flattenToArrayOffset: function ( array, offset ) { + ); - console.warn( "THREE.Matrix3: .flattenToArrayOffset is deprecated " + - "- just use .toArray instead." ); + return this; - return this.toArray( array, offset ); + }, - }, + clone: function () { - getNormalMatrix: function ( matrix4 ) { + return new this.constructor().fromArray( this.elements ); - return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose(); + }, - }, + copy: function ( m ) { - transposeIntoArray: function ( r ) { + var me = m.elements; - var m = this.elements; + this.set( - r[ 0 ] = m[ 0 ]; - r[ 1 ] = m[ 3 ]; - r[ 2 ] = m[ 6 ]; - r[ 3 ] = m[ 1 ]; - r[ 4 ] = m[ 4 ]; - r[ 5 ] = m[ 7 ]; - r[ 6 ] = m[ 2 ]; - r[ 7 ] = m[ 5 ]; - r[ 8 ] = m[ 8 ]; + me[ 0 ], me[ 3 ], me[ 6 ], + me[ 1 ], me[ 4 ], me[ 7 ], + me[ 2 ], me[ 5 ], me[ 8 ] - return this; + ); - }, + return this; - fromArray: function ( array ) { + }, - this.elements.set( array ); + setFromMatrix4: function( m ) { - return this; + var me = m.elements; - }, + this.set( - toArray: function ( array, offset ) { + me[ 0 ], me[ 4 ], me[ 8 ], + me[ 1 ], me[ 5 ], me[ 9 ], + me[ 2 ], me[ 6 ], me[ 10 ] - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + ); - var te = this.elements; + return this; - array[ offset ] = te[ 0 ]; - array[ offset + 1 ] = te[ 1 ]; - array[ offset + 2 ] = te[ 2 ]; + }, - array[ offset + 3 ] = te[ 3 ]; - array[ offset + 4 ] = te[ 4 ]; - array[ offset + 5 ] = te[ 5 ]; + applyToVector3Array: function () { - array[ offset + 6 ] = te[ 6 ]; - array[ offset + 7 ] = te[ 7 ]; - array[ offset + 8 ] = te[ 8 ]; + var v1; - return array; + return function applyToVector3Array( array, offset, length ) { - } + if ( v1 === undefined ) v1 = new Vector3(); + if ( offset === undefined ) offset = 0; + if ( length === undefined ) length = array.length; - }; + for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) { - /** - * @author bhouston / http://clara.io - */ + v1.fromArray( array, j ); + v1.applyMatrix3( this ); + v1.toArray( array, j ); - function Plane( normal, constant ) { + } - this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 ); - this.constant = ( constant !== undefined ) ? constant : 0; + return array; - }; + }; - Plane.prototype = { + }(), - constructor: Plane, + applyToBuffer: function () { - set: function ( normal, constant ) { + var v1; - this.normal.copy( normal ); - this.constant = constant; + return function applyToBuffer( buffer, offset, length ) { - return this; + if ( v1 === undefined ) v1 = new Vector3(); + if ( offset === undefined ) offset = 0; + if ( length === undefined ) length = buffer.length / buffer.itemSize; - }, + for ( var i = 0, j = offset; i < length; i ++, j ++ ) { - setComponents: function ( x, y, z, w ) { + v1.x = buffer.getX( j ); + v1.y = buffer.getY( j ); + v1.z = buffer.getZ( j ); - this.normal.set( x, y, z ); - this.constant = w; + v1.applyMatrix3( this ); - return this; + buffer.setXYZ( v1.x, v1.y, v1.z ); - }, + } - setFromNormalAndCoplanarPoint: function ( normal, point ) { + return buffer; - this.normal.copy( normal ); - this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized + }; - return this; + }(), - }, + multiplyScalar: function ( s ) { - setFromCoplanarPoints: function () { + var te = this.elements; - var v1 = new Vector3(); - var v2 = new Vector3(); + te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s; + te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s; + te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s; - return function setFromCoplanarPoints( a, b, c ) { + return this; - var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize(); + }, - // Q: should an error be thrown if normal is zero (e.g. degenerate plane)? + determinant: function () { - this.setFromNormalAndCoplanarPoint( normal, a ); + var te = this.elements; - return this; + var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ], + d = te[ 3 ], e = te[ 4 ], f = te[ 5 ], + g = te[ 6 ], h = te[ 7 ], i = te[ 8 ]; - }; + return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g; - }(), + }, - clone: function () { + getInverse: function ( matrix, throwOnDegenerate ) { - return new this.constructor().copy( this ); + if ( (matrix && matrix.isMatrix4) ) { - }, + console.error( "THREE.Matrix3.getInverse no longer takes a Matrix4 argument." ); - copy: function ( plane ) { + } - this.normal.copy( plane.normal ); - this.constant = plane.constant; + var me = matrix.elements, + te = this.elements, - return this; + n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], + n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ], + n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ], - }, + t11 = n33 * n22 - n32 * n23, + t12 = n32 * n13 - n33 * n12, + t13 = n23 * n12 - n22 * n13, - normalize: function () { + det = n11 * t11 + n21 * t12 + n31 * t13; - // Note: will lead to a divide by zero if the plane is invalid. + if ( det === 0 ) { - var inverseNormalLength = 1.0 / this.normal.length(); - this.normal.multiplyScalar( inverseNormalLength ); - this.constant *= inverseNormalLength; + var msg = "THREE.Matrix3.getInverse(): can't invert matrix, determinant is 0"; - return this; + if ( throwOnDegenerate === true ) { - }, + throw new Error( msg ); - negate: function () { + } else { - this.constant *= - 1; - this.normal.negate(); + console.warn( msg ); - return this; + } - }, + return this.identity(); + } - distanceToPoint: function ( point ) { + var detInv = 1 / det; - return this.normal.dot( point ) + this.constant; + te[ 0 ] = t11 * detInv; + te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv; + te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv; - }, + te[ 3 ] = t12 * detInv; + te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv; + te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv; - distanceToSphere: function ( sphere ) { + te[ 6 ] = t13 * detInv; + te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv; + te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv; - return this.distanceToPoint( sphere.center ) - sphere.radius; + return this; - }, + }, - projectPoint: function ( point, optionalTarget ) { + transpose: function () { - return this.orthoPoint( point, optionalTarget ).sub( point ).negate(); + var tmp, m = this.elements; - }, + tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp; + tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp; + tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp; - orthoPoint: function ( point, optionalTarget ) { + return this; - var perpendicularMagnitude = this.distanceToPoint( point ); + }, - var result = optionalTarget || new Vector3(); - return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude ); + flattenToArrayOffset: function ( array, offset ) { - }, + console.warn( "THREE.Matrix3: .flattenToArrayOffset is deprecated " + + "- just use .toArray instead." ); - intersectLine: function () { + return this.toArray( array, offset ); - var v1 = new Vector3(); + }, - return function intersectLine( line, optionalTarget ) { + getNormalMatrix: function ( matrix4 ) { - var result = optionalTarget || new Vector3(); + return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose(); - var direction = line.delta( v1 ); + }, - var denominator = this.normal.dot( direction ); + transposeIntoArray: function ( r ) { - if ( denominator === 0 ) { + var m = this.elements; - // line is coplanar, return origin - if ( this.distanceToPoint( line.start ) === 0 ) { + r[ 0 ] = m[ 0 ]; + r[ 1 ] = m[ 3 ]; + r[ 2 ] = m[ 6 ]; + r[ 3 ] = m[ 1 ]; + r[ 4 ] = m[ 4 ]; + r[ 5 ] = m[ 7 ]; + r[ 6 ] = m[ 2 ]; + r[ 7 ] = m[ 5 ]; + r[ 8 ] = m[ 8 ]; - return result.copy( line.start ); + return this; - } + }, - // Unsure if this is the correct method to handle this case. - return undefined; + fromArray: function ( array ) { - } + this.elements.set( array ); - var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator; + return this; - if ( t < 0 || t > 1 ) { + }, - return undefined; + toArray: function ( array, offset ) { - } + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - return result.copy( direction ).multiplyScalar( t ).add( line.start ); + var te = this.elements; - }; + array[ offset ] = te[ 0 ]; + array[ offset + 1 ] = te[ 1 ]; + array[ offset + 2 ] = te[ 2 ]; - }(), + array[ offset + 3 ] = te[ 3 ]; + array[ offset + 4 ] = te[ 4 ]; + array[ offset + 5 ] = te[ 5 ]; - intersectsLine: function ( line ) { + array[ offset + 6 ] = te[ 6 ]; + array[ offset + 7 ] = te[ 7 ]; + array[ offset + 8 ] = te[ 8 ]; - // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it. + return array; - var startSign = this.distanceToPoint( line.start ); - var endSign = this.distanceToPoint( line.end ); + } - return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 ); + }; - }, + /** + * @author bhouston / http://clara.io + */ - intersectsBox: function ( box ) { + function Plane( normal, constant ) { - return box.intersectsPlane( this ); + this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 ); + this.constant = ( constant !== undefined ) ? constant : 0; - }, + } - intersectsSphere: function ( sphere ) { + Plane.prototype = { - return sphere.intersectsPlane( this ); + constructor: Plane, - }, + set: function ( normal, constant ) { - coplanarPoint: function ( optionalTarget ) { + this.normal.copy( normal ); + this.constant = constant; - var result = optionalTarget || new Vector3(); - return result.copy( this.normal ).multiplyScalar( - this.constant ); + return this; - }, + }, - applyMatrix4: function () { + setComponents: function ( x, y, z, w ) { - var v1 = new Vector3(); - var m1 = new Matrix3(); + this.normal.set( x, y, z ); + this.constant = w; - return function applyMatrix4( matrix, optionalNormalMatrix ) { + return this; - var referencePoint = this.coplanarPoint( v1 ).applyMatrix4( matrix ); + }, - // transform normal based on theory here: - // http://www.songho.ca/opengl/gl_normaltransform.html - var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix ); - var normal = this.normal.applyMatrix3( normalMatrix ).normalize(); + setFromNormalAndCoplanarPoint: function ( normal, point ) { - // recalculate constant (like in setFromNormalAndCoplanarPoint) - this.constant = - referencePoint.dot( normal ); + this.normal.copy( normal ); + this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized - return this; + return this; - }; + }, - }(), + setFromCoplanarPoints: function () { - translate: function ( offset ) { + var v1 = new Vector3(); + var v2 = new Vector3(); - this.constant = this.constant - offset.dot( this.normal ); + return function setFromCoplanarPoints( a, b, c ) { - return this; + var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize(); - }, + // Q: should an error be thrown if normal is zero (e.g. degenerate plane)? - equals: function ( plane ) { + this.setFromNormalAndCoplanarPoint( normal, a ); - return plane.normal.equals( this.normal ) && ( plane.constant === this.constant ); + return this; - } + }; - }; + }(), - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * @author bhouston / http://clara.io - */ + clone: function () { - function Frustum( p0, p1, p2, p3, p4, p5 ) { + return new this.constructor().copy( this ); - this.planes = [ + }, - ( p0 !== undefined ) ? p0 : new Plane(), - ( p1 !== undefined ) ? p1 : new Plane(), - ( p2 !== undefined ) ? p2 : new Plane(), - ( p3 !== undefined ) ? p3 : new Plane(), - ( p4 !== undefined ) ? p4 : new Plane(), - ( p5 !== undefined ) ? p5 : new Plane() + copy: function ( plane ) { - ]; + this.normal.copy( plane.normal ); + this.constant = plane.constant; - }; + return this; - Frustum.prototype = { + }, - constructor: Frustum, + normalize: function () { - set: function ( p0, p1, p2, p3, p4, p5 ) { + // Note: will lead to a divide by zero if the plane is invalid. - var planes = this.planes; + var inverseNormalLength = 1.0 / this.normal.length(); + this.normal.multiplyScalar( inverseNormalLength ); + this.constant *= inverseNormalLength; - planes[ 0 ].copy( p0 ); - planes[ 1 ].copy( p1 ); - planes[ 2 ].copy( p2 ); - planes[ 3 ].copy( p3 ); - planes[ 4 ].copy( p4 ); - planes[ 5 ].copy( p5 ); + return this; - return this; + }, - }, + negate: function () { - clone: function () { + this.constant *= - 1; + this.normal.negate(); - return new this.constructor().copy( this ); + return this; - }, + }, - copy: function ( frustum ) { + distanceToPoint: function ( point ) { - var planes = this.planes; + return this.normal.dot( point ) + this.constant; - for ( var i = 0; i < 6; i ++ ) { + }, - planes[ i ].copy( frustum.planes[ i ] ); + distanceToSphere: function ( sphere ) { - } + return this.distanceToPoint( sphere.center ) - sphere.radius; - return this; + }, - }, + projectPoint: function ( point, optionalTarget ) { - setFromMatrix: function ( m ) { + return this.orthoPoint( point, optionalTarget ).sub( point ).negate(); - var planes = this.planes; - var me = m.elements; - var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ]; - var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ]; - var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ]; - var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ]; + }, - planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize(); - planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize(); - planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize(); - planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize(); - planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); - planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize(); + orthoPoint: function ( point, optionalTarget ) { - return this; + var perpendicularMagnitude = this.distanceToPoint( point ); - }, + var result = optionalTarget || new Vector3(); + return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude ); - intersectsObject: function () { + }, - var sphere = new Sphere(); + intersectLine: function () { - return function intersectsObject( object ) { + var v1 = new Vector3(); - var geometry = object.geometry; + return function intersectLine( line, optionalTarget ) { - if ( geometry.boundingSphere === null ) - geometry.computeBoundingSphere(); + var result = optionalTarget || new Vector3(); - sphere.copy( geometry.boundingSphere ) - .applyMatrix4( object.matrixWorld ); + var direction = line.delta( v1 ); - return this.intersectsSphere( sphere ); + var denominator = this.normal.dot( direction ); - }; + if ( denominator === 0 ) { - }(), + // line is coplanar, return origin + if ( this.distanceToPoint( line.start ) === 0 ) { - intersectsSprite: function () { + return result.copy( line.start ); - var sphere = new Sphere(); + } - return function intersectsSprite( sprite ) { + // Unsure if this is the correct method to handle this case. + return undefined; - sphere.center.set( 0, 0, 0 ); - sphere.radius = 0.7071067811865476; - sphere.applyMatrix4( sprite.matrixWorld ); + } - return this.intersectsSphere( sphere ); + var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator; - }; + if ( t < 0 || t > 1 ) { - }(), + return undefined; - intersectsSphere: function ( sphere ) { + } - var planes = this.planes; - var center = sphere.center; - var negRadius = - sphere.radius; + return result.copy( direction ).multiplyScalar( t ).add( line.start ); - for ( var i = 0; i < 6; i ++ ) { + }; - var distance = planes[ i ].distanceToPoint( center ); + }(), - if ( distance < negRadius ) { + intersectsLine: function ( line ) { - return false; + // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it. - } + var startSign = this.distanceToPoint( line.start ); + var endSign = this.distanceToPoint( line.end ); - } + return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 ); - return true; + }, - }, + intersectsBox: function ( box ) { - intersectsBox: function () { + return box.intersectsPlane( this ); - var p1 = new Vector3(), - p2 = new Vector3(); + }, - return function intersectsBox( box ) { + intersectsSphere: function ( sphere ) { - var planes = this.planes; + return sphere.intersectsPlane( this ); - for ( var i = 0; i < 6 ; i ++ ) { + }, - var plane = planes[ i ]; + coplanarPoint: function ( optionalTarget ) { - p1.x = plane.normal.x > 0 ? box.min.x : box.max.x; - p2.x = plane.normal.x > 0 ? box.max.x : box.min.x; - p1.y = plane.normal.y > 0 ? box.min.y : box.max.y; - p2.y = plane.normal.y > 0 ? box.max.y : box.min.y; - p1.z = plane.normal.z > 0 ? box.min.z : box.max.z; - p2.z = plane.normal.z > 0 ? box.max.z : box.min.z; + var result = optionalTarget || new Vector3(); + return result.copy( this.normal ).multiplyScalar( - this.constant ); - var d1 = plane.distanceToPoint( p1 ); - var d2 = plane.distanceToPoint( p2 ); + }, - // if both outside plane, no intersection + applyMatrix4: function () { - if ( d1 < 0 && d2 < 0 ) { + var v1 = new Vector3(); + var m1 = new Matrix3(); - return false; + return function applyMatrix4( matrix, optionalNormalMatrix ) { - } + var referencePoint = this.coplanarPoint( v1 ).applyMatrix4( matrix ); - } + // transform normal based on theory here: + // http://www.songho.ca/opengl/gl_normaltransform.html + var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix ); + var normal = this.normal.applyMatrix3( normalMatrix ).normalize(); - return true; + // recalculate constant (like in setFromNormalAndCoplanarPoint) + this.constant = - referencePoint.dot( normal ); - }; + return this; - }(), + }; + }(), - containsPoint: function ( point ) { + translate: function ( offset ) { - var planes = this.planes; + this.constant = this.constant - offset.dot( this.normal ); - for ( var i = 0; i < 6; i ++ ) { + return this; - if ( planes[ i ].distanceToPoint( point ) < 0 ) { + }, - return false; + equals: function ( plane ) { - } + return plane.normal.equals( this.normal ) && ( plane.constant === this.constant ); - } + } - return true; + }; - } + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * @author bhouston / http://clara.io + */ - }; + function Frustum( p0, p1, p2, p3, p4, p5 ) { - /** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - */ + this.planes = [ - function WebGLShadowMap( _renderer, _lights, _objects, capabilities ) { + ( p0 !== undefined ) ? p0 : new Plane(), + ( p1 !== undefined ) ? p1 : new Plane(), + ( p2 !== undefined ) ? p2 : new Plane(), + ( p3 !== undefined ) ? p3 : new Plane(), + ( p4 !== undefined ) ? p4 : new Plane(), + ( p5 !== undefined ) ? p5 : new Plane() - var _gl = _renderer.context, - _state = _renderer.state, - _frustum = new Frustum(), - _projScreenMatrix = new Matrix4(), + ]; - _lightShadows = _lights.shadows, + } - _shadowMapSize = new Vector2(), - _maxShadowMapSize = new Vector2( capabilities.maxTextureSize, capabilities.maxTextureSize ), + Frustum.prototype = { - _lookTarget = new Vector3(), - _lightPositionWorld = new Vector3(), + constructor: Frustum, - _renderList = [], + set: function ( p0, p1, p2, p3, p4, p5 ) { - _MorphingFlag = 1, - _SkinningFlag = 2, + var planes = this.planes; - _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1, + planes[ 0 ].copy( p0 ); + planes[ 1 ].copy( p1 ); + planes[ 2 ].copy( p2 ); + planes[ 3 ].copy( p3 ); + planes[ 4 ].copy( p4 ); + planes[ 5 ].copy( p5 ); - _depthMaterials = new Array( _NumberOfMaterialVariants ), - _distanceMaterials = new Array( _NumberOfMaterialVariants ), + return this; - _materialCache = {}; + }, - var cubeDirections = [ - new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ), - new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 ) - ]; + clone: function () { - var cubeUps = [ - new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), - new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 ) - ]; + return new this.constructor().copy( this ); - var cube2DViewPorts = [ - new Vector4(), new Vector4(), new Vector4(), - new Vector4(), new Vector4(), new Vector4() - ]; + }, - // init + copy: function ( frustum ) { - var depthMaterialTemplate = new MeshDepthMaterial(); - depthMaterialTemplate.depthPacking = RGBADepthPacking; - depthMaterialTemplate.clipping = true; + var planes = this.planes; - var distanceShader = exports.ShaderLib[ "distanceRGBA" ]; - var distanceUniforms = exports.UniformsUtils.clone( distanceShader.uniforms ); + for ( var i = 0; i < 6; i ++ ) { - for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) { + planes[ i ].copy( frustum.planes[ i ] ); - var useMorphing = ( i & _MorphingFlag ) !== 0; - var useSkinning = ( i & _SkinningFlag ) !== 0; + } - var depthMaterial = depthMaterialTemplate.clone(); - depthMaterial.morphTargets = useMorphing; - depthMaterial.skinning = useSkinning; + return this; - _depthMaterials[ i ] = depthMaterial; + }, - var distanceMaterial = new ShaderMaterial( { - defines: { - 'USE_SHADOWMAP': '' - }, - uniforms: distanceUniforms, - vertexShader: distanceShader.vertexShader, - fragmentShader: distanceShader.fragmentShader, - morphTargets: useMorphing, - skinning: useSkinning, - clipping: true - } ); + setFromMatrix: function ( m ) { - _distanceMaterials[ i ] = distanceMaterial; + var planes = this.planes; + var me = m.elements; + var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ]; + var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ]; + var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ]; + var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ]; - } + planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize(); + planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize(); + planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize(); + planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize(); + planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); + planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize(); - // + return this; - var scope = this; + }, - this.enabled = false; + intersectsObject: function () { - this.autoUpdate = true; - this.needsUpdate = false; + var sphere = new Sphere(); - this.type = PCFShadowMap; + return function intersectsObject( object ) { - this.renderReverseSided = true; - this.renderSingleSided = true; + var geometry = object.geometry; - this.render = function ( scene, camera ) { + if ( geometry.boundingSphere === null ) + geometry.computeBoundingSphere(); - if ( scope.enabled === false ) return; - if ( scope.autoUpdate === false && scope.needsUpdate === false ) return; + sphere.copy( geometry.boundingSphere ) + .applyMatrix4( object.matrixWorld ); - if ( _lightShadows.length === 0 ) return; + return this.intersectsSphere( sphere ); - // Set GL state for depth map. - _state.clearColor( 1, 1, 1, 1 ); - _state.disable( _gl.BLEND ); - _state.setDepthTest( true ); - _state.setScissorTest( false ); + }; - // render depth map + }(), - var faceCount, isPointLight; + intersectsSprite: function () { - for ( var i = 0, il = _lightShadows.length; i < il; i ++ ) { + var sphere = new Sphere(); - var light = _lightShadows[ i ]; - var shadow = light.shadow; + return function intersectsSprite( sprite ) { - if ( shadow === undefined ) { + sphere.center.set( 0, 0, 0 ); + sphere.radius = 0.7071067811865476; + sphere.applyMatrix4( sprite.matrixWorld ); - console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' ); - continue; + return this.intersectsSphere( sphere ); - } + }; - var shadowCamera = shadow.camera; + }(), - _shadowMapSize.copy( shadow.mapSize ); - _shadowMapSize.min( _maxShadowMapSize ); + intersectsSphere: function ( sphere ) { - if ( (light && light.isPointLight) ) { + var planes = this.planes; + var center = sphere.center; + var negRadius = - sphere.radius; - faceCount = 6; - isPointLight = true; + for ( var i = 0; i < 6; i ++ ) { - var vpWidth = _shadowMapSize.x; - var vpHeight = _shadowMapSize.y; + var distance = planes[ i ].distanceToPoint( center ); - // These viewports map a cube-map onto a 2D texture with the - // following orientation: - // - // xzXZ - // y Y - // - // X - Positive x direction - // x - Negative x direction - // Y - Positive y direction - // y - Negative y direction - // Z - Positive z direction - // z - Negative z direction + if ( distance < negRadius ) { - // positive X - cube2DViewPorts[ 0 ].set( vpWidth * 2, vpHeight, vpWidth, vpHeight ); - // negative X - cube2DViewPorts[ 1 ].set( 0, vpHeight, vpWidth, vpHeight ); - // positive Z - cube2DViewPorts[ 2 ].set( vpWidth * 3, vpHeight, vpWidth, vpHeight ); - // negative Z - cube2DViewPorts[ 3 ].set( vpWidth, vpHeight, vpWidth, vpHeight ); - // positive Y - cube2DViewPorts[ 4 ].set( vpWidth * 3, 0, vpWidth, vpHeight ); - // negative Y - cube2DViewPorts[ 5 ].set( vpWidth, 0, vpWidth, vpHeight ); + return false; - _shadowMapSize.x *= 4.0; - _shadowMapSize.y *= 2.0; + } - } else { + } - faceCount = 1; - isPointLight = false; + return true; - } + }, - if ( shadow.map === null ) { + intersectsBox: function () { - var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat }; + var p1 = new Vector3(), + p2 = new Vector3(); - shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars ); + return function intersectsBox( box ) { - shadowCamera.updateProjectionMatrix(); + var planes = this.planes; - } + for ( var i = 0; i < 6 ; i ++ ) { - if ( (shadow && shadow.isSpotLightShadow) ) { + var plane = planes[ i ]; - shadow.update( light ); + p1.x = plane.normal.x > 0 ? box.min.x : box.max.x; + p2.x = plane.normal.x > 0 ? box.max.x : box.min.x; + p1.y = plane.normal.y > 0 ? box.min.y : box.max.y; + p2.y = plane.normal.y > 0 ? box.max.y : box.min.y; + p1.z = plane.normal.z > 0 ? box.min.z : box.max.z; + p2.z = plane.normal.z > 0 ? box.max.z : box.min.z; - } + var d1 = plane.distanceToPoint( p1 ); + var d2 = plane.distanceToPoint( p2 ); - var shadowMap = shadow.map; - var shadowMatrix = shadow.matrix; + // if both outside plane, no intersection - _lightPositionWorld.setFromMatrixPosition( light.matrixWorld ); - shadowCamera.position.copy( _lightPositionWorld ); + if ( d1 < 0 && d2 < 0 ) { - _renderer.setRenderTarget( shadowMap ); - _renderer.clear(); + return false; - // render shadow map for each cube face (if omni-directional) or - // run a single pass if not + } - for ( var face = 0; face < faceCount; face ++ ) { + } - if ( isPointLight ) { + return true; - _lookTarget.copy( shadowCamera.position ); - _lookTarget.add( cubeDirections[ face ] ); - shadowCamera.up.copy( cubeUps[ face ] ); - shadowCamera.lookAt( _lookTarget ); + }; - var vpDimensions = cube2DViewPorts[ face ]; - _state.viewport( vpDimensions ); + }(), - } else { - _lookTarget.setFromMatrixPosition( light.target.matrixWorld ); - shadowCamera.lookAt( _lookTarget ); + containsPoint: function ( point ) { - } + var planes = this.planes; - shadowCamera.updateMatrixWorld(); - shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld ); + for ( var i = 0; i < 6; i ++ ) { - // compute shadow matrix + if ( planes[ i ].distanceToPoint( point ) < 0 ) { - shadowMatrix.set( - 0.5, 0.0, 0.0, 0.5, - 0.0, 0.5, 0.0, 0.5, - 0.0, 0.0, 0.5, 0.5, - 0.0, 0.0, 0.0, 1.0 - ); + return false; - shadowMatrix.multiply( shadowCamera.projectionMatrix ); - shadowMatrix.multiply( shadowCamera.matrixWorldInverse ); + } - // update camera matrices and frustum + } - _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse ); - _frustum.setFromMatrix( _projScreenMatrix ); + return true; - // set object matrices & frustum culling + } - _renderList.length = 0; + }; - projectObject( scene, camera, shadowCamera ); + /** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + */ - // render shadow map - // render regular objects + function WebGLShadowMap( _renderer, _lights, _objects, capabilities ) { - for ( var j = 0, jl = _renderList.length; j < jl; j ++ ) { + var _gl = _renderer.context, + _state = _renderer.state, + _frustum = new Frustum(), + _projScreenMatrix = new Matrix4(), - var object = _renderList[ j ]; - var geometry = _objects.update( object ); - var material = object.material; + _lightShadows = _lights.shadows, - if ( (material && material.isMultiMaterial) ) { + _shadowMapSize = new Vector2(), + _maxShadowMapSize = new Vector2( capabilities.maxTextureSize, capabilities.maxTextureSize ), - var groups = geometry.groups; - var materials = material.materials; + _lookTarget = new Vector3(), + _lightPositionWorld = new Vector3(), - for ( var k = 0, kl = groups.length; k < kl; k ++ ) { + _renderList = [], - var group = groups[ k ]; - var groupMaterial = materials[ group.materialIndex ]; + _MorphingFlag = 1, + _SkinningFlag = 2, - if ( groupMaterial.visible === true ) { + _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1, - var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld ); - _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group ); + _depthMaterials = new Array( _NumberOfMaterialVariants ), + _distanceMaterials = new Array( _NumberOfMaterialVariants ), - } + _materialCache = {}; - } + var cubeDirections = [ + new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ), + new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 ) + ]; - } else { + var cubeUps = [ + new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), + new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 ) + ]; - var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld ); - _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null ); + var cube2DViewPorts = [ + new Vector4(), new Vector4(), new Vector4(), + new Vector4(), new Vector4(), new Vector4() + ]; - } + // init - } + var depthMaterialTemplate = new MeshDepthMaterial(); + depthMaterialTemplate.depthPacking = RGBADepthPacking; + depthMaterialTemplate.clipping = true; - } + var distanceShader = exports.ShaderLib[ "distanceRGBA" ]; + var distanceUniforms = exports.UniformsUtils.clone( distanceShader.uniforms ); - } + for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) { - // Restore GL state. - var clearColor = _renderer.getClearColor(), - clearAlpha = _renderer.getClearAlpha(); - _renderer.setClearColor( clearColor, clearAlpha ); + var useMorphing = ( i & _MorphingFlag ) !== 0; + var useSkinning = ( i & _SkinningFlag ) !== 0; - scope.needsUpdate = false; + var depthMaterial = depthMaterialTemplate.clone(); + depthMaterial.morphTargets = useMorphing; + depthMaterial.skinning = useSkinning; - }; + _depthMaterials[ i ] = depthMaterial; - function getDepthMaterial( object, material, isPointLight, lightPositionWorld ) { + var distanceMaterial = new ShaderMaterial( { + defines: { + 'USE_SHADOWMAP': '' + }, + uniforms: distanceUniforms, + vertexShader: distanceShader.vertexShader, + fragmentShader: distanceShader.fragmentShader, + morphTargets: useMorphing, + skinning: useSkinning, + clipping: true + } ); - var geometry = object.geometry; + _distanceMaterials[ i ] = distanceMaterial; - var result = null; + } - var materialVariants = _depthMaterials; - var customMaterial = object.customDepthMaterial; + // - if ( isPointLight ) { + var scope = this; - materialVariants = _distanceMaterials; - customMaterial = object.customDistanceMaterial; + this.enabled = false; - } + this.autoUpdate = true; + this.needsUpdate = false; - if ( ! customMaterial ) { + this.type = PCFShadowMap; - var useMorphing = false; + this.renderReverseSided = true; + this.renderSingleSided = true; - if ( material.morphTargets ) { + this.render = function ( scene, camera ) { - if ( (geometry && geometry.isBufferGeometry) ) { + if ( scope.enabled === false ) return; + if ( scope.autoUpdate === false && scope.needsUpdate === false ) return; - useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0; + if ( _lightShadows.length === 0 ) return; - } else if ( (geometry && geometry.isGeometry) ) { + // Set GL state for depth map. + _state.clearColor( 1, 1, 1, 1 ); + _state.disable( _gl.BLEND ); + _state.setDepthTest( true ); + _state.setScissorTest( false ); - useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0; + // render depth map - } + var faceCount, isPointLight; - } + for ( var i = 0, il = _lightShadows.length; i < il; i ++ ) { - var useSkinning = (object && object.isSkinnedMesh) && material.skinning; + var light = _lightShadows[ i ]; + var shadow = light.shadow; - var variantIndex = 0; + if ( shadow === undefined ) { - if ( useMorphing ) variantIndex |= _MorphingFlag; - if ( useSkinning ) variantIndex |= _SkinningFlag; + console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' ); + continue; - result = materialVariants[ variantIndex ]; + } - } else { + var shadowCamera = shadow.camera; - result = customMaterial; + _shadowMapSize.copy( shadow.mapSize ); + _shadowMapSize.min( _maxShadowMapSize ); - } + if ( (light && light.isPointLight) ) { - if ( _renderer.localClippingEnabled && - material.clipShadows === true && - material.clippingPlanes.length !== 0 ) { + faceCount = 6; + isPointLight = true; - // in this case we need a unique material instance reflecting the - // appropriate state + var vpWidth = _shadowMapSize.x; + var vpHeight = _shadowMapSize.y; - var keyA = result.uuid, keyB = material.uuid; + // These viewports map a cube-map onto a 2D texture with the + // following orientation: + // + // xzXZ + // y Y + // + // X - Positive x direction + // x - Negative x direction + // Y - Positive y direction + // y - Negative y direction + // Z - Positive z direction + // z - Negative z direction - var materialsForVariant = _materialCache[ keyA ]; + // positive X + cube2DViewPorts[ 0 ].set( vpWidth * 2, vpHeight, vpWidth, vpHeight ); + // negative X + cube2DViewPorts[ 1 ].set( 0, vpHeight, vpWidth, vpHeight ); + // positive Z + cube2DViewPorts[ 2 ].set( vpWidth * 3, vpHeight, vpWidth, vpHeight ); + // negative Z + cube2DViewPorts[ 3 ].set( vpWidth, vpHeight, vpWidth, vpHeight ); + // positive Y + cube2DViewPorts[ 4 ].set( vpWidth * 3, 0, vpWidth, vpHeight ); + // negative Y + cube2DViewPorts[ 5 ].set( vpWidth, 0, vpWidth, vpHeight ); - if ( materialsForVariant === undefined ) { + _shadowMapSize.x *= 4.0; + _shadowMapSize.y *= 2.0; - materialsForVariant = {}; - _materialCache[ keyA ] = materialsForVariant; + } else { - } + faceCount = 1; + isPointLight = false; - var cachedMaterial = materialsForVariant[ keyB ]; + } - if ( cachedMaterial === undefined ) { + if ( shadow.map === null ) { - cachedMaterial = result.clone(); - materialsForVariant[ keyB ] = cachedMaterial; + var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat }; - } + shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars ); - result = cachedMaterial; + shadowCamera.updateProjectionMatrix(); - } + } - result.visible = material.visible; - result.wireframe = material.wireframe; + if ( (shadow && shadow.isSpotLightShadow) ) { - var side = material.side; + shadow.update( light ); - if ( scope.renderSingleSided && side == DoubleSide ) { + } - side = FrontSide; + var shadowMap = shadow.map; + var shadowMatrix = shadow.matrix; - } + _lightPositionWorld.setFromMatrixPosition( light.matrixWorld ); + shadowCamera.position.copy( _lightPositionWorld ); - if ( scope.renderReverseSided ) { + _renderer.setRenderTarget( shadowMap ); + _renderer.clear(); - if ( side === FrontSide ) side = BackSide; - else if ( side === BackSide ) side = FrontSide; + // render shadow map for each cube face (if omni-directional) or + // run a single pass if not - } + for ( var face = 0; face < faceCount; face ++ ) { - result.side = side; + if ( isPointLight ) { - result.clipShadows = material.clipShadows; - result.clippingPlanes = material.clippingPlanes; + _lookTarget.copy( shadowCamera.position ); + _lookTarget.add( cubeDirections[ face ] ); + shadowCamera.up.copy( cubeUps[ face ] ); + shadowCamera.lookAt( _lookTarget ); - result.wireframeLinewidth = material.wireframeLinewidth; - result.linewidth = material.linewidth; + var vpDimensions = cube2DViewPorts[ face ]; + _state.viewport( vpDimensions ); - if ( isPointLight && result.uniforms.lightPos !== undefined ) { + } else { - result.uniforms.lightPos.value.copy( lightPositionWorld ); + _lookTarget.setFromMatrixPosition( light.target.matrixWorld ); + shadowCamera.lookAt( _lookTarget ); - } + } - return result; + shadowCamera.updateMatrixWorld(); + shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld ); - } + // compute shadow matrix - function projectObject( object, camera, shadowCamera ) { + shadowMatrix.set( + 0.5, 0.0, 0.0, 0.5, + 0.0, 0.5, 0.0, 0.5, + 0.0, 0.0, 0.5, 0.5, + 0.0, 0.0, 0.0, 1.0 + ); - if ( object.visible === false ) return; + shadowMatrix.multiply( shadowCamera.projectionMatrix ); + shadowMatrix.multiply( shadowCamera.matrixWorldInverse ); - if ( object.layers.test( camera.layers ) && ( (object && object.isMesh) || (object && object.isLine) || (object && object.isPoints) ) ) { + // update camera matrices and frustum - if ( object.castShadow && ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) ) { + _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse ); + _frustum.setFromMatrix( _projScreenMatrix ); - var material = object.material; + // set object matrices & frustum culling - if ( material.visible === true ) { + _renderList.length = 0; - object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld ); - _renderList.push( object ); + projectObject( scene, camera, shadowCamera ); - } + // render shadow map + // render regular objects - } + for ( var j = 0, jl = _renderList.length; j < jl; j ++ ) { - } + var object = _renderList[ j ]; + var geometry = _objects.update( object ); + var material = object.material; - var children = object.children; + if ( (material && material.isMultiMaterial) ) { - for ( var i = 0, l = children.length; i < l; i ++ ) { + var groups = geometry.groups; + var materials = material.materials; - projectObject( children[ i ], camera, shadowCamera ); + for ( var k = 0, kl = groups.length; k < kl; k ++ ) { - } + var group = groups[ k ]; + var groupMaterial = materials[ group.materialIndex ]; - } + if ( groupMaterial.visible === true ) { - }; + var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld ); + _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group ); - exports.WebGLShader = ( function () { + } - function addLineNumbers( string ) { + } - var lines = string.split( '\n' ); + } else { - for ( var i = 0; i < lines.length; i ++ ) { + var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld ); + _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null ); - lines[ i ] = ( i + 1 ) + ': ' + lines[ i ]; + } - } + } - return lines.join( '\n' ); + } - } + } - return function WebGLShader( gl, type, string ) { + // Restore GL state. + var clearColor = _renderer.getClearColor(), + clearAlpha = _renderer.getClearAlpha(); + _renderer.setClearColor( clearColor, clearAlpha ); - var shader = gl.createShader( type ); + scope.needsUpdate = false; - gl.shaderSource( shader, string ); - gl.compileShader( shader ); + }; - if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) { + function getDepthMaterial( object, material, isPointLight, lightPositionWorld ) { - console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' ); + var geometry = object.geometry; - } + var result = null; - if ( gl.getShaderInfoLog( shader ) !== '' ) { + var materialVariants = _depthMaterials; + var customMaterial = object.customDepthMaterial; - console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) ); + if ( isPointLight ) { - } + materialVariants = _distanceMaterials; + customMaterial = object.customDistanceMaterial; - // --enable-privileged-webgl-extension - // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) ); + } - return shader; + if ( ! customMaterial ) { - }; + var useMorphing = false; - } )(); + if ( material.morphTargets ) { - /** - * @author fordacious / fordacious.github.io - */ + if ( (geometry && geometry.isBufferGeometry) ) { - function WebGLProperties() { + useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0; - var properties = {}; + } else if ( (geometry && geometry.isGeometry) ) { - this.get = function ( object ) { + useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0; - var uuid = object.uuid; - var map = properties[ uuid ]; + } - if ( map === undefined ) { + } - map = {}; - properties[ uuid ] = map; + var useSkinning = object.isSkinnedMesh && material.skinning; - } + var variantIndex = 0; - return map; + if ( useMorphing ) variantIndex |= _MorphingFlag; + if ( useSkinning ) variantIndex |= _SkinningFlag; - }; + result = materialVariants[ variantIndex ]; - this.delete = function ( object ) { + } else { - delete properties[ object.uuid ]; + result = customMaterial; - }; + } - this.clear = function () { + if ( _renderer.localClippingEnabled && + material.clipShadows === true && + material.clippingPlanes.length !== 0 ) { - properties = {}; + // in this case we need a unique material instance reflecting the + // appropriate state - }; + var keyA = result.uuid, keyB = material.uuid; - }; + var materialsForVariant = _materialCache[ keyA ]; - exports.WebGLProgram = ( function () { + if ( materialsForVariant === undefined ) { - var programIdCount = 0; + materialsForVariant = {}; + _materialCache[ keyA ] = materialsForVariant; - function getEncodingComponents( encoding ) { + } - switch ( encoding ) { + var cachedMaterial = materialsForVariant[ keyB ]; - case LinearEncoding: - return [ 'Linear','( value )' ]; - case sRGBEncoding: - return [ 'sRGB','( value )' ]; - case RGBEEncoding: - return [ 'RGBE','( value )' ]; - case RGBM7Encoding: - return [ 'RGBM','( value, 7.0 )' ]; - case RGBM16Encoding: - return [ 'RGBM','( value, 16.0 )' ]; - case RGBDEncoding: - return [ 'RGBD','( value, 256.0 )' ]; - case GammaEncoding: - return [ 'Gamma','( value, float( GAMMA_FACTOR ) )' ]; - default: - throw new Error( 'unsupported encoding: ' + encoding ); + if ( cachedMaterial === undefined ) { - } + cachedMaterial = result.clone(); + materialsForVariant[ keyB ] = cachedMaterial; - } + } - function getTexelDecodingFunction( functionName, encoding ) { + result = cachedMaterial; - var components = getEncodingComponents( encoding ); - return "vec4 " + functionName + "( vec4 value ) { return " + components[ 0 ] + "ToLinear" + components[ 1 ] + "; }"; + } - } + result.visible = material.visible; + result.wireframe = material.wireframe; - function getTexelEncodingFunction( functionName, encoding ) { + var side = material.side; - var components = getEncodingComponents( encoding ); - return "vec4 " + functionName + "( vec4 value ) { return LinearTo" + components[ 0 ] + components[ 1 ] + "; }"; + if ( scope.renderSingleSided && side == DoubleSide ) { - } + side = FrontSide; - function getToneMappingFunction( functionName, toneMapping ) { + } - var toneMappingName; + if ( scope.renderReverseSided ) { - switch ( toneMapping ) { + if ( side === FrontSide ) side = BackSide; + else if ( side === BackSide ) side = FrontSide; - case LinearToneMapping: - toneMappingName = "Linear"; - break; + } - case ReinhardToneMapping: - toneMappingName = "Reinhard"; - break; + result.side = side; - case Uncharted2ToneMapping: - toneMappingName = "Uncharted2"; - break; + result.clipShadows = material.clipShadows; + result.clippingPlanes = material.clippingPlanes; - case CineonToneMapping: - toneMappingName = "OptimizedCineon"; - break; + result.wireframeLinewidth = material.wireframeLinewidth; + result.linewidth = material.linewidth; - default: - throw new Error( 'unsupported toneMapping: ' + toneMapping ); + if ( isPointLight && result.uniforms.lightPos !== undefined ) { - } + result.uniforms.lightPos.value.copy( lightPositionWorld ); - return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }"; + } - } + return result; - function generateExtensions( extensions, parameters, rendererExtensions ) { + } - extensions = extensions || {}; + function projectObject( object, camera, shadowCamera ) { - var chunks = [ - ( extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.normalMap || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '', - ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '', - ( extensions.drawBuffers ) && rendererExtensions.get( 'WEBGL_draw_buffers' ) ? '#extension GL_EXT_draw_buffers : require' : '', - ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ? '#extension GL_EXT_shader_texture_lod : enable' : '', - ]; + if ( object.visible === false ) return; - return chunks.filter( filterEmptyLine ).join( '\n' ); + var visible = ( object.layers.mask & camera.layers.mask ) !== 0; - } + if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) { - function generateDefines( defines ) { + if ( object.castShadow && ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) ) { - var chunks = []; + var material = object.material; - for ( var name in defines ) { + if ( material.visible === true ) { - var value = defines[ name ]; + object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld ); + _renderList.push( object ); - if ( value === false ) continue; + } - chunks.push( '#define ' + name + ' ' + value ); + } - } + } - return chunks.join( '\n' ); + var children = object.children; - } + for ( var i = 0, l = children.length; i < l; i ++ ) { - function fetchAttributeLocations( gl, program, identifiers ) { + projectObject( children[ i ], camera, shadowCamera ); - var attributes = {}; + } - var n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES ); + } - for ( var i = 0; i < n; i ++ ) { + } - var info = gl.getActiveAttrib( program, i ); - var name = info.name; + exports.WebGLShader = ( function () { - // console.log("THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:", name, i ); + function addLineNumbers( string ) { - attributes[ name ] = gl.getAttribLocation( program, name ); + var lines = string.split( '\n' ); - } + for ( var i = 0; i < lines.length; i ++ ) { - return attributes; + lines[ i ] = ( i + 1 ) + ': ' + lines[ i ]; - } + } - function filterEmptyLine( string ) { + return lines.join( '\n' ); - return string !== ''; + } - } + return function WebGLShader( gl, type, string ) { - function replaceLightNums( string, parameters ) { + var shader = gl.createShader( type ); - return string - .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights ) - .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights ) - .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights ) - .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights ); + gl.shaderSource( shader, string ); + gl.compileShader( shader ); - } + if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) { - function parseIncludes( string ) { + console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' ); - var pattern = /#include +<([\w\d.]+)>/g; + } - function replace( match, include ) { + if ( gl.getShaderInfoLog( shader ) !== '' ) { - var replace = ShaderChunk[ include ]; + console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) ); - if ( replace === undefined ) { + } - throw new Error( 'Can not resolve #include <' + include + '>' ); + // --enable-privileged-webgl-extension + // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) ); - } + return shader; - return parseIncludes( replace ); + }; - } + } )(); - return string.replace( pattern, replace ); + /** + * @author fordacious / fordacious.github.io + */ - } + function WebGLProperties() { - function unrollLoops( string ) { + var properties = {}; - var pattern = /for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g; + this.get = function ( object ) { - function replace( match, start, end, snippet ) { + var uuid = object.uuid; + var map = properties[ uuid ]; - var unroll = ''; + if ( map === undefined ) { - for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) { + map = {}; + properties[ uuid ] = map; - unroll += snippet.replace( /\[ i \]/g, '[ ' + i + ' ]' ); + } - } + return map; - return unroll; + }; - } + this.delete = function ( object ) { - return string.replace( pattern, replace ); + delete properties[ object.uuid ]; - } + }; - return function WebGLProgram( renderer, code, material, parameters ) { + this.clear = function () { - var gl = renderer.context; + properties = {}; - var extensions = material.extensions; - var defines = material.defines; + }; - var vertexShader = material.__webglShader.vertexShader; - var fragmentShader = material.__webglShader.fragmentShader; + } - var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC'; + exports.WebGLProgram = ( function () { - if ( parameters.shadowMapType === PCFShadowMap ) { + var programIdCount = 0; - shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF'; + function getEncodingComponents( encoding ) { - } else if ( parameters.shadowMapType === PCFSoftShadowMap ) { + switch ( encoding ) { - shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT'; + case LinearEncoding: + return [ 'Linear','( value )' ]; + case sRGBEncoding: + return [ 'sRGB','( value )' ]; + case RGBEEncoding: + return [ 'RGBE','( value )' ]; + case RGBM7Encoding: + return [ 'RGBM','( value, 7.0 )' ]; + case RGBM16Encoding: + return [ 'RGBM','( value, 16.0 )' ]; + case RGBDEncoding: + return [ 'RGBD','( value, 256.0 )' ]; + case GammaEncoding: + return [ 'Gamma','( value, float( GAMMA_FACTOR ) )' ]; + default: + throw new Error( 'unsupported encoding: ' + encoding ); - } + } - var envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; - var envMapModeDefine = 'ENVMAP_MODE_REFLECTION'; - var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY'; + } - if ( parameters.envMap ) { + function getTexelDecodingFunction( functionName, encoding ) { - switch ( material.envMap.mapping ) { + var components = getEncodingComponents( encoding ); + return "vec4 " + functionName + "( vec4 value ) { return " + components[ 0 ] + "ToLinear" + components[ 1 ] + "; }"; - case CubeReflectionMapping: - case CubeRefractionMapping: - envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; - break; + } - case CubeUVReflectionMapping: - case CubeUVRefractionMapping: - envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV'; - break; + function getTexelEncodingFunction( functionName, encoding ) { - case EquirectangularReflectionMapping: - case EquirectangularRefractionMapping: - envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC'; - break; + var components = getEncodingComponents( encoding ); + return "vec4 " + functionName + "( vec4 value ) { return LinearTo" + components[ 0 ] + components[ 1 ] + "; }"; - case SphericalReflectionMapping: - envMapTypeDefine = 'ENVMAP_TYPE_SPHERE'; - break; + } - } + function getToneMappingFunction( functionName, toneMapping ) { - switch ( material.envMap.mapping ) { + var toneMappingName; - case CubeRefractionMapping: - case EquirectangularRefractionMapping: - envMapModeDefine = 'ENVMAP_MODE_REFRACTION'; - break; + switch ( toneMapping ) { - } + case LinearToneMapping: + toneMappingName = "Linear"; + break; - switch ( material.combine ) { + case ReinhardToneMapping: + toneMappingName = "Reinhard"; + break; - case MultiplyOperation: - envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY'; - break; + case Uncharted2ToneMapping: + toneMappingName = "Uncharted2"; + break; - case MixOperation: - envMapBlendingDefine = 'ENVMAP_BLENDING_MIX'; - break; + case CineonToneMapping: + toneMappingName = "OptimizedCineon"; + break; - case AddOperation: - envMapBlendingDefine = 'ENVMAP_BLENDING_ADD'; - break; + default: + throw new Error( 'unsupported toneMapping: ' + toneMapping ); - } + } - } + return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }"; - var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0; + } - // console.log( 'building new program ' ); + function generateExtensions( extensions, parameters, rendererExtensions ) { - // + extensions = extensions || {}; - var customExtensions = generateExtensions( extensions, parameters, renderer.extensions ); + var chunks = [ + ( extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.normalMap || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '', + ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '', + ( extensions.drawBuffers ) && rendererExtensions.get( 'WEBGL_draw_buffers' ) ? '#extension GL_EXT_draw_buffers : require' : '', + ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ? '#extension GL_EXT_shader_texture_lod : enable' : '', + ]; - var customDefines = generateDefines( defines ); + return chunks.filter( filterEmptyLine ).join( '\n' ); - // + } - var program = gl.createProgram(); + function generateDefines( defines ) { - var prefixVertex, prefixFragment; + var chunks = []; - if ( (material && material.isRawShaderMaterial) ) { + for ( var name in defines ) { - prefixVertex = [ + var value = defines[ name ]; - customDefines + if ( value === false ) continue; - ].filter( filterEmptyLine ).join( '\n' ); + chunks.push( '#define ' + name + ' ' + value ); - prefixFragment = [ + } - customDefines + return chunks.join( '\n' ); - ].filter( filterEmptyLine ).join( '\n' ); + } - } else { + function fetchAttributeLocations( gl, program, identifiers ) { - prefixVertex = [ + var attributes = {}; - 'precision ' + parameters.precision + ' float;', - 'precision ' + parameters.precision + ' int;', + var n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES ); - '#define SHADER_NAME ' + material.__webglShader.name, + for ( var i = 0; i < n; i ++ ) { - customDefines, + var info = gl.getActiveAttrib( program, i ); + var name = info.name; - parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', + // console.log("THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:", name, i ); - '#define GAMMA_FACTOR ' + gammaFactorDefine, + attributes[ name ] = gl.getAttribLocation( program, name ); - '#define MAX_BONES ' + parameters.maxBones, + } - parameters.map ? '#define USE_MAP' : '', - parameters.envMap ? '#define USE_ENVMAP' : '', - parameters.envMap ? '#define ' + envMapModeDefine : '', - parameters.lightMap ? '#define USE_LIGHTMAP' : '', - parameters.aoMap ? '#define USE_AOMAP' : '', - parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', - parameters.bumpMap ? '#define USE_BUMPMAP' : '', - parameters.normalMap ? '#define USE_NORMALMAP' : '', - parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '', - parameters.specularMap ? '#define USE_SPECULARMAP' : '', - parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', - parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', - parameters.alphaMap ? '#define USE_ALPHAMAP' : '', - parameters.vertexColors ? '#define USE_COLOR' : '', + return attributes; - parameters.flatShading ? '#define FLAT_SHADED' : '', + } - parameters.skinning ? '#define USE_SKINNING' : '', - parameters.useVertexTexture ? '#define BONE_TEXTURE' : '', + function filterEmptyLine( string ) { - parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', - parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', - parameters.doubleSided ? '#define DOUBLE_SIDED' : '', - parameters.flipSided ? '#define FLIP_SIDED' : '', + return string !== ''; - '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes, + } - parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', - parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', + function replaceLightNums( string, parameters ) { - parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '', + return string + .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights ) + .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights ) + .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights ) + .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights ); - parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', - parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '', + } - 'uniform mat4 modelMatrix;', - 'uniform mat4 modelViewMatrix;', - 'uniform mat4 projectionMatrix;', - 'uniform mat4 viewMatrix;', - 'uniform mat3 normalMatrix;', - 'uniform vec3 cameraPosition;', + function parseIncludes( string ) { - 'attribute vec3 position;', - 'attribute vec3 normal;', - 'attribute vec2 uv;', + var pattern = /#include +<([\w\d.]+)>/g; - '#ifdef USE_COLOR', + function replace( match, include ) { - ' attribute vec3 color;', + var replace = ShaderChunk[ include ]; - '#endif', + if ( replace === undefined ) { - '#ifdef USE_MORPHTARGETS', + throw new Error( 'Can not resolve #include <' + include + '>' ); - ' attribute vec3 morphTarget0;', - ' attribute vec3 morphTarget1;', - ' attribute vec3 morphTarget2;', - ' attribute vec3 morphTarget3;', + } - ' #ifdef USE_MORPHNORMALS', + return parseIncludes( replace ); - ' attribute vec3 morphNormal0;', - ' attribute vec3 morphNormal1;', - ' attribute vec3 morphNormal2;', - ' attribute vec3 morphNormal3;', + } - ' #else', + return string.replace( pattern, replace ); - ' attribute vec3 morphTarget4;', - ' attribute vec3 morphTarget5;', - ' attribute vec3 morphTarget6;', - ' attribute vec3 morphTarget7;', + } - ' #endif', + function unrollLoops( string ) { - '#endif', + var pattern = /for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g; - '#ifdef USE_SKINNING', + function replace( match, start, end, snippet ) { - ' attribute vec4 skinIndex;', - ' attribute vec4 skinWeight;', + var unroll = ''; - '#endif', + for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) { - '\n' + unroll += snippet.replace( /\[ i \]/g, '[ ' + i + ' ]' ); - ].filter( filterEmptyLine ).join( '\n' ); + } - prefixFragment = [ + return unroll; - customExtensions, + } - 'precision ' + parameters.precision + ' float;', - 'precision ' + parameters.precision + ' int;', + return string.replace( pattern, replace ); - '#define SHADER_NAME ' + material.__webglShader.name, + } - customDefines, + return function WebGLProgram( renderer, code, material, parameters ) { - parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '', + var gl = renderer.context; - '#define GAMMA_FACTOR ' + gammaFactorDefine, + var extensions = material.extensions; + var defines = material.defines; - ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '', - ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '', + var vertexShader = material.__webglShader.vertexShader; + var fragmentShader = material.__webglShader.fragmentShader; - parameters.map ? '#define USE_MAP' : '', - parameters.envMap ? '#define USE_ENVMAP' : '', - parameters.envMap ? '#define ' + envMapTypeDefine : '', - parameters.envMap ? '#define ' + envMapModeDefine : '', - parameters.envMap ? '#define ' + envMapBlendingDefine : '', - parameters.lightMap ? '#define USE_LIGHTMAP' : '', - parameters.aoMap ? '#define USE_AOMAP' : '', - parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', - parameters.bumpMap ? '#define USE_BUMPMAP' : '', - parameters.normalMap ? '#define USE_NORMALMAP' : '', - parameters.specularMap ? '#define USE_SPECULARMAP' : '', - parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', - parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', - parameters.alphaMap ? '#define USE_ALPHAMAP' : '', - parameters.vertexColors ? '#define USE_COLOR' : '', + var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC'; - parameters.flatShading ? '#define FLAT_SHADED' : '', + if ( parameters.shadowMapType === PCFShadowMap ) { - parameters.doubleSided ? '#define DOUBLE_SIDED' : '', - parameters.flipSided ? '#define FLIP_SIDED' : '', + shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF'; - '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes, + } else if ( parameters.shadowMapType === PCFSoftShadowMap ) { - parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', - parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', + shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT'; - parameters.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : '', + } - parameters.physicallyCorrectLights ? "#define PHYSICALLY_CORRECT_LIGHTS" : '', + var envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; + var envMapModeDefine = 'ENVMAP_MODE_REFLECTION'; + var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY'; - parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', - parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '', + if ( parameters.envMap ) { - parameters.envMap && renderer.extensions.get( 'EXT_shader_texture_lod' ) ? '#define TEXTURE_LOD_EXT' : '', + switch ( material.envMap.mapping ) { - 'uniform mat4 viewMatrix;', - 'uniform vec3 cameraPosition;', + case CubeReflectionMapping: + case CubeRefractionMapping: + envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; + break; - ( parameters.toneMapping !== NoToneMapping ) ? "#define TONE_MAPPING" : '', - ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below - ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( "toneMapping", parameters.toneMapping ) : '', + case CubeUVReflectionMapping: + case CubeUVRefractionMapping: + envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV'; + break; - ( parameters.outputEncoding || parameters.mapEncoding || parameters.envMapEncoding || parameters.emissiveMapEncoding ) ? ShaderChunk[ 'encodings_pars_fragment' ] : '', // this code is required here because it is used by the various encoding/decoding function defined below - parameters.mapEncoding ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '', - parameters.envMapEncoding ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '', - parameters.emissiveMapEncoding ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '', - parameters.outputEncoding ? getTexelEncodingFunction( "linearToOutputTexel", parameters.outputEncoding ) : '', + case EquirectangularReflectionMapping: + case EquirectangularRefractionMapping: + envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC'; + break; - parameters.depthPacking ? "#define DEPTH_PACKING " + material.depthPacking : '', + case SphericalReflectionMapping: + envMapTypeDefine = 'ENVMAP_TYPE_SPHERE'; + break; - '\n' + } - ].filter( filterEmptyLine ).join( '\n' ); + switch ( material.envMap.mapping ) { - } + case CubeRefractionMapping: + case EquirectangularRefractionMapping: + envMapModeDefine = 'ENVMAP_MODE_REFRACTION'; + break; - vertexShader = parseIncludes( vertexShader, parameters ); - vertexShader = replaceLightNums( vertexShader, parameters ); + } - fragmentShader = parseIncludes( fragmentShader, parameters ); - fragmentShader = replaceLightNums( fragmentShader, parameters ); + switch ( material.combine ) { - if ( (material && material.isShaderMaterial) === false ) { + case MultiplyOperation: + envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY'; + break; - vertexShader = unrollLoops( vertexShader ); - fragmentShader = unrollLoops( fragmentShader ); + case MixOperation: + envMapBlendingDefine = 'ENVMAP_BLENDING_MIX'; + break; - } + case AddOperation: + envMapBlendingDefine = 'ENVMAP_BLENDING_ADD'; + break; - var vertexGlsl = prefixVertex + vertexShader; - var fragmentGlsl = prefixFragment + fragmentShader; + } - // console.log( '*VERTEX*', vertexGlsl ); - // console.log( '*FRAGMENT*', fragmentGlsl ); + } - var glVertexShader = exports.WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl ); - var glFragmentShader = exports.WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl ); + var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0; - gl.attachShader( program, glVertexShader ); - gl.attachShader( program, glFragmentShader ); + // console.log( 'building new program ' ); - // Force a particular attribute to index 0. + // - if ( material.index0AttributeName !== undefined ) { + var customExtensions = generateExtensions( extensions, parameters, renderer.extensions ); - gl.bindAttribLocation( program, 0, material.index0AttributeName ); + var customDefines = generateDefines( defines ); - } else if ( parameters.morphTargets === true ) { + // - // programs with morphTargets displace position out of attribute 0 - gl.bindAttribLocation( program, 0, 'position' ); + var program = gl.createProgram(); - } + var prefixVertex, prefixFragment; - gl.linkProgram( program ); + if ( (material && material.isRawShaderMaterial) ) { - var programLog = gl.getProgramInfoLog( program ); - var vertexLog = gl.getShaderInfoLog( glVertexShader ); - var fragmentLog = gl.getShaderInfoLog( glFragmentShader ); + prefixVertex = [ - var runnable = true; - var haveDiagnostics = true; + customDefines - // console.log( '**VERTEX**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glVertexShader ) ); - // console.log( '**FRAGMENT**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glFragmentShader ) ); + ].filter( filterEmptyLine ).join( '\n' ); - if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) { + prefixFragment = [ - runnable = false; + customDefines - console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter( program, gl.VALIDATE_STATUS ), 'gl.getProgramInfoLog', programLog, vertexLog, fragmentLog ); + ].filter( filterEmptyLine ).join( '\n' ); - } else if ( programLog !== '' ) { + } else { - console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog ); + prefixVertex = [ - } else if ( vertexLog === '' || fragmentLog === '' ) { + 'precision ' + parameters.precision + ' float;', + 'precision ' + parameters.precision + ' int;', - haveDiagnostics = false; + '#define SHADER_NAME ' + material.__webglShader.name, - } + customDefines, - if ( haveDiagnostics ) { + parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', - this.diagnostics = { + '#define GAMMA_FACTOR ' + gammaFactorDefine, - runnable: runnable, - material: material, + '#define MAX_BONES ' + parameters.maxBones, - programLog: programLog, + parameters.map ? '#define USE_MAP' : '', + parameters.envMap ? '#define USE_ENVMAP' : '', + parameters.envMap ? '#define ' + envMapModeDefine : '', + parameters.lightMap ? '#define USE_LIGHTMAP' : '', + parameters.aoMap ? '#define USE_AOMAP' : '', + parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', + parameters.bumpMap ? '#define USE_BUMPMAP' : '', + parameters.normalMap ? '#define USE_NORMALMAP' : '', + parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '', + parameters.specularMap ? '#define USE_SPECULARMAP' : '', + parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', + parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', + parameters.alphaMap ? '#define USE_ALPHAMAP' : '', + parameters.vertexColors ? '#define USE_COLOR' : '', - vertexShader: { + parameters.flatShading ? '#define FLAT_SHADED' : '', - log: vertexLog, - prefix: prefixVertex + parameters.skinning ? '#define USE_SKINNING' : '', + parameters.useVertexTexture ? '#define BONE_TEXTURE' : '', - }, + parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', + parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', + parameters.doubleSided ? '#define DOUBLE_SIDED' : '', + parameters.flipSided ? '#define FLIP_SIDED' : '', - fragmentShader: { + '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes, - log: fragmentLog, - prefix: prefixFragment + parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', + parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', - } + parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '', - }; + parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', + parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '', - } + 'uniform mat4 modelMatrix;', + 'uniform mat4 modelViewMatrix;', + 'uniform mat4 projectionMatrix;', + 'uniform mat4 viewMatrix;', + 'uniform mat3 normalMatrix;', + 'uniform vec3 cameraPosition;', - // clean up + 'attribute vec3 position;', + 'attribute vec3 normal;', + 'attribute vec2 uv;', - gl.deleteShader( glVertexShader ); - gl.deleteShader( glFragmentShader ); + '#ifdef USE_COLOR', - // set up caching for uniform locations + ' attribute vec3 color;', - var cachedUniforms; + '#endif', - this.getUniforms = function() { + '#ifdef USE_MORPHTARGETS', - if ( cachedUniforms === undefined ) { + ' attribute vec3 morphTarget0;', + ' attribute vec3 morphTarget1;', + ' attribute vec3 morphTarget2;', + ' attribute vec3 morphTarget3;', - cachedUniforms = - new exports.WebGLUniforms( gl, program, renderer ); + ' #ifdef USE_MORPHNORMALS', - } + ' attribute vec3 morphNormal0;', + ' attribute vec3 morphNormal1;', + ' attribute vec3 morphNormal2;', + ' attribute vec3 morphNormal3;', - return cachedUniforms; + ' #else', - }; + ' attribute vec3 morphTarget4;', + ' attribute vec3 morphTarget5;', + ' attribute vec3 morphTarget6;', + ' attribute vec3 morphTarget7;', - // set up caching for attribute locations + ' #endif', - var cachedAttributes; + '#endif', - this.getAttributes = function() { + '#ifdef USE_SKINNING', - if ( cachedAttributes === undefined ) { + ' attribute vec4 skinIndex;', + ' attribute vec4 skinWeight;', - cachedAttributes = fetchAttributeLocations( gl, program ); + '#endif', - } + '\n' - return cachedAttributes; + ].filter( filterEmptyLine ).join( '\n' ); - }; + prefixFragment = [ - // free resource + customExtensions, - this.destroy = function() { + 'precision ' + parameters.precision + ' float;', + 'precision ' + parameters.precision + ' int;', - gl.deleteProgram( program ); - this.program = undefined; + '#define SHADER_NAME ' + material.__webglShader.name, - }; + customDefines, - // DEPRECATED + parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '', - Object.defineProperties( this, { + '#define GAMMA_FACTOR ' + gammaFactorDefine, - uniforms: { - get: function() { + ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '', + ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '', - console.warn( 'THREE.WebGLProgram: .uniforms is now .getUniforms().' ); - return this.getUniforms(); + parameters.map ? '#define USE_MAP' : '', + parameters.envMap ? '#define USE_ENVMAP' : '', + parameters.envMap ? '#define ' + envMapTypeDefine : '', + parameters.envMap ? '#define ' + envMapModeDefine : '', + parameters.envMap ? '#define ' + envMapBlendingDefine : '', + parameters.lightMap ? '#define USE_LIGHTMAP' : '', + parameters.aoMap ? '#define USE_AOMAP' : '', + parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', + parameters.bumpMap ? '#define USE_BUMPMAP' : '', + parameters.normalMap ? '#define USE_NORMALMAP' : '', + parameters.specularMap ? '#define USE_SPECULARMAP' : '', + parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', + parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', + parameters.alphaMap ? '#define USE_ALPHAMAP' : '', + parameters.vertexColors ? '#define USE_COLOR' : '', - } - }, + parameters.flatShading ? '#define FLAT_SHADED' : '', - attributes: { - get: function() { + parameters.doubleSided ? '#define DOUBLE_SIDED' : '', + parameters.flipSided ? '#define FLIP_SIDED' : '', - console.warn( 'THREE.WebGLProgram: .attributes is now .getAttributes().' ); - return this.getAttributes(); + '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes, - } - } + parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', + parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', - } ); + parameters.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : '', + parameters.physicallyCorrectLights ? "#define PHYSICALLY_CORRECT_LIGHTS" : '', - // + parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', + parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '', - this.id = programIdCount ++; - this.code = code; - this.usedTimes = 1; - this.program = program; - this.vertexShader = glVertexShader; - this.fragmentShader = glFragmentShader; + parameters.envMap && renderer.extensions.get( 'EXT_shader_texture_lod' ) ? '#define TEXTURE_LOD_EXT' : '', - return this; + 'uniform mat4 viewMatrix;', + 'uniform vec3 cameraPosition;', - }; + ( parameters.toneMapping !== NoToneMapping ) ? "#define TONE_MAPPING" : '', + ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below + ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( "toneMapping", parameters.toneMapping ) : '', - } )(); + ( parameters.outputEncoding || parameters.mapEncoding || parameters.envMapEncoding || parameters.emissiveMapEncoding ) ? ShaderChunk[ 'encodings_pars_fragment' ] : '', // this code is required here because it is used by the various encoding/decoding function defined below + parameters.mapEncoding ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '', + parameters.envMapEncoding ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '', + parameters.emissiveMapEncoding ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '', + parameters.outputEncoding ? getTexelEncodingFunction( "linearToOutputTexel", parameters.outputEncoding ) : '', - function WebGLPrograms( renderer, capabilities ) { + parameters.depthPacking ? "#define DEPTH_PACKING " + material.depthPacking : '', - var programs = []; + '\n' - var shaderIDs = { - MeshDepthMaterial: 'depth', - MeshNormalMaterial: 'normal', - MeshBasicMaterial: 'basic', - MeshLambertMaterial: 'lambert', - MeshPhongMaterial: 'phong', - MeshStandardMaterial: 'physical', - MeshPhysicalMaterial: 'physical', - LineBasicMaterial: 'basic', - LineDashedMaterial: 'dashed', - PointsMaterial: 'points' - }; + ].filter( filterEmptyLine ).join( '\n' ); - var parameterNames = [ - "precision", "supportsVertexTextures", "map", "mapEncoding", "envMap", "envMapMode", "envMapEncoding", - "lightMap", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "displacementMap", "specularMap", - "roughnessMap", "metalnessMap", - "alphaMap", "combine", "vertexColors", "fog", "useFog", "fogExp", - "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning", - "maxBones", "useVertexTexture", "morphTargets", "morphNormals", - "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha", - "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", - "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights', - "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "depthPacking" - ]; + } + vertexShader = parseIncludes( vertexShader, parameters ); + vertexShader = replaceLightNums( vertexShader, parameters ); - function allocateBones( object ) { + fragmentShader = parseIncludes( fragmentShader, parameters ); + fragmentShader = replaceLightNums( fragmentShader, parameters ); - if ( capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture ) { + if ( (material && material.isShaderMaterial) === false ) { - return 1024; + vertexShader = unrollLoops( vertexShader ); + fragmentShader = unrollLoops( fragmentShader ); - } else { + } - // default for when object is not specified - // ( for example when prebuilding shader to be used with multiple objects ) - // - // - leave some extra space for other uniforms - // - limit here is ANGLE's 254 max uniform vectors - // (up to 54 should be safe) + var vertexGlsl = prefixVertex + vertexShader; + var fragmentGlsl = prefixFragment + fragmentShader; - var nVertexUniforms = capabilities.maxVertexUniforms; - var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 ); + // console.log( '*VERTEX*', vertexGlsl ); + // console.log( '*FRAGMENT*', fragmentGlsl ); - var maxBones = nVertexMatrices; + var glVertexShader = exports.WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl ); + var glFragmentShader = exports.WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl ); - if ( object !== undefined && (object && object.isSkinnedMesh) ) { + gl.attachShader( program, glVertexShader ); + gl.attachShader( program, glFragmentShader ); - maxBones = Math.min( object.skeleton.bones.length, maxBones ); + // Force a particular attribute to index 0. - if ( maxBones < object.skeleton.bones.length ) { + if ( material.index0AttributeName !== undefined ) { - console.warn( 'WebGLRenderer: too many bones - ' + object.skeleton.bones.length + ', this GPU supports just ' + maxBones + ' (try OpenGL instead of ANGLE)' ); + gl.bindAttribLocation( program, 0, material.index0AttributeName ); - } + } else if ( parameters.morphTargets === true ) { - } + // programs with morphTargets displace position out of attribute 0 + gl.bindAttribLocation( program, 0, 'position' ); - return maxBones; + } - } + gl.linkProgram( program ); - } + var programLog = gl.getProgramInfoLog( program ); + var vertexLog = gl.getShaderInfoLog( glVertexShader ); + var fragmentLog = gl.getShaderInfoLog( glFragmentShader ); - function getTextureEncodingFromMap( map, gammaOverrideLinear ) { + var runnable = true; + var haveDiagnostics = true; - var encoding; + // console.log( '**VERTEX**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glVertexShader ) ); + // console.log( '**FRAGMENT**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glFragmentShader ) ); - if ( ! map ) { + if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) { - encoding = LinearEncoding; + runnable = false; - } else if ( (map && map.isTexture) ) { + console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter( program, gl.VALIDATE_STATUS ), 'gl.getProgramInfoLog', programLog, vertexLog, fragmentLog ); - encoding = map.encoding; + } else if ( programLog !== '' ) { - } else if ( (map && map.isWebGLRenderTarget) ) { + console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog ); - console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." ); - encoding = map.texture.encoding; + } else if ( vertexLog === '' || fragmentLog === '' ) { - } + haveDiagnostics = false; - // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point. - if ( encoding === LinearEncoding && gammaOverrideLinear ) { + } - encoding = GammaEncoding; + if ( haveDiagnostics ) { - } + this.diagnostics = { - return encoding; + runnable: runnable, + material: material, - } + programLog: programLog, - this.getParameters = function ( material, lights, fog, nClipPlanes, object ) { + vertexShader: { - var shaderID = shaderIDs[ material.type ]; + log: vertexLog, + prefix: prefixVertex - // heuristics to create shader parameters according to lights in the scene - // (not to blow over maxLights budget) + }, - var maxBones = allocateBones( object ); - var precision = renderer.getPrecision(); + fragmentShader: { - if ( material.precision !== null ) { + log: fragmentLog, + prefix: prefixFragment - precision = capabilities.getMaxPrecision( material.precision ); + } - if ( precision !== material.precision ) { + }; - console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' ); + } - } + // clean up - } + gl.deleteShader( glVertexShader ); + gl.deleteShader( glFragmentShader ); - var currentRenderTarget = renderer.getCurrentRenderTarget(); + // set up caching for uniform locations - var parameters = { + var cachedUniforms; - shaderID: shaderID, + this.getUniforms = function() { - precision: precision, - supportsVertexTextures: capabilities.vertexTextures, - outputEncoding: getTextureEncodingFromMap( ( ! currentRenderTarget ) ? null : currentRenderTarget.texture, renderer.gammaOutput ), - map: !! material.map, - mapEncoding: getTextureEncodingFromMap( material.map, renderer.gammaInput ), - envMap: !! material.envMap, - envMapMode: material.envMap && material.envMap.mapping, - envMapEncoding: getTextureEncodingFromMap( material.envMap, renderer.gammaInput ), - envMapCubeUV: ( !! material.envMap ) && ( ( material.envMap.mapping === CubeUVReflectionMapping ) || ( material.envMap.mapping === CubeUVRefractionMapping ) ), - lightMap: !! material.lightMap, - aoMap: !! material.aoMap, - emissiveMap: !! material.emissiveMap, - emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap, renderer.gammaInput ), - bumpMap: !! material.bumpMap, - normalMap: !! material.normalMap, - displacementMap: !! material.displacementMap, - roughnessMap: !! material.roughnessMap, - metalnessMap: !! material.metalnessMap, - specularMap: !! material.specularMap, - alphaMap: !! material.alphaMap, + if ( cachedUniforms === undefined ) { - combine: material.combine, + cachedUniforms = + new exports.WebGLUniforms( gl, program, renderer ); - vertexColors: material.vertexColors, + } - fog: !! fog, - useFog: material.fog, - fogExp: (fog && fog.isFogExp2), + return cachedUniforms; - flatShading: material.shading === FlatShading, + }; - sizeAttenuation: material.sizeAttenuation, - logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer, + // set up caching for attribute locations - skinning: material.skinning, - maxBones: maxBones, - useVertexTexture: capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture, + var cachedAttributes; - morphTargets: material.morphTargets, - morphNormals: material.morphNormals, - maxMorphTargets: renderer.maxMorphTargets, - maxMorphNormals: renderer.maxMorphNormals, + this.getAttributes = function() { - numDirLights: lights.directional.length, - numPointLights: lights.point.length, - numSpotLights: lights.spot.length, - numHemiLights: lights.hemi.length, + if ( cachedAttributes === undefined ) { - numClippingPlanes: nClipPlanes, + cachedAttributes = fetchAttributeLocations( gl, program ); - shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && lights.shadows.length > 0, - shadowMapType: renderer.shadowMap.type, + } - toneMapping: renderer.toneMapping, - physicallyCorrectLights: renderer.physicallyCorrectLights, + return cachedAttributes; - premultipliedAlpha: material.premultipliedAlpha, + }; - alphaTest: material.alphaTest, - doubleSided: material.side === DoubleSide, - flipSided: material.side === BackSide, + // free resource - depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false + this.destroy = function() { - }; + gl.deleteProgram( program ); + this.program = undefined; - return parameters; + }; - }; + // DEPRECATED - this.getProgramCode = function ( material, parameters ) { + Object.defineProperties( this, { - var array = []; + uniforms: { + get: function() { - if ( parameters.shaderID ) { + console.warn( 'THREE.WebGLProgram: .uniforms is now .getUniforms().' ); + return this.getUniforms(); - array.push( parameters.shaderID ); + } + }, - } else { + attributes: { + get: function() { - array.push( material.fragmentShader ); - array.push( material.vertexShader ); + console.warn( 'THREE.WebGLProgram: .attributes is now .getAttributes().' ); + return this.getAttributes(); - } + } + } - if ( material.defines !== undefined ) { + } ); - for ( var name in material.defines ) { - array.push( name ); - array.push( material.defines[ name ] ); + // - } + this.id = programIdCount ++; + this.code = code; + this.usedTimes = 1; + this.program = program; + this.vertexShader = glVertexShader; + this.fragmentShader = glFragmentShader; - } + return this; - for ( var i = 0; i < parameterNames.length; i ++ ) { + }; - array.push( parameters[ parameterNames[ i ] ] ); + } )(); - } + function WebGLPrograms( renderer, capabilities ) { - return array.join(); + var programs = []; - }; + var shaderIDs = { + MeshDepthMaterial: 'depth', + MeshNormalMaterial: 'normal', + MeshBasicMaterial: 'basic', + MeshLambertMaterial: 'lambert', + MeshPhongMaterial: 'phong', + MeshStandardMaterial: 'physical', + MeshPhysicalMaterial: 'physical', + LineBasicMaterial: 'basic', + LineDashedMaterial: 'dashed', + PointsMaterial: 'points' + }; - this.acquireProgram = function ( material, parameters, code ) { + var parameterNames = [ + "precision", "supportsVertexTextures", "map", "mapEncoding", "envMap", "envMapMode", "envMapEncoding", + "lightMap", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "displacementMap", "specularMap", + "roughnessMap", "metalnessMap", + "alphaMap", "combine", "vertexColors", "fog", "useFog", "fogExp", + "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning", + "maxBones", "useVertexTexture", "morphTargets", "morphNormals", + "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha", + "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", + "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights', + "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "depthPacking" + ]; - var program; - // Check if code has been already compiled - for ( var p = 0, pl = programs.length; p < pl; p ++ ) { + function allocateBones( object ) { - var programInfo = programs[ p ]; + if ( capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture ) { - if ( programInfo.code === code ) { + return 1024; - program = programInfo; - ++ program.usedTimes; + } else { - break; + // default for when object is not specified + // ( for example when prebuilding shader to be used with multiple objects ) + // + // - leave some extra space for other uniforms + // - limit here is ANGLE's 254 max uniform vectors + // (up to 54 should be safe) - } + var nVertexUniforms = capabilities.maxVertexUniforms; + var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 ); - } + var maxBones = nVertexMatrices; - if ( program === undefined ) { + if ( object !== undefined && (object && object.isSkinnedMesh) ) { - program = new exports.WebGLProgram( renderer, code, material, parameters ); - programs.push( program ); + maxBones = Math.min( object.skeleton.bones.length, maxBones ); - } + if ( maxBones < object.skeleton.bones.length ) { - return program; + console.warn( 'WebGLRenderer: too many bones - ' + object.skeleton.bones.length + ', this GPU supports just ' + maxBones + ' (try OpenGL instead of ANGLE)' ); - }; + } - this.releaseProgram = function( program ) { + } - if ( -- program.usedTimes === 0 ) { + return maxBones; - // Remove from unordered set - var i = programs.indexOf( program ); - programs[ i ] = programs[ programs.length - 1 ]; - programs.pop(); + } - // Free WebGL resources - program.destroy(); + } - } + function getTextureEncodingFromMap( map, gammaOverrideLinear ) { - }; + var encoding; - // Exposed for resource monitoring & error feedback via renderer.info: - this.programs = programs; + if ( ! map ) { - }; + encoding = LinearEncoding; - /** - * @author mrdoob / http://mrdoob.com/ - */ + } else if ( (map && map.isTexture) ) { - function BufferAttribute( array, itemSize, normalized ) { + encoding = map.encoding; - this.uuid = exports.Math.generateUUID(); + } else if ( (map && map.isWebGLRenderTarget) ) { - this.array = array; - this.itemSize = itemSize; + console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." ); + encoding = map.texture.encoding; - this.dynamic = false; - this.updateRange = { offset: 0, count: - 1 }; + } - this.version = 0; - this.normalized = normalized === true; + // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point. + if ( encoding === LinearEncoding && gammaOverrideLinear ) { - } + encoding = GammaEncoding; - BufferAttribute.prototype = { + } - constructor: BufferAttribute, + return encoding; - isBufferAttribute: true, + } - get count() { + this.getParameters = function ( material, lights, fog, nClipPlanes, object ) { - return this.array.length / this.itemSize; + var shaderID = shaderIDs[ material.type ]; - }, + // heuristics to create shader parameters according to lights in the scene + // (not to blow over maxLights budget) - set needsUpdate( value ) { + var maxBones = allocateBones( object ); + var precision = renderer.getPrecision(); - if ( value === true ) this.version ++; + if ( material.precision !== null ) { - }, + precision = capabilities.getMaxPrecision( material.precision ); - setDynamic: function ( value ) { + if ( precision !== material.precision ) { - this.dynamic = value; + console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' ); - return this; + } - }, + } - copy: function ( source ) { + var currentRenderTarget = renderer.getCurrentRenderTarget(); - this.array = new source.array.constructor( source.array ); - this.itemSize = source.itemSize; + var parameters = { - this.dynamic = source.dynamic; + shaderID: shaderID, - return this; + precision: precision, + supportsVertexTextures: capabilities.vertexTextures, + outputEncoding: getTextureEncodingFromMap( ( ! currentRenderTarget ) ? null : currentRenderTarget.texture, renderer.gammaOutput ), + map: !! material.map, + mapEncoding: getTextureEncodingFromMap( material.map, renderer.gammaInput ), + envMap: !! material.envMap, + envMapMode: material.envMap && material.envMap.mapping, + envMapEncoding: getTextureEncodingFromMap( material.envMap, renderer.gammaInput ), + envMapCubeUV: ( !! material.envMap ) && ( ( material.envMap.mapping === CubeUVReflectionMapping ) || ( material.envMap.mapping === CubeUVRefractionMapping ) ), + lightMap: !! material.lightMap, + aoMap: !! material.aoMap, + emissiveMap: !! material.emissiveMap, + emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap, renderer.gammaInput ), + bumpMap: !! material.bumpMap, + normalMap: !! material.normalMap, + displacementMap: !! material.displacementMap, + roughnessMap: !! material.roughnessMap, + metalnessMap: !! material.metalnessMap, + specularMap: !! material.specularMap, + alphaMap: !! material.alphaMap, - }, + combine: material.combine, - copyAt: function ( index1, attribute, index2 ) { + vertexColors: material.vertexColors, - index1 *= this.itemSize; - index2 *= attribute.itemSize; + fog: !! fog, + useFog: material.fog, + fogExp: (fog && fog.isFogExp2), - for ( var i = 0, l = this.itemSize; i < l; i ++ ) { + flatShading: material.shading === FlatShading, - this.array[ index1 + i ] = attribute.array[ index2 + i ]; + sizeAttenuation: material.sizeAttenuation, + logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer, - } + skinning: material.skinning, + maxBones: maxBones, + useVertexTexture: capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture, - return this; + morphTargets: material.morphTargets, + morphNormals: material.morphNormals, + maxMorphTargets: renderer.maxMorphTargets, + maxMorphNormals: renderer.maxMorphNormals, - }, + numDirLights: lights.directional.length, + numPointLights: lights.point.length, + numSpotLights: lights.spot.length, + numHemiLights: lights.hemi.length, - copyArray: function ( array ) { + numClippingPlanes: nClipPlanes, - this.array.set( array ); + shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && lights.shadows.length > 0, + shadowMapType: renderer.shadowMap.type, - return this; + toneMapping: renderer.toneMapping, + physicallyCorrectLights: renderer.physicallyCorrectLights, - }, + premultipliedAlpha: material.premultipliedAlpha, - copyColorsArray: function ( colors ) { + alphaTest: material.alphaTest, + doubleSided: material.side === DoubleSide, + flipSided: material.side === BackSide, - var array = this.array, offset = 0; + depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false - for ( var i = 0, l = colors.length; i < l; i ++ ) { + }; - var color = colors[ i ]; + return parameters; - if ( color === undefined ) { + }; - console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i ); - color = new Color(); + this.getProgramCode = function ( material, parameters ) { - } + var array = []; - array[ offset ++ ] = color.r; - array[ offset ++ ] = color.g; - array[ offset ++ ] = color.b; + if ( parameters.shaderID ) { - } + array.push( parameters.shaderID ); - return this; + } else { - }, + array.push( material.fragmentShader ); + array.push( material.vertexShader ); - copyIndicesArray: function ( indices ) { + } - var array = this.array, offset = 0; + if ( material.defines !== undefined ) { - for ( var i = 0, l = indices.length; i < l; i ++ ) { + for ( var name in material.defines ) { - var index = indices[ i ]; + array.push( name ); + array.push( material.defines[ name ] ); - array[ offset ++ ] = index.a; - array[ offset ++ ] = index.b; - array[ offset ++ ] = index.c; + } - } + } - return this; + for ( var i = 0; i < parameterNames.length; i ++ ) { - }, + array.push( parameters[ parameterNames[ i ] ] ); - copyVector2sArray: function ( vectors ) { + } - var array = this.array, offset = 0; + return array.join(); - for ( var i = 0, l = vectors.length; i < l; i ++ ) { + }; - var vector = vectors[ i ]; + this.acquireProgram = function ( material, parameters, code ) { - if ( vector === undefined ) { + var program; - console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i ); - vector = new Vector2(); + // Check if code has been already compiled + for ( var p = 0, pl = programs.length; p < pl; p ++ ) { - } + var programInfo = programs[ p ]; - array[ offset ++ ] = vector.x; - array[ offset ++ ] = vector.y; + if ( programInfo.code === code ) { - } + program = programInfo; + ++ program.usedTimes; - return this; + break; - }, + } - copyVector3sArray: function ( vectors ) { + } - var array = this.array, offset = 0; + if ( program === undefined ) { - for ( var i = 0, l = vectors.length; i < l; i ++ ) { + program = new exports.WebGLProgram( renderer, code, material, parameters ); + programs.push( program ); - var vector = vectors[ i ]; + } - if ( vector === undefined ) { + return program; - console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i ); - vector = new Vector3(); + }; - } + this.releaseProgram = function( program ) { - array[ offset ++ ] = vector.x; - array[ offset ++ ] = vector.y; - array[ offset ++ ] = vector.z; + if ( -- program.usedTimes === 0 ) { - } + // Remove from unordered set + var i = programs.indexOf( program ); + programs[ i ] = programs[ programs.length - 1 ]; + programs.pop(); - return this; + // Free WebGL resources + program.destroy(); - }, + } - copyVector4sArray: function ( vectors ) { + }; - var array = this.array, offset = 0; + // Exposed for resource monitoring & error feedback via renderer.info: + this.programs = programs; - for ( var i = 0, l = vectors.length; i < l; i ++ ) { + } - var vector = vectors[ i ]; + /** + * @author mrdoob / http://mrdoob.com/ + */ - if ( vector === undefined ) { + function BufferAttribute( array, itemSize, normalized ) { - console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i ); - vector = new Vector4(); + if ( Array.isArray( array ) ) { - } + throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' ); - array[ offset ++ ] = vector.x; - array[ offset ++ ] = vector.y; - array[ offset ++ ] = vector.z; - array[ offset ++ ] = vector.w; + } - } + this.uuid = exports.Math.generateUUID(); - return this; + this.array = array; + this.itemSize = itemSize; + this.normalized = normalized === true; - }, + this.dynamic = false; + this.updateRange = { offset: 0, count: - 1 }; - set: function ( value, offset ) { + this.version = 0; - if ( offset === undefined ) offset = 0; + } - this.array.set( value, offset ); + BufferAttribute.prototype = { - return this; + constructor: BufferAttribute, - }, + isBufferAttribute: true, - getX: function ( index ) { + get count() { - return this.array[ index * this.itemSize ]; + return this.array.length / this.itemSize; - }, + }, - setX: function ( index, x ) { + set needsUpdate( value ) { - this.array[ index * this.itemSize ] = x; + if ( value === true ) this.version ++; - return this; + }, - }, + setDynamic: function ( value ) { - getY: function ( index ) { + this.dynamic = value; - return this.array[ index * this.itemSize + 1 ]; + return this; - }, + }, - setY: function ( index, y ) { + copy: function ( source ) { - this.array[ index * this.itemSize + 1 ] = y; + this.array = new source.array.constructor( source.array ); + this.itemSize = source.itemSize; + this.normalized = source.normalized; - return this; + this.dynamic = source.dynamic; - }, + return this; - getZ: function ( index ) { + }, - return this.array[ index * this.itemSize + 2 ]; + copyAt: function ( index1, attribute, index2 ) { - }, + index1 *= this.itemSize; + index2 *= attribute.itemSize; - setZ: function ( index, z ) { + for ( var i = 0, l = this.itemSize; i < l; i ++ ) { - this.array[ index * this.itemSize + 2 ] = z; + this.array[ index1 + i ] = attribute.array[ index2 + i ]; - return this; + } - }, + return this; - getW: function ( index ) { + }, - return this.array[ index * this.itemSize + 3 ]; + copyArray: function ( array ) { - }, + this.array.set( array ); - setW: function ( index, w ) { + return this; - this.array[ index * this.itemSize + 3 ] = w; + }, - return this; + copyColorsArray: function ( colors ) { - }, + var array = this.array, offset = 0; - setXY: function ( index, x, y ) { + for ( var i = 0, l = colors.length; i < l; i ++ ) { - index *= this.itemSize; + var color = colors[ i ]; - this.array[ index + 0 ] = x; - this.array[ index + 1 ] = y; + if ( color === undefined ) { - return this; + console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i ); + color = new Color(); - }, + } - setXYZ: function ( index, x, y, z ) { + array[ offset ++ ] = color.r; + array[ offset ++ ] = color.g; + array[ offset ++ ] = color.b; - index *= this.itemSize; + } - this.array[ index + 0 ] = x; - this.array[ index + 1 ] = y; - this.array[ index + 2 ] = z; + return this; - return this; + }, - }, + copyIndicesArray: function ( indices ) { - setXYZW: function ( index, x, y, z, w ) { + var array = this.array, offset = 0; - index *= this.itemSize; + for ( var i = 0, l = indices.length; i < l; i ++ ) { - this.array[ index + 0 ] = x; - this.array[ index + 1 ] = y; - this.array[ index + 2 ] = z; - this.array[ index + 3 ] = w; + var index = indices[ i ]; - return this; + array[ offset ++ ] = index.a; + array[ offset ++ ] = index.b; + array[ offset ++ ] = index.c; - }, + } - clone: function () { + return this; - return new this.constructor().copy( this ); + }, - } + copyVector2sArray: function ( vectors ) { - }; + var array = this.array, offset = 0; - // + for ( var i = 0, l = vectors.length; i < l; i ++ ) { - function Int8Attribute( array, itemSize ) { + var vector = vectors[ i ]; - return new BufferAttribute( new Int8Array( array ), itemSize ); + if ( vector === undefined ) { - } + console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i ); + vector = new Vector2(); - function Uint8Attribute( array, itemSize ) { + } - return new BufferAttribute( new Uint8Array( array ), itemSize ); + array[ offset ++ ] = vector.x; + array[ offset ++ ] = vector.y; - } + } - function Uint8ClampedAttribute( array, itemSize ) { + return this; - return new BufferAttribute( new Uint8ClampedArray( array ), itemSize ); + }, - } + copyVector3sArray: function ( vectors ) { - function Int16Attribute( array, itemSize ) { + var array = this.array, offset = 0; - return new BufferAttribute( new Int16Array( array ), itemSize ); + for ( var i = 0, l = vectors.length; i < l; i ++ ) { - } + var vector = vectors[ i ]; - function Uint16Attribute( array, itemSize ) { + if ( vector === undefined ) { - return new BufferAttribute( new Uint16Array( array ), itemSize ); + console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i ); + vector = new Vector3(); - } + } - function Int32Attribute( array, itemSize ) { + array[ offset ++ ] = vector.x; + array[ offset ++ ] = vector.y; + array[ offset ++ ] = vector.z; - return new BufferAttribute( new Int32Array( array ), itemSize ); + } - } + return this; - function Uint32Attribute( array, itemSize ) { + }, - return new BufferAttribute( new Uint32Array( array ), itemSize ); + copyVector4sArray: function ( vectors ) { - } + var array = this.array, offset = 0; - function Float32Attribute( array, itemSize ) { + for ( var i = 0, l = vectors.length; i < l; i ++ ) { - return new BufferAttribute( new Float32Array( array ), itemSize ); + var vector = vectors[ i ]; - } + if ( vector === undefined ) { - function Float64Attribute( array, itemSize ) { + console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i ); + vector = new Vector4(); - return new BufferAttribute( new Float64Array( array ), itemSize ); + } - } + array[ offset ++ ] = vector.x; + array[ offset ++ ] = vector.y; + array[ offset ++ ] = vector.z; + array[ offset ++ ] = vector.w; - // Deprecated + } - function DynamicBufferAttribute( array, itemSize ) { + return this; - console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' ); - return new BufferAttribute( array, itemSize ).setDynamic( true ); + }, - } + set: function ( value, offset ) { - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + if ( offset === undefined ) offset = 0; - function Face3( a, b, c, normal, color, materialIndex ) { + this.array.set( value, offset ); - this.a = a; - this.b = b; - this.c = c; + return this; - this.normal = (normal && normal.isVector3) ? normal : new Vector3(); - this.vertexNormals = Array.isArray( normal ) ? normal : []; + }, - this.color = (color && color.isColor) ? color : new Color(); - this.vertexColors = Array.isArray( color ) ? color : []; + getX: function ( index ) { - this.materialIndex = materialIndex !== undefined ? materialIndex : 0; + return this.array[ index * this.itemSize ]; - }; + }, - Face3.prototype = { + setX: function ( index, x ) { - constructor: Face3, + this.array[ index * this.itemSize ] = x; - clone: function () { + return this; - return new this.constructor().copy( this ); + }, - }, + getY: function ( index ) { - copy: function ( source ) { + return this.array[ index * this.itemSize + 1 ]; - this.a = source.a; - this.b = source.b; - this.c = source.c; + }, - this.normal.copy( source.normal ); - this.color.copy( source.color ); + setY: function ( index, y ) { - this.materialIndex = source.materialIndex; + this.array[ index * this.itemSize + 1 ] = y; - for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) { + return this; - this.vertexNormals[ i ] = source.vertexNormals[ i ].clone(); + }, - } + getZ: function ( index ) { - for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) { + return this.array[ index * this.itemSize + 2 ]; - this.vertexColors[ i ] = source.vertexColors[ i ].clone(); + }, - } + setZ: function ( index, z ) { - return this; + this.array[ index * this.itemSize + 2 ] = z; - } + return this; - }; + }, - /** - * @author mrdoob / http://mrdoob.com/ - * @author WestLangley / http://github.com/WestLangley - * @author bhouston / http://clara.io - */ + getW: function ( index ) { - function Euler( x, y, z, order ) { + return this.array[ index * this.itemSize + 3 ]; - this._x = x || 0; - this._y = y || 0; - this._z = z || 0; - this._order = order || Euler.DefaultOrder; + }, - }; + setW: function ( index, w ) { - Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ]; + this.array[ index * this.itemSize + 3 ] = w; - Euler.DefaultOrder = 'XYZ'; + return this; - Euler.prototype = { + }, - constructor: Euler, + setXY: function ( index, x, y ) { - isEuler: true, + index *= this.itemSize; - get x () { + this.array[ index + 0 ] = x; + this.array[ index + 1 ] = y; - return this._x; + return this; - }, + }, - set x ( value ) { + setXYZ: function ( index, x, y, z ) { - this._x = value; - this.onChangeCallback(); + index *= this.itemSize; - }, + this.array[ index + 0 ] = x; + this.array[ index + 1 ] = y; + this.array[ index + 2 ] = z; - get y () { + return this; - return this._y; + }, - }, + setXYZW: function ( index, x, y, z, w ) { - set y ( value ) { + index *= this.itemSize; - this._y = value; - this.onChangeCallback(); + this.array[ index + 0 ] = x; + this.array[ index + 1 ] = y; + this.array[ index + 2 ] = z; + this.array[ index + 3 ] = w; - }, + return this; - get z () { + }, - return this._z; + clone: function () { - }, + return new this.constructor().copy( this ); - set z ( value ) { + } - this._z = value; - this.onChangeCallback(); + }; - }, + // - get order () { + function Int8Attribute( array, itemSize ) { - return this._order; + return new BufferAttribute( new Int8Array( array ), itemSize ); - }, + } - set order ( value ) { + function Uint8Attribute( array, itemSize ) { - this._order = value; - this.onChangeCallback(); + return new BufferAttribute( new Uint8Array( array ), itemSize ); - }, + } - set: function ( x, y, z, order ) { + function Uint8ClampedAttribute( array, itemSize ) { - this._x = x; - this._y = y; - this._z = z; - this._order = order || this._order; + return new BufferAttribute( new Uint8ClampedArray( array ), itemSize ); - this.onChangeCallback(); + } - return this; + function Int16Attribute( array, itemSize ) { - }, + return new BufferAttribute( new Int16Array( array ), itemSize ); - clone: function () { + } - return new this.constructor( this._x, this._y, this._z, this._order ); + function Uint16Attribute( array, itemSize ) { - }, + return new BufferAttribute( new Uint16Array( array ), itemSize ); - copy: function ( euler ) { + } - this._x = euler._x; - this._y = euler._y; - this._z = euler._z; - this._order = euler._order; + function Int32Attribute( array, itemSize ) { - this.onChangeCallback(); + return new BufferAttribute( new Int32Array( array ), itemSize ); - return this; + } - }, + function Uint32Attribute( array, itemSize ) { - setFromRotationMatrix: function ( m, order, update ) { + return new BufferAttribute( new Uint32Array( array ), itemSize ); - var clamp = exports.Math.clamp; + } - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + function Float32Attribute( array, itemSize ) { - var te = m.elements; - var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ]; - var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ]; - var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ]; + return new BufferAttribute( new Float32Array( array ), itemSize ); - order = order || this._order; + } - if ( order === 'XYZ' ) { + function Float64Attribute( array, itemSize ) { - this._y = Math.asin( clamp( m13, - 1, 1 ) ); + return new BufferAttribute( new Float64Array( array ), itemSize ); - if ( Math.abs( m13 ) < 0.99999 ) { + } - this._x = Math.atan2( - m23, m33 ); - this._z = Math.atan2( - m12, m11 ); + // Deprecated - } else { + function DynamicBufferAttribute( array, itemSize ) { - this._x = Math.atan2( m32, m22 ); - this._z = 0; + console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' ); + return new BufferAttribute( array, itemSize ).setDynamic( true ); - } + } - } else if ( order === 'YXZ' ) { + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - this._x = Math.asin( - clamp( m23, - 1, 1 ) ); + function Face3( a, b, c, normal, color, materialIndex ) { - if ( Math.abs( m23 ) < 0.99999 ) { + this.a = a; + this.b = b; + this.c = c; - this._y = Math.atan2( m13, m33 ); - this._z = Math.atan2( m21, m22 ); + this.normal = (normal && normal.isVector3) ? normal : new Vector3(); + this.vertexNormals = Array.isArray( normal ) ? normal : []; - } else { + this.color = (color && color.isColor) ? color : new Color(); + this.vertexColors = Array.isArray( color ) ? color : []; - this._y = Math.atan2( - m31, m11 ); - this._z = 0; + this.materialIndex = materialIndex !== undefined ? materialIndex : 0; - } + } - } else if ( order === 'ZXY' ) { + Face3.prototype = { - this._x = Math.asin( clamp( m32, - 1, 1 ) ); + constructor: Face3, - if ( Math.abs( m32 ) < 0.99999 ) { + clone: function () { - this._y = Math.atan2( - m31, m33 ); - this._z = Math.atan2( - m12, m22 ); + return new this.constructor().copy( this ); - } else { + }, - this._y = 0; - this._z = Math.atan2( m21, m11 ); + copy: function ( source ) { - } + this.a = source.a; + this.b = source.b; + this.c = source.c; - } else if ( order === 'ZYX' ) { + this.normal.copy( source.normal ); + this.color.copy( source.color ); - this._y = Math.asin( - clamp( m31, - 1, 1 ) ); + this.materialIndex = source.materialIndex; - if ( Math.abs( m31 ) < 0.99999 ) { + for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) { - this._x = Math.atan2( m32, m33 ); - this._z = Math.atan2( m21, m11 ); + this.vertexNormals[ i ] = source.vertexNormals[ i ].clone(); - } else { + } - this._x = 0; - this._z = Math.atan2( - m12, m22 ); + for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) { - } + this.vertexColors[ i ] = source.vertexColors[ i ].clone(); - } else if ( order === 'YZX' ) { + } - this._z = Math.asin( clamp( m21, - 1, 1 ) ); + return this; - if ( Math.abs( m21 ) < 0.99999 ) { + } - this._x = Math.atan2( - m23, m22 ); - this._y = Math.atan2( - m31, m11 ); + }; - } else { + /** + * @author mrdoob / http://mrdoob.com/ + * @author WestLangley / http://github.com/WestLangley + * @author bhouston / http://clara.io + */ - this._x = 0; - this._y = Math.atan2( m13, m33 ); + function Euler( x, y, z, order ) { - } + this._x = x || 0; + this._y = y || 0; + this._z = z || 0; + this._order = order || Euler.DefaultOrder; - } else if ( order === 'XZY' ) { + } - this._z = Math.asin( - clamp( m12, - 1, 1 ) ); + Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ]; - if ( Math.abs( m12 ) < 0.99999 ) { + Euler.DefaultOrder = 'XYZ'; - this._x = Math.atan2( m32, m22 ); - this._y = Math.atan2( m13, m11 ); + Euler.prototype = { - } else { + constructor: Euler, - this._x = Math.atan2( - m23, m33 ); - this._y = 0; + isEuler: true, - } + get x () { - } else { + return this._x; - console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order ); + }, - } + set x ( value ) { - this._order = order; + this._x = value; + this.onChangeCallback(); - if ( update !== false ) this.onChangeCallback(); + }, - return this; + get y () { - }, + return this._y; - setFromQuaternion: function () { + }, - var matrix; + set y ( value ) { - return function setFromQuaternion( q, order, update ) { + this._y = value; + this.onChangeCallback(); - if ( matrix === undefined ) matrix = new Matrix4(); + }, - matrix.makeRotationFromQuaternion( q ); + get z () { - return this.setFromRotationMatrix( matrix, order, update ); + return this._z; - }; + }, - }(), + set z ( value ) { - setFromVector3: function ( v, order ) { + this._z = value; + this.onChangeCallback(); - return this.set( v.x, v.y, v.z, order || this._order ); + }, - }, + get order () { - reorder: function () { + return this._order; - // WARNING: this discards revolution information -bhouston + }, - var q = new Quaternion(); + set order ( value ) { - return function reorder( newOrder ) { + this._order = value; + this.onChangeCallback(); - q.setFromEuler( this ); + }, - return this.setFromQuaternion( q, newOrder ); + set: function ( x, y, z, order ) { - }; + this._x = x; + this._y = y; + this._z = z; + this._order = order || this._order; - }(), + this.onChangeCallback(); - equals: function ( euler ) { + return this; - return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order ); + }, - }, + clone: function () { - fromArray: function ( array ) { + return new this.constructor( this._x, this._y, this._z, this._order ); - this._x = array[ 0 ]; - this._y = array[ 1 ]; - this._z = array[ 2 ]; - if ( array[ 3 ] !== undefined ) this._order = array[ 3 ]; + }, - this.onChangeCallback(); + copy: function ( euler ) { - return this; + this._x = euler._x; + this._y = euler._y; + this._z = euler._z; + this._order = euler._order; - }, + this.onChangeCallback(); - toArray: function ( array, offset ) { + return this; - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + }, - array[ offset ] = this._x; - array[ offset + 1 ] = this._y; - array[ offset + 2 ] = this._z; - array[ offset + 3 ] = this._order; + setFromRotationMatrix: function ( m, order, update ) { - return array; + var clamp = exports.Math.clamp; - }, + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - toVector3: function ( optionalResult ) { + var te = m.elements; + var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ]; + var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ]; + var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ]; - if ( optionalResult ) { + order = order || this._order; - return optionalResult.set( this._x, this._y, this._z ); + if ( order === 'XYZ' ) { - } else { + this._y = Math.asin( clamp( m13, - 1, 1 ) ); - return new Vector3( this._x, this._y, this._z ); + if ( Math.abs( m13 ) < 0.99999 ) { - } + this._x = Math.atan2( - m23, m33 ); + this._z = Math.atan2( - m12, m11 ); - }, + } else { - onChange: function ( callback ) { + this._x = Math.atan2( m32, m22 ); + this._z = 0; - this.onChangeCallback = callback; + } - return this; + } else if ( order === 'YXZ' ) { - }, + this._x = Math.asin( - clamp( m23, - 1, 1 ) ); - onChangeCallback: function () {} + if ( Math.abs( m23 ) < 0.99999 ) { - }; + this._y = Math.atan2( m13, m33 ); + this._z = Math.atan2( m21, m22 ); - /** - * @author mrdoob / http://mrdoob.com/ - */ + } else { - function Layers() { + this._y = Math.atan2( - m31, m11 ); + this._z = 0; - this.mask = 1; + } - }; + } else if ( order === 'ZXY' ) { - Layers.prototype = { + this._x = Math.asin( clamp( m32, - 1, 1 ) ); - constructor: Layers, + if ( Math.abs( m32 ) < 0.99999 ) { - set: function ( channel ) { + this._y = Math.atan2( - m31, m33 ); + this._z = Math.atan2( - m12, m22 ); - this.mask = 1 << channel; + } else { - }, + this._y = 0; + this._z = Math.atan2( m21, m11 ); - enable: function ( channel ) { + } - this.mask |= 1 << channel; + } else if ( order === 'ZYX' ) { - }, + this._y = Math.asin( - clamp( m31, - 1, 1 ) ); - toggle: function ( channel ) { + if ( Math.abs( m31 ) < 0.99999 ) { - this.mask ^= 1 << channel; + this._x = Math.atan2( m32, m33 ); + this._z = Math.atan2( m21, m11 ); - }, + } else { - disable: function ( channel ) { + this._x = 0; + this._z = Math.atan2( - m12, m22 ); - this.mask &= ~ ( 1 << channel ); + } - }, + } else if ( order === 'YZX' ) { - test: function ( layers ) { + this._z = Math.asin( clamp( m21, - 1, 1 ) ); - return ( this.mask & layers.mask ) !== 0; + if ( Math.abs( m21 ) < 0.99999 ) { - } + this._x = Math.atan2( - m23, m22 ); + this._y = Math.atan2( - m31, m11 ); - }; + } else { - /** - * @author mrdoob / http://mrdoob.com/ - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author WestLangley / http://github.com/WestLangley - * @author elephantatwork / www.elephantatwork.ch - */ + this._x = 0; + this._y = Math.atan2( m13, m33 ); - function Object3D() { + } - Object.defineProperty( this, 'id', { value: Object3DIdCount() } ); + } else if ( order === 'XZY' ) { - this.uuid = exports.Math.generateUUID(); + this._z = Math.asin( - clamp( m12, - 1, 1 ) ); - this.name = ''; - this.type = 'Object3D'; + if ( Math.abs( m12 ) < 0.99999 ) { - this.parent = null; - this.children = []; + this._x = Math.atan2( m32, m22 ); + this._y = Math.atan2( m13, m11 ); - this.up = Object3D.DefaultUp.clone(); + } else { - var position = new Vector3(); - var rotation = new Euler(); - var quaternion = new Quaternion(); - var scale = new Vector3( 1, 1, 1 ); + this._x = Math.atan2( - m23, m33 ); + this._y = 0; - function onRotationChange() { + } - quaternion.setFromEuler( rotation, false ); + } else { - } + console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order ); - function onQuaternionChange() { + } - rotation.setFromQuaternion( quaternion, undefined, false ); + this._order = order; - } + if ( update !== false ) this.onChangeCallback(); - rotation.onChange( onRotationChange ); - quaternion.onChange( onQuaternionChange ); + return this; - Object.defineProperties( this, { - position: { - enumerable: true, - value: position - }, - rotation: { - enumerable: true, - value: rotation - }, - quaternion: { - enumerable: true, - value: quaternion - }, - scale: { - enumerable: true, - value: scale - }, - modelViewMatrix: { - value: new Matrix4() - }, - normalMatrix: { - value: new Matrix3() - } - } ); + }, - this.matrix = new Matrix4(); - this.matrixWorld = new Matrix4(); + setFromQuaternion: function () { - this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate; - this.matrixWorldNeedsUpdate = false; + var matrix; - this.layers = new Layers(); - this.visible = true; + return function setFromQuaternion( q, order, update ) { - this.castShadow = false; - this.receiveShadow = false; + if ( matrix === undefined ) matrix = new Matrix4(); - this.frustumCulled = true; - this.renderOrder = 0; + matrix.makeRotationFromQuaternion( q ); - this.userData = {}; + return this.setFromRotationMatrix( matrix, order, update ); - }; + }; - Object3D.DefaultUp = new Vector3( 0, 1, 0 ); - Object3D.DefaultMatrixAutoUpdate = true; + }(), - Object.assign( Object3D.prototype, EventDispatcher.prototype, { + setFromVector3: function ( v, order ) { - isObject3D: true, + return this.set( v.x, v.y, v.z, order || this._order ); - applyMatrix: function ( matrix ) { + }, - this.matrix.multiplyMatrices( matrix, this.matrix ); + reorder: function () { - this.matrix.decompose( this.position, this.quaternion, this.scale ); + // WARNING: this discards revolution information -bhouston - }, + var q = new Quaternion(); - setRotationFromAxisAngle: function ( axis, angle ) { + return function reorder( newOrder ) { - // assumes axis is normalized + q.setFromEuler( this ); - this.quaternion.setFromAxisAngle( axis, angle ); + return this.setFromQuaternion( q, newOrder ); - }, + }; - setRotationFromEuler: function ( euler ) { + }(), - this.quaternion.setFromEuler( euler, true ); + equals: function ( euler ) { - }, + return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order ); - setRotationFromMatrix: function ( m ) { + }, - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + fromArray: function ( array ) { - this.quaternion.setFromRotationMatrix( m ); + this._x = array[ 0 ]; + this._y = array[ 1 ]; + this._z = array[ 2 ]; + if ( array[ 3 ] !== undefined ) this._order = array[ 3 ]; - }, + this.onChangeCallback(); - setRotationFromQuaternion: function ( q ) { + return this; - // assumes q is normalized + }, - this.quaternion.copy( q ); + toArray: function ( array, offset ) { - }, + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - rotateOnAxis: function () { + array[ offset ] = this._x; + array[ offset + 1 ] = this._y; + array[ offset + 2 ] = this._z; + array[ offset + 3 ] = this._order; - // rotate object on axis in object space - // axis is assumed to be normalized + return array; - var q1 = new Quaternion(); + }, - return function rotateOnAxis( axis, angle ) { + toVector3: function ( optionalResult ) { - q1.setFromAxisAngle( axis, angle ); + if ( optionalResult ) { - this.quaternion.multiply( q1 ); + return optionalResult.set( this._x, this._y, this._z ); - return this; + } else { - }; + return new Vector3( this._x, this._y, this._z ); - }(), + } - rotateX: function () { + }, - var v1 = new Vector3( 1, 0, 0 ); + onChange: function ( callback ) { - return function rotateX( angle ) { + this.onChangeCallback = callback; - return this.rotateOnAxis( v1, angle ); + return this; - }; + }, - }(), + onChangeCallback: function () {} - rotateY: function () { + }; - var v1 = new Vector3( 0, 1, 0 ); + /** + * @author mrdoob / http://mrdoob.com/ + */ - return function rotateY( angle ) { + function Layers() { - return this.rotateOnAxis( v1, angle ); + this.mask = 1; - }; + } - }(), + Layers.prototype = { - rotateZ: function () { + constructor: Layers, - var v1 = new Vector3( 0, 0, 1 ); + set: function ( channel ) { - return function rotateZ( angle ) { + this.mask = 1 << channel; - return this.rotateOnAxis( v1, angle ); + }, - }; + enable: function ( channel ) { - }(), + this.mask |= 1 << channel; - translateOnAxis: function () { + }, - // translate object by distance along axis in object space - // axis is assumed to be normalized + toggle: function ( channel ) { - var v1 = new Vector3(); + this.mask ^= 1 << channel; - return function translateOnAxis( axis, distance ) { + }, - v1.copy( axis ).applyQuaternion( this.quaternion ); + disable: function ( channel ) { - this.position.add( v1.multiplyScalar( distance ) ); + this.mask &= ~ ( 1 << channel ); - return this; + }, - }; + test: function ( layers ) { - }(), + return ( this.mask & layers.mask ) !== 0; - translateX: function () { + } - var v1 = new Vector3( 1, 0, 0 ); + }; - return function translateX( distance ) { + /** + * @author mrdoob / http://mrdoob.com/ + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + * @author WestLangley / http://github.com/WestLangley + * @author elephantatwork / www.elephantatwork.ch + */ - return this.translateOnAxis( v1, distance ); + function Object3D() { - }; + Object.defineProperty( this, 'id', { value: Object3DIdCount() } ); - }(), + this.uuid = exports.Math.generateUUID(); - translateY: function () { + this.name = ''; + this.type = 'Object3D'; - var v1 = new Vector3( 0, 1, 0 ); + this.parent = null; + this.children = []; - return function translateY( distance ) { + this.up = Object3D.DefaultUp.clone(); - return this.translateOnAxis( v1, distance ); + var position = new Vector3(); + var rotation = new Euler(); + var quaternion = new Quaternion(); + var scale = new Vector3( 1, 1, 1 ); - }; + function onRotationChange() { - }(), + quaternion.setFromEuler( rotation, false ); - translateZ: function () { + } - var v1 = new Vector3( 0, 0, 1 ); + function onQuaternionChange() { - return function translateZ( distance ) { + rotation.setFromQuaternion( quaternion, undefined, false ); - return this.translateOnAxis( v1, distance ); + } - }; + rotation.onChange( onRotationChange ); + quaternion.onChange( onQuaternionChange ); + + Object.defineProperties( this, { + position: { + enumerable: true, + value: position + }, + rotation: { + enumerable: true, + value: rotation + }, + quaternion: { + enumerable: true, + value: quaternion + }, + scale: { + enumerable: true, + value: scale + }, + modelViewMatrix: { + value: new Matrix4() + }, + normalMatrix: { + value: new Matrix3() + } + } ); - }(), + this.matrix = new Matrix4(); + this.matrixWorld = new Matrix4(); - localToWorld: function ( vector ) { + this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate; + this.matrixWorldNeedsUpdate = false; - return vector.applyMatrix4( this.matrixWorld ); + this.layers = new Layers(); + this.visible = true; - }, + this.castShadow = false; + this.receiveShadow = false; - worldToLocal: function () { + this.frustumCulled = true; + this.renderOrder = 0; - var m1 = new Matrix4(); + this.userData = {}; - return function worldToLocal( vector ) { + } - return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) ); + Object3D.DefaultUp = new Vector3( 0, 1, 0 ); + Object3D.DefaultMatrixAutoUpdate = true; - }; + Object.assign( Object3D.prototype, EventDispatcher.prototype, { - }(), + isObject3D: true, - lookAt: function () { + applyMatrix: function ( matrix ) { - // This routine does not support objects with rotated and/or translated parent(s) + this.matrix.multiplyMatrices( matrix, this.matrix ); - var m1 = new Matrix4(); + this.matrix.decompose( this.position, this.quaternion, this.scale ); - return function lookAt( vector ) { + }, - m1.lookAt( vector, this.position, this.up ); + setRotationFromAxisAngle: function ( axis, angle ) { - this.quaternion.setFromRotationMatrix( m1 ); + // assumes axis is normalized - }; + this.quaternion.setFromAxisAngle( axis, angle ); - }(), + }, - add: function ( object ) { + setRotationFromEuler: function ( euler ) { - if ( arguments.length > 1 ) { + this.quaternion.setFromEuler( euler, true ); - for ( var i = 0; i < arguments.length; i ++ ) { + }, - this.add( arguments[ i ] ); + setRotationFromMatrix: function ( m ) { - } + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - return this; + this.quaternion.setFromRotationMatrix( m ); - } + }, - if ( object === this ) { + setRotationFromQuaternion: function ( q ) { - console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object ); - return this; + // assumes q is normalized - } + this.quaternion.copy( q ); - if ( (object && object.isObject3D) ) { + }, - if ( object.parent !== null ) { + rotateOnAxis: function () { - object.parent.remove( object ); + // rotate object on axis in object space + // axis is assumed to be normalized - } + var q1 = new Quaternion(); - object.parent = this; - object.dispatchEvent( { type: 'added' } ); + return function rotateOnAxis( axis, angle ) { - this.children.push( object ); + q1.setFromAxisAngle( axis, angle ); - } else { + this.quaternion.multiply( q1 ); - console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object ); + return this; - } + }; - return this; + }(), - }, + rotateX: function () { - remove: function ( object ) { + var v1 = new Vector3( 1, 0, 0 ); - if ( arguments.length > 1 ) { + return function rotateX( angle ) { - for ( var i = 0; i < arguments.length; i ++ ) { + return this.rotateOnAxis( v1, angle ); - this.remove( arguments[ i ] ); + }; - } + }(), - } + rotateY: function () { - var index = this.children.indexOf( object ); + var v1 = new Vector3( 0, 1, 0 ); - if ( index !== - 1 ) { + return function rotateY( angle ) { - object.parent = null; + return this.rotateOnAxis( v1, angle ); - object.dispatchEvent( { type: 'removed' } ); + }; - this.children.splice( index, 1 ); + }(), - } + rotateZ: function () { - }, + var v1 = new Vector3( 0, 0, 1 ); - getObjectById: function ( id ) { + return function rotateZ( angle ) { - return this.getObjectByProperty( 'id', id ); + return this.rotateOnAxis( v1, angle ); - }, + }; - getObjectByName: function ( name ) { + }(), - return this.getObjectByProperty( 'name', name ); + translateOnAxis: function () { - }, + // translate object by distance along axis in object space + // axis is assumed to be normalized - getObjectByProperty: function ( name, value ) { + var v1 = new Vector3(); - if ( this[ name ] === value ) return this; + return function translateOnAxis( axis, distance ) { - for ( var i = 0, l = this.children.length; i < l; i ++ ) { + v1.copy( axis ).applyQuaternion( this.quaternion ); - var child = this.children[ i ]; - var object = child.getObjectByProperty( name, value ); + this.position.add( v1.multiplyScalar( distance ) ); - if ( object !== undefined ) { + return this; - return object; + }; - } + }(), - } + translateX: function () { - return undefined; + var v1 = new Vector3( 1, 0, 0 ); - }, + return function translateX( distance ) { - getWorldPosition: function ( optionalTarget ) { + return this.translateOnAxis( v1, distance ); - var result = optionalTarget || new Vector3(); + }; - this.updateMatrixWorld( true ); + }(), - return result.setFromMatrixPosition( this.matrixWorld ); + translateY: function () { - }, + var v1 = new Vector3( 0, 1, 0 ); - getWorldQuaternion: function () { + return function translateY( distance ) { - var position = new Vector3(); - var scale = new Vector3(); + return this.translateOnAxis( v1, distance ); - return function getWorldQuaternion( optionalTarget ) { + }; - var result = optionalTarget || new Quaternion(); + }(), - this.updateMatrixWorld( true ); + translateZ: function () { - this.matrixWorld.decompose( position, result, scale ); + var v1 = new Vector3( 0, 0, 1 ); - return result; + return function translateZ( distance ) { - }; + return this.translateOnAxis( v1, distance ); - }(), + }; - getWorldRotation: function () { + }(), - var quaternion = new Quaternion(); + localToWorld: function ( vector ) { - return function getWorldRotation( optionalTarget ) { + return vector.applyMatrix4( this.matrixWorld ); - var result = optionalTarget || new Euler(); + }, - this.getWorldQuaternion( quaternion ); + worldToLocal: function () { - return result.setFromQuaternion( quaternion, this.rotation.order, false ); + var m1 = new Matrix4(); - }; + return function worldToLocal( vector ) { - }(), + return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) ); - getWorldScale: function () { + }; - var position = new Vector3(); - var quaternion = new Quaternion(); + }(), - return function getWorldScale( optionalTarget ) { + lookAt: function () { - var result = optionalTarget || new Vector3(); + // This routine does not support objects with rotated and/or translated parent(s) - this.updateMatrixWorld( true ); + var m1 = new Matrix4(); - this.matrixWorld.decompose( position, quaternion, result ); + return function lookAt( vector ) { - return result; + m1.lookAt( vector, this.position, this.up ); - }; + this.quaternion.setFromRotationMatrix( m1 ); - }(), + }; - getWorldDirection: function () { + }(), - var quaternion = new Quaternion(); + add: function ( object ) { - return function getWorldDirection( optionalTarget ) { + if ( arguments.length > 1 ) { - var result = optionalTarget || new Vector3(); + for ( var i = 0; i < arguments.length; i ++ ) { - this.getWorldQuaternion( quaternion ); + this.add( arguments[ i ] ); - return result.set( 0, 0, 1 ).applyQuaternion( quaternion ); + } - }; + return this; - }(), + } - raycast: function () {}, + if ( object === this ) { - traverse: function ( callback ) { + console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object ); + return this; - callback( this ); + } - var children = this.children; + if ( (object && object.isObject3D) ) { - for ( var i = 0, l = children.length; i < l; i ++ ) { + if ( object.parent !== null ) { - children[ i ].traverse( callback ); + object.parent.remove( object ); - } + } - }, + object.parent = this; + object.dispatchEvent( { type: 'added' } ); - traverseVisible: function ( callback ) { + this.children.push( object ); - if ( this.visible === false ) return; + } else { - callback( this ); + console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object ); - var children = this.children; + } - for ( var i = 0, l = children.length; i < l; i ++ ) { + return this; - children[ i ].traverseVisible( callback ); + }, - } + remove: function ( object ) { - }, + if ( arguments.length > 1 ) { - traverseAncestors: function ( callback ) { + for ( var i = 0; i < arguments.length; i ++ ) { - var parent = this.parent; + this.remove( arguments[ i ] ); - if ( parent !== null ) { + } - callback( parent ); + } - parent.traverseAncestors( callback ); + var index = this.children.indexOf( object ); - } + if ( index !== - 1 ) { - }, + object.parent = null; - updateMatrix: function () { + object.dispatchEvent( { type: 'removed' } ); - this.matrix.compose( this.position, this.quaternion, this.scale ); + this.children.splice( index, 1 ); - this.matrixWorldNeedsUpdate = true; + } - }, + }, - updateMatrixWorld: function ( force ) { + getObjectById: function ( id ) { - if ( this.matrixAutoUpdate === true ) this.updateMatrix(); + return this.getObjectByProperty( 'id', id ); - if ( this.matrixWorldNeedsUpdate === true || force === true ) { + }, - if ( this.parent === null ) { + getObjectByName: function ( name ) { - this.matrixWorld.copy( this.matrix ); + return this.getObjectByProperty( 'name', name ); - } else { + }, - this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); + getObjectByProperty: function ( name, value ) { - } + if ( this[ name ] === value ) return this; - this.matrixWorldNeedsUpdate = false; + for ( var i = 0, l = this.children.length; i < l; i ++ ) { - force = true; + var child = this.children[ i ]; + var object = child.getObjectByProperty( name, value ); - } + if ( object !== undefined ) { - // update children + return object; - for ( var i = 0, l = this.children.length; i < l; i ++ ) { + } - this.children[ i ].updateMatrixWorld( force ); + } - } + return undefined; - }, + }, - toJSON: function ( meta ) { + getWorldPosition: function ( optionalTarget ) { - // meta is '' when called from JSON.stringify - var isRootObject = ( meta === undefined || meta === '' ); + var result = optionalTarget || new Vector3(); - var output = {}; + this.updateMatrixWorld( true ); - // meta is a hash used to collect geometries, materials. - // not providing it implies that this is the root object - // being serialized. - if ( isRootObject ) { + return result.setFromMatrixPosition( this.matrixWorld ); - // initialize meta obj - meta = { - geometries: {}, - materials: {}, - textures: {}, - images: {} - }; + }, - output.metadata = { - version: 4.4, - type: 'Object', - generator: 'Object3D.toJSON' - }; + getWorldQuaternion: function () { - } + var position = new Vector3(); + var scale = new Vector3(); - // standard Object3D serialization + return function getWorldQuaternion( optionalTarget ) { - var object = {}; + var result = optionalTarget || new Quaternion(); - object.uuid = this.uuid; - object.type = this.type; + this.updateMatrixWorld( true ); - if ( this.name !== '' ) object.name = this.name; - if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData; - if ( this.castShadow === true ) object.castShadow = true; - if ( this.receiveShadow === true ) object.receiveShadow = true; - if ( this.visible === false ) object.visible = false; + this.matrixWorld.decompose( position, result, scale ); - object.matrix = this.matrix.toArray(); + return result; - // + }; - if ( this.geometry !== undefined ) { + }(), - if ( meta.geometries[ this.geometry.uuid ] === undefined ) { + getWorldRotation: function () { - meta.geometries[ this.geometry.uuid ] = this.geometry.toJSON( meta ); + var quaternion = new Quaternion(); - } + return function getWorldRotation( optionalTarget ) { - object.geometry = this.geometry.uuid; + var result = optionalTarget || new Euler(); - } + this.getWorldQuaternion( quaternion ); - if ( this.material !== undefined ) { + return result.setFromQuaternion( quaternion, this.rotation.order, false ); - if ( meta.materials[ this.material.uuid ] === undefined ) { + }; - meta.materials[ this.material.uuid ] = this.material.toJSON( meta ); + }(), - } + getWorldScale: function () { - object.material = this.material.uuid; + var position = new Vector3(); + var quaternion = new Quaternion(); - } + return function getWorldScale( optionalTarget ) { - // + var result = optionalTarget || new Vector3(); - if ( this.children.length > 0 ) { + this.updateMatrixWorld( true ); - object.children = []; + this.matrixWorld.decompose( position, quaternion, result ); - for ( var i = 0; i < this.children.length; i ++ ) { + return result; - object.children.push( this.children[ i ].toJSON( meta ).object ); + }; - } + }(), - } + getWorldDirection: function () { - if ( isRootObject ) { + var quaternion = new Quaternion(); - var geometries = extractFromCache( meta.geometries ); - var materials = extractFromCache( meta.materials ); - var textures = extractFromCache( meta.textures ); - var images = extractFromCache( meta.images ); + return function getWorldDirection( optionalTarget ) { - if ( geometries.length > 0 ) output.geometries = geometries; - if ( materials.length > 0 ) output.materials = materials; - if ( textures.length > 0 ) output.textures = textures; - if ( images.length > 0 ) output.images = images; + var result = optionalTarget || new Vector3(); - } + this.getWorldQuaternion( quaternion ); - output.object = object; + return result.set( 0, 0, 1 ).applyQuaternion( quaternion ); - return output; + }; - // extract data from the cache hash - // remove metadata on each item - // and return as array - function extractFromCache( cache ) { + }(), - var values = []; - for ( var key in cache ) { + raycast: function () {}, - var data = cache[ key ]; - delete data.metadata; - values.push( data ); + traverse: function ( callback ) { - } - return values; + callback( this ); - } + var children = this.children; - }, + for ( var i = 0, l = children.length; i < l; i ++ ) { - clone: function ( recursive ) { + children[ i ].traverse( callback ); - return new this.constructor().copy( this, recursive ); + } - }, + }, - copy: function ( source, recursive ) { + traverseVisible: function ( callback ) { - if ( recursive === undefined ) recursive = true; + if ( this.visible === false ) return; - this.name = source.name; + callback( this ); - this.up.copy( source.up ); + var children = this.children; - this.position.copy( source.position ); - this.quaternion.copy( source.quaternion ); - this.scale.copy( source.scale ); + for ( var i = 0, l = children.length; i < l; i ++ ) { - this.matrix.copy( source.matrix ); - this.matrixWorld.copy( source.matrixWorld ); + children[ i ].traverseVisible( callback ); - this.matrixAutoUpdate = source.matrixAutoUpdate; - this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate; + } - this.visible = source.visible; + }, - this.castShadow = source.castShadow; - this.receiveShadow = source.receiveShadow; + traverseAncestors: function ( callback ) { - this.frustumCulled = source.frustumCulled; - this.renderOrder = source.renderOrder; + var parent = this.parent; - this.userData = JSON.parse( JSON.stringify( source.userData ) ); + if ( parent !== null ) { - if ( recursive === true ) { + callback( parent ); - for ( var i = 0; i < source.children.length; i ++ ) { + parent.traverseAncestors( callback ); - var child = source.children[ i ]; - this.add( child.clone() ); + } - } + }, - } + updateMatrix: function () { - return this; + this.matrix.compose( this.position, this.quaternion, this.scale ); - } + this.matrixWorldNeedsUpdate = true; - } ); + }, - var count$3 = 0; - function Object3DIdCount() { return count$3++; }; + updateMatrixWorld: function ( force ) { - /** - * @author mrdoob / http://mrdoob.com/ - * @author kile / http://kile.stravaganza.org/ - * @author alteredq / http://alteredqualia.com/ - * @author mikael emtinger / http://gomo.se/ - * @author zz85 / http://www.lab4games.net/zz85/blog - * @author bhouston / http://clara.io - */ + if ( this.matrixAutoUpdate === true ) this.updateMatrix(); - function Geometry() { + if ( this.matrixWorldNeedsUpdate === true || force === true ) { - Object.defineProperty( this, 'id', { value: GeometryIdCount() } ); + if ( this.parent === null ) { - this.uuid = exports.Math.generateUUID(); + this.matrixWorld.copy( this.matrix ); - this.name = ''; - this.type = 'Geometry'; + } else { - this.vertices = []; - this.colors = []; - this.faces = []; - this.faceVertexUvs = [ [] ]; + this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); - this.morphTargets = []; - this.morphNormals = []; + } - this.skinWeights = []; - this.skinIndices = []; + this.matrixWorldNeedsUpdate = false; - this.lineDistances = []; + force = true; - this.boundingBox = null; - this.boundingSphere = null; + } - // update flags + // update children - this.elementsNeedUpdate = false; - this.verticesNeedUpdate = false; - this.uvsNeedUpdate = false; - this.normalsNeedUpdate = false; - this.colorsNeedUpdate = false; - this.lineDistancesNeedUpdate = false; - this.groupsNeedUpdate = false; + var children = this.children; - }; + for ( var i = 0, l = children.length; i < l; i ++ ) { - Object.assign( Geometry.prototype, EventDispatcher.prototype, { + children[ i ].updateMatrixWorld( force ); - isGeometry: true, + } - applyMatrix: function ( matrix ) { + }, - var normalMatrix = new Matrix3().getNormalMatrix( matrix ); + toJSON: function ( meta ) { - for ( var i = 0, il = this.vertices.length; i < il; i ++ ) { + // meta is '' when called from JSON.stringify + var isRootObject = ( meta === undefined || meta === '' ); - var vertex = this.vertices[ i ]; - vertex.applyMatrix4( matrix ); + var output = {}; - } + // meta is a hash used to collect geometries, materials. + // not providing it implies that this is the root object + // being serialized. + if ( isRootObject ) { - for ( var i = 0, il = this.faces.length; i < il; i ++ ) { + // initialize meta obj + meta = { + geometries: {}, + materials: {}, + textures: {}, + images: {} + }; - var face = this.faces[ i ]; - face.normal.applyMatrix3( normalMatrix ).normalize(); + output.metadata = { + version: 4.4, + type: 'Object', + generator: 'Object3D.toJSON' + }; - for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) { + } - face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize(); + // standard Object3D serialization - } + var object = {}; - } + object.uuid = this.uuid; + object.type = this.type; - if ( this.boundingBox !== null ) { + if ( this.name !== '' ) object.name = this.name; + if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData; + if ( this.castShadow === true ) object.castShadow = true; + if ( this.receiveShadow === true ) object.receiveShadow = true; + if ( this.visible === false ) object.visible = false; - this.computeBoundingBox(); + object.matrix = this.matrix.toArray(); - } + // - if ( this.boundingSphere !== null ) { + if ( this.geometry !== undefined ) { - this.computeBoundingSphere(); + if ( meta.geometries[ this.geometry.uuid ] === undefined ) { - } + meta.geometries[ this.geometry.uuid ] = this.geometry.toJSON( meta ); - this.verticesNeedUpdate = true; - this.normalsNeedUpdate = true; + } - return this; + object.geometry = this.geometry.uuid; - }, + } - rotateX: function () { + if ( this.material !== undefined ) { - // rotate geometry around world x-axis + if ( meta.materials[ this.material.uuid ] === undefined ) { - var m1; + meta.materials[ this.material.uuid ] = this.material.toJSON( meta ); - return function rotateX( angle ) { + } - if ( m1 === undefined ) m1 = new Matrix4(); + object.material = this.material.uuid; - m1.makeRotationX( angle ); + } - this.applyMatrix( m1 ); + // - return this; + if ( this.children.length > 0 ) { - }; + object.children = []; - }(), + for ( var i = 0; i < this.children.length; i ++ ) { - rotateY: function () { + object.children.push( this.children[ i ].toJSON( meta ).object ); - // rotate geometry around world y-axis + } - var m1; + } - return function rotateY( angle ) { + if ( isRootObject ) { - if ( m1 === undefined ) m1 = new Matrix4(); + var geometries = extractFromCache( meta.geometries ); + var materials = extractFromCache( meta.materials ); + var textures = extractFromCache( meta.textures ); + var images = extractFromCache( meta.images ); - m1.makeRotationY( angle ); + if ( geometries.length > 0 ) output.geometries = geometries; + if ( materials.length > 0 ) output.materials = materials; + if ( textures.length > 0 ) output.textures = textures; + if ( images.length > 0 ) output.images = images; - this.applyMatrix( m1 ); + } - return this; + output.object = object; - }; + return output; - }(), + // extract data from the cache hash + // remove metadata on each item + // and return as array + function extractFromCache( cache ) { - rotateZ: function () { + var values = []; + for ( var key in cache ) { - // rotate geometry around world z-axis + var data = cache[ key ]; + delete data.metadata; + values.push( data ); - var m1; + } + return values; - return function rotateZ( angle ) { + } - if ( m1 === undefined ) m1 = new Matrix4(); + }, - m1.makeRotationZ( angle ); + clone: function ( recursive ) { - this.applyMatrix( m1 ); + return new this.constructor().copy( this, recursive ); - return this; + }, - }; + copy: function ( source, recursive ) { - }(), + if ( recursive === undefined ) recursive = true; - translate: function () { + this.name = source.name; - // translate geometry + this.up.copy( source.up ); - var m1; + this.position.copy( source.position ); + this.quaternion.copy( source.quaternion ); + this.scale.copy( source.scale ); - return function translate( x, y, z ) { + this.matrix.copy( source.matrix ); + this.matrixWorld.copy( source.matrixWorld ); - if ( m1 === undefined ) m1 = new Matrix4(); + this.matrixAutoUpdate = source.matrixAutoUpdate; + this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate; - m1.makeTranslation( x, y, z ); + this.visible = source.visible; - this.applyMatrix( m1 ); + this.castShadow = source.castShadow; + this.receiveShadow = source.receiveShadow; - return this; + this.frustumCulled = source.frustumCulled; + this.renderOrder = source.renderOrder; - }; + this.userData = JSON.parse( JSON.stringify( source.userData ) ); - }(), + if ( recursive === true ) { - scale: function () { + for ( var i = 0; i < source.children.length; i ++ ) { - // scale geometry + var child = source.children[ i ]; + this.add( child.clone() ); - var m1; + } - return function scale( x, y, z ) { + } - if ( m1 === undefined ) m1 = new Matrix4(); + return this; - m1.makeScale( x, y, z ); + } - this.applyMatrix( m1 ); + } ); - return this; + var count$3 = 0; + function Object3DIdCount() { return count$3++; }; - }; + /** + * @author mrdoob / http://mrdoob.com/ + * @author kile / http://kile.stravaganza.org/ + * @author alteredq / http://alteredqualia.com/ + * @author mikael emtinger / http://gomo.se/ + * @author zz85 / http://www.lab4games.net/zz85/blog + * @author bhouston / http://clara.io + */ - }(), + function Geometry() { - lookAt: function () { + Object.defineProperty( this, 'id', { value: GeometryIdCount() } ); - var obj; + this.uuid = exports.Math.generateUUID(); - return function lookAt( vector ) { + this.name = ''; + this.type = 'Geometry'; - if ( obj === undefined ) obj = new Object3D(); + this.vertices = []; + this.colors = []; + this.faces = []; + this.faceVertexUvs = [ [] ]; - obj.lookAt( vector ); + this.morphTargets = []; + this.morphNormals = []; - obj.updateMatrix(); + this.skinWeights = []; + this.skinIndices = []; - this.applyMatrix( obj.matrix ); + this.lineDistances = []; - }; + this.boundingBox = null; + this.boundingSphere = null; - }(), + // update flags - fromBufferGeometry: function ( geometry ) { + this.elementsNeedUpdate = false; + this.verticesNeedUpdate = false; + this.uvsNeedUpdate = false; + this.normalsNeedUpdate = false; + this.colorsNeedUpdate = false; + this.lineDistancesNeedUpdate = false; + this.groupsNeedUpdate = false; - var scope = this; + } - var indices = geometry.index !== null ? geometry.index.array : undefined; - var attributes = geometry.attributes; + Object.assign( Geometry.prototype, EventDispatcher.prototype, { - var positions = attributes.position.array; - var normals = attributes.normal !== undefined ? attributes.normal.array : undefined; - var colors = attributes.color !== undefined ? attributes.color.array : undefined; - var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined; - var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined; + isGeometry: true, - if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = []; + applyMatrix: function ( matrix ) { - var tempNormals = []; - var tempUVs = []; - var tempUVs2 = []; + var normalMatrix = new Matrix3().getNormalMatrix( matrix ); - for ( var i = 0, j = 0; i < positions.length; i += 3, j += 2 ) { + for ( var i = 0, il = this.vertices.length; i < il; i ++ ) { - scope.vertices.push( new Vector3( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ) ); + var vertex = this.vertices[ i ]; + vertex.applyMatrix4( matrix ); - if ( normals !== undefined ) { + } - tempNormals.push( new Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) ); + for ( var i = 0, il = this.faces.length; i < il; i ++ ) { - } + var face = this.faces[ i ]; + face.normal.applyMatrix3( normalMatrix ).normalize(); - if ( colors !== undefined ) { + for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) { - scope.colors.push( new Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) ); + face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize(); - } + } - if ( uvs !== undefined ) { + } - tempUVs.push( new Vector2( uvs[ j ], uvs[ j + 1 ] ) ); + if ( this.boundingBox !== null ) { - } + this.computeBoundingBox(); - if ( uvs2 !== undefined ) { + } - tempUVs2.push( new Vector2( uvs2[ j ], uvs2[ j + 1 ] ) ); + if ( this.boundingSphere !== null ) { - } + this.computeBoundingSphere(); - } + } - function addFace( a, b, c, materialIndex ) { + this.verticesNeedUpdate = true; + this.normalsNeedUpdate = true; - var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : []; - var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : []; + return this; - var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex ); + }, - scope.faces.push( face ); + rotateX: function () { - if ( uvs !== undefined ) { + // rotate geometry around world x-axis - scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] ); + var m1; - } + return function rotateX( angle ) { - if ( uvs2 !== undefined ) { + if ( m1 === undefined ) m1 = new Matrix4(); - scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] ); + m1.makeRotationX( angle ); - } + this.applyMatrix( m1 ); - } + return this; - if ( indices !== undefined ) { + }; - var groups = geometry.groups; + }(), - if ( groups.length > 0 ) { + rotateY: function () { - for ( var i = 0; i < groups.length; i ++ ) { + // rotate geometry around world y-axis - var group = groups[ i ]; + var m1; - var start = group.start; - var count = group.count; + return function rotateY( angle ) { - for ( var j = start, jl = start + count; j < jl; j += 3 ) { + if ( m1 === undefined ) m1 = new Matrix4(); - addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex ); + m1.makeRotationY( angle ); - } + this.applyMatrix( m1 ); - } + return this; - } else { + }; - for ( var i = 0; i < indices.length; i += 3 ) { + }(), - addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] ); + rotateZ: function () { - } + // rotate geometry around world z-axis - } + var m1; - } else { + return function rotateZ( angle ) { - for ( var i = 0; i < positions.length / 3; i += 3 ) { + if ( m1 === undefined ) m1 = new Matrix4(); - addFace( i, i + 1, i + 2 ); + m1.makeRotationZ( angle ); - } + this.applyMatrix( m1 ); - } + return this; - this.computeFaceNormals(); + }; - if ( geometry.boundingBox !== null ) { + }(), - this.boundingBox = geometry.boundingBox.clone(); + translate: function () { - } + // translate geometry - if ( geometry.boundingSphere !== null ) { + var m1; - this.boundingSphere = geometry.boundingSphere.clone(); + return function translate( x, y, z ) { - } + if ( m1 === undefined ) m1 = new Matrix4(); - return this; + m1.makeTranslation( x, y, z ); - }, + this.applyMatrix( m1 ); - center: function () { + return this; - this.computeBoundingBox(); + }; - var offset = this.boundingBox.center().negate(); + }(), - this.translate( offset.x, offset.y, offset.z ); + scale: function () { - return offset; + // scale geometry - }, + var m1; - normalize: function () { + return function scale( x, y, z ) { - this.computeBoundingSphere(); + if ( m1 === undefined ) m1 = new Matrix4(); - var center = this.boundingSphere.center; - var radius = this.boundingSphere.radius; + m1.makeScale( x, y, z ); - var s = radius === 0 ? 1 : 1.0 / radius; + this.applyMatrix( m1 ); - var matrix = new Matrix4(); - matrix.set( - s, 0, 0, - s * center.x, - 0, s, 0, - s * center.y, - 0, 0, s, - s * center.z, - 0, 0, 0, 1 - ); + return this; - this.applyMatrix( matrix ); + }; - return this; + }(), - }, + lookAt: function () { - computeFaceNormals: function () { + var obj; - var cb = new Vector3(), ab = new Vector3(); + return function lookAt( vector ) { - for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) { + if ( obj === undefined ) obj = new Object3D(); - var face = this.faces[ f ]; + obj.lookAt( vector ); - var vA = this.vertices[ face.a ]; - var vB = this.vertices[ face.b ]; - var vC = this.vertices[ face.c ]; + obj.updateMatrix(); - cb.subVectors( vC, vB ); - ab.subVectors( vA, vB ); - cb.cross( ab ); + this.applyMatrix( obj.matrix ); - cb.normalize(); + }; - face.normal.copy( cb ); + }(), - } + fromBufferGeometry: function ( geometry ) { - }, + var scope = this; - computeVertexNormals: function ( areaWeighted ) { + var indices = geometry.index !== null ? geometry.index.array : undefined; + var attributes = geometry.attributes; - if ( areaWeighted === undefined ) areaWeighted = true; + var positions = attributes.position.array; + var normals = attributes.normal !== undefined ? attributes.normal.array : undefined; + var colors = attributes.color !== undefined ? attributes.color.array : undefined; + var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined; + var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined; - var v, vl, f, fl, face, vertices; + if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = []; - vertices = new Array( this.vertices.length ); + var tempNormals = []; + var tempUVs = []; + var tempUVs2 = []; - for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) { + for ( var i = 0, j = 0; i < positions.length; i += 3, j += 2 ) { - vertices[ v ] = new Vector3(); + scope.vertices.push( new Vector3( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ) ); - } + if ( normals !== undefined ) { - if ( areaWeighted ) { + tempNormals.push( new Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) ); - // vertex normals weighted by triangle areas - // http://www.iquilezles.org/www/articles/normals/normals.htm + } - var vA, vB, vC; - var cb = new Vector3(), ab = new Vector3(); + if ( colors !== undefined ) { - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + scope.colors.push( new Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) ); - face = this.faces[ f ]; + } - vA = this.vertices[ face.a ]; - vB = this.vertices[ face.b ]; - vC = this.vertices[ face.c ]; + if ( uvs !== undefined ) { - cb.subVectors( vC, vB ); - ab.subVectors( vA, vB ); - cb.cross( ab ); + tempUVs.push( new Vector2( uvs[ j ], uvs[ j + 1 ] ) ); - vertices[ face.a ].add( cb ); - vertices[ face.b ].add( cb ); - vertices[ face.c ].add( cb ); + } - } + if ( uvs2 !== undefined ) { - } else { + tempUVs2.push( new Vector2( uvs2[ j ], uvs2[ j + 1 ] ) ); - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + } - face = this.faces[ f ]; + } - vertices[ face.a ].add( face.normal ); - vertices[ face.b ].add( face.normal ); - vertices[ face.c ].add( face.normal ); + function addFace( a, b, c, materialIndex ) { - } + var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : []; + var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : []; - } + var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex ); - for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) { + scope.faces.push( face ); - vertices[ v ].normalize(); + if ( uvs !== undefined ) { - } + scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] ); - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + } - face = this.faces[ f ]; + if ( uvs2 !== undefined ) { - var vertexNormals = face.vertexNormals; + scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] ); - if ( vertexNormals.length === 3 ) { + } - vertexNormals[ 0 ].copy( vertices[ face.a ] ); - vertexNormals[ 1 ].copy( vertices[ face.b ] ); - vertexNormals[ 2 ].copy( vertices[ face.c ] ); + } - } else { + if ( indices !== undefined ) { - vertexNormals[ 0 ] = vertices[ face.a ].clone(); - vertexNormals[ 1 ] = vertices[ face.b ].clone(); - vertexNormals[ 2 ] = vertices[ face.c ].clone(); + var groups = geometry.groups; - } + if ( groups.length > 0 ) { - } + for ( var i = 0; i < groups.length; i ++ ) { - if ( this.faces.length > 0 ) { + var group = groups[ i ]; - this.normalsNeedUpdate = true; + var start = group.start; + var count = group.count; - } + for ( var j = start, jl = start + count; j < jl; j += 3 ) { - }, + addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex ); - computeMorphNormals: function () { + } - var i, il, f, fl, face; + } - // save original normals - // - create temp variables on first access - // otherwise just copy (for faster repeated calls) + } else { - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + for ( var i = 0; i < indices.length; i += 3 ) { - face = this.faces[ f ]; + addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] ); - if ( ! face.__originalFaceNormal ) { + } - face.__originalFaceNormal = face.normal.clone(); + } - } else { + } else { - face.__originalFaceNormal.copy( face.normal ); + for ( var i = 0; i < positions.length / 3; i += 3 ) { - } + addFace( i, i + 1, i + 2 ); - if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = []; + } - for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) { + } - if ( ! face.__originalVertexNormals[ i ] ) { + this.computeFaceNormals(); - face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone(); + if ( geometry.boundingBox !== null ) { - } else { + this.boundingBox = geometry.boundingBox.clone(); - face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] ); + } - } + if ( geometry.boundingSphere !== null ) { - } + this.boundingSphere = geometry.boundingSphere.clone(); - } + } - // use temp geometry to compute face and vertex normals for each morph + return this; - var tmpGeo = new Geometry(); - tmpGeo.faces = this.faces; + }, - for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) { + center: function () { - // create on first access + this.computeBoundingBox(); - if ( ! this.morphNormals[ i ] ) { + var offset = this.boundingBox.center().negate(); - this.morphNormals[ i ] = {}; - this.morphNormals[ i ].faceNormals = []; - this.morphNormals[ i ].vertexNormals = []; + this.translate( offset.x, offset.y, offset.z ); - var dstNormalsFace = this.morphNormals[ i ].faceNormals; - var dstNormalsVertex = this.morphNormals[ i ].vertexNormals; + return offset; - var faceNormal, vertexNormals; + }, - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + normalize: function () { - faceNormal = new Vector3(); - vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() }; + this.computeBoundingSphere(); - dstNormalsFace.push( faceNormal ); - dstNormalsVertex.push( vertexNormals ); + var center = this.boundingSphere.center; + var radius = this.boundingSphere.radius; - } + var s = radius === 0 ? 1 : 1.0 / radius; - } + var matrix = new Matrix4(); + matrix.set( + s, 0, 0, - s * center.x, + 0, s, 0, - s * center.y, + 0, 0, s, - s * center.z, + 0, 0, 0, 1 + ); - var morphNormals = this.morphNormals[ i ]; + this.applyMatrix( matrix ); - // set vertices to morph target + return this; - tmpGeo.vertices = this.morphTargets[ i ].vertices; + }, - // compute morph normals + computeFaceNormals: function () { - tmpGeo.computeFaceNormals(); - tmpGeo.computeVertexNormals(); + var cb = new Vector3(), ab = new Vector3(); - // store morph normals + for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) { - var faceNormal, vertexNormals; + var face = this.faces[ f ]; - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + var vA = this.vertices[ face.a ]; + var vB = this.vertices[ face.b ]; + var vC = this.vertices[ face.c ]; - face = this.faces[ f ]; + cb.subVectors( vC, vB ); + ab.subVectors( vA, vB ); + cb.cross( ab ); - faceNormal = morphNormals.faceNormals[ f ]; - vertexNormals = morphNormals.vertexNormals[ f ]; + cb.normalize(); - faceNormal.copy( face.normal ); + face.normal.copy( cb ); - vertexNormals.a.copy( face.vertexNormals[ 0 ] ); - vertexNormals.b.copy( face.vertexNormals[ 1 ] ); - vertexNormals.c.copy( face.vertexNormals[ 2 ] ); + } - } + }, - } + computeVertexNormals: function ( areaWeighted ) { - // restore original normals + if ( areaWeighted === undefined ) areaWeighted = true; - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + var v, vl, f, fl, face, vertices; - face = this.faces[ f ]; + vertices = new Array( this.vertices.length ); - face.normal = face.__originalFaceNormal; - face.vertexNormals = face.__originalVertexNormals; + for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) { - } + vertices[ v ] = new Vector3(); - }, + } - computeTangents: function () { + if ( areaWeighted ) { - console.warn( 'THREE.Geometry: .computeTangents() has been removed.' ); + // vertex normals weighted by triangle areas + // http://www.iquilezles.org/www/articles/normals/normals.htm - }, + var vA, vB, vC; + var cb = new Vector3(), ab = new Vector3(); - computeLineDistances: function () { + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - var d = 0; - var vertices = this.vertices; + face = this.faces[ f ]; - for ( var i = 0, il = vertices.length; i < il; i ++ ) { + vA = this.vertices[ face.a ]; + vB = this.vertices[ face.b ]; + vC = this.vertices[ face.c ]; - if ( i > 0 ) { + cb.subVectors( vC, vB ); + ab.subVectors( vA, vB ); + cb.cross( ab ); - d += vertices[ i ].distanceTo( vertices[ i - 1 ] ); + vertices[ face.a ].add( cb ); + vertices[ face.b ].add( cb ); + vertices[ face.c ].add( cb ); - } + } - this.lineDistances[ i ] = d; + } else { - } + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - }, + face = this.faces[ f ]; - computeBoundingBox: function () { + vertices[ face.a ].add( face.normal ); + vertices[ face.b ].add( face.normal ); + vertices[ face.c ].add( face.normal ); - if ( this.boundingBox === null ) { + } - this.boundingBox = new Box3(); + } - } + for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) { - this.boundingBox.setFromPoints( this.vertices ); + vertices[ v ].normalize(); - }, + } - computeBoundingSphere: function () { + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - if ( this.boundingSphere === null ) { + face = this.faces[ f ]; - this.boundingSphere = new Sphere(); + var vertexNormals = face.vertexNormals; - } + if ( vertexNormals.length === 3 ) { - this.boundingSphere.setFromPoints( this.vertices ); + vertexNormals[ 0 ].copy( vertices[ face.a ] ); + vertexNormals[ 1 ].copy( vertices[ face.b ] ); + vertexNormals[ 2 ].copy( vertices[ face.c ] ); - }, + } else { - merge: function ( geometry, matrix, materialIndexOffset ) { + vertexNormals[ 0 ] = vertices[ face.a ].clone(); + vertexNormals[ 1 ] = vertices[ face.b ].clone(); + vertexNormals[ 2 ] = vertices[ face.c ].clone(); - if ( (geometry && geometry.isGeometry) === false ) { + } - console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry ); - return; + } - } + if ( this.faces.length > 0 ) { - var normalMatrix, - vertexOffset = this.vertices.length, - vertices1 = this.vertices, - vertices2 = geometry.vertices, - faces1 = this.faces, - faces2 = geometry.faces, - uvs1 = this.faceVertexUvs[ 0 ], - uvs2 = geometry.faceVertexUvs[ 0 ]; + this.normalsNeedUpdate = true; - if ( materialIndexOffset === undefined ) materialIndexOffset = 0; + } - if ( matrix !== undefined ) { + }, - normalMatrix = new Matrix3().getNormalMatrix( matrix ); + computeMorphNormals: function () { - } + var i, il, f, fl, face; - // vertices + // save original normals + // - create temp variables on first access + // otherwise just copy (for faster repeated calls) - for ( var i = 0, il = vertices2.length; i < il; i ++ ) { + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - var vertex = vertices2[ i ]; + face = this.faces[ f ]; - var vertexCopy = vertex.clone(); + if ( ! face.__originalFaceNormal ) { - if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix ); + face.__originalFaceNormal = face.normal.clone(); - vertices1.push( vertexCopy ); + } else { - } + face.__originalFaceNormal.copy( face.normal ); - // faces + } - for ( i = 0, il = faces2.length; i < il; i ++ ) { + if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = []; - var face = faces2[ i ], faceCopy, normal, color, - faceVertexNormals = face.vertexNormals, - faceVertexColors = face.vertexColors; + for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) { - faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset ); - faceCopy.normal.copy( face.normal ); + if ( ! face.__originalVertexNormals[ i ] ) { - if ( normalMatrix !== undefined ) { + face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone(); - faceCopy.normal.applyMatrix3( normalMatrix ).normalize(); + } else { - } + face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] ); - for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) { + } - normal = faceVertexNormals[ j ].clone(); + } - if ( normalMatrix !== undefined ) { + } - normal.applyMatrix3( normalMatrix ).normalize(); + // use temp geometry to compute face and vertex normals for each morph - } + var tmpGeo = new Geometry(); + tmpGeo.faces = this.faces; - faceCopy.vertexNormals.push( normal ); + for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) { - } + // create on first access - faceCopy.color.copy( face.color ); + if ( ! this.morphNormals[ i ] ) { - for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) { + this.morphNormals[ i ] = {}; + this.morphNormals[ i ].faceNormals = []; + this.morphNormals[ i ].vertexNormals = []; - color = faceVertexColors[ j ]; - faceCopy.vertexColors.push( color.clone() ); + var dstNormalsFace = this.morphNormals[ i ].faceNormals; + var dstNormalsVertex = this.morphNormals[ i ].vertexNormals; - } + var faceNormal, vertexNormals; - faceCopy.materialIndex = face.materialIndex + materialIndexOffset; + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - faces1.push( faceCopy ); + faceNormal = new Vector3(); + vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() }; - } + dstNormalsFace.push( faceNormal ); + dstNormalsVertex.push( vertexNormals ); - // uvs + } - for ( i = 0, il = uvs2.length; i < il; i ++ ) { + } - var uv = uvs2[ i ], uvCopy = []; + var morphNormals = this.morphNormals[ i ]; - if ( uv === undefined ) { + // set vertices to morph target - continue; + tmpGeo.vertices = this.morphTargets[ i ].vertices; - } + // compute morph normals - for ( var j = 0, jl = uv.length; j < jl; j ++ ) { + tmpGeo.computeFaceNormals(); + tmpGeo.computeVertexNormals(); - uvCopy.push( uv[ j ].clone() ); + // store morph normals - } + var faceNormal, vertexNormals; - uvs1.push( uvCopy ); + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - } + face = this.faces[ f ]; - }, + faceNormal = morphNormals.faceNormals[ f ]; + vertexNormals = morphNormals.vertexNormals[ f ]; - mergeMesh: function ( mesh ) { + faceNormal.copy( face.normal ); - if ( (mesh && mesh.isMesh) === false ) { + vertexNormals.a.copy( face.vertexNormals[ 0 ] ); + vertexNormals.b.copy( face.vertexNormals[ 1 ] ); + vertexNormals.c.copy( face.vertexNormals[ 2 ] ); - console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh ); - return; + } - } + } - mesh.matrixAutoUpdate && mesh.updateMatrix(); + // restore original normals - this.merge( mesh.geometry, mesh.matrix ); + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - }, + face = this.faces[ f ]; - /* - * Checks for duplicate vertices with hashmap. - * Duplicated vertices are removed - * and faces' vertices are updated. - */ + face.normal = face.__originalFaceNormal; + face.vertexNormals = face.__originalVertexNormals; - mergeVertices: function () { + } - var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique) - var unique = [], changes = []; + }, - var v, key; - var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001 - var precision = Math.pow( 10, precisionPoints ); - var i, il, face; - var indices, j, jl; + computeTangents: function () { - for ( i = 0, il = this.vertices.length; i < il; i ++ ) { + console.warn( 'THREE.Geometry: .computeTangents() has been removed.' ); - v = this.vertices[ i ]; - key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision ); + }, - if ( verticesMap[ key ] === undefined ) { + computeLineDistances: function () { - verticesMap[ key ] = i; - unique.push( this.vertices[ i ] ); - changes[ i ] = unique.length - 1; + var d = 0; + var vertices = this.vertices; - } else { + for ( var i = 0, il = vertices.length; i < il; i ++ ) { - //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]); - changes[ i ] = changes[ verticesMap[ key ] ]; + if ( i > 0 ) { - } + d += vertices[ i ].distanceTo( vertices[ i - 1 ] ); - } + } + this.lineDistances[ i ] = d; - // if faces are completely degenerate after merging vertices, we - // have to remove them from the geometry. - var faceIndicesToRemove = []; + } - for ( i = 0, il = this.faces.length; i < il; i ++ ) { + }, - face = this.faces[ i ]; + computeBoundingBox: function () { - face.a = changes[ face.a ]; - face.b = changes[ face.b ]; - face.c = changes[ face.c ]; + if ( this.boundingBox === null ) { - indices = [ face.a, face.b, face.c ]; + this.boundingBox = new Box3(); - var dupIndex = - 1; + } - // if any duplicate vertices are found in a Face3 - // we have to remove the face as nothing can be saved - for ( var n = 0; n < 3; n ++ ) { + this.boundingBox.setFromPoints( this.vertices ); - if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) { + }, - dupIndex = n; - faceIndicesToRemove.push( i ); - break; + computeBoundingSphere: function () { - } + if ( this.boundingSphere === null ) { - } + this.boundingSphere = new Sphere(); - } + } - for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) { + this.boundingSphere.setFromPoints( this.vertices ); - var idx = faceIndicesToRemove[ i ]; + }, - this.faces.splice( idx, 1 ); + merge: function ( geometry, matrix, materialIndexOffset ) { - for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) { + if ( (geometry && geometry.isGeometry) === false ) { - this.faceVertexUvs[ j ].splice( idx, 1 ); + console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry ); + return; - } + } - } + var normalMatrix, + vertexOffset = this.vertices.length, + vertices1 = this.vertices, + vertices2 = geometry.vertices, + faces1 = this.faces, + faces2 = geometry.faces, + uvs1 = this.faceVertexUvs[ 0 ], + uvs2 = geometry.faceVertexUvs[ 0 ]; - // Use unique set of vertices + if ( materialIndexOffset === undefined ) materialIndexOffset = 0; - var diff = this.vertices.length - unique.length; - this.vertices = unique; - return diff; + if ( matrix !== undefined ) { - }, + normalMatrix = new Matrix3().getNormalMatrix( matrix ); - sortFacesByMaterialIndex: function () { + } - var faces = this.faces; - var length = faces.length; + // vertices - // tag faces + for ( var i = 0, il = vertices2.length; i < il; i ++ ) { - for ( var i = 0; i < length; i ++ ) { + var vertex = vertices2[ i ]; - faces[ i ]._id = i; + var vertexCopy = vertex.clone(); - } + if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix ); - // sort faces + vertices1.push( vertexCopy ); - function materialIndexSort( a, b ) { + } - return a.materialIndex - b.materialIndex; + // faces - } + for ( i = 0, il = faces2.length; i < il; i ++ ) { - faces.sort( materialIndexSort ); + var face = faces2[ i ], faceCopy, normal, color, + faceVertexNormals = face.vertexNormals, + faceVertexColors = face.vertexColors; - // sort uvs + faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset ); + faceCopy.normal.copy( face.normal ); - var uvs1 = this.faceVertexUvs[ 0 ]; - var uvs2 = this.faceVertexUvs[ 1 ]; + if ( normalMatrix !== undefined ) { - var newUvs1, newUvs2; + faceCopy.normal.applyMatrix3( normalMatrix ).normalize(); - if ( uvs1 && uvs1.length === length ) newUvs1 = []; - if ( uvs2 && uvs2.length === length ) newUvs2 = []; + } - for ( var i = 0; i < length; i ++ ) { + for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) { - var id = faces[ i ]._id; + normal = faceVertexNormals[ j ].clone(); - if ( newUvs1 ) newUvs1.push( uvs1[ id ] ); - if ( newUvs2 ) newUvs2.push( uvs2[ id ] ); + if ( normalMatrix !== undefined ) { - } + normal.applyMatrix3( normalMatrix ).normalize(); - if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1; - if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2; + } - }, + faceCopy.vertexNormals.push( normal ); - toJSON: function () { + } - var data = { - metadata: { - version: 4.4, - type: 'Geometry', - generator: 'Geometry.toJSON' - } - }; + faceCopy.color.copy( face.color ); - // standard Geometry serialization + for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) { - data.uuid = this.uuid; - data.type = this.type; - if ( this.name !== '' ) data.name = this.name; + color = faceVertexColors[ j ]; + faceCopy.vertexColors.push( color.clone() ); - if ( this.parameters !== undefined ) { + } - var parameters = this.parameters; + faceCopy.materialIndex = face.materialIndex + materialIndexOffset; - for ( var key in parameters ) { + faces1.push( faceCopy ); - if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ]; + } - } + // uvs - return data; + for ( i = 0, il = uvs2.length; i < il; i ++ ) { - } + var uv = uvs2[ i ], uvCopy = []; - var vertices = []; + if ( uv === undefined ) { - for ( var i = 0; i < this.vertices.length; i ++ ) { + continue; - var vertex = this.vertices[ i ]; - vertices.push( vertex.x, vertex.y, vertex.z ); + } - } + for ( var j = 0, jl = uv.length; j < jl; j ++ ) { - var faces = []; - var normals = []; - var normalsHash = {}; - var colors = []; - var colorsHash = {}; - var uvs = []; - var uvsHash = {}; + uvCopy.push( uv[ j ].clone() ); - for ( var i = 0; i < this.faces.length; i ++ ) { + } - var face = this.faces[ i ]; + uvs1.push( uvCopy ); - var hasMaterial = true; - var hasFaceUv = false; // deprecated - var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined; - var hasFaceNormal = face.normal.length() > 0; - var hasFaceVertexNormal = face.vertexNormals.length > 0; - var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1; - var hasFaceVertexColor = face.vertexColors.length > 0; + } - var faceType = 0; + }, - faceType = setBit( faceType, 0, 0 ); // isQuad - faceType = setBit( faceType, 1, hasMaterial ); - faceType = setBit( faceType, 2, hasFaceUv ); - faceType = setBit( faceType, 3, hasFaceVertexUv ); - faceType = setBit( faceType, 4, hasFaceNormal ); - faceType = setBit( faceType, 5, hasFaceVertexNormal ); - faceType = setBit( faceType, 6, hasFaceColor ); - faceType = setBit( faceType, 7, hasFaceVertexColor ); + mergeMesh: function ( mesh ) { - faces.push( faceType ); - faces.push( face.a, face.b, face.c ); - faces.push( face.materialIndex ); + if ( (mesh && mesh.isMesh) === false ) { - if ( hasFaceVertexUv ) { + console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh ); + return; - var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ]; + } - faces.push( - getUvIndex( faceVertexUvs[ 0 ] ), - getUvIndex( faceVertexUvs[ 1 ] ), - getUvIndex( faceVertexUvs[ 2 ] ) - ); + mesh.matrixAutoUpdate && mesh.updateMatrix(); - } + this.merge( mesh.geometry, mesh.matrix ); - if ( hasFaceNormal ) { + }, - faces.push( getNormalIndex( face.normal ) ); + /* + * Checks for duplicate vertices with hashmap. + * Duplicated vertices are removed + * and faces' vertices are updated. + */ - } + mergeVertices: function () { - if ( hasFaceVertexNormal ) { + var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique) + var unique = [], changes = []; - var vertexNormals = face.vertexNormals; + var v, key; + var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001 + var precision = Math.pow( 10, precisionPoints ); + var i, il, face; + var indices, j, jl; - faces.push( - getNormalIndex( vertexNormals[ 0 ] ), - getNormalIndex( vertexNormals[ 1 ] ), - getNormalIndex( vertexNormals[ 2 ] ) - ); + for ( i = 0, il = this.vertices.length; i < il; i ++ ) { - } + v = this.vertices[ i ]; + key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision ); - if ( hasFaceColor ) { + if ( verticesMap[ key ] === undefined ) { - faces.push( getColorIndex( face.color ) ); + verticesMap[ key ] = i; + unique.push( this.vertices[ i ] ); + changes[ i ] = unique.length - 1; - } + } else { - if ( hasFaceVertexColor ) { + //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]); + changes[ i ] = changes[ verticesMap[ key ] ]; - var vertexColors = face.vertexColors; + } - faces.push( - getColorIndex( vertexColors[ 0 ] ), - getColorIndex( vertexColors[ 1 ] ), - getColorIndex( vertexColors[ 2 ] ) - ); + } - } - } + // if faces are completely degenerate after merging vertices, we + // have to remove them from the geometry. + var faceIndicesToRemove = []; - function setBit( value, position, enabled ) { + for ( i = 0, il = this.faces.length; i < il; i ++ ) { - return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) ); + face = this.faces[ i ]; - } + face.a = changes[ face.a ]; + face.b = changes[ face.b ]; + face.c = changes[ face.c ]; - function getNormalIndex( normal ) { + indices = [ face.a, face.b, face.c ]; - var hash = normal.x.toString() + normal.y.toString() + normal.z.toString(); + var dupIndex = - 1; - if ( normalsHash[ hash ] !== undefined ) { + // if any duplicate vertices are found in a Face3 + // we have to remove the face as nothing can be saved + for ( var n = 0; n < 3; n ++ ) { - return normalsHash[ hash ]; + if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) { - } + dupIndex = n; + faceIndicesToRemove.push( i ); + break; - normalsHash[ hash ] = normals.length / 3; - normals.push( normal.x, normal.y, normal.z ); + } - return normalsHash[ hash ]; + } - } + } - function getColorIndex( color ) { + for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) { - var hash = color.r.toString() + color.g.toString() + color.b.toString(); + var idx = faceIndicesToRemove[ i ]; - if ( colorsHash[ hash ] !== undefined ) { + this.faces.splice( idx, 1 ); - return colorsHash[ hash ]; + for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) { - } + this.faceVertexUvs[ j ].splice( idx, 1 ); - colorsHash[ hash ] = colors.length; - colors.push( color.getHex() ); + } - return colorsHash[ hash ]; + } - } + // Use unique set of vertices - function getUvIndex( uv ) { + var diff = this.vertices.length - unique.length; + this.vertices = unique; + return diff; - var hash = uv.x.toString() + uv.y.toString(); + }, - if ( uvsHash[ hash ] !== undefined ) { + sortFacesByMaterialIndex: function () { - return uvsHash[ hash ]; + var faces = this.faces; + var length = faces.length; - } + // tag faces - uvsHash[ hash ] = uvs.length / 2; - uvs.push( uv.x, uv.y ); + for ( var i = 0; i < length; i ++ ) { - return uvsHash[ hash ]; + faces[ i ]._id = i; - } + } - data.data = {}; + // sort faces - data.data.vertices = vertices; - data.data.normals = normals; - if ( colors.length > 0 ) data.data.colors = colors; - if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility - data.data.faces = faces; + function materialIndexSort( a, b ) { - return data; + return a.materialIndex - b.materialIndex; - }, + } - clone: function () { + faces.sort( materialIndexSort ); - /* - // Handle primitives + // sort uvs - var parameters = this.parameters; + var uvs1 = this.faceVertexUvs[ 0 ]; + var uvs2 = this.faceVertexUvs[ 1 ]; - if ( parameters !== undefined ) { + var newUvs1, newUvs2; - var values = []; + if ( uvs1 && uvs1.length === length ) newUvs1 = []; + if ( uvs2 && uvs2.length === length ) newUvs2 = []; - for ( var key in parameters ) { + for ( var i = 0; i < length; i ++ ) { - values.push( parameters[ key ] ); + var id = faces[ i ]._id; - } + if ( newUvs1 ) newUvs1.push( uvs1[ id ] ); + if ( newUvs2 ) newUvs2.push( uvs2[ id ] ); - var geometry = Object.create( this.constructor.prototype ); - this.constructor.apply( geometry, values ); - return geometry; + } - } + if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1; + if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2; - return new this.constructor().copy( this ); - */ + }, - return new Geometry().copy( this ); + toJSON: function () { - }, + var data = { + metadata: { + version: 4.4, + type: 'Geometry', + generator: 'Geometry.toJSON' + } + }; - copy: function ( source ) { + // standard Geometry serialization - this.vertices = []; - this.faces = []; - this.faceVertexUvs = [ [] ]; + data.uuid = this.uuid; + data.type = this.type; + if ( this.name !== '' ) data.name = this.name; - var vertices = source.vertices; + if ( this.parameters !== undefined ) { - for ( var i = 0, il = vertices.length; i < il; i ++ ) { + var parameters = this.parameters; - this.vertices.push( vertices[ i ].clone() ); + for ( var key in parameters ) { - } + if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ]; - var faces = source.faces; + } - for ( var i = 0, il = faces.length; i < il; i ++ ) { + return data; - this.faces.push( faces[ i ].clone() ); + } - } + var vertices = []; - for ( var i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) { + for ( var i = 0; i < this.vertices.length; i ++ ) { - var faceVertexUvs = source.faceVertexUvs[ i ]; + var vertex = this.vertices[ i ]; + vertices.push( vertex.x, vertex.y, vertex.z ); - if ( this.faceVertexUvs[ i ] === undefined ) { + } - this.faceVertexUvs[ i ] = []; + var faces = []; + var normals = []; + var normalsHash = {}; + var colors = []; + var colorsHash = {}; + var uvs = []; + var uvsHash = {}; - } + for ( var i = 0; i < this.faces.length; i ++ ) { - for ( var j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) { + var face = this.faces[ i ]; - var uvs = faceVertexUvs[ j ], uvsCopy = []; + var hasMaterial = true; + var hasFaceUv = false; // deprecated + var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined; + var hasFaceNormal = face.normal.length() > 0; + var hasFaceVertexNormal = face.vertexNormals.length > 0; + var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1; + var hasFaceVertexColor = face.vertexColors.length > 0; - for ( var k = 0, kl = uvs.length; k < kl; k ++ ) { + var faceType = 0; - var uv = uvs[ k ]; + faceType = setBit( faceType, 0, 0 ); // isQuad + faceType = setBit( faceType, 1, hasMaterial ); + faceType = setBit( faceType, 2, hasFaceUv ); + faceType = setBit( faceType, 3, hasFaceVertexUv ); + faceType = setBit( faceType, 4, hasFaceNormal ); + faceType = setBit( faceType, 5, hasFaceVertexNormal ); + faceType = setBit( faceType, 6, hasFaceColor ); + faceType = setBit( faceType, 7, hasFaceVertexColor ); - uvsCopy.push( uv.clone() ); + faces.push( faceType ); + faces.push( face.a, face.b, face.c ); + faces.push( face.materialIndex ); - } + if ( hasFaceVertexUv ) { - this.faceVertexUvs[ i ].push( uvsCopy ); + var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ]; - } + faces.push( + getUvIndex( faceVertexUvs[ 0 ] ), + getUvIndex( faceVertexUvs[ 1 ] ), + getUvIndex( faceVertexUvs[ 2 ] ) + ); - } + } - return this; + if ( hasFaceNormal ) { - }, + faces.push( getNormalIndex( face.normal ) ); - dispose: function () { + } - this.dispatchEvent( { type: 'dispose' } ); + if ( hasFaceVertexNormal ) { - } + var vertexNormals = face.vertexNormals; - } ); + faces.push( + getNormalIndex( vertexNormals[ 0 ] ), + getNormalIndex( vertexNormals[ 1 ] ), + getNormalIndex( vertexNormals[ 2 ] ) + ); - var count$2 = 0; - function GeometryIdCount() { return count$2++; }; + } - /** - * @author mrdoob / http://mrdoob.com/ - */ + if ( hasFaceColor ) { - function DirectGeometry() { + faces.push( getColorIndex( face.color ) ); - Object.defineProperty( this, 'id', { value: GeometryIdCount() } ); + } - this.uuid = exports.Math.generateUUID(); + if ( hasFaceVertexColor ) { - this.name = ''; - this.type = 'DirectGeometry'; + var vertexColors = face.vertexColors; - this.indices = []; - this.vertices = []; - this.normals = []; - this.colors = []; - this.uvs = []; - this.uvs2 = []; + faces.push( + getColorIndex( vertexColors[ 0 ] ), + getColorIndex( vertexColors[ 1 ] ), + getColorIndex( vertexColors[ 2 ] ) + ); - this.groups = []; + } - this.morphTargets = {}; + } - this.skinWeights = []; - this.skinIndices = []; + function setBit( value, position, enabled ) { - // this.lineDistances = []; + return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) ); - this.boundingBox = null; - this.boundingSphere = null; + } - // update flags + function getNormalIndex( normal ) { - this.verticesNeedUpdate = false; - this.normalsNeedUpdate = false; - this.colorsNeedUpdate = false; - this.uvsNeedUpdate = false; - this.groupsNeedUpdate = false; + var hash = normal.x.toString() + normal.y.toString() + normal.z.toString(); - }; + if ( normalsHash[ hash ] !== undefined ) { - Object.assign( DirectGeometry.prototype, EventDispatcher.prototype, { + return normalsHash[ hash ]; - computeBoundingBox: Geometry.prototype.computeBoundingBox, - computeBoundingSphere: Geometry.prototype.computeBoundingSphere, + } - computeFaceNormals: function () { + normalsHash[ hash ] = normals.length / 3; + normals.push( normal.x, normal.y, normal.z ); - console.warn( 'THREE.DirectGeometry: computeFaceNormals() is not a method of this type of geometry.' ); + return normalsHash[ hash ]; - }, + } - computeVertexNormals: function () { + function getColorIndex( color ) { - console.warn( 'THREE.DirectGeometry: computeVertexNormals() is not a method of this type of geometry.' ); + var hash = color.r.toString() + color.g.toString() + color.b.toString(); - }, + if ( colorsHash[ hash ] !== undefined ) { - computeGroups: function ( geometry ) { + return colorsHash[ hash ]; - var group; - var groups = []; - var materialIndex; + } - var faces = geometry.faces; + colorsHash[ hash ] = colors.length; + colors.push( color.getHex() ); - for ( var i = 0; i < faces.length; i ++ ) { + return colorsHash[ hash ]; - var face = faces[ i ]; + } - // materials + function getUvIndex( uv ) { - if ( face.materialIndex !== materialIndex ) { + var hash = uv.x.toString() + uv.y.toString(); - materialIndex = face.materialIndex; + if ( uvsHash[ hash ] !== undefined ) { - if ( group !== undefined ) { + return uvsHash[ hash ]; - group.count = ( i * 3 ) - group.start; - groups.push( group ); + } - } + uvsHash[ hash ] = uvs.length / 2; + uvs.push( uv.x, uv.y ); - group = { - start: i * 3, - materialIndex: materialIndex - }; + return uvsHash[ hash ]; - } + } - } + data.data = {}; - if ( group !== undefined ) { + data.data.vertices = vertices; + data.data.normals = normals; + if ( colors.length > 0 ) data.data.colors = colors; + if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility + data.data.faces = faces; - group.count = ( i * 3 ) - group.start; - groups.push( group ); + return data; - } + }, - this.groups = groups; + clone: function () { - }, + /* + // Handle primitives - fromGeometry: function ( geometry ) { + var parameters = this.parameters; - var faces = geometry.faces; - var vertices = geometry.vertices; - var faceVertexUvs = geometry.faceVertexUvs; + if ( parameters !== undefined ) { - var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0; - var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0; + var values = []; - // morphs + for ( var key in parameters ) { - var morphTargets = geometry.morphTargets; - var morphTargetsLength = morphTargets.length; + values.push( parameters[ key ] ); - var morphTargetsPosition; + } - if ( morphTargetsLength > 0 ) { + var geometry = Object.create( this.constructor.prototype ); + this.constructor.apply( geometry, values ); + return geometry; - morphTargetsPosition = []; + } - for ( var i = 0; i < morphTargetsLength; i ++ ) { + return new this.constructor().copy( this ); + */ - morphTargetsPosition[ i ] = []; + return new Geometry().copy( this ); - } + }, - this.morphTargets.position = morphTargetsPosition; + copy: function ( source ) { - } + this.vertices = []; + this.faces = []; + this.faceVertexUvs = [ [] ]; - var morphNormals = geometry.morphNormals; - var morphNormalsLength = morphNormals.length; + var vertices = source.vertices; - var morphTargetsNormal; + for ( var i = 0, il = vertices.length; i < il; i ++ ) { - if ( morphNormalsLength > 0 ) { + this.vertices.push( vertices[ i ].clone() ); - morphTargetsNormal = []; + } - for ( var i = 0; i < morphNormalsLength; i ++ ) { + var faces = source.faces; - morphTargetsNormal[ i ] = []; + for ( var i = 0, il = faces.length; i < il; i ++ ) { - } + this.faces.push( faces[ i ].clone() ); - this.morphTargets.normal = morphTargetsNormal; + } - } + for ( var i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) { - // skins + var faceVertexUvs = source.faceVertexUvs[ i ]; - var skinIndices = geometry.skinIndices; - var skinWeights = geometry.skinWeights; + if ( this.faceVertexUvs[ i ] === undefined ) { - var hasSkinIndices = skinIndices.length === vertices.length; - var hasSkinWeights = skinWeights.length === vertices.length; + this.faceVertexUvs[ i ] = []; - // + } - for ( var i = 0; i < faces.length; i ++ ) { + for ( var j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) { - var face = faces[ i ]; + var uvs = faceVertexUvs[ j ], uvsCopy = []; - this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] ); + for ( var k = 0, kl = uvs.length; k < kl; k ++ ) { - var vertexNormals = face.vertexNormals; + var uv = uvs[ k ]; - if ( vertexNormals.length === 3 ) { + uvsCopy.push( uv.clone() ); - this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] ); + } - } else { + this.faceVertexUvs[ i ].push( uvsCopy ); - var normal = face.normal; + } - this.normals.push( normal, normal, normal ); + } - } + return this; - var vertexColors = face.vertexColors; + }, - if ( vertexColors.length === 3 ) { + dispose: function () { - this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] ); + this.dispatchEvent( { type: 'dispose' } ); - } else { + } - var color = face.color; + } ); - this.colors.push( color, color, color ); + var count$2 = 0; + function GeometryIdCount() { return count$2++; }; - } + /** + * @author mrdoob / http://mrdoob.com/ + */ - if ( hasFaceVertexUv === true ) { + function DirectGeometry() { - var vertexUvs = faceVertexUvs[ 0 ][ i ]; + Object.defineProperty( this, 'id', { value: GeometryIdCount() } ); - if ( vertexUvs !== undefined ) { + this.uuid = exports.Math.generateUUID(); - this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] ); + this.name = ''; + this.type = 'DirectGeometry'; - } else { + this.indices = []; + this.vertices = []; + this.normals = []; + this.colors = []; + this.uvs = []; + this.uvs2 = []; - console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i ); + this.groups = []; - this.uvs.push( new Vector2(), new Vector2(), new Vector2() ); + this.morphTargets = {}; - } + this.skinWeights = []; + this.skinIndices = []; - } + // this.lineDistances = []; - if ( hasFaceVertexUv2 === true ) { + this.boundingBox = null; + this.boundingSphere = null; - var vertexUvs = faceVertexUvs[ 1 ][ i ]; + // update flags - if ( vertexUvs !== undefined ) { + this.verticesNeedUpdate = false; + this.normalsNeedUpdate = false; + this.colorsNeedUpdate = false; + this.uvsNeedUpdate = false; + this.groupsNeedUpdate = false; - this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] ); + } - } else { + Object.assign( DirectGeometry.prototype, EventDispatcher.prototype, { - console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i ); + computeBoundingBox: Geometry.prototype.computeBoundingBox, + computeBoundingSphere: Geometry.prototype.computeBoundingSphere, - this.uvs2.push( new Vector2(), new Vector2(), new Vector2() ); + computeFaceNormals: function () { - } + console.warn( 'THREE.DirectGeometry: computeFaceNormals() is not a method of this type of geometry.' ); - } + }, - // morphs + computeVertexNormals: function () { - for ( var j = 0; j < morphTargetsLength; j ++ ) { + console.warn( 'THREE.DirectGeometry: computeVertexNormals() is not a method of this type of geometry.' ); - var morphTarget = morphTargets[ j ].vertices; + }, - morphTargetsPosition[ j ].push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] ); + computeGroups: function ( geometry ) { - } + var group; + var groups = []; + var materialIndex; - for ( var j = 0; j < morphNormalsLength; j ++ ) { + var faces = geometry.faces; - var morphNormal = morphNormals[ j ].vertexNormals[ i ]; + for ( var i = 0; i < faces.length; i ++ ) { - morphTargetsNormal[ j ].push( morphNormal.a, morphNormal.b, morphNormal.c ); + var face = faces[ i ]; - } + // materials - // skins + if ( face.materialIndex !== materialIndex ) { - if ( hasSkinIndices ) { + materialIndex = face.materialIndex; - this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] ); + if ( group !== undefined ) { - } + group.count = ( i * 3 ) - group.start; + groups.push( group ); - if ( hasSkinWeights ) { + } - this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] ); + group = { + start: i * 3, + materialIndex: materialIndex + }; - } + } - } + } - this.computeGroups( geometry ); + if ( group !== undefined ) { - this.verticesNeedUpdate = geometry.verticesNeedUpdate; - this.normalsNeedUpdate = geometry.normalsNeedUpdate; - this.colorsNeedUpdate = geometry.colorsNeedUpdate; - this.uvsNeedUpdate = geometry.uvsNeedUpdate; - this.groupsNeedUpdate = geometry.groupsNeedUpdate; + group.count = ( i * 3 ) - group.start; + groups.push( group ); - return this; + } - }, + this.groups = groups; - dispose: function () { + }, - this.dispatchEvent( { type: 'dispose' } ); + fromGeometry: function ( geometry ) { - } + var faces = geometry.faces; + var vertices = geometry.vertices; + var faceVertexUvs = geometry.faceVertexUvs; - } ); + var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0; + var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0; - /** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - */ + // morphs - function BufferGeometry() { + var morphTargets = geometry.morphTargets; + var morphTargetsLength = morphTargets.length; - Object.defineProperty( this, 'id', { value: GeometryIdCount() } ); + var morphTargetsPosition; - this.uuid = exports.Math.generateUUID(); + if ( morphTargetsLength > 0 ) { - this.name = ''; - this.type = 'BufferGeometry'; + morphTargetsPosition = []; - this.index = null; - this.attributes = {}; + for ( var i = 0; i < morphTargetsLength; i ++ ) { - this.morphAttributes = {}; + morphTargetsPosition[ i ] = []; - this.groups = []; + } - this.boundingBox = null; - this.boundingSphere = null; + this.morphTargets.position = morphTargetsPosition; - this.drawRange = { start: 0, count: Infinity }; + } - }; + var morphNormals = geometry.morphNormals; + var morphNormalsLength = morphNormals.length; - Object.assign( BufferGeometry.prototype, EventDispatcher.prototype, { + var morphTargetsNormal; - isBufferGeometry: true, + if ( morphNormalsLength > 0 ) { - getIndex: function () { + morphTargetsNormal = []; - return this.index; + for ( var i = 0; i < morphNormalsLength; i ++ ) { - }, + morphTargetsNormal[ i ] = []; - setIndex: function ( index ) { + } - this.index = index; + this.morphTargets.normal = morphTargetsNormal; - }, + } - addAttribute: function ( name, attribute ) { + // skins - if ( (attribute && attribute.isBufferAttribute) === false && (attribute && attribute.isInterleavedBufferAttribute) === false ) { + var skinIndices = geometry.skinIndices; + var skinWeights = geometry.skinWeights; - console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' ); + var hasSkinIndices = skinIndices.length === vertices.length; + var hasSkinWeights = skinWeights.length === vertices.length; - this.addAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) ); + // - return; + for ( var i = 0; i < faces.length; i ++ ) { - } + var face = faces[ i ]; - if ( name === 'index' ) { + this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] ); - console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' ); - this.setIndex( attribute ); + var vertexNormals = face.vertexNormals; - return; + if ( vertexNormals.length === 3 ) { - } + this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] ); - this.attributes[ name ] = attribute; + } else { - return this; + var normal = face.normal; - }, + this.normals.push( normal, normal, normal ); - getAttribute: function ( name ) { + } - return this.attributes[ name ]; + var vertexColors = face.vertexColors; - }, + if ( vertexColors.length === 3 ) { - removeAttribute: function ( name ) { + this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] ); - delete this.attributes[ name ]; + } else { - return this; + var color = face.color; - }, + this.colors.push( color, color, color ); - addGroup: function ( start, count, materialIndex ) { + } - this.groups.push( { + if ( hasFaceVertexUv === true ) { - start: start, - count: count, - materialIndex: materialIndex !== undefined ? materialIndex : 0 + var vertexUvs = faceVertexUvs[ 0 ][ i ]; - } ); + if ( vertexUvs !== undefined ) { - }, + this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] ); - clearGroups: function () { + } else { - this.groups = []; + console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i ); - }, + this.uvs.push( new Vector2(), new Vector2(), new Vector2() ); - setDrawRange: function ( start, count ) { + } - this.drawRange.start = start; - this.drawRange.count = count; + } - }, + if ( hasFaceVertexUv2 === true ) { - applyMatrix: function ( matrix ) { + var vertexUvs = faceVertexUvs[ 1 ][ i ]; - var position = this.attributes.position; + if ( vertexUvs !== undefined ) { - if ( position !== undefined ) { + this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] ); - matrix.applyToVector3Array( position.array ); - position.needsUpdate = true; + } else { - } + console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i ); - var normal = this.attributes.normal; + this.uvs2.push( new Vector2(), new Vector2(), new Vector2() ); - if ( normal !== undefined ) { + } - var normalMatrix = new Matrix3().getNormalMatrix( matrix ); + } - normalMatrix.applyToVector3Array( normal.array ); - normal.needsUpdate = true; + // morphs - } + for ( var j = 0; j < morphTargetsLength; j ++ ) { - if ( this.boundingBox !== null ) { + var morphTarget = morphTargets[ j ].vertices; - this.computeBoundingBox(); + morphTargetsPosition[ j ].push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] ); - } + } - if ( this.boundingSphere !== null ) { + for ( var j = 0; j < morphNormalsLength; j ++ ) { - this.computeBoundingSphere(); + var morphNormal = morphNormals[ j ].vertexNormals[ i ]; - } + morphTargetsNormal[ j ].push( morphNormal.a, morphNormal.b, morphNormal.c ); - return this; + } - }, + // skins - rotateX: function () { + if ( hasSkinIndices ) { - // rotate geometry around world x-axis + this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] ); - var m1; + } - return function rotateX( angle ) { + if ( hasSkinWeights ) { - if ( m1 === undefined ) m1 = new Matrix4(); + this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] ); - m1.makeRotationX( angle ); + } - this.applyMatrix( m1 ); + } - return this; + this.computeGroups( geometry ); - }; + this.verticesNeedUpdate = geometry.verticesNeedUpdate; + this.normalsNeedUpdate = geometry.normalsNeedUpdate; + this.colorsNeedUpdate = geometry.colorsNeedUpdate; + this.uvsNeedUpdate = geometry.uvsNeedUpdate; + this.groupsNeedUpdate = geometry.groupsNeedUpdate; - }(), + return this; - rotateY: function () { + }, - // rotate geometry around world y-axis + dispose: function () { - var m1; + this.dispatchEvent( { type: 'dispose' } ); - return function rotateY( angle ) { + } - if ( m1 === undefined ) m1 = new Matrix4(); + } ); - m1.makeRotationY( angle ); + /** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + */ - this.applyMatrix( m1 ); + function BufferGeometry() { - return this; + Object.defineProperty( this, 'id', { value: GeometryIdCount() } ); - }; + this.uuid = exports.Math.generateUUID(); - }(), + this.name = ''; + this.type = 'BufferGeometry'; - rotateZ: function () { + this.index = null; + this.attributes = {}; - // rotate geometry around world z-axis + this.morphAttributes = {}; - var m1; + this.groups = []; - return function rotateZ( angle ) { + this.boundingBox = null; + this.boundingSphere = null; - if ( m1 === undefined ) m1 = new Matrix4(); + this.drawRange = { start: 0, count: Infinity }; - m1.makeRotationZ( angle ); + } - this.applyMatrix( m1 ); + Object.assign( BufferGeometry.prototype, EventDispatcher.prototype, { - return this; + isBufferGeometry: true, - }; + getIndex: function () { - }(), + return this.index; - translate: function () { + }, - // translate geometry + setIndex: function ( index ) { - var m1; + this.index = index; - return function translate( x, y, z ) { + }, - if ( m1 === undefined ) m1 = new Matrix4(); + addAttribute: function ( name, attribute ) { - m1.makeTranslation( x, y, z ); + if ( (attribute && attribute.isBufferAttribute) === false && (attribute && attribute.isInterleavedBufferAttribute) === false ) { - this.applyMatrix( m1 ); + console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' ); - return this; + this.addAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) ); - }; + return; - }(), + } - scale: function () { + if ( name === 'index' ) { - // scale geometry + console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' ); + this.setIndex( attribute ); - var m1; + return; - return function scale( x, y, z ) { + } - if ( m1 === undefined ) m1 = new Matrix4(); + this.attributes[ name ] = attribute; - m1.makeScale( x, y, z ); + return this; - this.applyMatrix( m1 ); + }, - return this; + getAttribute: function ( name ) { - }; + return this.attributes[ name ]; - }(), + }, - lookAt: function () { + removeAttribute: function ( name ) { - var obj; + delete this.attributes[ name ]; - return function lookAt( vector ) { + return this; - if ( obj === undefined ) obj = new Object3D(); + }, - obj.lookAt( vector ); + addGroup: function ( start, count, materialIndex ) { - obj.updateMatrix(); + this.groups.push( { - this.applyMatrix( obj.matrix ); + start: start, + count: count, + materialIndex: materialIndex !== undefined ? materialIndex : 0 - }; + } ); - }(), + }, - center: function () { + clearGroups: function () { - this.computeBoundingBox(); + this.groups = []; - var offset = this.boundingBox.center().negate(); + }, - this.translate( offset.x, offset.y, offset.z ); + setDrawRange: function ( start, count ) { - return offset; + this.drawRange.start = start; + this.drawRange.count = count; - }, + }, - setFromObject: function ( object ) { + applyMatrix: function ( matrix ) { - // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this ); + var position = this.attributes.position; - var geometry = object.geometry; + if ( position !== undefined ) { - if ( (object && object.isPoints) || (object && object.isLine) ) { + matrix.applyToVector3Array( position.array ); + position.needsUpdate = true; - var positions = new Float32Attribute( geometry.vertices.length * 3, 3 ); - var colors = new Float32Attribute( geometry.colors.length * 3, 3 ); + } - this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) ); - this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) ); + var normal = this.attributes.normal; - if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) { + if ( normal !== undefined ) { - var lineDistances = new Float32Attribute( geometry.lineDistances.length, 1 ); + var normalMatrix = new Matrix3().getNormalMatrix( matrix ); - this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) ); + normalMatrix.applyToVector3Array( normal.array ); + normal.needsUpdate = true; - } + } - if ( geometry.boundingSphere !== null ) { + if ( this.boundingBox !== null ) { - this.boundingSphere = geometry.boundingSphere.clone(); + this.computeBoundingBox(); - } + } - if ( geometry.boundingBox !== null ) { + if ( this.boundingSphere !== null ) { - this.boundingBox = geometry.boundingBox.clone(); + this.computeBoundingSphere(); - } + } - } else if ( (object && object.isMesh) ) { + return this; - if ( (geometry && geometry.isGeometry) ) { + }, - this.fromGeometry( geometry ); + rotateX: function () { - } + // rotate geometry around world x-axis - } + var m1; - return this; + return function rotateX( angle ) { - }, + if ( m1 === undefined ) m1 = new Matrix4(); - updateFromObject: function ( object ) { + m1.makeRotationX( angle ); - var geometry = object.geometry; + this.applyMatrix( m1 ); - if ( (object && object.isMesh) ) { + return this; - var direct = geometry.__directGeometry; + }; - if ( direct === undefined || geometry.elementsNeedUpdate === true ) { + }(), - return this.fromGeometry( geometry ); + rotateY: function () { - } + // rotate geometry around world y-axis - direct.verticesNeedUpdate = geometry.verticesNeedUpdate || geometry.elementsNeedUpdate; - direct.normalsNeedUpdate = geometry.normalsNeedUpdate || geometry.elementsNeedUpdate; - direct.colorsNeedUpdate = geometry.colorsNeedUpdate || geometry.elementsNeedUpdate; - direct.uvsNeedUpdate = geometry.uvsNeedUpdate || geometry.elementsNeedUpdate; - direct.groupsNeedUpdate = geometry.groupsNeedUpdate || geometry.elementsNeedUpdate; + var m1; - geometry.elementsNeedUpdate = false; - geometry.verticesNeedUpdate = false; - geometry.normalsNeedUpdate = false; - geometry.colorsNeedUpdate = false; - geometry.uvsNeedUpdate = false; - geometry.groupsNeedUpdate = false; + return function rotateY( angle ) { - geometry = direct; + if ( m1 === undefined ) m1 = new Matrix4(); - } + m1.makeRotationY( angle ); - var attribute; + this.applyMatrix( m1 ); - if ( geometry.verticesNeedUpdate === true ) { + return this; - attribute = this.attributes.position; + }; - if ( attribute !== undefined ) { + }(), - attribute.copyVector3sArray( geometry.vertices ); - attribute.needsUpdate = true; + rotateZ: function () { - } + // rotate geometry around world z-axis - geometry.verticesNeedUpdate = false; + var m1; - } + return function rotateZ( angle ) { - if ( geometry.normalsNeedUpdate === true ) { + if ( m1 === undefined ) m1 = new Matrix4(); - attribute = this.attributes.normal; + m1.makeRotationZ( angle ); - if ( attribute !== undefined ) { + this.applyMatrix( m1 ); - attribute.copyVector3sArray( geometry.normals ); - attribute.needsUpdate = true; + return this; - } + }; - geometry.normalsNeedUpdate = false; + }(), - } + translate: function () { - if ( geometry.colorsNeedUpdate === true ) { + // translate geometry - attribute = this.attributes.color; + var m1; - if ( attribute !== undefined ) { + return function translate( x, y, z ) { - attribute.copyColorsArray( geometry.colors ); - attribute.needsUpdate = true; + if ( m1 === undefined ) m1 = new Matrix4(); - } + m1.makeTranslation( x, y, z ); - geometry.colorsNeedUpdate = false; + this.applyMatrix( m1 ); - } + return this; - if ( geometry.uvsNeedUpdate ) { + }; - attribute = this.attributes.uv; + }(), - if ( attribute !== undefined ) { + scale: function () { - attribute.copyVector2sArray( geometry.uvs ); - attribute.needsUpdate = true; + // scale geometry - } + var m1; - geometry.uvsNeedUpdate = false; + return function scale( x, y, z ) { - } + if ( m1 === undefined ) m1 = new Matrix4(); - if ( geometry.lineDistancesNeedUpdate ) { + m1.makeScale( x, y, z ); - attribute = this.attributes.lineDistance; + this.applyMatrix( m1 ); - if ( attribute !== undefined ) { + return this; - attribute.copyArray( geometry.lineDistances ); - attribute.needsUpdate = true; + }; - } + }(), - geometry.lineDistancesNeedUpdate = false; + lookAt: function () { - } + var obj; - if ( geometry.groupsNeedUpdate ) { + return function lookAt( vector ) { - geometry.computeGroups( object.geometry ); - this.groups = geometry.groups; + if ( obj === undefined ) obj = new Object3D(); - geometry.groupsNeedUpdate = false; + obj.lookAt( vector ); - } + obj.updateMatrix(); - return this; + this.applyMatrix( obj.matrix ); - }, + }; - fromGeometry: function ( geometry ) { + }(), - geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry ); + center: function () { - return this.fromDirectGeometry( geometry.__directGeometry ); + this.computeBoundingBox(); - }, + var offset = this.boundingBox.center().negate(); - fromDirectGeometry: function ( geometry ) { + this.translate( offset.x, offset.y, offset.z ); - var positions = new Float32Array( geometry.vertices.length * 3 ); - this.addAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) ); + return offset; - if ( geometry.normals.length > 0 ) { + }, - var normals = new Float32Array( geometry.normals.length * 3 ); - this.addAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) ); + setFromObject: function ( object ) { - } + // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this ); - if ( geometry.colors.length > 0 ) { + var geometry = object.geometry; - var colors = new Float32Array( geometry.colors.length * 3 ); - this.addAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) ); + if ( (object && object.isPoints) || (object && object.isLine) ) { - } + var positions = new Float32Attribute( geometry.vertices.length * 3, 3 ); + var colors = new Float32Attribute( geometry.colors.length * 3, 3 ); - if ( geometry.uvs.length > 0 ) { + this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) ); + this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) ); - var uvs = new Float32Array( geometry.uvs.length * 2 ); - this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) ); + if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) { - } + var lineDistances = new Float32Attribute( geometry.lineDistances.length, 1 ); - if ( geometry.uvs2.length > 0 ) { + this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) ); - var uvs2 = new Float32Array( geometry.uvs2.length * 2 ); - this.addAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) ); + } - } + if ( geometry.boundingSphere !== null ) { - if ( geometry.indices.length > 0 ) { + this.boundingSphere = geometry.boundingSphere.clone(); - var TypeArray = geometry.vertices.length > 65535 ? Uint32Array : Uint16Array; - var indices = new TypeArray( geometry.indices.length * 3 ); - this.setIndex( new BufferAttribute( indices, 1 ).copyIndicesArray( geometry.indices ) ); + } - } + if ( geometry.boundingBox !== null ) { - // groups + this.boundingBox = geometry.boundingBox.clone(); - this.groups = geometry.groups; + } - // morphs + } else if ( (object && object.isMesh) ) { - for ( var name in geometry.morphTargets ) { + if ( (geometry && geometry.isGeometry) ) { - var array = []; - var morphTargets = geometry.morphTargets[ name ]; + this.fromGeometry( geometry ); - for ( var i = 0, l = morphTargets.length; i < l; i ++ ) { + } - var morphTarget = morphTargets[ i ]; + } - var attribute = new Float32Attribute( morphTarget.length * 3, 3 ); + return this; - array.push( attribute.copyVector3sArray( morphTarget ) ); + }, - } + updateFromObject: function ( object ) { - this.morphAttributes[ name ] = array; + var geometry = object.geometry; - } + if ( (object && object.isMesh) ) { - // skinning + var direct = geometry.__directGeometry; - if ( geometry.skinIndices.length > 0 ) { + if ( direct === undefined || geometry.elementsNeedUpdate === true ) { - var skinIndices = new Float32Attribute( geometry.skinIndices.length * 4, 4 ); - this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) ); + return this.fromGeometry( geometry ); - } + } - if ( geometry.skinWeights.length > 0 ) { + direct.verticesNeedUpdate = geometry.verticesNeedUpdate || geometry.elementsNeedUpdate; + direct.normalsNeedUpdate = geometry.normalsNeedUpdate || geometry.elementsNeedUpdate; + direct.colorsNeedUpdate = geometry.colorsNeedUpdate || geometry.elementsNeedUpdate; + direct.uvsNeedUpdate = geometry.uvsNeedUpdate || geometry.elementsNeedUpdate; + direct.groupsNeedUpdate = geometry.groupsNeedUpdate || geometry.elementsNeedUpdate; - var skinWeights = new Float32Attribute( geometry.skinWeights.length * 4, 4 ); - this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) ); + geometry.elementsNeedUpdate = false; + geometry.verticesNeedUpdate = false; + geometry.normalsNeedUpdate = false; + geometry.colorsNeedUpdate = false; + geometry.uvsNeedUpdate = false; + geometry.groupsNeedUpdate = false; - } + geometry = direct; - // + } - if ( geometry.boundingSphere !== null ) { + var attribute; - this.boundingSphere = geometry.boundingSphere.clone(); + if ( geometry.verticesNeedUpdate === true ) { - } + attribute = this.attributes.position; - if ( geometry.boundingBox !== null ) { + if ( attribute !== undefined ) { - this.boundingBox = geometry.boundingBox.clone(); + attribute.copyVector3sArray( geometry.vertices ); + attribute.needsUpdate = true; - } + } - return this; + geometry.verticesNeedUpdate = false; - }, + } - computeBoundingBox: function () { + if ( geometry.normalsNeedUpdate === true ) { - if ( this.boundingBox === null ) { + attribute = this.attributes.normal; - this.boundingBox = new Box3(); + if ( attribute !== undefined ) { - } + attribute.copyVector3sArray( geometry.normals ); + attribute.needsUpdate = true; - var positions = this.attributes.position.array; + } - if ( positions !== undefined ) { + geometry.normalsNeedUpdate = false; - this.boundingBox.setFromArray( positions ); + } - } else { + if ( geometry.colorsNeedUpdate === true ) { - this.boundingBox.makeEmpty(); + attribute = this.attributes.color; - } + if ( attribute !== undefined ) { - if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) { + attribute.copyColorsArray( geometry.colors ); + attribute.needsUpdate = true; - console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this ); + } - } + geometry.colorsNeedUpdate = false; - }, + } - computeBoundingSphere: function () { + if ( geometry.uvsNeedUpdate ) { - var box = new Box3(); - var vector = new Vector3(); + attribute = this.attributes.uv; - return function computeBoundingSphere() { + if ( attribute !== undefined ) { - if ( this.boundingSphere === null ) { + attribute.copyVector2sArray( geometry.uvs ); + attribute.needsUpdate = true; - this.boundingSphere = new Sphere(); + } - } + geometry.uvsNeedUpdate = false; - var positions = this.attributes.position; + } - if ( positions ) { + if ( geometry.lineDistancesNeedUpdate ) { - var array = positions.array; - var center = this.boundingSphere.center; + attribute = this.attributes.lineDistance; - box.setFromArray( array ); - box.center( center ); + if ( attribute !== undefined ) { - // hoping to find a boundingSphere with a radius smaller than the - // boundingSphere of the boundingBox: sqrt(3) smaller in the best case + attribute.copyArray( geometry.lineDistances ); + attribute.needsUpdate = true; - var maxRadiusSq = 0; + } - for ( var i = 0, il = array.length; i < il; i += 3 ) { + geometry.lineDistancesNeedUpdate = false; - vector.fromArray( array, i ); - maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) ); + } - } + if ( geometry.groupsNeedUpdate ) { - this.boundingSphere.radius = Math.sqrt( maxRadiusSq ); + geometry.computeGroups( object.geometry ); + this.groups = geometry.groups; - if ( isNaN( this.boundingSphere.radius ) ) { + geometry.groupsNeedUpdate = false; - console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this ); + } - } + return this; - } + }, - }; + fromGeometry: function ( geometry ) { - }(), + geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry ); - computeFaceNormals: function () { + return this.fromDirectGeometry( geometry.__directGeometry ); - // backwards compatibility + }, - }, + fromDirectGeometry: function ( geometry ) { - computeVertexNormals: function () { + var positions = new Float32Array( geometry.vertices.length * 3 ); + this.addAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) ); - var index = this.index; - var attributes = this.attributes; - var groups = this.groups; + if ( geometry.normals.length > 0 ) { - if ( attributes.position ) { + var normals = new Float32Array( geometry.normals.length * 3 ); + this.addAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) ); - var positions = attributes.position.array; + } - if ( attributes.normal === undefined ) { + if ( geometry.colors.length > 0 ) { - this.addAttribute( 'normal', new BufferAttribute( new Float32Array( positions.length ), 3 ) ); + var colors = new Float32Array( geometry.colors.length * 3 ); + this.addAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) ); - } else { + } - // reset existing normals to zero + if ( geometry.uvs.length > 0 ) { - var array = attributes.normal.array; + var uvs = new Float32Array( geometry.uvs.length * 2 ); + this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) ); - for ( var i = 0, il = array.length; i < il; i ++ ) { + } - array[ i ] = 0; + if ( geometry.uvs2.length > 0 ) { - } + var uvs2 = new Float32Array( geometry.uvs2.length * 2 ); + this.addAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) ); - } + } - var normals = attributes.normal.array; + if ( geometry.indices.length > 0 ) { - var vA, vB, vC, + var TypeArray = geometry.vertices.length > 65535 ? Uint32Array : Uint16Array; + var indices = new TypeArray( geometry.indices.length * 3 ); + this.setIndex( new BufferAttribute( indices, 1 ).copyIndicesArray( geometry.indices ) ); - pA = new Vector3(), - pB = new Vector3(), - pC = new Vector3(), + } - cb = new Vector3(), - ab = new Vector3(); + // groups - // indexed elements + this.groups = geometry.groups; - if ( index ) { + // morphs - var indices = index.array; + for ( var name in geometry.morphTargets ) { - if ( groups.length === 0 ) { + var array = []; + var morphTargets = geometry.morphTargets[ name ]; - this.addGroup( 0, indices.length ); + for ( var i = 0, l = morphTargets.length; i < l; i ++ ) { - } + var morphTarget = morphTargets[ i ]; - for ( var j = 0, jl = groups.length; j < jl; ++ j ) { + var attribute = new Float32Attribute( morphTarget.length * 3, 3 ); - var group = groups[ j ]; + array.push( attribute.copyVector3sArray( morphTarget ) ); - var start = group.start; - var count = group.count; + } - for ( var i = start, il = start + count; i < il; i += 3 ) { + this.morphAttributes[ name ] = array; - vA = indices[ i + 0 ] * 3; - vB = indices[ i + 1 ] * 3; - vC = indices[ i + 2 ] * 3; + } - pA.fromArray( positions, vA ); - pB.fromArray( positions, vB ); - pC.fromArray( positions, vC ); + // skinning - cb.subVectors( pC, pB ); - ab.subVectors( pA, pB ); - cb.cross( ab ); + if ( geometry.skinIndices.length > 0 ) { - normals[ vA ] += cb.x; - normals[ vA + 1 ] += cb.y; - normals[ vA + 2 ] += cb.z; + var skinIndices = new Float32Attribute( geometry.skinIndices.length * 4, 4 ); + this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) ); - normals[ vB ] += cb.x; - normals[ vB + 1 ] += cb.y; - normals[ vB + 2 ] += cb.z; + } - normals[ vC ] += cb.x; - normals[ vC + 1 ] += cb.y; - normals[ vC + 2 ] += cb.z; + if ( geometry.skinWeights.length > 0 ) { - } + var skinWeights = new Float32Attribute( geometry.skinWeights.length * 4, 4 ); + this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) ); - } + } - } else { + // - // non-indexed elements (unconnected triangle soup) + if ( geometry.boundingSphere !== null ) { - for ( var i = 0, il = positions.length; i < il; i += 9 ) { + this.boundingSphere = geometry.boundingSphere.clone(); - pA.fromArray( positions, i ); - pB.fromArray( positions, i + 3 ); - pC.fromArray( positions, i + 6 ); + } - cb.subVectors( pC, pB ); - ab.subVectors( pA, pB ); - cb.cross( ab ); + if ( geometry.boundingBox !== null ) { - normals[ i ] = cb.x; - normals[ i + 1 ] = cb.y; - normals[ i + 2 ] = cb.z; + this.boundingBox = geometry.boundingBox.clone(); - normals[ i + 3 ] = cb.x; - normals[ i + 4 ] = cb.y; - normals[ i + 5 ] = cb.z; + } - normals[ i + 6 ] = cb.x; - normals[ i + 7 ] = cb.y; - normals[ i + 8 ] = cb.z; + return this; - } + }, - } + computeBoundingBox: function () { - this.normalizeNormals(); + if ( this.boundingBox === null ) { - attributes.normal.needsUpdate = true; + this.boundingBox = new Box3(); - } + } - }, + var positions = this.attributes.position.array; - merge: function ( geometry, offset ) { + if ( positions !== undefined ) { - if ( (geometry && geometry.isBufferGeometry) === false ) { + this.boundingBox.setFromArray( positions ); - console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry ); - return; + } else { - } + this.boundingBox.makeEmpty(); - if ( offset === undefined ) offset = 0; + } - var attributes = this.attributes; + if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) { - for ( var key in attributes ) { + console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this ); - if ( geometry.attributes[ key ] === undefined ) continue; + } - var attribute1 = attributes[ key ]; - var attributeArray1 = attribute1.array; + }, - var attribute2 = geometry.attributes[ key ]; - var attributeArray2 = attribute2.array; + computeBoundingSphere: function () { - var attributeSize = attribute2.itemSize; + var box = new Box3(); + var vector = new Vector3(); - for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) { + return function computeBoundingSphere() { - attributeArray1[ j ] = attributeArray2[ i ]; + if ( this.boundingSphere === null ) { - } + this.boundingSphere = new Sphere(); - } + } - return this; + var positions = this.attributes.position; - }, + if ( positions ) { - normalizeNormals: function () { + var array = positions.array; + var center = this.boundingSphere.center; - var normals = this.attributes.normal.array; + box.setFromArray( array ); + box.center( center ); - var x, y, z, n; + // hoping to find a boundingSphere with a radius smaller than the + // boundingSphere of the boundingBox: sqrt(3) smaller in the best case - for ( var i = 0, il = normals.length; i < il; i += 3 ) { + var maxRadiusSq = 0; - x = normals[ i ]; - y = normals[ i + 1 ]; - z = normals[ i + 2 ]; + for ( var i = 0, il = array.length; i < il; i += 3 ) { - n = 1.0 / Math.sqrt( x * x + y * y + z * z ); + vector.fromArray( array, i ); + maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) ); - normals[ i ] *= n; - normals[ i + 1 ] *= n; - normals[ i + 2 ] *= n; + } - } + this.boundingSphere.radius = Math.sqrt( maxRadiusSq ); - }, + if ( isNaN( this.boundingSphere.radius ) ) { - toNonIndexed: function () { + console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this ); - if ( this.index === null ) { + } - console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' ); - return this; + } - } + }; - var geometry2 = new BufferGeometry(); + }(), - var indices = this.index.array; - var attributes = this.attributes; + computeFaceNormals: function () { - for ( var name in attributes ) { + // backwards compatibility - var attribute = attributes[ name ]; + }, - var array = attribute.array; - var itemSize = attribute.itemSize; + computeVertexNormals: function () { - var array2 = new array.constructor( indices.length * itemSize ); + var index = this.index; + var attributes = this.attributes; + var groups = this.groups; - var index = 0, index2 = 0; + if ( attributes.position ) { - for ( var i = 0, l = indices.length; i < l; i ++ ) { + var positions = attributes.position.array; - index = indices[ i ] * itemSize; + if ( attributes.normal === undefined ) { - for ( var j = 0; j < itemSize; j ++ ) { + this.addAttribute( 'normal', new BufferAttribute( new Float32Array( positions.length ), 3 ) ); - array2[ index2 ++ ] = array[ index ++ ]; + } else { - } + // reset existing normals to zero - } + var array = attributes.normal.array; - geometry2.addAttribute( name, new BufferAttribute( array2, itemSize ) ); + for ( var i = 0, il = array.length; i < il; i ++ ) { - } + array[ i ] = 0; - return geometry2; + } - }, + } - toJSON: function () { + var normals = attributes.normal.array; - var data = { - metadata: { - version: 4.4, - type: 'BufferGeometry', - generator: 'BufferGeometry.toJSON' - } - }; + var vA, vB, vC, - // standard BufferGeometry serialization + pA = new Vector3(), + pB = new Vector3(), + pC = new Vector3(), - data.uuid = this.uuid; - data.type = this.type; - if ( this.name !== '' ) data.name = this.name; + cb = new Vector3(), + ab = new Vector3(); - if ( this.parameters !== undefined ) { + // indexed elements - var parameters = this.parameters; + if ( index ) { - for ( var key in parameters ) { + var indices = index.array; - if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ]; + if ( groups.length === 0 ) { - } + this.addGroup( 0, indices.length ); - return data; + } - } + for ( var j = 0, jl = groups.length; j < jl; ++ j ) { - data.data = { attributes: {} }; + var group = groups[ j ]; - var index = this.index; + var start = group.start; + var count = group.count; - if ( index !== null ) { + for ( var i = start, il = start + count; i < il; i += 3 ) { - var array = Array.prototype.slice.call( index.array ); + vA = indices[ i + 0 ] * 3; + vB = indices[ i + 1 ] * 3; + vC = indices[ i + 2 ] * 3; - data.data.index = { - type: index.array.constructor.name, - array: array - }; + pA.fromArray( positions, vA ); + pB.fromArray( positions, vB ); + pC.fromArray( positions, vC ); - } + cb.subVectors( pC, pB ); + ab.subVectors( pA, pB ); + cb.cross( ab ); - var attributes = this.attributes; + normals[ vA ] += cb.x; + normals[ vA + 1 ] += cb.y; + normals[ vA + 2 ] += cb.z; - for ( var key in attributes ) { + normals[ vB ] += cb.x; + normals[ vB + 1 ] += cb.y; + normals[ vB + 2 ] += cb.z; - var attribute = attributes[ key ]; + normals[ vC ] += cb.x; + normals[ vC + 1 ] += cb.y; + normals[ vC + 2 ] += cb.z; - var array = Array.prototype.slice.call( attribute.array ); + } - data.data.attributes[ key ] = { - itemSize: attribute.itemSize, - type: attribute.array.constructor.name, - array: array, - normalized: attribute.normalized - }; + } - } + } else { - var groups = this.groups; + // non-indexed elements (unconnected triangle soup) - if ( groups.length > 0 ) { + for ( var i = 0, il = positions.length; i < il; i += 9 ) { - data.data.groups = JSON.parse( JSON.stringify( groups ) ); + pA.fromArray( positions, i ); + pB.fromArray( positions, i + 3 ); + pC.fromArray( positions, i + 6 ); - } + cb.subVectors( pC, pB ); + ab.subVectors( pA, pB ); + cb.cross( ab ); - var boundingSphere = this.boundingSphere; + normals[ i ] = cb.x; + normals[ i + 1 ] = cb.y; + normals[ i + 2 ] = cb.z; - if ( boundingSphere !== null ) { + normals[ i + 3 ] = cb.x; + normals[ i + 4 ] = cb.y; + normals[ i + 5 ] = cb.z; - data.data.boundingSphere = { - center: boundingSphere.center.toArray(), - radius: boundingSphere.radius - }; + normals[ i + 6 ] = cb.x; + normals[ i + 7 ] = cb.y; + normals[ i + 8 ] = cb.z; - } + } - return data; + } - }, + this.normalizeNormals(); - clone: function () { + attributes.normal.needsUpdate = true; - /* - // Handle primitives + } - var parameters = this.parameters; + }, - if ( parameters !== undefined ) { + merge: function ( geometry, offset ) { - var values = []; + if ( (geometry && geometry.isBufferGeometry) === false ) { - for ( var key in parameters ) { + console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry ); + return; - values.push( parameters[ key ] ); + } - } + if ( offset === undefined ) offset = 0; - var geometry = Object.create( this.constructor.prototype ); - this.constructor.apply( geometry, values ); - return geometry; + var attributes = this.attributes; - } + for ( var key in attributes ) { - return new this.constructor().copy( this ); - */ + if ( geometry.attributes[ key ] === undefined ) continue; - return new BufferGeometry().copy( this ); + var attribute1 = attributes[ key ]; + var attributeArray1 = attribute1.array; - }, + var attribute2 = geometry.attributes[ key ]; + var attributeArray2 = attribute2.array; - copy: function ( source ) { + var attributeSize = attribute2.itemSize; - var index = source.index; + for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) { - if ( index !== null ) { + attributeArray1[ j ] = attributeArray2[ i ]; - this.setIndex( index.clone() ); + } - } + } - var attributes = source.attributes; + return this; - for ( var name in attributes ) { + }, - var attribute = attributes[ name ]; - this.addAttribute( name, attribute.clone() ); + normalizeNormals: function () { - } + var normals = this.attributes.normal.array; - var groups = source.groups; + var x, y, z, n; - for ( var i = 0, l = groups.length; i < l; i ++ ) { + for ( var i = 0, il = normals.length; i < il; i += 3 ) { - var group = groups[ i ]; - this.addGroup( group.start, group.count, group.materialIndex ); + x = normals[ i ]; + y = normals[ i + 1 ]; + z = normals[ i + 2 ]; - } + n = 1.0 / Math.sqrt( x * x + y * y + z * z ); - return this; + normals[ i ] *= n; + normals[ i + 1 ] *= n; + normals[ i + 2 ] *= n; - }, + } - dispose: function () { + }, - this.dispatchEvent( { type: 'dispose' } ); + toNonIndexed: function () { - } + if ( this.index === null ) { - } ); + console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' ); + return this; - BufferGeometry.MaxIndex = 65535; + } - /** - * @author mrdoob / http://mrdoob.com/ - */ + var geometry2 = new BufferGeometry(); - function WebGLGeometries( gl, properties, info ) { + var indices = this.index.array; + var attributes = this.attributes; - var geometries = {}; + for ( var name in attributes ) { - function get( object ) { + var attribute = attributes[ name ]; - var geometry = object.geometry; + var array = attribute.array; + var itemSize = attribute.itemSize; - if ( geometries[ geometry.id ] !== undefined ) { + var array2 = new array.constructor( indices.length * itemSize ); - return geometries[ geometry.id ]; + var index = 0, index2 = 0; - } + for ( var i = 0, l = indices.length; i < l; i ++ ) { - geometry.addEventListener( 'dispose', onGeometryDispose ); + index = indices[ i ] * itemSize; - var buffergeometry; + for ( var j = 0; j < itemSize; j ++ ) { - if ( (geometry && geometry.isBufferGeometry) ) { + array2[ index2 ++ ] = array[ index ++ ]; - buffergeometry = geometry; + } - } else if ( (geometry && geometry.isGeometry) ) { + } - if ( geometry._bufferGeometry === undefined ) { + geometry2.addAttribute( name, new BufferAttribute( array2, itemSize ) ); - geometry._bufferGeometry = new BufferGeometry().setFromObject( object ); + } - } + return geometry2; - buffergeometry = geometry._bufferGeometry; + }, - } + toJSON: function () { - geometries[ geometry.id ] = buffergeometry; + var data = { + metadata: { + version: 4.4, + type: 'BufferGeometry', + generator: 'BufferGeometry.toJSON' + } + }; - info.memory.geometries ++; + // standard BufferGeometry serialization - return buffergeometry; + data.uuid = this.uuid; + data.type = this.type; + if ( this.name !== '' ) data.name = this.name; - } + if ( this.parameters !== undefined ) { - function onGeometryDispose( event ) { + var parameters = this.parameters; - var geometry = event.target; - var buffergeometry = geometries[ geometry.id ]; + for ( var key in parameters ) { - if ( buffergeometry.index !== null ) { + if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ]; - deleteAttribute( buffergeometry.index ); + } - } + return data; - deleteAttributes( buffergeometry.attributes ); + } - geometry.removeEventListener( 'dispose', onGeometryDispose ); + data.data = { attributes: {} }; - delete geometries[ geometry.id ]; + var index = this.index; - // TODO + if ( index !== null ) { - var property = properties.get( geometry ); + var array = Array.prototype.slice.call( index.array ); - if ( property.wireframe ) { + data.data.index = { + type: index.array.constructor.name, + array: array + }; - deleteAttribute( property.wireframe ); + } - } + var attributes = this.attributes; - properties.delete( geometry ); + for ( var key in attributes ) { - var bufferproperty = properties.get( buffergeometry ); + var attribute = attributes[ key ]; - if ( bufferproperty.wireframe ) { + var array = Array.prototype.slice.call( attribute.array ); - deleteAttribute( bufferproperty.wireframe ); + data.data.attributes[ key ] = { + itemSize: attribute.itemSize, + type: attribute.array.constructor.name, + array: array, + normalized: attribute.normalized + }; - } + } - properties.delete( buffergeometry ); + var groups = this.groups; - // + if ( groups.length > 0 ) { - info.memory.geometries --; + data.data.groups = JSON.parse( JSON.stringify( groups ) ); - } + } - function getAttributeBuffer( attribute ) { + var boundingSphere = this.boundingSphere; - if ( (attribute && attribute.isInterleavedBufferAttribute) ) { + if ( boundingSphere !== null ) { - return properties.get( attribute.data ).__webglBuffer; + data.data.boundingSphere = { + center: boundingSphere.center.toArray(), + radius: boundingSphere.radius + }; - } + } - return properties.get( attribute ).__webglBuffer; + return data; - } + }, - function deleteAttribute( attribute ) { + clone: function () { - var buffer = getAttributeBuffer( attribute ); + /* + // Handle primitives - if ( buffer !== undefined ) { + var parameters = this.parameters; - gl.deleteBuffer( buffer ); - removeAttributeBuffer( attribute ); + if ( parameters !== undefined ) { - } + var values = []; - } + for ( var key in parameters ) { - function deleteAttributes( attributes ) { + values.push( parameters[ key ] ); - for ( var name in attributes ) { + } - deleteAttribute( attributes[ name ] ); + var geometry = Object.create( this.constructor.prototype ); + this.constructor.apply( geometry, values ); + return geometry; - } + } - } + return new this.constructor().copy( this ); + */ - function removeAttributeBuffer( attribute ) { + return new BufferGeometry().copy( this ); - if ( (attribute && attribute.isInterleavedBufferAttribute) ) { + }, - properties.delete( attribute.data ); + copy: function ( source ) { - } else { + var index = source.index; - properties.delete( attribute ); + if ( index !== null ) { - } + this.setIndex( index.clone() ); - } + } - this.get = get; + var attributes = source.attributes; - }; + for ( var name in attributes ) { - /** - * @author mrdoob / http://mrdoob.com/ - */ + var attribute = attributes[ name ]; + this.addAttribute( name, attribute.clone() ); - function WebGLObjects( gl, properties, info ) { + } - var geometries = new WebGLGeometries( gl, properties, info ); + var groups = source.groups; - // + for ( var i = 0, l = groups.length; i < l; i ++ ) { - function update( object ) { + var group = groups[ i ]; + this.addGroup( group.start, group.count, group.materialIndex ); - // TODO: Avoid updating twice (when using shadowMap). Maybe add frame counter. + } - var geometry = geometries.get( object ); + return this; - if ( (object.geometry && object.geometry.isGeometry) ) { + }, - geometry.updateFromObject( object ); + dispose: function () { - } + this.dispatchEvent( { type: 'dispose' } ); - var index = geometry.index; - var attributes = geometry.attributes; + } - if ( index !== null ) { + } ); - updateAttribute( index, gl.ELEMENT_ARRAY_BUFFER ); + BufferGeometry.MaxIndex = 65535; - } + /** + * @author mrdoob / http://mrdoob.com/ + */ - for ( var name in attributes ) { + function WebGLGeometries( gl, properties, info ) { - updateAttribute( attributes[ name ], gl.ARRAY_BUFFER ); + var geometries = {}; - } + function get( object ) { - // morph targets + var geometry = object.geometry; - var morphAttributes = geometry.morphAttributes; + if ( geometries[ geometry.id ] !== undefined ) { - for ( var name in morphAttributes ) { + return geometries[ geometry.id ]; - var array = morphAttributes[ name ]; + } - for ( var i = 0, l = array.length; i < l; i ++ ) { + geometry.addEventListener( 'dispose', onGeometryDispose ); - updateAttribute( array[ i ], gl.ARRAY_BUFFER ); + var buffergeometry; - } + if ( (geometry && geometry.isBufferGeometry) ) { - } + buffergeometry = geometry; - return geometry; + } else if ( (geometry && geometry.isGeometry) ) { - } + if ( geometry._bufferGeometry === undefined ) { - function updateAttribute( attribute, bufferType ) { + geometry._bufferGeometry = new BufferGeometry().setFromObject( object ); - var data = ( (attribute && attribute.isInterleavedBufferAttribute) ) ? attribute.data : attribute; + } - var attributeProperties = properties.get( data ); + buffergeometry = geometry._bufferGeometry; - if ( attributeProperties.__webglBuffer === undefined ) { + } - createBuffer( attributeProperties, data, bufferType ); + geometries[ geometry.id ] = buffergeometry; - } else if ( attributeProperties.version !== data.version ) { + info.memory.geometries ++; - updateBuffer( attributeProperties, data, bufferType ); + return buffergeometry; - } + } - } + function onGeometryDispose( event ) { - function createBuffer( attributeProperties, data, bufferType ) { + var geometry = event.target; + var buffergeometry = geometries[ geometry.id ]; - attributeProperties.__webglBuffer = gl.createBuffer(); - gl.bindBuffer( bufferType, attributeProperties.__webglBuffer ); + if ( buffergeometry.index !== null ) { - var usage = data.dynamic ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW; + deleteAttribute( buffergeometry.index ); - gl.bufferData( bufferType, data.array, usage ); + } - attributeProperties.version = data.version; + deleteAttributes( buffergeometry.attributes ); - } + geometry.removeEventListener( 'dispose', onGeometryDispose ); - function updateBuffer( attributeProperties, data, bufferType ) { + delete geometries[ geometry.id ]; - gl.bindBuffer( bufferType, attributeProperties.__webglBuffer ); + // TODO - if ( data.dynamic === false || data.updateRange.count === - 1 ) { + var property = properties.get( geometry ); - // Not using update ranges + if ( property.wireframe ) { - gl.bufferSubData( bufferType, 0, data.array ); + deleteAttribute( property.wireframe ); - } else if ( data.updateRange.count === 0 ) { + } - console.error( 'THREE.WebGLObjects.updateBuffer: dynamic THREE.BufferAttribute marked as needsUpdate but updateRange.count is 0, ensure you are using set methods or updating manually.' ); + properties.delete( geometry ); - } else { + var bufferproperty = properties.get( buffergeometry ); - gl.bufferSubData( bufferType, data.updateRange.offset * data.array.BYTES_PER_ELEMENT, - data.array.subarray( data.updateRange.offset, data.updateRange.offset + data.updateRange.count ) ); + if ( bufferproperty.wireframe ) { - data.updateRange.count = 0; // reset range + deleteAttribute( bufferproperty.wireframe ); - } + } - attributeProperties.version = data.version; + properties.delete( buffergeometry ); - } + // - function getAttributeBuffer( attribute ) { + info.memory.geometries --; - if ( (attribute && attribute.isInterleavedBufferAttribute) ) { + } - return properties.get( attribute.data ).__webglBuffer; + function getAttributeBuffer( attribute ) { - } + if ( (attribute && attribute.isInterleavedBufferAttribute) ) { - return properties.get( attribute ).__webglBuffer; + return properties.get( attribute.data ).__webglBuffer; - } + } - function getWireframeAttribute( geometry ) { + return properties.get( attribute ).__webglBuffer; - var property = properties.get( geometry ); + } - if ( property.wireframe !== undefined ) { + function deleteAttribute( attribute ) { - return property.wireframe; + var buffer = getAttributeBuffer( attribute ); - } + if ( buffer !== undefined ) { - var indices = []; + gl.deleteBuffer( buffer ); + removeAttributeBuffer( attribute ); - var index = geometry.index; - var attributes = geometry.attributes; - var position = attributes.position; + } - // console.time( 'wireframe' ); + } - if ( index !== null ) { + function deleteAttributes( attributes ) { - var edges = {}; - var array = index.array; + for ( var name in attributes ) { - for ( var i = 0, l = array.length; i < l; i += 3 ) { + deleteAttribute( attributes[ name ] ); - var a = array[ i + 0 ]; - var b = array[ i + 1 ]; - var c = array[ i + 2 ]; + } - if ( checkEdge( edges, a, b ) ) indices.push( a, b ); - if ( checkEdge( edges, b, c ) ) indices.push( b, c ); - if ( checkEdge( edges, c, a ) ) indices.push( c, a ); + } - } + function removeAttributeBuffer( attribute ) { - } else { + if ( (attribute && attribute.isInterleavedBufferAttribute) ) { - var array = attributes.position.array; + properties.delete( attribute.data ); - for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) { + } else { - var a = i + 0; - var b = i + 1; - var c = i + 2; + properties.delete( attribute ); - indices.push( a, b, b, c, c, a ); + } - } + } - } + this.get = get; - // console.timeEnd( 'wireframe' ); + } - var TypeArray = position.count > 65535 ? Uint32Array : Uint16Array; - var attribute = new BufferAttribute( new TypeArray( indices ), 1 ); + /** + * @author mrdoob / http://mrdoob.com/ + */ - updateAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER ); + function WebGLObjects( gl, properties, info ) { - property.wireframe = attribute; + var geometries = new WebGLGeometries( gl, properties, info ); - return attribute; + // - } + function update( object ) { - function checkEdge( edges, a, b ) { + // TODO: Avoid updating twice (when using shadowMap). Maybe add frame counter. - if ( a > b ) { + var geometry = geometries.get( object ); - var tmp = a; - a = b; - b = tmp; + if ( (object.geometry && object.geometry.isGeometry) ) { - } + geometry.updateFromObject( object ); - var list = edges[ a ]; + } - if ( list === undefined ) { + var index = geometry.index; + var attributes = geometry.attributes; - edges[ a ] = [ b ]; - return true; + if ( index !== null ) { - } else if ( list.indexOf( b ) === -1 ) { + updateAttribute( index, gl.ELEMENT_ARRAY_BUFFER ); - list.push( b ); - return true; + } - } + for ( var name in attributes ) { - return false; + updateAttribute( attributes[ name ], gl.ARRAY_BUFFER ); - } + } - this.getAttributeBuffer = getAttributeBuffer; - this.getWireframeAttribute = getWireframeAttribute; + // morph targets - this.update = update; + var morphAttributes = geometry.morphAttributes; - }; + for ( var name in morphAttributes ) { - /** - * @author mrdoob / http://mrdoob.com/ - */ + var array = morphAttributes[ name ]; - function WebGLLights() { + for ( var i = 0, l = array.length; i < l; i ++ ) { - var lights = {}; + updateAttribute( array[ i ], gl.ARRAY_BUFFER ); - this.get = function ( light ) { + } - if ( lights[ light.id ] !== undefined ) { + } - return lights[ light.id ]; + return geometry; - } + } - var uniforms; + function updateAttribute( attribute, bufferType ) { - switch ( light.type ) { + var data = ( (attribute && attribute.isInterleavedBufferAttribute) ) ? attribute.data : attribute; - case 'DirectionalLight': - uniforms = { - direction: new Vector3(), - color: new Color(), + var attributeProperties = properties.get( data ); - shadow: false, - shadowBias: 0, - shadowRadius: 1, - shadowMapSize: new Vector2() - }; - break; + if ( attributeProperties.__webglBuffer === undefined ) { - case 'SpotLight': - uniforms = { - position: new Vector3(), - direction: new Vector3(), - color: new Color(), - distance: 0, - coneCos: 0, - penumbraCos: 0, - decay: 0, + createBuffer( attributeProperties, data, bufferType ); - shadow: false, - shadowBias: 0, - shadowRadius: 1, - shadowMapSize: new Vector2() - }; - break; + } else if ( attributeProperties.version !== data.version ) { - case 'PointLight': - uniforms = { - position: new Vector3(), - color: new Color(), - distance: 0, - decay: 0, + updateBuffer( attributeProperties, data, bufferType ); - shadow: false, - shadowBias: 0, - shadowRadius: 1, - shadowMapSize: new Vector2() - }; - break; + } - case 'HemisphereLight': - uniforms = { - direction: new Vector3(), - skyColor: new Color(), - groundColor: new Color() - }; - break; + } - } + function createBuffer( attributeProperties, data, bufferType ) { - lights[ light.id ] = uniforms; + attributeProperties.__webglBuffer = gl.createBuffer(); + gl.bindBuffer( bufferType, attributeProperties.__webglBuffer ); - return uniforms; + var usage = data.dynamic ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW; - }; + gl.bufferData( bufferType, data.array, usage ); - }; + attributeProperties.version = data.version; - function WebGLCapabilities( gl, extensions, parameters ) { + } - var maxAnisotropy; + function updateBuffer( attributeProperties, data, bufferType ) { - function getMaxAnisotropy() { + gl.bindBuffer( bufferType, attributeProperties.__webglBuffer ); - if ( maxAnisotropy !== undefined ) return maxAnisotropy; + if ( data.dynamic === false || data.updateRange.count === - 1 ) { - var extension = extensions.get( 'EXT_texture_filter_anisotropic' ); + // Not using update ranges - if ( extension !== null ) { + gl.bufferSubData( bufferType, 0, data.array ); - maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT ); + } else if ( data.updateRange.count === 0 ) { - } else { + console.error( 'THREE.WebGLObjects.updateBuffer: dynamic THREE.BufferAttribute marked as needsUpdate but updateRange.count is 0, ensure you are using set methods or updating manually.' ); - maxAnisotropy = 0; + } else { - } + gl.bufferSubData( bufferType, data.updateRange.offset * data.array.BYTES_PER_ELEMENT, + data.array.subarray( data.updateRange.offset, data.updateRange.offset + data.updateRange.count ) ); - return maxAnisotropy; + data.updateRange.count = 0; // reset range - } + } - function getMaxPrecision( precision ) { + attributeProperties.version = data.version; - if ( precision === 'highp' ) { + } - if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 && - gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) { + function getAttributeBuffer( attribute ) { - return 'highp'; + if ( (attribute && attribute.isInterleavedBufferAttribute) ) { - } + return properties.get( attribute.data ).__webglBuffer; - precision = 'mediump'; + } - } + return properties.get( attribute ).__webglBuffer; - if ( precision === 'mediump' ) { + } - if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 && - gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) { + function getWireframeAttribute( geometry ) { - return 'mediump'; + var property = properties.get( geometry ); - } + if ( property.wireframe !== undefined ) { - } + return property.wireframe; - return 'lowp'; + } - } + var indices = []; - this.getMaxAnisotropy = getMaxAnisotropy; - this.getMaxPrecision = getMaxPrecision; + var index = geometry.index; + var attributes = geometry.attributes; + var position = attributes.position; - this.precision = parameters.precision !== undefined ? parameters.precision : 'highp'; - this.logarithmicDepthBuffer = parameters.logarithmicDepthBuffer !== undefined ? parameters.logarithmicDepthBuffer : false; + // console.time( 'wireframe' ); - this.maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS ); - this.maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ); - this.maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE ); - this.maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE ); + if ( index !== null ) { - this.maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS ); - this.maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS ); - this.maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS ); - this.maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS ); + var edges = {}; + var array = index.array; - this.vertexTextures = this.maxVertexTextures > 0; - this.floatFragmentTextures = !! extensions.get( 'OES_texture_float' ); - this.floatVertexTextures = this.vertexTextures && this.floatFragmentTextures; + for ( var i = 0, l = array.length; i < l; i += 3 ) { - var _maxPrecision = getMaxPrecision( this.precision ); + var a = array[ i + 0 ]; + var b = array[ i + 1 ]; + var c = array[ i + 2 ]; - if ( _maxPrecision !== this.precision ) { + if ( checkEdge( edges, a, b ) ) indices.push( a, b ); + if ( checkEdge( edges, b, c ) ) indices.push( b, c ); + if ( checkEdge( edges, c, a ) ) indices.push( c, a ); - console.warn( 'THREE.WebGLRenderer:', this.precision, 'not supported, using', _maxPrecision, 'instead.' ); - this.precision = _maxPrecision; + } - } + } else { - if ( this.logarithmicDepthBuffer ) { + var array = attributes.position.array; - this.logarithmicDepthBuffer = !! extensions.get( 'EXT_frag_depth' ); + for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) { - } + var a = i + 0; + var b = i + 1; + var c = i + 2; - }; + indices.push( a, b, b, c, c, a ); - /** - * @author mrdoob / http://mrdoob.com/ - */ + } - function WebGLExtensions( gl ) { + } - var extensions = {}; + // console.timeEnd( 'wireframe' ); - this.get = function ( name ) { + var TypeArray = position.count > 65535 ? Uint32Array : Uint16Array; + var attribute = new BufferAttribute( new TypeArray( indices ), 1 ); - if ( extensions[ name ] !== undefined ) { + updateAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER ); - return extensions[ name ]; + property.wireframe = attribute; - } + return attribute; - var extension; + } - switch ( name ) { + function checkEdge( edges, a, b ) { - case 'WEBGL_depth_texture': - extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' ); - break; + if ( a > b ) { - case 'EXT_texture_filter_anisotropic': - extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' ); - break; + var tmp = a; + a = b; + b = tmp; - case 'WEBGL_compressed_texture_s3tc': - extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' ); - break; + } - case 'WEBGL_compressed_texture_pvrtc': - extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' ); - break; + var list = edges[ a ]; - case 'WEBGL_compressed_texture_etc1': - extension = gl.getExtension( 'WEBGL_compressed_texture_etc1' ); - break; + if ( list === undefined ) { - default: - extension = gl.getExtension( name ); + edges[ a ] = [ b ]; + return true; - } + } else if ( list.indexOf( b ) === -1 ) { - if ( extension === null ) { + list.push( b ); + return true; - console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' ); + } - } + return false; - extensions[ name ] = extension; + } - return extension; + this.getAttributeBuffer = getAttributeBuffer; + this.getWireframeAttribute = getWireframeAttribute; - }; + this.update = update; - }; + } - /** - * @author mrdoob / http://mrdoob.com/ - */ + /** + * @author mrdoob / http://mrdoob.com/ + */ - function WebGLIndexedBufferRenderer( _gl, extensions, _infoRender ) { + function WebGLLights() { - var mode; + var lights = {}; - function setMode( value ) { + this.get = function ( light ) { - mode = value; + if ( lights[ light.id ] !== undefined ) { - } + return lights[ light.id ]; - var type, size; + } - function setIndex( index ) { + var uniforms; - if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) { + switch ( light.type ) { - type = _gl.UNSIGNED_INT; - size = 4; + case 'DirectionalLight': + uniforms = { + direction: new Vector3(), + color: new Color(), - } else { + shadow: false, + shadowBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2() + }; + break; - type = _gl.UNSIGNED_SHORT; - size = 2; + case 'SpotLight': + uniforms = { + position: new Vector3(), + direction: new Vector3(), + color: new Color(), + distance: 0, + coneCos: 0, + penumbraCos: 0, + decay: 0, - } + shadow: false, + shadowBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2() + }; + break; - } + case 'PointLight': + uniforms = { + position: new Vector3(), + color: new Color(), + distance: 0, + decay: 0, - function render( start, count ) { + shadow: false, + shadowBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2() + }; + break; - _gl.drawElements( mode, count, type, start * size ); + case 'HemisphereLight': + uniforms = { + direction: new Vector3(), + skyColor: new Color(), + groundColor: new Color() + }; + break; - _infoRender.calls ++; - _infoRender.vertices += count; - if ( mode === _gl.TRIANGLES ) _infoRender.faces += count / 3; + } - } + lights[ light.id ] = uniforms; - function renderInstances( geometry, start, count ) { + return uniforms; - var extension = extensions.get( 'ANGLE_instanced_arrays' ); + }; - if ( extension === null ) { + } - console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); - return; + function WebGLCapabilities( gl, extensions, parameters ) { - } + var maxAnisotropy; - extension.drawElementsInstancedANGLE( mode, count, type, start * size, geometry.maxInstancedCount ); + function getMaxAnisotropy() { - _infoRender.calls ++; - _infoRender.vertices += count * geometry.maxInstancedCount; - if ( mode === _gl.TRIANGLES ) _infoRender.faces += geometry.maxInstancedCount * count / 3; - } + if ( maxAnisotropy !== undefined ) return maxAnisotropy; - this.setMode = setMode; - this.setIndex = setIndex; - this.render = render; - this.renderInstances = renderInstances; + var extension = extensions.get( 'EXT_texture_filter_anisotropic' ); - }; + if ( extension !== null ) { - function WebGLClipping() { + maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT ); - var scope = this, + } else { - globalState = null, - numGlobalPlanes = 0, - localClippingEnabled = false, - renderingShadows = false, + maxAnisotropy = 0; - plane = new Plane(), - viewNormalMatrix = new Matrix3(), + } - uniform = { value: null, needsUpdate: false }; + return maxAnisotropy; - this.uniform = uniform; - this.numPlanes = 0; + } - this.init = function( planes, enableLocalClipping, camera ) { + function getMaxPrecision( precision ) { - var enabled = - planes.length !== 0 || - enableLocalClipping || - // enable state of previous frame - the clipping code has to - // run another frame in order to reset the state: - numGlobalPlanes !== 0 || - localClippingEnabled; + if ( precision === 'highp' ) { - localClippingEnabled = enableLocalClipping; + if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 && + gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) { - globalState = projectPlanes( planes, camera, 0 ); - numGlobalPlanes = planes.length; + return 'highp'; - return enabled; + } - }; + precision = 'mediump'; - this.beginShadows = function() { + } - renderingShadows = true; - projectPlanes( null ); + if ( precision === 'mediump' ) { - }; + if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 && + gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) { - this.endShadows = function() { + return 'mediump'; - renderingShadows = false; - resetGlobalState(); + } - }; + } - this.setState = function( planes, clipShadows, camera, cache, fromCache ) { + return 'lowp'; - if ( ! localClippingEnabled || - planes === null || planes.length === 0 || - renderingShadows && ! clipShadows ) { - // there's no local clipping + } - if ( renderingShadows ) { - // there's no global clipping + this.getMaxAnisotropy = getMaxAnisotropy; + this.getMaxPrecision = getMaxPrecision; - projectPlanes( null ); + this.precision = parameters.precision !== undefined ? parameters.precision : 'highp'; + this.logarithmicDepthBuffer = parameters.logarithmicDepthBuffer !== undefined ? parameters.logarithmicDepthBuffer : false; - } else { + this.maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS ); + this.maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ); + this.maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE ); + this.maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE ); - resetGlobalState(); - } + this.maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS ); + this.maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS ); + this.maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS ); + this.maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS ); - } else { + this.vertexTextures = this.maxVertexTextures > 0; + this.floatFragmentTextures = !! extensions.get( 'OES_texture_float' ); + this.floatVertexTextures = this.vertexTextures && this.floatFragmentTextures; - var nGlobal = renderingShadows ? 0 : numGlobalPlanes, - lGlobal = nGlobal * 4, + var _maxPrecision = getMaxPrecision( this.precision ); - dstArray = cache.clippingState || null; + if ( _maxPrecision !== this.precision ) { - uniform.value = dstArray; // ensure unique state + console.warn( 'THREE.WebGLRenderer:', this.precision, 'not supported, using', _maxPrecision, 'instead.' ); + this.precision = _maxPrecision; - dstArray = projectPlanes( planes, camera, lGlobal, fromCache ); + } - for ( var i = 0; i !== lGlobal; ++ i ) { + if ( this.logarithmicDepthBuffer ) { - dstArray[ i ] = globalState[ i ]; + this.logarithmicDepthBuffer = !! extensions.get( 'EXT_frag_depth' ); - } + } - cache.clippingState = dstArray; - this.numPlanes += nGlobal; + } - } + /** + * @author mrdoob / http://mrdoob.com/ + */ + function WebGLExtensions( gl ) { - }; + var extensions = {}; - function resetGlobalState() { + this.get = function ( name ) { - if ( uniform.value !== globalState ) { + if ( extensions[ name ] !== undefined ) { - uniform.value = globalState; - uniform.needsUpdate = numGlobalPlanes > 0; + return extensions[ name ]; - } + } - scope.numPlanes = numGlobalPlanes; + var extension; - } + switch ( name ) { - function projectPlanes( planes, camera, dstOffset, skipTransform ) { + case 'WEBGL_depth_texture': + extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' ); + break; - var nPlanes = planes !== null ? planes.length : 0, - dstArray = null; + case 'EXT_texture_filter_anisotropic': + extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' ); + break; - if ( nPlanes !== 0 ) { + case 'WEBGL_compressed_texture_s3tc': + extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' ); + break; - dstArray = uniform.value; + case 'WEBGL_compressed_texture_pvrtc': + extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' ); + break; - if ( skipTransform !== true || dstArray === null ) { + case 'WEBGL_compressed_texture_etc1': + extension = gl.getExtension( 'WEBGL_compressed_texture_etc1' ); + break; - var flatSize = dstOffset + nPlanes * 4, - viewMatrix = camera.matrixWorldInverse; + default: + extension = gl.getExtension( name ); - viewNormalMatrix.getNormalMatrix( viewMatrix ); + } - if ( dstArray === null || dstArray.length < flatSize ) { + if ( extension === null ) { - dstArray = new Float32Array( flatSize ); + console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' ); - } + } - for ( var i = 0, i4 = dstOffset; - i !== nPlanes; ++ i, i4 += 4 ) { + extensions[ name ] = extension; - plane.copy( planes[ i ] ). - applyMatrix4( viewMatrix, viewNormalMatrix ); + return extension; - plane.normal.toArray( dstArray, i4 ); - dstArray[ i4 + 3 ] = plane.constant; + }; - } + } - } + /** + * @author mrdoob / http://mrdoob.com/ + */ - uniform.value = dstArray; - uniform.needsUpdate = true; + function WebGLIndexedBufferRenderer( _gl, extensions, _infoRender ) { - } + var mode; - scope.numPlanes = nPlanes; - return dstArray; + function setMode( value ) { - } + mode = value; - }; + } - /** - * @author mrdoob / http://mrdoob.com/ - */ + var type, size; - function WebGLBufferRenderer( _gl, extensions, _infoRender ) { + function setIndex( index ) { - var mode; + if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) { - function setMode( value ) { + type = _gl.UNSIGNED_INT; + size = 4; - mode = value; + } else { - } + type = _gl.UNSIGNED_SHORT; + size = 2; - function render( start, count ) { + } - _gl.drawArrays( mode, start, count ); + } - _infoRender.calls ++; - _infoRender.vertices += count; - if ( mode === _gl.TRIANGLES ) _infoRender.faces += count / 3; + function render( start, count ) { - } + _gl.drawElements( mode, count, type, start * size ); - function renderInstances( geometry ) { + _infoRender.calls ++; + _infoRender.vertices += count; + if ( mode === _gl.TRIANGLES ) _infoRender.faces += count / 3; - var extension = extensions.get( 'ANGLE_instanced_arrays' ); + } - if ( extension === null ) { + function renderInstances( geometry, start, count ) { - console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); - return; + var extension = extensions.get( 'ANGLE_instanced_arrays' ); - } + if ( extension === null ) { - var position = geometry.attributes.position; + console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); + return; - var count = 0; + } - if ( (position && position.isInterleavedBufferAttribute) ) { + extension.drawElementsInstancedANGLE( mode, count, type, start * size, geometry.maxInstancedCount ); - count = position.data.count; + _infoRender.calls ++; + _infoRender.vertices += count * geometry.maxInstancedCount; + if ( mode === _gl.TRIANGLES ) _infoRender.faces += geometry.maxInstancedCount * count / 3; + } - extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount ); + this.setMode = setMode; + this.setIndex = setIndex; + this.render = render; + this.renderInstances = renderInstances; - } else { + } - count = position.count; + function WebGLClipping() { - extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount ); + var scope = this, - } + globalState = null, + numGlobalPlanes = 0, + localClippingEnabled = false, + renderingShadows = false, - _infoRender.calls ++; - _infoRender.vertices += count * geometry.maxInstancedCount; - if ( mode === _gl.TRIANGLES ) _infoRender.faces += geometry.maxInstancedCount * count / 3; + plane = new Plane(), + viewNormalMatrix = new Matrix3(), - } + uniform = { value: null, needsUpdate: false }; - this.setMode = setMode; - this.render = render; - this.renderInstances = renderInstances; + this.uniform = uniform; + this.numPlanes = 0; - }; + this.init = function( planes, enableLocalClipping, camera ) { - /** - * @author alteredq / http://alteredqualia.com - */ + var enabled = + planes.length !== 0 || + enableLocalClipping || + // enable state of previous frame - the clipping code has to + // run another frame in order to reset the state: + numGlobalPlanes !== 0 || + localClippingEnabled; - function WebGLRenderTargetCube( width, height, options ) { + localClippingEnabled = enableLocalClipping; - WebGLRenderTarget.call( this, width, height, options ); + globalState = projectPlanes( planes, camera, 0 ); + numGlobalPlanes = planes.length; - this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5 - this.activeMipMapLevel = 0; + return enabled; - }; + }; - WebGLRenderTargetCube.prototype = Object.create( WebGLRenderTarget.prototype ); - WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube; + this.beginShadows = function() { - WebGLRenderTargetCube.prototype.isWebGLRenderTargetCube = true; + renderingShadows = true; + projectPlanes( null ); - /** - * @author Mugen87 / https://github.com/Mugen87 - */ + }; - function BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) { + this.endShadows = function() { - BufferGeometry.call( this ); + renderingShadows = false; + resetGlobalState(); - this.type = 'BoxBufferGeometry'; + }; - this.parameters = { - width: width, - height: height, - depth: depth, - widthSegments: widthSegments, - heightSegments: heightSegments, - depthSegments: depthSegments - }; + this.setState = function( planes, clipShadows, camera, cache, fromCache ) { - var scope = this; + if ( ! localClippingEnabled || + planes === null || planes.length === 0 || + renderingShadows && ! clipShadows ) { + // there's no local clipping - // segments - widthSegments = Math.floor( widthSegments ) || 1; - heightSegments = Math.floor( heightSegments ) || 1; - depthSegments = Math.floor( depthSegments ) || 1; + if ( renderingShadows ) { + // there's no global clipping - // these are used to calculate buffer length - var vertexCount = calculateVertexCount( widthSegments, heightSegments, depthSegments ); - var indexCount = calculateIndexCount( widthSegments, heightSegments, depthSegments ); + projectPlanes( null ); - // buffers - var indices = new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ); - var vertices = new Float32Array( vertexCount * 3 ); - var normals = new Float32Array( vertexCount * 3 ); - var uvs = new Float32Array( vertexCount * 2 ); + } else { - // offset variables - var vertexBufferOffset = 0; - var uvBufferOffset = 0; - var indexBufferOffset = 0; - var numberOfVertices = 0; + resetGlobalState(); + } - // group variables - var groupStart = 0; + } else { - // build each side of the box geometry - buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px - buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx - buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py - buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny - buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz - buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz + var nGlobal = renderingShadows ? 0 : numGlobalPlanes, + lGlobal = nGlobal * 4, - // build geometry - this.setIndex( new BufferAttribute( indices, 1 ) ); - this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) ); - this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) ); - this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) ); + dstArray = cache.clippingState || null; - // helper functions + uniform.value = dstArray; // ensure unique state - function calculateVertexCount( w, h, d ) { + dstArray = projectPlanes( planes, camera, lGlobal, fromCache ); - var vertices = 0; + for ( var i = 0; i !== lGlobal; ++ i ) { - // calculate the amount of vertices for each side (plane) - vertices += (w + 1) * (h + 1) * 2; // xy - vertices += (w + 1) * (d + 1) * 2; // xz - vertices += (d + 1) * (h + 1) * 2; // zy + dstArray[ i ] = globalState[ i ]; - return vertices; + } - } + cache.clippingState = dstArray; + this.numPlanes += nGlobal; - function calculateIndexCount( w, h, d ) { + } - var index = 0; - // calculate the amount of squares for each side - index += w * h * 2; // xy - index += w * d * 2; // xz - index += d * h * 2; // zy + }; - return index * 6; // two triangles per square => six vertices per square + function resetGlobalState() { - } + if ( uniform.value !== globalState ) { - function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) { + uniform.value = globalState; + uniform.needsUpdate = numGlobalPlanes > 0; - var segmentWidth = width / gridX; - var segmentHeight = height / gridY; + } - var widthHalf = width / 2; - var heightHalf = height / 2; - var depthHalf = depth / 2; + scope.numPlanes = numGlobalPlanes; - var gridX1 = gridX + 1; - var gridY1 = gridY + 1; + } - var vertexCounter = 0; - var groupCount = 0; + function projectPlanes( planes, camera, dstOffset, skipTransform ) { - var vector = new Vector3(); + var nPlanes = planes !== null ? planes.length : 0, + dstArray = null; - // generate vertices, normals and uvs + if ( nPlanes !== 0 ) { - for ( var iy = 0; iy < gridY1; iy ++ ) { + dstArray = uniform.value; - var y = iy * segmentHeight - heightHalf; + if ( skipTransform !== true || dstArray === null ) { - for ( var ix = 0; ix < gridX1; ix ++ ) { + var flatSize = dstOffset + nPlanes * 4, + viewMatrix = camera.matrixWorldInverse; - var x = ix * segmentWidth - widthHalf; + viewNormalMatrix.getNormalMatrix( viewMatrix ); - // set values to correct vector component - vector[ u ] = x * udir; - vector[ v ] = y * vdir; - vector[ w ] = depthHalf; + if ( dstArray === null || dstArray.length < flatSize ) { - // now apply vector to vertex buffer - vertices[ vertexBufferOffset ] = vector.x; - vertices[ vertexBufferOffset + 1 ] = vector.y; - vertices[ vertexBufferOffset + 2 ] = vector.z; + dstArray = new Float32Array( flatSize ); - // set values to correct vector component - vector[ u ] = 0; - vector[ v ] = 0; - vector[ w ] = depth > 0 ? 1 : - 1; + } - // now apply vector to normal buffer - normals[ vertexBufferOffset ] = vector.x; - normals[ vertexBufferOffset + 1 ] = vector.y; - normals[ vertexBufferOffset + 2 ] = vector.z; + for ( var i = 0, i4 = dstOffset; + i !== nPlanes; ++ i, i4 += 4 ) { - // uvs - uvs[ uvBufferOffset ] = ix / gridX; - uvs[ uvBufferOffset + 1 ] = 1 - ( iy / gridY ); + plane.copy( planes[ i ] ). + applyMatrix4( viewMatrix, viewNormalMatrix ); - // update offsets and counters - vertexBufferOffset += 3; - uvBufferOffset += 2; - vertexCounter += 1; + plane.normal.toArray( dstArray, i4 ); + dstArray[ i4 + 3 ] = plane.constant; - } + } - } + } - // 1. you need three indices to draw a single face - // 2. a single segment consists of two faces - // 3. so we need to generate six (2*3) indices per segment + uniform.value = dstArray; + uniform.needsUpdate = true; - for ( iy = 0; iy < gridY; iy ++ ) { + } - for ( ix = 0; ix < gridX; ix ++ ) { + scope.numPlanes = nPlanes; + return dstArray; - // indices - var a = numberOfVertices + ix + gridX1 * iy; - var b = numberOfVertices + ix + gridX1 * ( iy + 1 ); - var c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 ); - var d = numberOfVertices + ( ix + 1 ) + gridX1 * iy; + } - // face one - indices[ indexBufferOffset ] = a; - indices[ indexBufferOffset + 1 ] = b; - indices[ indexBufferOffset + 2 ] = d; + } - // face two - indices[ indexBufferOffset + 3 ] = b; - indices[ indexBufferOffset + 4 ] = c; - indices[ indexBufferOffset + 5 ] = d; + /** + * @author mrdoob / http://mrdoob.com/ + */ - // update offsets and counters - indexBufferOffset += 6; - groupCount += 6; + function WebGLBufferRenderer( _gl, extensions, _infoRender ) { - } + var mode; - } + function setMode( value ) { - // add a group to the geometry. this will ensure multi material support - scope.addGroup( groupStart, groupCount, materialIndex ); + mode = value; - // calculate new start value for groups - groupStart += groupCount; + } - // update total number of vertices - numberOfVertices += vertexCounter; + function render( start, count ) { - } + _gl.drawArrays( mode, start, count ); - }; + _infoRender.calls ++; + _infoRender.vertices += count; + if ( mode === _gl.TRIANGLES ) _infoRender.faces += count / 3; - BoxBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); - BoxBufferGeometry.prototype.constructor = BoxBufferGeometry; + } - /** - * @author bhouston / http://clara.io - */ + function renderInstances( geometry ) { - function Ray( origin, direction ) { + var extension = extensions.get( 'ANGLE_instanced_arrays' ); - this.origin = ( origin !== undefined ) ? origin : new Vector3(); - this.direction = ( direction !== undefined ) ? direction : new Vector3(); + if ( extension === null ) { - }; + console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); + return; - Ray.prototype = { + } - constructor: Ray, + var position = geometry.attributes.position; - set: function ( origin, direction ) { + var count = 0; - this.origin.copy( origin ); - this.direction.copy( direction ); + if ( (position && position.isInterleavedBufferAttribute) ) { - return this; + count = position.data.count; - }, + extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount ); - clone: function () { + } else { - return new this.constructor().copy( this ); + count = position.count; - }, + extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount ); - copy: function ( ray ) { + } - this.origin.copy( ray.origin ); - this.direction.copy( ray.direction ); + _infoRender.calls ++; + _infoRender.vertices += count * geometry.maxInstancedCount; + if ( mode === _gl.TRIANGLES ) _infoRender.faces += geometry.maxInstancedCount * count / 3; - return this; + } - }, + this.setMode = setMode; + this.render = render; + this.renderInstances = renderInstances; - at: function ( t, optionalTarget ) { + } - var result = optionalTarget || new Vector3(); + /** + * @author alteredq / http://alteredqualia.com + */ - return result.copy( this.direction ).multiplyScalar( t ).add( this.origin ); + function WebGLRenderTargetCube( width, height, options ) { - }, + WebGLRenderTarget.call( this, width, height, options ); - lookAt: function ( v ) { + this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5 + this.activeMipMapLevel = 0; - this.direction.copy( v ).sub( this.origin ).normalize(); + } - return this; + WebGLRenderTargetCube.prototype = Object.create( WebGLRenderTarget.prototype ); + WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube; - }, + WebGLRenderTargetCube.prototype.isWebGLRenderTargetCube = true; - recast: function () { + /** + * @author Mugen87 / https://github.com/Mugen87 + */ - var v1 = new Vector3(); + function BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) { - return function recast( t ) { + BufferGeometry.call( this ); - this.origin.copy( this.at( t, v1 ) ); + this.type = 'BoxBufferGeometry'; - return this; + this.parameters = { + width: width, + height: height, + depth: depth, + widthSegments: widthSegments, + heightSegments: heightSegments, + depthSegments: depthSegments + }; - }; + var scope = this; - }(), + // segments + widthSegments = Math.floor( widthSegments ) || 1; + heightSegments = Math.floor( heightSegments ) || 1; + depthSegments = Math.floor( depthSegments ) || 1; - closestPointToPoint: function ( point, optionalTarget ) { + // these are used to calculate buffer length + var vertexCount = calculateVertexCount( widthSegments, heightSegments, depthSegments ); + var indexCount = calculateIndexCount( widthSegments, heightSegments, depthSegments ); - var result = optionalTarget || new Vector3(); - result.subVectors( point, this.origin ); - var directionDistance = result.dot( this.direction ); + // buffers + var indices = new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ); + var vertices = new Float32Array( vertexCount * 3 ); + var normals = new Float32Array( vertexCount * 3 ); + var uvs = new Float32Array( vertexCount * 2 ); - if ( directionDistance < 0 ) { + // offset variables + var vertexBufferOffset = 0; + var uvBufferOffset = 0; + var indexBufferOffset = 0; + var numberOfVertices = 0; - return result.copy( this.origin ); + // group variables + var groupStart = 0; - } + // build each side of the box geometry + buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px + buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx + buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py + buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny + buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz + buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz - return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); + // build geometry + this.setIndex( new BufferAttribute( indices, 1 ) ); + this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) ); + this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) ); + this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) ); - }, + // helper functions - distanceToPoint: function ( point ) { + function calculateVertexCount( w, h, d ) { - return Math.sqrt( this.distanceSqToPoint( point ) ); + var vertices = 0; - }, + // calculate the amount of vertices for each side (plane) + vertices += (w + 1) * (h + 1) * 2; // xy + vertices += (w + 1) * (d + 1) * 2; // xz + vertices += (d + 1) * (h + 1) * 2; // zy - distanceSqToPoint: function () { + return vertices; - var v1 = new Vector3(); + } - return function distanceSqToPoint( point ) { + function calculateIndexCount( w, h, d ) { - var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction ); + var index = 0; - // point behind the ray + // calculate the amount of squares for each side + index += w * h * 2; // xy + index += w * d * 2; // xz + index += d * h * 2; // zy - if ( directionDistance < 0 ) { + return index * 6; // two triangles per square => six vertices per square - return this.origin.distanceToSquared( point ); + } - } + function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) { - v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); + var segmentWidth = width / gridX; + var segmentHeight = height / gridY; - return v1.distanceToSquared( point ); + var widthHalf = width / 2; + var heightHalf = height / 2; + var depthHalf = depth / 2; - }; + var gridX1 = gridX + 1; + var gridY1 = gridY + 1; - }(), + var vertexCounter = 0; + var groupCount = 0; - distanceSqToSegment: function () { + var vector = new Vector3(); - var segCenter = new Vector3(); - var segDir = new Vector3(); - var diff = new Vector3(); + // generate vertices, normals and uvs - return function distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) { + for ( var iy = 0; iy < gridY1; iy ++ ) { - // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h - // It returns the min distance between the ray and the segment - // defined by v0 and v1 - // It can also set two optional targets : - // - The closest point on the ray - // - The closest point on the segment + var y = iy * segmentHeight - heightHalf; - segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 ); - segDir.copy( v1 ).sub( v0 ).normalize(); - diff.copy( this.origin ).sub( segCenter ); + for ( var ix = 0; ix < gridX1; ix ++ ) { - var segExtent = v0.distanceTo( v1 ) * 0.5; - var a01 = - this.direction.dot( segDir ); - var b0 = diff.dot( this.direction ); - var b1 = - diff.dot( segDir ); - var c = diff.lengthSq(); - var det = Math.abs( 1 - a01 * a01 ); - var s0, s1, sqrDist, extDet; + var x = ix * segmentWidth - widthHalf; - if ( det > 0 ) { + // set values to correct vector component + vector[ u ] = x * udir; + vector[ v ] = y * vdir; + vector[ w ] = depthHalf; - // The ray and segment are not parallel. + // now apply vector to vertex buffer + vertices[ vertexBufferOffset ] = vector.x; + vertices[ vertexBufferOffset + 1 ] = vector.y; + vertices[ vertexBufferOffset + 2 ] = vector.z; - s0 = a01 * b1 - b0; - s1 = a01 * b0 - b1; - extDet = segExtent * det; + // set values to correct vector component + vector[ u ] = 0; + vector[ v ] = 0; + vector[ w ] = depth > 0 ? 1 : - 1; - if ( s0 >= 0 ) { + // now apply vector to normal buffer + normals[ vertexBufferOffset ] = vector.x; + normals[ vertexBufferOffset + 1 ] = vector.y; + normals[ vertexBufferOffset + 2 ] = vector.z; - if ( s1 >= - extDet ) { + // uvs + uvs[ uvBufferOffset ] = ix / gridX; + uvs[ uvBufferOffset + 1 ] = 1 - ( iy / gridY ); - if ( s1 <= extDet ) { + // update offsets and counters + vertexBufferOffset += 3; + uvBufferOffset += 2; + vertexCounter += 1; - // region 0 - // Minimum at interior points of ray and segment. + } - var invDet = 1 / det; - s0 *= invDet; - s1 *= invDet; - sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c; + } - } else { + // 1. you need three indices to draw a single face + // 2. a single segment consists of two faces + // 3. so we need to generate six (2*3) indices per segment - // region 1 + for ( iy = 0; iy < gridY; iy ++ ) { - s1 = segExtent; - s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + for ( ix = 0; ix < gridX; ix ++ ) { - } + // indices + var a = numberOfVertices + ix + gridX1 * iy; + var b = numberOfVertices + ix + gridX1 * ( iy + 1 ); + var c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 ); + var d = numberOfVertices + ( ix + 1 ) + gridX1 * iy; - } else { + // face one + indices[ indexBufferOffset ] = a; + indices[ indexBufferOffset + 1 ] = b; + indices[ indexBufferOffset + 2 ] = d; - // region 5 + // face two + indices[ indexBufferOffset + 3 ] = b; + indices[ indexBufferOffset + 4 ] = c; + indices[ indexBufferOffset + 5 ] = d; - s1 = - segExtent; - s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + // update offsets and counters + indexBufferOffset += 6; + groupCount += 6; - } + } - } else { + } - if ( s1 <= - extDet ) { + // add a group to the geometry. this will ensure multi material support + scope.addGroup( groupStart, groupCount, materialIndex ); - // region 4 + // calculate new start value for groups + groupStart += groupCount; - s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) ); - s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + // update total number of vertices + numberOfVertices += vertexCounter; - } else if ( s1 <= extDet ) { + } - // region 3 + } - s0 = 0; - s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent ); - sqrDist = s1 * ( s1 + 2 * b1 ) + c; + BoxBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + BoxBufferGeometry.prototype.constructor = BoxBufferGeometry; - } else { + /** + * @author bhouston / http://clara.io + */ - // region 2 + function Ray( origin, direction ) { - s0 = Math.max( 0, - ( a01 * segExtent + b0 ) ); - s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + this.origin = ( origin !== undefined ) ? origin : new Vector3(); + this.direction = ( direction !== undefined ) ? direction : new Vector3(); - } + } - } + Ray.prototype = { - } else { + constructor: Ray, - // Ray and segment are parallel. + set: function ( origin, direction ) { - s1 = ( a01 > 0 ) ? - segExtent : segExtent; - s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + this.origin.copy( origin ); + this.direction.copy( direction ); - } + return this; - if ( optionalPointOnRay ) { + }, - optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin ); + clone: function () { - } + return new this.constructor().copy( this ); - if ( optionalPointOnSegment ) { + }, - optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter ); + copy: function ( ray ) { - } + this.origin.copy( ray.origin ); + this.direction.copy( ray.direction ); - return sqrDist; + return this; - }; + }, - }(), + at: function ( t, optionalTarget ) { - intersectSphere: function () { + var result = optionalTarget || new Vector3(); - var v1 = new Vector3(); + return result.copy( this.direction ).multiplyScalar( t ).add( this.origin ); - return function intersectSphere( sphere, optionalTarget ) { + }, - v1.subVectors( sphere.center, this.origin ); - var tca = v1.dot( this.direction ); - var d2 = v1.dot( v1 ) - tca * tca; - var radius2 = sphere.radius * sphere.radius; + lookAt: function ( v ) { - if ( d2 > radius2 ) return null; + this.direction.copy( v ).sub( this.origin ).normalize(); - var thc = Math.sqrt( radius2 - d2 ); + return this; - // t0 = first intersect point - entrance on front of sphere - var t0 = tca - thc; + }, - // t1 = second intersect point - exit point on back of sphere - var t1 = tca + thc; + recast: function () { - // test to see if both t0 and t1 are behind the ray - if so, return null - if ( t0 < 0 && t1 < 0 ) return null; + var v1 = new Vector3(); - // test to see if t0 is behind the ray: - // if it is, the ray is inside the sphere, so return the second exit point scaled by t1, - // in order to always return an intersect point that is in front of the ray. - if ( t0 < 0 ) return this.at( t1, optionalTarget ); + return function recast( t ) { - // else t0 is in front of the ray, so return the first collision point scaled by t0 - return this.at( t0, optionalTarget ); + this.origin.copy( this.at( t, v1 ) ); - }; + return this; - }(), + }; - intersectsSphere: function ( sphere ) { + }(), - return this.distanceToPoint( sphere.center ) <= sphere.radius; + closestPointToPoint: function ( point, optionalTarget ) { - }, + var result = optionalTarget || new Vector3(); + result.subVectors( point, this.origin ); + var directionDistance = result.dot( this.direction ); - distanceToPlane: function ( plane ) { + if ( directionDistance < 0 ) { - var denominator = plane.normal.dot( this.direction ); + return result.copy( this.origin ); - if ( denominator === 0 ) { + } - // line is coplanar, return origin - if ( plane.distanceToPoint( this.origin ) === 0 ) { + return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); - return 0; + }, - } + distanceToPoint: function ( point ) { - // Null is preferable to undefined since undefined means.... it is undefined + return Math.sqrt( this.distanceSqToPoint( point ) ); - return null; + }, - } + distanceSqToPoint: function () { - var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator; + var v1 = new Vector3(); - // Return if the ray never intersects the plane + return function distanceSqToPoint( point ) { - return t >= 0 ? t : null; + var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction ); - }, + // point behind the ray - intersectPlane: function ( plane, optionalTarget ) { + if ( directionDistance < 0 ) { - var t = this.distanceToPlane( plane ); + return this.origin.distanceToSquared( point ); - if ( t === null ) { + } - return null; + v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); - } + return v1.distanceToSquared( point ); - return this.at( t, optionalTarget ); + }; - }, + }(), + distanceSqToSegment: function () { + var segCenter = new Vector3(); + var segDir = new Vector3(); + var diff = new Vector3(); - intersectsPlane: function ( plane ) { + return function distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) { - // check if the ray lies on the plane first + // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h + // It returns the min distance between the ray and the segment + // defined by v0 and v1 + // It can also set two optional targets : + // - The closest point on the ray + // - The closest point on the segment - var distToPoint = plane.distanceToPoint( this.origin ); + segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 ); + segDir.copy( v1 ).sub( v0 ).normalize(); + diff.copy( this.origin ).sub( segCenter ); - if ( distToPoint === 0 ) { + var segExtent = v0.distanceTo( v1 ) * 0.5; + var a01 = - this.direction.dot( segDir ); + var b0 = diff.dot( this.direction ); + var b1 = - diff.dot( segDir ); + var c = diff.lengthSq(); + var det = Math.abs( 1 - a01 * a01 ); + var s0, s1, sqrDist, extDet; - return true; + if ( det > 0 ) { - } + // The ray and segment are not parallel. - var denominator = plane.normal.dot( this.direction ); + s0 = a01 * b1 - b0; + s1 = a01 * b0 - b1; + extDet = segExtent * det; - if ( denominator * distToPoint < 0 ) { + if ( s0 >= 0 ) { - return true; + if ( s1 >= - extDet ) { - } + if ( s1 <= extDet ) { - // ray origin is behind the plane (and is pointing behind it) + // region 0 + // Minimum at interior points of ray and segment. - return false; + var invDet = 1 / det; + s0 *= invDet; + s1 *= invDet; + sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c; - }, + } else { - intersectBox: function ( box, optionalTarget ) { + // region 1 - var tmin, tmax, tymin, tymax, tzmin, tzmax; + s1 = segExtent; + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - var invdirx = 1 / this.direction.x, - invdiry = 1 / this.direction.y, - invdirz = 1 / this.direction.z; + } - var origin = this.origin; + } else { - if ( invdirx >= 0 ) { + // region 5 - tmin = ( box.min.x - origin.x ) * invdirx; - tmax = ( box.max.x - origin.x ) * invdirx; + s1 = - segExtent; + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - } else { + } - tmin = ( box.max.x - origin.x ) * invdirx; - tmax = ( box.min.x - origin.x ) * invdirx; + } else { - } + if ( s1 <= - extDet ) { - if ( invdiry >= 0 ) { + // region 4 - tymin = ( box.min.y - origin.y ) * invdiry; - tymax = ( box.max.y - origin.y ) * invdiry; + s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) ); + s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - } else { + } else if ( s1 <= extDet ) { - tymin = ( box.max.y - origin.y ) * invdiry; - tymax = ( box.min.y - origin.y ) * invdiry; + // region 3 - } + s0 = 0; + s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent ); + sqrDist = s1 * ( s1 + 2 * b1 ) + c; - if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null; + } else { - // These lines also handle the case where tmin or tmax is NaN - // (result of 0 * Infinity). x !== x returns true if x is NaN + // region 2 - if ( tymin > tmin || tmin !== tmin ) tmin = tymin; + s0 = Math.max( 0, - ( a01 * segExtent + b0 ) ); + s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - if ( tymax < tmax || tmax !== tmax ) tmax = tymax; + } - if ( invdirz >= 0 ) { + } - tzmin = ( box.min.z - origin.z ) * invdirz; - tzmax = ( box.max.z - origin.z ) * invdirz; + } else { - } else { + // Ray and segment are parallel. - tzmin = ( box.max.z - origin.z ) * invdirz; - tzmax = ( box.min.z - origin.z ) * invdirz; + s1 = ( a01 > 0 ) ? - segExtent : segExtent; + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - } + } - if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null; + if ( optionalPointOnRay ) { - if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin; + optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin ); - if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax; + } - //return point closest to the ray (positive side) + if ( optionalPointOnSegment ) { - if ( tmax < 0 ) return null; + optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter ); - return this.at( tmin >= 0 ? tmin : tmax, optionalTarget ); + } - }, + return sqrDist; - intersectsBox: ( function () { + }; - var v = new Vector3(); + }(), - return function intersectsBox( box ) { + intersectSphere: function () { - return this.intersectBox( box, v ) !== null; + var v1 = new Vector3(); - }; + return function intersectSphere( sphere, optionalTarget ) { - } )(), + v1.subVectors( sphere.center, this.origin ); + var tca = v1.dot( this.direction ); + var d2 = v1.dot( v1 ) - tca * tca; + var radius2 = sphere.radius * sphere.radius; - intersectTriangle: function () { + if ( d2 > radius2 ) return null; - // Compute the offset origin, edges, and normal. - var diff = new Vector3(); - var edge1 = new Vector3(); - var edge2 = new Vector3(); - var normal = new Vector3(); + var thc = Math.sqrt( radius2 - d2 ); - return function intersectTriangle( a, b, c, backfaceCulling, optionalTarget ) { + // t0 = first intersect point - entrance on front of sphere + var t0 = tca - thc; - // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h + // t1 = second intersect point - exit point on back of sphere + var t1 = tca + thc; - edge1.subVectors( b, a ); - edge2.subVectors( c, a ); - normal.crossVectors( edge1, edge2 ); + // test to see if both t0 and t1 are behind the ray - if so, return null + if ( t0 < 0 && t1 < 0 ) return null; - // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction, - // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by - // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2)) - // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q)) - // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N) - var DdN = this.direction.dot( normal ); - var sign; + // test to see if t0 is behind the ray: + // if it is, the ray is inside the sphere, so return the second exit point scaled by t1, + // in order to always return an intersect point that is in front of the ray. + if ( t0 < 0 ) return this.at( t1, optionalTarget ); - if ( DdN > 0 ) { + // else t0 is in front of the ray, so return the first collision point scaled by t0 + return this.at( t0, optionalTarget ); - if ( backfaceCulling ) return null; - sign = 1; + }; - } else if ( DdN < 0 ) { + }(), - sign = - 1; - DdN = - DdN; + intersectsSphere: function ( sphere ) { - } else { + return this.distanceToPoint( sphere.center ) <= sphere.radius; - return null; + }, - } + distanceToPlane: function ( plane ) { - diff.subVectors( this.origin, a ); - var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) ); + var denominator = plane.normal.dot( this.direction ); - // b1 < 0, no intersection - if ( DdQxE2 < 0 ) { + if ( denominator === 0 ) { - return null; + // line is coplanar, return origin + if ( plane.distanceToPoint( this.origin ) === 0 ) { - } + return 0; - var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) ); + } - // b2 < 0, no intersection - if ( DdE1xQ < 0 ) { + // Null is preferable to undefined since undefined means.... it is undefined - return null; + return null; - } + } - // b1+b2 > 1, no intersection - if ( DdQxE2 + DdE1xQ > DdN ) { + var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator; - return null; + // Return if the ray never intersects the plane - } + return t >= 0 ? t : null; - // Line intersects triangle, check if ray does. - var QdN = - sign * diff.dot( normal ); + }, - // t < 0, no intersection - if ( QdN < 0 ) { + intersectPlane: function ( plane, optionalTarget ) { - return null; + var t = this.distanceToPlane( plane ); - } + if ( t === null ) { - // Ray intersects triangle. - return this.at( QdN / DdN, optionalTarget ); + return null; - }; + } - }(), + return this.at( t, optionalTarget ); - applyMatrix4: function ( matrix4 ) { + }, - this.direction.add( this.origin ).applyMatrix4( matrix4 ); - this.origin.applyMatrix4( matrix4 ); - this.direction.sub( this.origin ); - this.direction.normalize(); - return this; - }, + intersectsPlane: function ( plane ) { - equals: function ( ray ) { + // check if the ray lies on the plane first - return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction ); + var distToPoint = plane.distanceToPoint( this.origin ); - } + if ( distToPoint === 0 ) { - }; + return true; - /** - * @author bhouston / http://clara.io - */ + } - function Line3( start, end ) { + var denominator = plane.normal.dot( this.direction ); - this.start = ( start !== undefined ) ? start : new Vector3(); - this.end = ( end !== undefined ) ? end : new Vector3(); + if ( denominator * distToPoint < 0 ) { - }; + return true; - Line3.prototype = { + } - constructor: Line3, + // ray origin is behind the plane (and is pointing behind it) - set: function ( start, end ) { + return false; - this.start.copy( start ); - this.end.copy( end ); + }, - return this; + intersectBox: function ( box, optionalTarget ) { - }, + var tmin, tmax, tymin, tymax, tzmin, tzmax; - clone: function () { + var invdirx = 1 / this.direction.x, + invdiry = 1 / this.direction.y, + invdirz = 1 / this.direction.z; - return new this.constructor().copy( this ); + var origin = this.origin; - }, + if ( invdirx >= 0 ) { - copy: function ( line ) { + tmin = ( box.min.x - origin.x ) * invdirx; + tmax = ( box.max.x - origin.x ) * invdirx; - this.start.copy( line.start ); - this.end.copy( line.end ); + } else { - return this; + tmin = ( box.max.x - origin.x ) * invdirx; + tmax = ( box.min.x - origin.x ) * invdirx; - }, + } - center: function ( optionalTarget ) { + if ( invdiry >= 0 ) { - var result = optionalTarget || new Vector3(); - return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 ); + tymin = ( box.min.y - origin.y ) * invdiry; + tymax = ( box.max.y - origin.y ) * invdiry; - }, + } else { - delta: function ( optionalTarget ) { + tymin = ( box.max.y - origin.y ) * invdiry; + tymax = ( box.min.y - origin.y ) * invdiry; - var result = optionalTarget || new Vector3(); - return result.subVectors( this.end, this.start ); + } - }, + if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null; - distanceSq: function () { + // These lines also handle the case where tmin or tmax is NaN + // (result of 0 * Infinity). x !== x returns true if x is NaN - return this.start.distanceToSquared( this.end ); + if ( tymin > tmin || tmin !== tmin ) tmin = tymin; - }, + if ( tymax < tmax || tmax !== tmax ) tmax = tymax; - distance: function () { + if ( invdirz >= 0 ) { - return this.start.distanceTo( this.end ); + tzmin = ( box.min.z - origin.z ) * invdirz; + tzmax = ( box.max.z - origin.z ) * invdirz; - }, + } else { - at: function ( t, optionalTarget ) { + tzmin = ( box.max.z - origin.z ) * invdirz; + tzmax = ( box.min.z - origin.z ) * invdirz; - var result = optionalTarget || new Vector3(); + } - return this.delta( result ).multiplyScalar( t ).add( this.start ); + if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null; - }, + if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin; - closestPointToPointParameter: function () { + if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax; - var startP = new Vector3(); - var startEnd = new Vector3(); + //return point closest to the ray (positive side) - return function closestPointToPointParameter( point, clampToLine ) { + if ( tmax < 0 ) return null; - startP.subVectors( point, this.start ); - startEnd.subVectors( this.end, this.start ); + return this.at( tmin >= 0 ? tmin : tmax, optionalTarget ); - var startEnd2 = startEnd.dot( startEnd ); - var startEnd_startP = startEnd.dot( startP ); + }, - var t = startEnd_startP / startEnd2; + intersectsBox: ( function () { - if ( clampToLine ) { + var v = new Vector3(); - t = exports.Math.clamp( t, 0, 1 ); + return function intersectsBox( box ) { - } + return this.intersectBox( box, v ) !== null; - return t; + }; - }; + } )(), - }(), + intersectTriangle: function () { - closestPointToPoint: function ( point, clampToLine, optionalTarget ) { + // Compute the offset origin, edges, and normal. + var diff = new Vector3(); + var edge1 = new Vector3(); + var edge2 = new Vector3(); + var normal = new Vector3(); - var t = this.closestPointToPointParameter( point, clampToLine ); + return function intersectTriangle( a, b, c, backfaceCulling, optionalTarget ) { - var result = optionalTarget || new Vector3(); + // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h - return this.delta( result ).multiplyScalar( t ).add( this.start ); + edge1.subVectors( b, a ); + edge2.subVectors( c, a ); + normal.crossVectors( edge1, edge2 ); - }, + // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction, + // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by + // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2)) + // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q)) + // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N) + var DdN = this.direction.dot( normal ); + var sign; - applyMatrix4: function ( matrix ) { + if ( DdN > 0 ) { - this.start.applyMatrix4( matrix ); - this.end.applyMatrix4( matrix ); + if ( backfaceCulling ) return null; + sign = 1; - return this; + } else if ( DdN < 0 ) { - }, + sign = - 1; + DdN = - DdN; - equals: function ( line ) { + } else { - return line.start.equals( this.start ) && line.end.equals( this.end ); + return null; - } + } - }; + diff.subVectors( this.origin, a ); + var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) ); - /** - * @author bhouston / http://clara.io - * @author mrdoob / http://mrdoob.com/ - */ + // b1 < 0, no intersection + if ( DdQxE2 < 0 ) { - function Triangle( a, b, c ) { + return null; - this.a = ( a !== undefined ) ? a : new Vector3(); - this.b = ( b !== undefined ) ? b : new Vector3(); - this.c = ( c !== undefined ) ? c : new Vector3(); + } - }; + var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) ); - Triangle.normal = function () { + // b2 < 0, no intersection + if ( DdE1xQ < 0 ) { - var v0 = new Vector3(); + return null; - return function normal( a, b, c, optionalTarget ) { + } - var result = optionalTarget || new Vector3(); + // b1+b2 > 1, no intersection + if ( DdQxE2 + DdE1xQ > DdN ) { - result.subVectors( c, b ); - v0.subVectors( a, b ); - result.cross( v0 ); + return null; - var resultLengthSq = result.lengthSq(); - if ( resultLengthSq > 0 ) { + } - return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) ); + // Line intersects triangle, check if ray does. + var QdN = - sign * diff.dot( normal ); - } + // t < 0, no intersection + if ( QdN < 0 ) { - return result.set( 0, 0, 0 ); + return null; - }; + } - }(); + // Ray intersects triangle. + return this.at( QdN / DdN, optionalTarget ); - // static/instance method to calculate barycentric coordinates - // based on: http://www.blackpawn.com/texts/pointinpoly/default.html - Triangle.barycoordFromPoint = function () { + }; - var v0 = new Vector3(); - var v1 = new Vector3(); - var v2 = new Vector3(); + }(), - return function barycoordFromPoint( point, a, b, c, optionalTarget ) { + applyMatrix4: function ( matrix4 ) { - v0.subVectors( c, a ); - v1.subVectors( b, a ); - v2.subVectors( point, a ); + this.direction.add( this.origin ).applyMatrix4( matrix4 ); + this.origin.applyMatrix4( matrix4 ); + this.direction.sub( this.origin ); + this.direction.normalize(); - var dot00 = v0.dot( v0 ); - var dot01 = v0.dot( v1 ); - var dot02 = v0.dot( v2 ); - var dot11 = v1.dot( v1 ); - var dot12 = v1.dot( v2 ); + return this; - var denom = ( dot00 * dot11 - dot01 * dot01 ); + }, - var result = optionalTarget || new Vector3(); + equals: function ( ray ) { - // collinear or singular triangle - if ( denom === 0 ) { + return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction ); - // arbitrary location outside of triangle? - // not sure if this is the best idea, maybe should be returning undefined - return result.set( - 2, - 1, - 1 ); + } - } + }; - var invDenom = 1 / denom; - var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom; - var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom; + /** + * @author bhouston / http://clara.io + */ - // barycentric coordinates must always sum to 1 - return result.set( 1 - u - v, v, u ); + function Line3( start, end ) { - }; + this.start = ( start !== undefined ) ? start : new Vector3(); + this.end = ( end !== undefined ) ? end : new Vector3(); - }(); + } - Triangle.containsPoint = function () { + Line3.prototype = { - var v1 = new Vector3(); + constructor: Line3, - return function containsPoint( point, a, b, c ) { + set: function ( start, end ) { - var result = Triangle.barycoordFromPoint( point, a, b, c, v1 ); + this.start.copy( start ); + this.end.copy( end ); - return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 ); + return this; - }; + }, - }(); + clone: function () { - Triangle.prototype = { + return new this.constructor().copy( this ); - constructor: Triangle, + }, - set: function ( a, b, c ) { + copy: function ( line ) { - this.a.copy( a ); - this.b.copy( b ); - this.c.copy( c ); + this.start.copy( line.start ); + this.end.copy( line.end ); - return this; + return this; - }, + }, - setFromPointsAndIndices: function ( points, i0, i1, i2 ) { + center: function ( optionalTarget ) { - this.a.copy( points[ i0 ] ); - this.b.copy( points[ i1 ] ); - this.c.copy( points[ i2 ] ); + var result = optionalTarget || new Vector3(); + return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 ); - return this; + }, - }, + delta: function ( optionalTarget ) { - clone: function () { + var result = optionalTarget || new Vector3(); + return result.subVectors( this.end, this.start ); - return new this.constructor().copy( this ); + }, - }, + distanceSq: function () { - copy: function ( triangle ) { + return this.start.distanceToSquared( this.end ); - this.a.copy( triangle.a ); - this.b.copy( triangle.b ); - this.c.copy( triangle.c ); + }, - return this; + distance: function () { - }, + return this.start.distanceTo( this.end ); - area: function () { + }, - var v0 = new Vector3(); - var v1 = new Vector3(); + at: function ( t, optionalTarget ) { - return function area() { + var result = optionalTarget || new Vector3(); - v0.subVectors( this.c, this.b ); - v1.subVectors( this.a, this.b ); + return this.delta( result ).multiplyScalar( t ).add( this.start ); - return v0.cross( v1 ).length() * 0.5; + }, - }; + closestPointToPointParameter: function () { - }(), + var startP = new Vector3(); + var startEnd = new Vector3(); - midpoint: function ( optionalTarget ) { + return function closestPointToPointParameter( point, clampToLine ) { - var result = optionalTarget || new Vector3(); - return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 ); + startP.subVectors( point, this.start ); + startEnd.subVectors( this.end, this.start ); - }, + var startEnd2 = startEnd.dot( startEnd ); + var startEnd_startP = startEnd.dot( startP ); - normal: function ( optionalTarget ) { + var t = startEnd_startP / startEnd2; - return Triangle.normal( this.a, this.b, this.c, optionalTarget ); + if ( clampToLine ) { - }, + t = exports.Math.clamp( t, 0, 1 ); - plane: function ( optionalTarget ) { + } - var result = optionalTarget || new Plane(); + return t; - return result.setFromCoplanarPoints( this.a, this.b, this.c ); + }; - }, + }(), - barycoordFromPoint: function ( point, optionalTarget ) { + closestPointToPoint: function ( point, clampToLine, optionalTarget ) { - return Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget ); + var t = this.closestPointToPointParameter( point, clampToLine ); - }, + var result = optionalTarget || new Vector3(); - containsPoint: function ( point ) { + return this.delta( result ).multiplyScalar( t ).add( this.start ); - return Triangle.containsPoint( point, this.a, this.b, this.c ); + }, - }, + applyMatrix4: function ( matrix ) { - closestPointToPoint: function () { + this.start.applyMatrix4( matrix ); + this.end.applyMatrix4( matrix ); - var plane, edgeList, projectedPoint, closestPoint; + return this; - return function closestPointToPoint( point, optionalTarget ) { + }, - if ( plane === undefined ) { + equals: function ( line ) { - plane = new Plane(); - edgeList = [ new Line3(), new Line3(), new Line3() ]; - projectedPoint = new Vector3(); - closestPoint = new Vector3(); + return line.start.equals( this.start ) && line.end.equals( this.end ); - } + } - var result = optionalTarget || new Vector3(); - var minDistance = Infinity; + }; - // project the point onto the plane of the triangle + /** + * @author bhouston / http://clara.io + * @author mrdoob / http://mrdoob.com/ + */ - plane.setFromCoplanarPoints( this.a, this.b, this.c ); - plane.projectPoint( point, projectedPoint ); + function Triangle( a, b, c ) { - // check if the projection lies within the triangle + this.a = ( a !== undefined ) ? a : new Vector3(); + this.b = ( b !== undefined ) ? b : new Vector3(); + this.c = ( c !== undefined ) ? c : new Vector3(); - if( this.containsPoint( projectedPoint ) === true ) { + } - // if so, this is the closest point + Triangle.normal = function () { - result.copy( projectedPoint ); + var v0 = new Vector3(); - } else { + return function normal( a, b, c, optionalTarget ) { - // if not, the point falls outside the triangle. the result is the closest point to the triangle's edges or vertices + var result = optionalTarget || new Vector3(); - edgeList[ 0 ].set( this.a, this.b ); - edgeList[ 1 ].set( this.b, this.c ); - edgeList[ 2 ].set( this.c, this.a ); + result.subVectors( c, b ); + v0.subVectors( a, b ); + result.cross( v0 ); - for( var i = 0; i < edgeList.length; i ++ ) { + var resultLengthSq = result.lengthSq(); + if ( resultLengthSq > 0 ) { - edgeList[ i ].closestPointToPoint( projectedPoint, true, closestPoint ); + return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) ); - var distance = projectedPoint.distanceToSquared( closestPoint ); + } - if( distance < minDistance ) { + return result.set( 0, 0, 0 ); - minDistance = distance; + }; - result.copy( closestPoint ); + }(); - } + // static/instance method to calculate barycentric coordinates + // based on: http://www.blackpawn.com/texts/pointinpoly/default.html + Triangle.barycoordFromPoint = function () { - } + var v0 = new Vector3(); + var v1 = new Vector3(); + var v2 = new Vector3(); - } + return function barycoordFromPoint( point, a, b, c, optionalTarget ) { - return result; + v0.subVectors( c, a ); + v1.subVectors( b, a ); + v2.subVectors( point, a ); - }; + var dot00 = v0.dot( v0 ); + var dot01 = v0.dot( v1 ); + var dot02 = v0.dot( v2 ); + var dot11 = v1.dot( v1 ); + var dot12 = v1.dot( v2 ); - }(), + var denom = ( dot00 * dot11 - dot01 * dot01 ); - equals: function ( triangle ) { + var result = optionalTarget || new Vector3(); - return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c ); + // collinear or singular triangle + if ( denom === 0 ) { - } + // arbitrary location outside of triangle? + // not sure if this is the best idea, maybe should be returning undefined + return result.set( - 2, - 1, - 1 ); - }; + } - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * opacity: , - * map: new THREE.Texture( ), - * - * aoMap: new THREE.Texture( ), - * aoMapIntensity: - * - * specularMap: new THREE.Texture( ), - * - * alphaMap: new THREE.Texture( ), - * - * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ), - * combine: THREE.Multiply, - * reflectivity: , - * refractionRatio: , - * - * shading: THREE.SmoothShading, - * depthTest: , - * depthWrite: , - * - * wireframe: , - * wireframeLinewidth: , - * - * skinning: , - * morphTargets: - * } - */ + var invDenom = 1 / denom; + var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom; + var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom; - function MeshBasicMaterial( parameters ) { + // barycentric coordinates must always sum to 1 + return result.set( 1 - u - v, v, u ); - Material.call( this ); + }; - this.type = 'MeshBasicMaterial'; + }(); - this.color = new Color( 0xffffff ); // emissive + Triangle.containsPoint = function () { - this.map = null; + var v1 = new Vector3(); - this.aoMap = null; - this.aoMapIntensity = 1.0; + return function containsPoint( point, a, b, c ) { - this.specularMap = null; + var result = Triangle.barycoordFromPoint( point, a, b, c, v1 ); - this.alphaMap = null; + return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 ); - this.envMap = null; - this.combine = MultiplyOperation; - this.reflectivity = 1; - this.refractionRatio = 0.98; + }; - this.wireframe = false; - this.wireframeLinewidth = 1; - this.wireframeLinecap = 'round'; - this.wireframeLinejoin = 'round'; + }(); - this.skinning = false; - this.morphTargets = false; + Triangle.prototype = { - this.lights = false; + constructor: Triangle, - this.setValues( parameters ); + set: function ( a, b, c ) { - }; + this.a.copy( a ); + this.b.copy( b ); + this.c.copy( c ); - MeshBasicMaterial.prototype = Object.create( Material.prototype ); - MeshBasicMaterial.prototype.constructor = MeshBasicMaterial; + return this; - MeshBasicMaterial.prototype.isMeshBasicMaterial = true; + }, - MeshBasicMaterial.prototype.copy = function ( source ) { + setFromPointsAndIndices: function ( points, i0, i1, i2 ) { - Material.prototype.copy.call( this, source ); + this.a.copy( points[ i0 ] ); + this.b.copy( points[ i1 ] ); + this.c.copy( points[ i2 ] ); - this.color.copy( source.color ); + return this; - this.map = source.map; + }, - this.aoMap = source.aoMap; - this.aoMapIntensity = source.aoMapIntensity; + clone: function () { - this.specularMap = source.specularMap; + return new this.constructor().copy( this ); - this.alphaMap = source.alphaMap; + }, - this.envMap = source.envMap; - this.combine = source.combine; - this.reflectivity = source.reflectivity; - this.refractionRatio = source.refractionRatio; + copy: function ( triangle ) { - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; - this.wireframeLinecap = source.wireframeLinecap; - this.wireframeLinejoin = source.wireframeLinejoin; + this.a.copy( triangle.a ); + this.b.copy( triangle.b ); + this.c.copy( triangle.c ); - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; + return this; - return this; + }, - }; + area: function () { - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * @author mikael emtinger / http://gomo.se/ - * @author jonobr1 / http://jonobr1.com/ - */ + var v0 = new Vector3(); + var v1 = new Vector3(); - function Mesh( geometry, material ) { + return function area() { - Object3D.call( this ); + v0.subVectors( this.c, this.b ); + v1.subVectors( this.a, this.b ); - this.type = 'Mesh'; + return v0.cross( v1 ).length() * 0.5; - this.geometry = geometry !== undefined ? geometry : new BufferGeometry(); - this.material = material !== undefined ? material : new MeshBasicMaterial( { color: Math.random() * 0xffffff } ); + }; - this.drawMode = TrianglesDrawMode; + }(), - this.updateMorphTargets(); + midpoint: function ( optionalTarget ) { - }; + var result = optionalTarget || new Vector3(); + return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 ); - Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), { + }, - constructor: Mesh, + normal: function ( optionalTarget ) { - isMesh: true, + return Triangle.normal( this.a, this.b, this.c, optionalTarget ); - setDrawMode: function ( value ) { + }, - this.drawMode = value; + plane: function ( optionalTarget ) { - }, + var result = optionalTarget || new Plane(); - copy: function ( source ) { + return result.setFromCoplanarPoints( this.a, this.b, this.c ); - Object3D.prototype.copy.call( this, source ); + }, - this.drawMode = source.drawMode; + barycoordFromPoint: function ( point, optionalTarget ) { - return this; + return Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget ); - }, + }, - updateMorphTargets: function () { + containsPoint: function ( point ) { - if ( this.geometry.morphTargets !== undefined && this.geometry.morphTargets.length > 0 ) { + return Triangle.containsPoint( point, this.a, this.b, this.c ); - this.morphTargetBase = - 1; - this.morphTargetInfluences = []; - this.morphTargetDictionary = {}; + }, - for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) { + closestPointToPoint: function () { - this.morphTargetInfluences.push( 0 ); - this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m; + var plane, edgeList, projectedPoint, closestPoint; - } + return function closestPointToPoint( point, optionalTarget ) { - } + if ( plane === undefined ) { - }, + plane = new Plane(); + edgeList = [ new Line3(), new Line3(), new Line3() ]; + projectedPoint = new Vector3(); + closestPoint = new Vector3(); - getMorphTargetIndexByName: function ( name ) { + } - if ( this.morphTargetDictionary[ name ] !== undefined ) { + var result = optionalTarget || new Vector3(); + var minDistance = Infinity; - return this.morphTargetDictionary[ name ]; + // project the point onto the plane of the triangle - } + plane.setFromCoplanarPoints( this.a, this.b, this.c ); + plane.projectPoint( point, projectedPoint ); - console.warn( 'THREE.Mesh.getMorphTargetIndexByName: morph target ' + name + ' does not exist. Returning 0.' ); + // check if the projection lies within the triangle - return 0; + if( this.containsPoint( projectedPoint ) === true ) { - }, + // if so, this is the closest point - raycast: ( function () { + result.copy( projectedPoint ); - var inverseMatrix = new Matrix4(); - var ray = new Ray(); - var sphere = new Sphere(); + } else { - var vA = new Vector3(); - var vB = new Vector3(); - var vC = new Vector3(); + // if not, the point falls outside the triangle. the result is the closest point to the triangle's edges or vertices - var tempA = new Vector3(); - var tempB = new Vector3(); - var tempC = new Vector3(); + edgeList[ 0 ].set( this.a, this.b ); + edgeList[ 1 ].set( this.b, this.c ); + edgeList[ 2 ].set( this.c, this.a ); - var uvA = new Vector2(); - var uvB = new Vector2(); - var uvC = new Vector2(); + for( var i = 0; i < edgeList.length; i ++ ) { - var barycoord = new Vector3(); + edgeList[ i ].closestPointToPoint( projectedPoint, true, closestPoint ); - var intersectionPoint = new Vector3(); - var intersectionPointWorld = new Vector3(); + var distance = projectedPoint.distanceToSquared( closestPoint ); - function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) { + if( distance < minDistance ) { - Triangle.barycoordFromPoint( point, p1, p2, p3, barycoord ); + minDistance = distance; - uv1.multiplyScalar( barycoord.x ); - uv2.multiplyScalar( barycoord.y ); - uv3.multiplyScalar( barycoord.z ); + result.copy( closestPoint ); - uv1.add( uv2 ).add( uv3 ); + } - return uv1.clone(); + } - } + } - function checkIntersection( object, raycaster, ray, pA, pB, pC, point ) { + return result; - var intersect; - var material = object.material; + }; - if ( material.side === BackSide ) { + }(), - intersect = ray.intersectTriangle( pC, pB, pA, true, point ); + equals: function ( triangle ) { - } else { + return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c ); - intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point ); + } - } + }; - if ( intersect === null ) return null; + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * color: , + * opacity: , + * map: new THREE.Texture( ), + * + * aoMap: new THREE.Texture( ), + * aoMapIntensity: + * + * specularMap: new THREE.Texture( ), + * + * alphaMap: new THREE.Texture( ), + * + * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ), + * combine: THREE.Multiply, + * reflectivity: , + * refractionRatio: , + * + * shading: THREE.SmoothShading, + * depthTest: , + * depthWrite: , + * + * wireframe: , + * wireframeLinewidth: , + * + * skinning: , + * morphTargets: + * } + */ + + function MeshBasicMaterial( parameters ) { + + Material.call( this ); + + this.type = 'MeshBasicMaterial'; + + this.color = new Color( 0xffffff ); // emissive + + this.map = null; + + this.aoMap = null; + this.aoMapIntensity = 1.0; + + this.specularMap = null; + + this.alphaMap = null; + + this.envMap = null; + this.combine = MultiplyOperation; + this.reflectivity = 1; + this.refractionRatio = 0.98; + + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; + + this.skinning = false; + this.morphTargets = false; + + this.lights = false; + + this.setValues( parameters ); - intersectionPointWorld.copy( point ); - intersectionPointWorld.applyMatrix4( object.matrixWorld ); + } - var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld ); + MeshBasicMaterial.prototype = Object.create( Material.prototype ); + MeshBasicMaterial.prototype.constructor = MeshBasicMaterial; - if ( distance < raycaster.near || distance > raycaster.far ) return null; + MeshBasicMaterial.prototype.isMeshBasicMaterial = true; - return { - distance: distance, - point: intersectionPointWorld.clone(), - object: object - }; + MeshBasicMaterial.prototype.copy = function ( source ) { - } + Material.prototype.copy.call( this, source ); - function checkBufferGeometryIntersection( object, raycaster, ray, positions, uvs, a, b, c ) { + this.color.copy( source.color ); - vA.fromArray( positions, a * 3 ); - vB.fromArray( positions, b * 3 ); - vC.fromArray( positions, c * 3 ); + this.map = source.map; - var intersection = checkIntersection( object, raycaster, ray, vA, vB, vC, intersectionPoint ); + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; - if ( intersection ) { + this.specularMap = source.specularMap; - if ( uvs ) { + this.alphaMap = source.alphaMap; - uvA.fromArray( uvs, a * 2 ); - uvB.fromArray( uvs, b * 2 ); - uvC.fromArray( uvs, c * 2 ); + this.envMap = source.envMap; + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; - intersection.uv = uvIntersection( intersectionPoint, vA, vB, vC, uvA, uvB, uvC ); + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; - } + this.skinning = source.skinning; + this.morphTargets = source.morphTargets; - intersection.face = new Face3( a, b, c, Triangle.normal( vA, vB, vC ) ); - intersection.faceIndex = a; + return this; - } + }; - return intersection; + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * @author mikael emtinger / http://gomo.se/ + * @author jonobr1 / http://jonobr1.com/ + */ - } + function Mesh( geometry, material ) { - return function raycast( raycaster, intersects ) { + Object3D.call( this ); - var geometry = this.geometry; - var material = this.material; - var matrixWorld = this.matrixWorld; + this.type = 'Mesh'; - if ( material === undefined ) return; + this.geometry = geometry !== undefined ? geometry : new BufferGeometry(); + this.material = material !== undefined ? material : new MeshBasicMaterial( { color: Math.random() * 0xffffff } ); - // Checking boundingSphere distance to ray + this.drawMode = TrianglesDrawMode; - if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + this.updateMorphTargets(); - sphere.copy( geometry.boundingSphere ); - sphere.applyMatrix4( matrixWorld ); + } - if ( raycaster.ray.intersectsSphere( sphere ) === false ) return; + Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), { - // + constructor: Mesh, - inverseMatrix.getInverse( matrixWorld ); - ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); + isMesh: true, - // Check boundingBox before continuing + setDrawMode: function ( value ) { - if ( geometry.boundingBox !== null ) { + this.drawMode = value; - if ( ray.intersectsBox( geometry.boundingBox ) === false ) return; + }, - } + copy: function ( source ) { - var uvs, intersection; + Object3D.prototype.copy.call( this, source ); - if ( (geometry && geometry.isBufferGeometry) ) { + this.drawMode = source.drawMode; - var a, b, c; - var index = geometry.index; - var attributes = geometry.attributes; - var positions = attributes.position.array; + return this; - if ( attributes.uv !== undefined ) { + }, - uvs = attributes.uv.array; + updateMorphTargets: function () { - } + if ( this.geometry.morphTargets !== undefined && this.geometry.morphTargets.length > 0 ) { - if ( index !== null ) { + this.morphTargetBase = - 1; + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; - var indices = index.array; + for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) { - for ( var i = 0, l = indices.length; i < l; i += 3 ) { + this.morphTargetInfluences.push( 0 ); + this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m; - a = indices[ i ]; - b = indices[ i + 1 ]; - c = indices[ i + 2 ]; + } - intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c ); + } - if ( intersection ) { + }, - intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indices buffer semantics - intersects.push( intersection ); + getMorphTargetIndexByName: function ( name ) { - } + if ( this.morphTargetDictionary[ name ] !== undefined ) { - } + return this.morphTargetDictionary[ name ]; - } else { + } + console.warn( 'THREE.Mesh.getMorphTargetIndexByName: morph target ' + name + ' does not exist. Returning 0.' ); - for ( var i = 0, l = positions.length; i < l; i += 9 ) { + return 0; - a = i / 3; - b = a + 1; - c = a + 2; + }, - intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c ); + raycast: ( function () { - if ( intersection ) { + var inverseMatrix = new Matrix4(); + var ray = new Ray(); + var sphere = new Sphere(); - intersection.index = a; // triangle number in positions buffer semantics - intersects.push( intersection ); + var vA = new Vector3(); + var vB = new Vector3(); + var vC = new Vector3(); - } + var tempA = new Vector3(); + var tempB = new Vector3(); + var tempC = new Vector3(); - } + var uvA = new Vector2(); + var uvB = new Vector2(); + var uvC = new Vector2(); - } + var barycoord = new Vector3(); - } else if ( (geometry && geometry.isGeometry) ) { + var intersectionPoint = new Vector3(); + var intersectionPointWorld = new Vector3(); - var fvA, fvB, fvC; - var isFaceMaterial = (material && material.isMultiMaterial); - var materials = isFaceMaterial === true ? material.materials : null; + function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) { - var vertices = geometry.vertices; - var faces = geometry.faces; - var faceVertexUvs = geometry.faceVertexUvs[ 0 ]; - if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs; + Triangle.barycoordFromPoint( point, p1, p2, p3, barycoord ); - for ( var f = 0, fl = faces.length; f < fl; f ++ ) { + uv1.multiplyScalar( barycoord.x ); + uv2.multiplyScalar( barycoord.y ); + uv3.multiplyScalar( barycoord.z ); - var face = faces[ f ]; - var faceMaterial = isFaceMaterial === true ? materials[ face.materialIndex ] : material; + uv1.add( uv2 ).add( uv3 ); - if ( faceMaterial === undefined ) continue; + return uv1.clone(); - fvA = vertices[ face.a ]; - fvB = vertices[ face.b ]; - fvC = vertices[ face.c ]; + } - if ( faceMaterial.morphTargets === true ) { + function checkIntersection( object, raycaster, ray, pA, pB, pC, point ) { - var morphTargets = geometry.morphTargets; - var morphInfluences = this.morphTargetInfluences; + var intersect; + var material = object.material; - vA.set( 0, 0, 0 ); - vB.set( 0, 0, 0 ); - vC.set( 0, 0, 0 ); + if ( material.side === BackSide ) { - for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) { + intersect = ray.intersectTriangle( pC, pB, pA, true, point ); - var influence = morphInfluences[ t ]; + } else { - if ( influence === 0 ) continue; + intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point ); - var targets = morphTargets[ t ].vertices; + } - vA.addScaledVector( tempA.subVectors( targets[ face.a ], fvA ), influence ); - vB.addScaledVector( tempB.subVectors( targets[ face.b ], fvB ), influence ); - vC.addScaledVector( tempC.subVectors( targets[ face.c ], fvC ), influence ); + if ( intersect === null ) return null; - } + intersectionPointWorld.copy( point ); + intersectionPointWorld.applyMatrix4( object.matrixWorld ); - vA.add( fvA ); - vB.add( fvB ); - vC.add( fvC ); + var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld ); - fvA = vA; - fvB = vB; - fvC = vC; + if ( distance < raycaster.near || distance > raycaster.far ) return null; - } + return { + distance: distance, + point: intersectionPointWorld.clone(), + object: object + }; - intersection = checkIntersection( this, raycaster, ray, fvA, fvB, fvC, intersectionPoint ); + } - if ( intersection ) { + function checkBufferGeometryIntersection( object, raycaster, ray, positions, uvs, a, b, c ) { - if ( uvs ) { + vA.fromArray( positions, a * 3 ); + vB.fromArray( positions, b * 3 ); + vC.fromArray( positions, c * 3 ); - var uvs_f = uvs[ f ]; - uvA.copy( uvs_f[ 0 ] ); - uvB.copy( uvs_f[ 1 ] ); - uvC.copy( uvs_f[ 2 ] ); + var intersection = checkIntersection( object, raycaster, ray, vA, vB, vC, intersectionPoint ); - intersection.uv = uvIntersection( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC ); + if ( intersection ) { - } + if ( uvs ) { - intersection.face = face; - intersection.faceIndex = f; - intersects.push( intersection ); + uvA.fromArray( uvs, a * 2 ); + uvB.fromArray( uvs, b * 2 ); + uvC.fromArray( uvs, c * 2 ); - } + intersection.uv = uvIntersection( intersectionPoint, vA, vB, vC, uvA, uvB, uvC ); - } + } - } + intersection.face = new Face3( a, b, c, Triangle.normal( vA, vB, vC ) ); + intersection.faceIndex = a; - }; + } - }() ), + return intersection; - clone: function () { + } - return new this.constructor( this.geometry, this.material ).copy( this ); + return function raycast( raycaster, intersects ) { - } + var geometry = this.geometry; + var material = this.material; + var matrixWorld = this.matrixWorld; - } ); + if ( material === undefined ) return; - /** - * @author mrdoob / http://mrdoob.com/ - * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as - */ + // Checking boundingSphere distance to ray - function PlaneBufferGeometry( width, height, widthSegments, heightSegments ) { + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); - BufferGeometry.call( this ); + sphere.copy( geometry.boundingSphere ); + sphere.applyMatrix4( matrixWorld ); - this.type = 'PlaneBufferGeometry'; + if ( raycaster.ray.intersectsSphere( sphere ) === false ) return; - this.parameters = { - width: width, - height: height, - widthSegments: widthSegments, - heightSegments: heightSegments - }; + // - var width_half = width / 2; - var height_half = height / 2; + inverseMatrix.getInverse( matrixWorld ); + ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); - var gridX = Math.floor( widthSegments ) || 1; - var gridY = Math.floor( heightSegments ) || 1; + // Check boundingBox before continuing - var gridX1 = gridX + 1; - var gridY1 = gridY + 1; + if ( geometry.boundingBox !== null ) { - var segment_width = width / gridX; - var segment_height = height / gridY; + if ( ray.intersectsBox( geometry.boundingBox ) === false ) return; - var vertices = new Float32Array( gridX1 * gridY1 * 3 ); - var normals = new Float32Array( gridX1 * gridY1 * 3 ); - var uvs = new Float32Array( gridX1 * gridY1 * 2 ); + } - var offset = 0; - var offset2 = 0; + var uvs, intersection; - for ( var iy = 0; iy < gridY1; iy ++ ) { + if ( (geometry && geometry.isBufferGeometry) ) { - var y = iy * segment_height - height_half; + var a, b, c; + var index = geometry.index; + var attributes = geometry.attributes; + var positions = attributes.position.array; - for ( var ix = 0; ix < gridX1; ix ++ ) { + if ( attributes.uv !== undefined ) { - var x = ix * segment_width - width_half; + uvs = attributes.uv.array; - vertices[ offset ] = x; - vertices[ offset + 1 ] = - y; + } - normals[ offset + 2 ] = 1; + if ( index !== null ) { - uvs[ offset2 ] = ix / gridX; - uvs[ offset2 + 1 ] = 1 - ( iy / gridY ); + var indices = index.array; - offset += 3; - offset2 += 2; + for ( var i = 0, l = indices.length; i < l; i += 3 ) { - } + a = indices[ i ]; + b = indices[ i + 1 ]; + c = indices[ i + 2 ]; - } + intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c ); - offset = 0; + if ( intersection ) { - var indices = new ( ( vertices.length / 3 ) > 65535 ? Uint32Array : Uint16Array )( gridX * gridY * 6 ); + intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indices buffer semantics + intersects.push( intersection ); - for ( var iy = 0; iy < gridY; iy ++ ) { + } - for ( var ix = 0; ix < gridX; ix ++ ) { + } - var a = ix + gridX1 * iy; - var b = ix + gridX1 * ( iy + 1 ); - var c = ( ix + 1 ) + gridX1 * ( iy + 1 ); - var d = ( ix + 1 ) + gridX1 * iy; + } else { - indices[ offset ] = a; - indices[ offset + 1 ] = b; - indices[ offset + 2 ] = d; - indices[ offset + 3 ] = b; - indices[ offset + 4 ] = c; - indices[ offset + 5 ] = d; + for ( var i = 0, l = positions.length; i < l; i += 9 ) { - offset += 6; + a = i / 3; + b = a + 1; + c = a + 2; - } + intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c ); - } + if ( intersection ) { - this.setIndex( new BufferAttribute( indices, 1 ) ); - this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) ); - this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) ); - this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) ); + intersection.index = a; // triangle number in positions buffer semantics + intersects.push( intersection ); - }; + } - PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); - PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry; + } - /** - * @author mrdoob / http://mrdoob.com/ - * @author mikael emtinger / http://gomo.se/ - * @author WestLangley / http://github.com/WestLangley - */ + } - function Camera() { + } else if ( (geometry && geometry.isGeometry) ) { - Object3D.call( this ); + var fvA, fvB, fvC; + var isFaceMaterial = (material && material.isMultiMaterial); + var materials = isFaceMaterial === true ? material.materials : null; - this.type = 'Camera'; + var vertices = geometry.vertices; + var faces = geometry.faces; + var faceVertexUvs = geometry.faceVertexUvs[ 0 ]; + if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs; - this.matrixWorldInverse = new Matrix4(); - this.projectionMatrix = new Matrix4(); + for ( var f = 0, fl = faces.length; f < fl; f ++ ) { - }; + var face = faces[ f ]; + var faceMaterial = isFaceMaterial === true ? materials[ face.materialIndex ] : material; - Camera.prototype = Object.create( Object3D.prototype ); - Camera.prototype.constructor = Camera; + if ( faceMaterial === undefined ) continue; - Camera.prototype.isCamera = true; + fvA = vertices[ face.a ]; + fvB = vertices[ face.b ]; + fvC = vertices[ face.c ]; - Camera.prototype.getWorldDirection = function () { + if ( faceMaterial.morphTargets === true ) { - var quaternion = new Quaternion(); + var morphTargets = geometry.morphTargets; + var morphInfluences = this.morphTargetInfluences; - return function getWorldDirection( optionalTarget ) { + vA.set( 0, 0, 0 ); + vB.set( 0, 0, 0 ); + vC.set( 0, 0, 0 ); - var result = optionalTarget || new Vector3(); + for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) { - this.getWorldQuaternion( quaternion ); + var influence = morphInfluences[ t ]; - return result.set( 0, 0, - 1 ).applyQuaternion( quaternion ); + if ( influence === 0 ) continue; - }; + var targets = morphTargets[ t ].vertices; - }(); + vA.addScaledVector( tempA.subVectors( targets[ face.a ], fvA ), influence ); + vB.addScaledVector( tempB.subVectors( targets[ face.b ], fvB ), influence ); + vC.addScaledVector( tempC.subVectors( targets[ face.c ], fvC ), influence ); - Camera.prototype.lookAt = function () { + } - // This routine does not support cameras with rotated and/or translated parent(s) + vA.add( fvA ); + vB.add( fvB ); + vC.add( fvC ); - var m1 = new Matrix4(); + fvA = vA; + fvB = vB; + fvC = vC; - return function lookAt( vector ) { + } - m1.lookAt( this.position, vector, this.up ); + intersection = checkIntersection( this, raycaster, ray, fvA, fvB, fvC, intersectionPoint ); - this.quaternion.setFromRotationMatrix( m1 ); + if ( intersection ) { - }; + if ( uvs ) { - }(); + var uvs_f = uvs[ f ]; + uvA.copy( uvs_f[ 0 ] ); + uvB.copy( uvs_f[ 1 ] ); + uvC.copy( uvs_f[ 2 ] ); - Camera.prototype.clone = function () { + intersection.uv = uvIntersection( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC ); - return new this.constructor().copy( this ); + } - }; + intersection.face = face; + intersection.faceIndex = f; + intersects.push( intersection ); - Camera.prototype.copy = function ( source ) { + } - Object3D.prototype.copy.call( this, source ); + } - this.matrixWorldInverse.copy( source.matrixWorldInverse ); - this.projectionMatrix.copy( source.projectionMatrix ); + } - return this; + }; - }; + }() ), - /** - * @author mrdoob / http://mrdoob.com/ - * @author greggman / http://games.greggman.com/ - * @author zz85 / http://www.lab4games.net/zz85/blog - * @author tschw - */ + clone: function () { - function PerspectiveCamera( fov, aspect, near, far ) { + return new this.constructor( this.geometry, this.material ).copy( this ); - Camera.call( this ); + } - this.type = 'PerspectiveCamera'; + } ); - this.fov = fov !== undefined ? fov : 50; - this.zoom = 1; + /** + * @author mrdoob / http://mrdoob.com/ + * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as + */ - this.near = near !== undefined ? near : 0.1; - this.far = far !== undefined ? far : 2000; - this.focus = 10; + function PlaneBufferGeometry( width, height, widthSegments, heightSegments ) { - this.aspect = aspect !== undefined ? aspect : 1; - this.view = null; + BufferGeometry.call( this ); - this.filmGauge = 35; // width of the film (default in millimeters) - this.filmOffset = 0; // horizontal film offset (same unit as gauge) + this.type = 'PlaneBufferGeometry'; - this.updateProjectionMatrix(); + this.parameters = { + width: width, + height: height, + widthSegments: widthSegments, + heightSegments: heightSegments + }; - }; + var width_half = width / 2; + var height_half = height / 2; - PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), { + var gridX = Math.floor( widthSegments ) || 1; + var gridY = Math.floor( heightSegments ) || 1; - constructor: PerspectiveCamera, + var gridX1 = gridX + 1; + var gridY1 = gridY + 1; - isPerspectiveCamera: true, + var segment_width = width / gridX; + var segment_height = height / gridY; - copy: function ( source ) { + var vertices = new Float32Array( gridX1 * gridY1 * 3 ); + var normals = new Float32Array( gridX1 * gridY1 * 3 ); + var uvs = new Float32Array( gridX1 * gridY1 * 2 ); - Camera.prototype.copy.call( this, source ); + var offset = 0; + var offset2 = 0; - this.fov = source.fov; - this.zoom = source.zoom; + for ( var iy = 0; iy < gridY1; iy ++ ) { - this.near = source.near; - this.far = source.far; - this.focus = source.focus; + var y = iy * segment_height - height_half; - this.aspect = source.aspect; - this.view = source.view === null ? null : Object.assign( {}, source.view ); + for ( var ix = 0; ix < gridX1; ix ++ ) { - this.filmGauge = source.filmGauge; - this.filmOffset = source.filmOffset; + var x = ix * segment_width - width_half; - return this; + vertices[ offset ] = x; + vertices[ offset + 1 ] = - y; - }, + normals[ offset + 2 ] = 1; - /** - * Sets the FOV by focal length in respect to the current .filmGauge. - * - * The default film gauge is 35, so that the focal length can be specified for - * a 35mm (full frame) camera. - * - * Values for focal length and film gauge must have the same unit. - */ - setFocalLength: function ( focalLength ) { + uvs[ offset2 ] = ix / gridX; + uvs[ offset2 + 1 ] = 1 - ( iy / gridY ); - // see http://www.bobatkins.com/photography/technical/field_of_view.html - var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength; + offset += 3; + offset2 += 2; - this.fov = exports.Math.RAD2DEG * 2 * Math.atan( vExtentSlope ); - this.updateProjectionMatrix(); + } - }, + } - /** - * Calculates the focal length from the current .fov and .filmGauge. - */ - getFocalLength: function () { + offset = 0; - var vExtentSlope = Math.tan( exports.Math.DEG2RAD * 0.5 * this.fov ); + var indices = new ( ( vertices.length / 3 ) > 65535 ? Uint32Array : Uint16Array )( gridX * gridY * 6 ); - return 0.5 * this.getFilmHeight() / vExtentSlope; + for ( var iy = 0; iy < gridY; iy ++ ) { - }, + for ( var ix = 0; ix < gridX; ix ++ ) { - getEffectiveFOV: function () { + var a = ix + gridX1 * iy; + var b = ix + gridX1 * ( iy + 1 ); + var c = ( ix + 1 ) + gridX1 * ( iy + 1 ); + var d = ( ix + 1 ) + gridX1 * iy; - return exports.Math.RAD2DEG * 2 * Math.atan( - Math.tan( exports.Math.DEG2RAD * 0.5 * this.fov ) / this.zoom ); + indices[ offset ] = a; + indices[ offset + 1 ] = b; + indices[ offset + 2 ] = d; - }, + indices[ offset + 3 ] = b; + indices[ offset + 4 ] = c; + indices[ offset + 5 ] = d; - getFilmWidth: function () { + offset += 6; - // film not completely covered in portrait format (aspect < 1) - return this.filmGauge * Math.min( this.aspect, 1 ); + } - }, + } - getFilmHeight: function () { + this.setIndex( new BufferAttribute( indices, 1 ) ); + this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) ); + this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) ); + this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) ); - // film not completely covered in landscape format (aspect > 1) - return this.filmGauge / Math.max( this.aspect, 1 ); + } - }, + PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry; - /** - * 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 - * - * var w = 1920; - * var h = 1080; - * var fullWidth = w * 3; - * var fullHeight = h * 2; - * - * --A-- - * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h ); - * --B-- - * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h ); - * --C-- - * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h ); - * --D-- - * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h ); - * --E-- - * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h ); - * --F-- - * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h ); - * - * Note there is no reason monitors have to be the same size or in a grid. - */ - setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) { + /** + * @author mrdoob / http://mrdoob.com/ + * @author mikael emtinger / http://gomo.se/ + * @author WestLangley / http://github.com/WestLangley + */ - this.aspect = fullWidth / fullHeight; + function Camera() { - this.view = { - fullWidth: fullWidth, - fullHeight: fullHeight, - offsetX: x, - offsetY: y, - width: width, - height: height - }; + Object3D.call( this ); - this.updateProjectionMatrix(); + this.type = 'Camera'; - }, + this.matrixWorldInverse = new Matrix4(); + this.projectionMatrix = new Matrix4(); - clearViewOffset: function() { + } - this.view = null; - this.updateProjectionMatrix(); + Camera.prototype = Object.create( Object3D.prototype ); + Camera.prototype.constructor = Camera; - }, + Camera.prototype.isCamera = true; - updateProjectionMatrix: function () { + Camera.prototype.getWorldDirection = function () { - var near = this.near, - top = near * Math.tan( - exports.Math.DEG2RAD * 0.5 * this.fov ) / this.zoom, - height = 2 * top, - width = this.aspect * height, - left = - 0.5 * width, - view = this.view; + var quaternion = new Quaternion(); - if ( view !== null ) { + return function getWorldDirection( optionalTarget ) { - var fullWidth = view.fullWidth, - fullHeight = view.fullHeight; + var result = optionalTarget || new Vector3(); - left += view.offsetX * width / fullWidth; - top -= view.offsetY * height / fullHeight; - width *= view.width / fullWidth; - height *= view.height / fullHeight; + this.getWorldQuaternion( quaternion ); - } + return result.set( 0, 0, - 1 ).applyQuaternion( quaternion ); - var skew = this.filmOffset; - if ( skew !== 0 ) left += near * skew / this.getFilmWidth(); + }; - this.projectionMatrix.makeFrustum( - left, left + width, top - height, top, near, this.far ); + }(); - }, + Camera.prototype.lookAt = function () { - toJSON: function ( meta ) { + // This routine does not support cameras with rotated and/or translated parent(s) - var data = Object3D.prototype.toJSON.call( this, meta ); + var m1 = new Matrix4(); - data.object.fov = this.fov; - data.object.zoom = this.zoom; + return function lookAt( vector ) { - data.object.near = this.near; - data.object.far = this.far; - data.object.focus = this.focus; + m1.lookAt( this.position, vector, this.up ); - data.object.aspect = this.aspect; + this.quaternion.setFromRotationMatrix( m1 ); - if ( this.view !== null ) data.object.view = Object.assign( {}, this.view ); + }; - data.object.filmGauge = this.filmGauge; - data.object.filmOffset = this.filmOffset; + }(); - return data; + Camera.prototype.clone = function () { - } + return new this.constructor().copy( this ); - } ); + }; - /** - * @author alteredq / http://alteredqualia.com/ - * @author arose / http://github.com/arose - */ + Camera.prototype.copy = function ( source ) { - function OrthographicCamera( left, right, top, bottom, near, far ) { + Object3D.prototype.copy.call( this, source ); - Camera.call( this ); + this.matrixWorldInverse.copy( source.matrixWorldInverse ); + this.projectionMatrix.copy( source.projectionMatrix ); - this.type = 'OrthographicCamera'; + return this; - this.zoom = 1; - this.view = null; + }; - this.left = left; - this.right = right; - this.top = top; - this.bottom = bottom; + /** + * @author mrdoob / http://mrdoob.com/ + * @author greggman / http://games.greggman.com/ + * @author zz85 / http://www.lab4games.net/zz85/blog + * @author tschw + */ - this.near = ( near !== undefined ) ? near : 0.1; - this.far = ( far !== undefined ) ? far : 2000; + function PerspectiveCamera( fov, aspect, near, far ) { - this.updateProjectionMatrix(); + Camera.call( this ); - }; + this.type = 'PerspectiveCamera'; - OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), { + this.fov = fov !== undefined ? fov : 50; + this.zoom = 1; - constructor: OrthographicCamera, + this.near = near !== undefined ? near : 0.1; + this.far = far !== undefined ? far : 2000; + this.focus = 10; - isOrthographicCamera: true, + this.aspect = aspect !== undefined ? aspect : 1; + this.view = null; - copy: function ( source ) { + this.filmGauge = 35; // width of the film (default in millimeters) + this.filmOffset = 0; // horizontal film offset (same unit as gauge) - Camera.prototype.copy.call( this, source ); + this.updateProjectionMatrix(); - 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 ); + PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), { - return this; + constructor: PerspectiveCamera, - }, + isPerspectiveCamera: true, - setViewOffset: function( fullWidth, fullHeight, x, y, width, height ) { + copy: function ( source ) { - this.view = { - fullWidth: fullWidth, - fullHeight: fullHeight, - offsetX: x, - offsetY: y, - width: width, - height: height - }; + Camera.prototype.copy.call( this, source ); - this.updateProjectionMatrix(); + this.fov = source.fov; + this.zoom = source.zoom; - }, + this.near = source.near; + this.far = source.far; + this.focus = source.focus; - clearViewOffset: function() { + this.aspect = source.aspect; + this.view = source.view === null ? null : Object.assign( {}, source.view ); - this.view = null; - this.updateProjectionMatrix(); + this.filmGauge = source.filmGauge; + this.filmOffset = source.filmOffset; - }, + return this; - updateProjectionMatrix: function () { + }, - var dx = ( this.right - this.left ) / ( 2 * this.zoom ); - var dy = ( this.top - this.bottom ) / ( 2 * this.zoom ); - var cx = ( this.right + this.left ) / 2; - var cy = ( this.top + this.bottom ) / 2; + /** + * Sets the FOV by focal length in respect to the current .filmGauge. + * + * The default film gauge is 35, so that the focal length can be specified for + * a 35mm (full frame) camera. + * + * Values for focal length and film gauge must have the same unit. + */ + setFocalLength: function ( focalLength ) { - var left = cx - dx; - var right = cx + dx; - var top = cy + dy; - var bottom = cy - dy; + // see http://www.bobatkins.com/photography/technical/field_of_view.html + var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength; - if ( this.view !== null ) { + this.fov = exports.Math.RAD2DEG * 2 * Math.atan( vExtentSlope ); + this.updateProjectionMatrix(); - var zoomW = this.zoom / ( this.view.width / this.view.fullWidth ); - var zoomH = this.zoom / ( this.view.height / this.view.fullHeight ); - var scaleW = ( this.right - this.left ) / this.view.width; - var scaleH = ( this.top - this.bottom ) / this.view.height; + }, - left += scaleW * ( this.view.offsetX / zoomW ); - right = left + scaleW * ( this.view.width / zoomW ); - top -= scaleH * ( this.view.offsetY / zoomH ); - bottom = top - scaleH * ( this.view.height / zoomH ); + /** + * Calculates the focal length from the current .fov and .filmGauge. + */ + getFocalLength: function () { - } + var vExtentSlope = Math.tan( exports.Math.DEG2RAD * 0.5 * this.fov ); - this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far ); + return 0.5 * this.getFilmHeight() / vExtentSlope; - }, + }, - toJSON: function ( meta ) { + getEffectiveFOV: function () { - var data = Object3D.prototype.toJSON.call( this, meta ); + return exports.Math.RAD2DEG * 2 * Math.atan( + Math.tan( exports.Math.DEG2RAD * 0.5 * this.fov ) / this.zoom ); - 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 ); + getFilmWidth: function () { - return data; + // film not completely covered in portrait format (aspect < 1) + return this.filmGauge * Math.min( this.aspect, 1 ); - } + }, - } ); + getFilmHeight: function () { - /** - * @author supereggbert / http://www.paulbrunt.co.uk/ - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * @author szimek / https://github.com/szimek/ - * @author tschw - */ + // film not completely covered in landscape format (aspect > 1) + return this.filmGauge / Math.max( this.aspect, 1 ); - function WebGLRenderer( parameters ) { + }, - console.log( 'THREE.WebGLRenderer', "80dev" ); + /** + * 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 + * + * var w = 1920; + * var h = 1080; + * var fullWidth = w * 3; + * var fullHeight = h * 2; + * + * --A-- + * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h ); + * --B-- + * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h ); + * --C-- + * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h ); + * --D-- + * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h ); + * --E-- + * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h ); + * --F-- + * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h ); + * + * Note there is no reason monitors have to be the same size or in a grid. + */ + setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) { + + this.aspect = fullWidth / fullHeight; + + this.view = { + fullWidth: fullWidth, + fullHeight: fullHeight, + offsetX: x, + offsetY: y, + width: width, + height: height + }; + + this.updateProjectionMatrix(); - parameters = parameters || {}; + }, - var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ), - _context = parameters.context !== undefined ? parameters.context : null, + clearViewOffset: function() { - _alpha = parameters.alpha !== undefined ? parameters.alpha : false, - _depth = parameters.depth !== undefined ? parameters.depth : true, - _stencil = parameters.stencil !== undefined ? parameters.stencil : true, - _antialias = parameters.antialias !== undefined ? parameters.antialias : false, - _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true, - _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false; + this.view = null; + this.updateProjectionMatrix(); - var lights = []; + }, - var opaqueObjects = []; - var opaqueObjectsLastIndex = - 1; - var transparentObjects = []; - var transparentObjectsLastIndex = - 1; + updateProjectionMatrix: function () { - var morphInfluences = new Float32Array( 8 ); + var near = this.near, + top = near * Math.tan( + exports.Math.DEG2RAD * 0.5 * this.fov ) / this.zoom, + height = 2 * top, + width = this.aspect * height, + left = - 0.5 * width, + view = this.view; - var sprites = []; - var lensFlares = []; + if ( view !== null ) { - // public properties + var fullWidth = view.fullWidth, + fullHeight = view.fullHeight; - this.domElement = _canvas; - this.context = null; + left += view.offsetX * width / fullWidth; + top -= view.offsetY * height / fullHeight; + width *= view.width / fullWidth; + height *= view.height / fullHeight; - // clearing + } - this.autoClear = true; - this.autoClearColor = true; - this.autoClearDepth = true; - this.autoClearStencil = true; + var skew = this.filmOffset; + if ( skew !== 0 ) left += near * skew / this.getFilmWidth(); - // scene graph + this.projectionMatrix.makeFrustum( + left, left + width, top - height, top, near, this.far ); - this.sortObjects = true; + }, - // user-defined clipping + toJSON: function ( meta ) { - this.clippingPlanes = []; - this.localClippingEnabled = false; + var data = Object3D.prototype.toJSON.call( this, meta ); - // physically based shading + data.object.fov = this.fov; + data.object.zoom = this.zoom; - this.gammaFactor = 2.0; // for backwards compatibility - this.gammaInput = false; - this.gammaOutput = false; + data.object.near = this.near; + data.object.far = this.far; + data.object.focus = this.focus; - // physical lights + data.object.aspect = this.aspect; - this.physicallyCorrectLights = false; + if ( this.view !== null ) data.object.view = Object.assign( {}, this.view ); - // tone mapping + data.object.filmGauge = this.filmGauge; + data.object.filmOffset = this.filmOffset; - this.toneMapping = LinearToneMapping; - this.toneMappingExposure = 1.0; - this.toneMappingWhitePoint = 1.0; + return data; - // morphs + } - this.maxMorphTargets = 8; - this.maxMorphNormals = 4; + } ); - // internal properties + /** + * @author alteredq / http://alteredqualia.com/ + * @author arose / http://github.com/arose + */ - var _this = this, + function OrthographicCamera( left, right, top, bottom, near, far ) { - // internal state cache + Camera.call( this ); - _currentProgram = null, - _currentRenderTarget = null, - _currentFramebuffer = null, - _currentMaterialId = - 1, - _currentGeometryProgram = '', - _currentCamera = null, + this.type = 'OrthographicCamera'; - _currentScissor = new Vector4(), - _currentScissorTest = null, + this.zoom = 1; + this.view = null; - _currentViewport = new Vector4(), + this.left = left; + this.right = right; + this.top = top; + this.bottom = bottom; - // + this.near = ( near !== undefined ) ? near : 0.1; + this.far = ( far !== undefined ) ? far : 2000; - _usedTextureUnits = 0, + this.updateProjectionMatrix(); - // + } - _clearColor = new Color( 0x000000 ), - _clearAlpha = 0, + OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), { - _width = _canvas.width, - _height = _canvas.height, + constructor: OrthographicCamera, - _pixelRatio = 1, + isOrthographicCamera: true, - _scissor = new Vector4( 0, 0, _width, _height ), - _scissorTest = false, + copy: function ( source ) { - _viewport = new Vector4( 0, 0, _width, _height ), + Camera.prototype.copy.call( this, source ); - // frustum + this.left = source.left; + this.right = source.right; + this.top = source.top; + this.bottom = source.bottom; + this.near = source.near; + this.far = source.far; - _frustum = new Frustum(), + this.zoom = source.zoom; + this.view = source.view === null ? null : Object.assign( {}, source.view ); - // clipping + return this; - _clipping = new WebGLClipping(), - _clippingEnabled = false, - _localClippingEnabled = false, + }, - _sphere = new Sphere(), + setViewOffset: function( fullWidth, fullHeight, x, y, width, height ) { - // camera matrices cache + this.view = { + fullWidth: fullWidth, + fullHeight: fullHeight, + offsetX: x, + offsetY: y, + width: width, + height: height + }; - _projScreenMatrix = new Matrix4(), + this.updateProjectionMatrix(); - _vector3 = new Vector3(), + }, - // light arrays cache + clearViewOffset: function() { - _lights = { + this.view = null; + this.updateProjectionMatrix(); - hash: '', + }, - ambient: [ 0, 0, 0 ], - directional: [], - directionalShadowMap: [], - directionalShadowMatrix: [], - spot: [], - spotShadowMap: [], - spotShadowMatrix: [], - point: [], - pointShadowMap: [], - pointShadowMatrix: [], - hemi: [], + updateProjectionMatrix: function () { - shadows: [] + var dx = ( this.right - this.left ) / ( 2 * this.zoom ); + var dy = ( this.top - this.bottom ) / ( 2 * this.zoom ); + var cx = ( this.right + this.left ) / 2; + var cy = ( this.top + this.bottom ) / 2; - }, + var left = cx - dx; + var right = cx + dx; + var top = cy + dy; + var bottom = cy - dy; - // info + if ( this.view !== null ) { - _infoRender = { + var zoomW = this.zoom / ( this.view.width / this.view.fullWidth ); + var zoomH = this.zoom / ( this.view.height / this.view.fullHeight ); + var scaleW = ( this.right - this.left ) / this.view.width; + var scaleH = ( this.top - this.bottom ) / this.view.height; - calls: 0, - vertices: 0, - faces: 0, - points: 0 + left += scaleW * ( this.view.offsetX / zoomW ); + right = left + scaleW * ( this.view.width / zoomW ); + top -= scaleH * ( this.view.offsetY / zoomH ); + bottom = top - scaleH * ( this.view.height / zoomH ); - }; + } - this.info = { + this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far ); - render: _infoRender, - memory: { + }, - geometries: 0, - textures: 0 + toJSON: function ( meta ) { - }, - programs: null + var data = Object3D.prototype.toJSON.call( this, 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 ); - // initialize + return data; - var _gl; + } - try { + } ); - var attributes = { - alpha: _alpha, - depth: _depth, - stencil: _stencil, - antialias: _antialias, - premultipliedAlpha: _premultipliedAlpha, - preserveDrawingBuffer: _preserveDrawingBuffer - }; + /** + * @author supereggbert / http://www.paulbrunt.co.uk/ + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * @author szimek / https://github.com/szimek/ + * @author tschw + */ - _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes ); + function WebGLRenderer( parameters ) { - if ( _gl === null ) { + console.log( 'THREE.WebGLRenderer', REVISION ); - if ( _canvas.getContext( 'webgl' ) !== null ) { + parameters = parameters || {}; - throw 'Error creating WebGL context with your selected attributes.'; + var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ), + _context = parameters.context !== undefined ? parameters.context : null, - } else { + _alpha = parameters.alpha !== undefined ? parameters.alpha : false, + _depth = parameters.depth !== undefined ? parameters.depth : true, + _stencil = parameters.stencil !== undefined ? parameters.stencil : true, + _antialias = parameters.antialias !== undefined ? parameters.antialias : false, + _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true, + _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false; - throw 'Error creating WebGL context.'; + var lights = []; - } + var opaqueObjects = []; + var opaqueObjectsLastIndex = - 1; + var transparentObjects = []; + var transparentObjectsLastIndex = - 1; - } + var morphInfluences = new Float32Array( 8 ); - // Some experimental-webgl implementations do not have getShaderPrecisionFormat + var sprites = []; + var lensFlares = []; - if ( _gl.getShaderPrecisionFormat === undefined ) { + // public properties - _gl.getShaderPrecisionFormat = function () { + this.domElement = _canvas; + this.context = null; - return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 }; + // clearing - }; + this.autoClear = true; + this.autoClearColor = true; + this.autoClearDepth = true; + this.autoClearStencil = true; - } + // scene graph - _canvas.addEventListener( 'webglcontextlost', onContextLost, false ); + this.sortObjects = true; - } catch ( error ) { + // user-defined clipping - console.error( 'THREE.WebGLRenderer: ' + error ); + this.clippingPlanes = []; + this.localClippingEnabled = false; - } + // physically based shading - var extensions = new WebGLExtensions( _gl ); + this.gammaFactor = 2.0; // for backwards compatibility + this.gammaInput = false; + this.gammaOutput = false; - extensions.get( 'WEBGL_depth_texture' ); - extensions.get( 'OES_texture_float' ); - extensions.get( 'OES_texture_float_linear' ); - extensions.get( 'OES_texture_half_float' ); - extensions.get( 'OES_texture_half_float_linear' ); - extensions.get( 'OES_standard_derivatives' ); - extensions.get( 'ANGLE_instanced_arrays' ); + // physical lights - if ( extensions.get( 'OES_element_index_uint' ) ) { + this.physicallyCorrectLights = false; - BufferGeometry.MaxIndex = 4294967296; + // tone mapping - } + this.toneMapping = LinearToneMapping; + this.toneMappingExposure = 1.0; + this.toneMappingWhitePoint = 1.0; - var capabilities = new WebGLCapabilities( _gl, extensions, parameters ); + // morphs - var state = new WebGLState( _gl, extensions, paramThreeToGL ); - var properties = new WebGLProperties(); - var textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, this.info ); - var objects = new WebGLObjects( _gl, properties, this.info ); - var programCache = new WebGLPrograms( this, capabilities ); - var lightCache = new WebGLLights(); + this.maxMorphTargets = 8; + this.maxMorphNormals = 4; - this.info.programs = programCache.programs; + // internal properties - var bufferRenderer = new WebGLBufferRenderer( _gl, extensions, _infoRender ); - var indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, _infoRender ); + var _this = this, - // + // internal state cache - var backgroundCamera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 ); - var backgroundCamera2 = new PerspectiveCamera(); - var backgroundPlaneMesh = new Mesh( - new PlaneBufferGeometry( 2, 2 ), - new MeshBasicMaterial( { depthTest: false, depthWrite: false, fog: false } ) - ); - var backgroundBoxShader = exports.ShaderLib[ 'cube' ]; - var backgroundBoxMesh = new Mesh( - new BoxBufferGeometry( 5, 5, 5 ), - new ShaderMaterial( { - uniforms: backgroundBoxShader.uniforms, - vertexShader: backgroundBoxShader.vertexShader, - fragmentShader: backgroundBoxShader.fragmentShader, - side: BackSide, - depthTest: false, - depthWrite: false, - fog: false - } ) - ); + _currentProgram = null, + _currentRenderTarget = null, + _currentFramebuffer = null, + _currentMaterialId = - 1, + _currentGeometryProgram = '', + _currentCamera = null, - // + _currentScissor = new Vector4(), + _currentScissorTest = null, - function getTargetPixelRatio() { + _currentViewport = new Vector4(), - return _currentRenderTarget === null ? _pixelRatio : 1; + // - } + _usedTextureUnits = 0, - function glClearColor( r, g, b, a ) { + // - if ( _premultipliedAlpha === true ) { + _clearColor = new Color( 0x000000 ), + _clearAlpha = 0, - r *= a; g *= a; b *= a; + _width = _canvas.width, + _height = _canvas.height, - } + _pixelRatio = 1, - state.clearColor( r, g, b, a ); + _scissor = new Vector4( 0, 0, _width, _height ), + _scissorTest = false, - } + _viewport = new Vector4( 0, 0, _width, _height ), - function setDefaultGLState() { + // frustum - state.init(); + _frustum = new Frustum(), - state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) ); - state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) ); + // clipping - glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); + _clipping = new WebGLClipping(), + _clippingEnabled = false, + _localClippingEnabled = false, - } + _sphere = new Sphere(), - function resetGLState() { + // camera matrices cache - _currentProgram = null; - _currentCamera = null; + _projScreenMatrix = new Matrix4(), - _currentGeometryProgram = ''; - _currentMaterialId = - 1; + _vector3 = new Vector3(), - state.reset(); + // light arrays cache - } + _lights = { - setDefaultGLState(); + hash: '', - this.context = _gl; - this.capabilities = capabilities; - this.extensions = extensions; - this.properties = properties; - this.state = state; + ambient: [ 0, 0, 0 ], + directional: [], + directionalShadowMap: [], + directionalShadowMatrix: [], + spot: [], + spotShadowMap: [], + spotShadowMatrix: [], + point: [], + pointShadowMap: [], + pointShadowMatrix: [], + hemi: [], - // shadow map + shadows: [] - var shadowMap = new WebGLShadowMap( this, _lights, objects, capabilities ); + }, - this.shadowMap = shadowMap; + // info + _infoRender = { - // Plugins + calls: 0, + vertices: 0, + faces: 0, + points: 0 - var spritePlugin = new SpritePlugin( this, sprites ); - var lensFlarePlugin = new LensFlarePlugin( this, lensFlares ); + }; - // API + this.info = { - this.getContext = function () { + render: _infoRender, + memory: { - return _gl; + geometries: 0, + textures: 0 - }; + }, + programs: null - this.getContextAttributes = function () { + }; - return _gl.getContextAttributes(); - }; + // initialize - this.forceContextLoss = function () { + var _gl; - extensions.get( 'WEBGL_lose_context' ).loseContext(); + try { - }; + var attributes = { + alpha: _alpha, + depth: _depth, + stencil: _stencil, + antialias: _antialias, + premultipliedAlpha: _premultipliedAlpha, + preserveDrawingBuffer: _preserveDrawingBuffer + }; - this.getMaxAnisotropy = function () { + _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes ); - return capabilities.getMaxAnisotropy(); + if ( _gl === null ) { - }; + if ( _canvas.getContext( 'webgl' ) !== null ) { - this.getPrecision = function () { + throw 'Error creating WebGL context with your selected attributes.'; - return capabilities.precision; + } else { - }; + throw 'Error creating WebGL context.'; - this.getPixelRatio = function () { + } - return _pixelRatio; + } - }; + // Some experimental-webgl implementations do not have getShaderPrecisionFormat - this.setPixelRatio = function ( value ) { + if ( _gl.getShaderPrecisionFormat === undefined ) { - if ( value === undefined ) return; + _gl.getShaderPrecisionFormat = function () { - _pixelRatio = value; + return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 }; - this.setSize( _viewport.z, _viewport.w, false ); + }; - }; + } - this.getSize = function () { + _canvas.addEventListener( 'webglcontextlost', onContextLost, false ); - return { - width: _width, - height: _height - }; + } catch ( error ) { - }; + console.error( 'THREE.WebGLRenderer: ' + error ); - this.setSize = function ( width, height, updateStyle ) { + } - _width = width; - _height = height; + var extensions = new WebGLExtensions( _gl ); - _canvas.width = width * _pixelRatio; - _canvas.height = height * _pixelRatio; + extensions.get( 'WEBGL_depth_texture' ); + extensions.get( 'OES_texture_float' ); + extensions.get( 'OES_texture_float_linear' ); + extensions.get( 'OES_texture_half_float' ); + extensions.get( 'OES_texture_half_float_linear' ); + extensions.get( 'OES_standard_derivatives' ); + extensions.get( 'ANGLE_instanced_arrays' ); - if ( updateStyle !== false ) { + if ( extensions.get( 'OES_element_index_uint' ) ) { - _canvas.style.width = width + 'px'; - _canvas.style.height = height + 'px'; + BufferGeometry.MaxIndex = 4294967296; - } + } - this.setViewport( 0, 0, width, height ); + var capabilities = new WebGLCapabilities( _gl, extensions, parameters ); - }; + var state = new WebGLState( _gl, extensions, paramThreeToGL ); + var properties = new WebGLProperties(); + var textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, this.info ); + var objects = new WebGLObjects( _gl, properties, this.info ); + var programCache = new WebGLPrograms( this, capabilities ); + var lightCache = new WebGLLights(); - this.setViewport = function ( x, y, width, height ) { + this.info.programs = programCache.programs; - state.viewport( _viewport.set( x, y, width, height ) ); + var bufferRenderer = new WebGLBufferRenderer( _gl, extensions, _infoRender ); + var indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, _infoRender ); - }; + // - this.setScissor = function ( x, y, width, height ) { + var backgroundCamera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 ); + var backgroundCamera2 = new PerspectiveCamera(); + var backgroundPlaneMesh = new Mesh( + new PlaneBufferGeometry( 2, 2 ), + new MeshBasicMaterial( { depthTest: false, depthWrite: false, fog: false } ) + ); + var backgroundBoxShader = exports.ShaderLib[ 'cube' ]; + var backgroundBoxMesh = new Mesh( + new BoxBufferGeometry( 5, 5, 5 ), + new ShaderMaterial( { + uniforms: backgroundBoxShader.uniforms, + vertexShader: backgroundBoxShader.vertexShader, + fragmentShader: backgroundBoxShader.fragmentShader, + side: BackSide, + depthTest: false, + depthWrite: false, + fog: false + } ) + ); - state.scissor( _scissor.set( x, y, width, height ) ); + // - }; + function getTargetPixelRatio() { - this.setScissorTest = function ( boolean ) { + return _currentRenderTarget === null ? _pixelRatio : 1; - state.setScissorTest( _scissorTest = boolean ); + } - }; + function glClearColor( r, g, b, a ) { - // Clearing + if ( _premultipliedAlpha === true ) { - this.getClearColor = function () { + r *= a; g *= a; b *= a; - return _clearColor; + } - }; + state.clearColor( r, g, b, a ); - this.setClearColor = function ( color, alpha ) { + } - _clearColor.set( color ); + function setDefaultGLState() { - _clearAlpha = alpha !== undefined ? alpha : 1; + state.init(); - glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); + state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) ); + state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) ); - }; + glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); - this.getClearAlpha = function () { + } - return _clearAlpha; + function resetGLState() { - }; + _currentProgram = null; + _currentCamera = null; - this.setClearAlpha = function ( alpha ) { + _currentGeometryProgram = ''; + _currentMaterialId = - 1; - _clearAlpha = alpha; + state.reset(); - glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); + } - }; + setDefaultGLState(); - this.clear = function ( color, depth, stencil ) { + this.context = _gl; + this.capabilities = capabilities; + this.extensions = extensions; + this.properties = properties; + this.state = state; - var bits = 0; + // shadow map - if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT; - if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT; - if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT; + var shadowMap = new WebGLShadowMap( this, _lights, objects, capabilities ); - _gl.clear( bits ); + this.shadowMap = shadowMap; - }; - this.clearColor = function () { + // Plugins - this.clear( true, false, false ); + var spritePlugin = new SpritePlugin( this, sprites ); + var lensFlarePlugin = new LensFlarePlugin( this, lensFlares ); - }; + // API - this.clearDepth = function () { + this.getContext = function () { - this.clear( false, true, false ); + return _gl; - }; + }; - this.clearStencil = function () { + this.getContextAttributes = function () { - this.clear( false, false, true ); + return _gl.getContextAttributes(); - }; + }; - this.clearTarget = function ( renderTarget, color, depth, stencil ) { + this.forceContextLoss = function () { - this.setRenderTarget( renderTarget ); - this.clear( color, depth, stencil ); + extensions.get( 'WEBGL_lose_context' ).loseContext(); - }; + }; - // Reset + this.getMaxAnisotropy = function () { - this.resetGLState = resetGLState; + return capabilities.getMaxAnisotropy(); - this.dispose = function() { + }; - transparentObjects = []; - transparentObjectsLastIndex = -1; - opaqueObjects = []; - opaqueObjectsLastIndex = -1; + this.getPrecision = function () { - _canvas.removeEventListener( 'webglcontextlost', onContextLost, false ); + return capabilities.precision; - }; + }; - // Events + this.getPixelRatio = function () { - function onContextLost( event ) { + return _pixelRatio; - event.preventDefault(); + }; - resetGLState(); - setDefaultGLState(); + this.setPixelRatio = function ( value ) { - properties.clear(); + if ( value === undefined ) return; - } + _pixelRatio = value; - function onMaterialDispose( event ) { + this.setSize( _viewport.z, _viewport.w, false ); - var material = event.target; + }; - material.removeEventListener( 'dispose', onMaterialDispose ); + this.getSize = function () { - deallocateMaterial( material ); + return { + width: _width, + height: _height + }; - } + }; - // Buffer deallocation + this.setSize = function ( width, height, updateStyle ) { - function deallocateMaterial( material ) { + _width = width; + _height = height; - releaseMaterialProgramReference( material ); + _canvas.width = width * _pixelRatio; + _canvas.height = height * _pixelRatio; - properties.delete( material ); + if ( updateStyle !== false ) { - } + _canvas.style.width = width + 'px'; + _canvas.style.height = height + 'px'; + } - function releaseMaterialProgramReference( material ) { + this.setViewport( 0, 0, width, height ); - var programInfo = properties.get( material ).program; + }; - material.program = undefined; + this.setViewport = function ( x, y, width, height ) { - if ( programInfo !== undefined ) { + state.viewport( _viewport.set( x, y, width, height ) ); - programCache.releaseProgram( programInfo ); + }; - } + this.setScissor = function ( x, y, width, height ) { - } + state.scissor( _scissor.set( x, y, width, height ) ); - // Buffer rendering + }; - this.renderBufferImmediate = function ( object, program, material ) { + this.setScissorTest = function ( boolean ) { - state.initAttributes(); + state.setScissorTest( _scissorTest = boolean ); - var buffers = properties.get( object ); + }; - if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer(); - if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer(); - if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer(); - if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer(); + // Clearing - var attributes = program.getAttributes(); + this.getClearColor = function () { - if ( object.hasPositions ) { + return _clearColor; - _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position ); - _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW ); + }; - state.enableAttribute( attributes.position ); - _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 ); + this.setClearColor = function ( color, alpha ) { - } + _clearColor.set( color ); - if ( object.hasNormals ) { + _clearAlpha = alpha !== undefined ? alpha : 1; - _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal ); + glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); - if ( material.type !== 'MeshPhongMaterial' && material.type !== 'MeshStandardMaterial' && material.type !== 'MeshPhysicalMaterial' && material.shading === FlatShading ) { + }; - for ( var i = 0, l = object.count * 3; i < l; i += 9 ) { + this.getClearAlpha = function () { - var array = object.normalArray; + return _clearAlpha; - var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3; - var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3; - var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3; + }; - array[ i + 0 ] = nx; - array[ i + 1 ] = ny; - array[ i + 2 ] = nz; + this.setClearAlpha = function ( alpha ) { - array[ i + 3 ] = nx; - array[ i + 4 ] = ny; - array[ i + 5 ] = nz; + _clearAlpha = alpha; - array[ i + 6 ] = nx; - array[ i + 7 ] = ny; - array[ i + 8 ] = nz; + glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); - } + }; - } + this.clear = function ( color, depth, stencil ) { - _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW ); + var bits = 0; - state.enableAttribute( attributes.normal ); + if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT; + if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT; + if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT; - _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 ); + _gl.clear( bits ); - } + }; - if ( object.hasUvs && material.map ) { + this.clearColor = function () { - _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv ); - _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW ); + this.clear( true, false, false ); - state.enableAttribute( attributes.uv ); + }; - _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 ); + this.clearDepth = function () { - } + this.clear( false, true, false ); - if ( object.hasColors && material.vertexColors !== NoColors ) { + }; - _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color ); - _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW ); + this.clearStencil = function () { - state.enableAttribute( attributes.color ); + this.clear( false, false, true ); - _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 ); + }; - } + this.clearTarget = function ( renderTarget, color, depth, stencil ) { - state.disableUnusedAttributes(); + this.setRenderTarget( renderTarget ); + this.clear( color, depth, stencil ); - _gl.drawArrays( _gl.TRIANGLES, 0, object.count ); + }; - object.count = 0; + // Reset - }; + this.resetGLState = resetGLState; - this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) { + this.dispose = function() { - setMaterial( material ); + transparentObjects = []; + transparentObjectsLastIndex = -1; + opaqueObjects = []; + opaqueObjectsLastIndex = -1; - var program = setProgram( camera, fog, material, object ); + _canvas.removeEventListener( 'webglcontextlost', onContextLost, false ); - var updateBuffers = false; - var geometryProgram = geometry.id + '_' + program.id + '_' + material.wireframe; + }; - if ( geometryProgram !== _currentGeometryProgram ) { + // Events - _currentGeometryProgram = geometryProgram; - updateBuffers = true; + function onContextLost( event ) { - } + event.preventDefault(); - // morph targets + resetGLState(); + setDefaultGLState(); - var morphTargetInfluences = object.morphTargetInfluences; + properties.clear(); - if ( morphTargetInfluences !== undefined ) { + } - var activeInfluences = []; + function onMaterialDispose( event ) { - for ( var i = 0, l = morphTargetInfluences.length; i < l; i ++ ) { + var material = event.target; - var influence = morphTargetInfluences[ i ]; - activeInfluences.push( [ influence, i ] ); + material.removeEventListener( 'dispose', onMaterialDispose ); - } + deallocateMaterial( material ); - activeInfluences.sort( absNumericalSort ); + } - if ( activeInfluences.length > 8 ) { + // Buffer deallocation - activeInfluences.length = 8; + function deallocateMaterial( material ) { - } + releaseMaterialProgramReference( material ); - var morphAttributes = geometry.morphAttributes; + properties.delete( material ); - for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) { + } - var influence = activeInfluences[ i ]; - morphInfluences[ i ] = influence[ 0 ]; - if ( influence[ 0 ] !== 0 ) { + function releaseMaterialProgramReference( material ) { - var index = influence[ 1 ]; + var programInfo = properties.get( material ).program; - if ( material.morphTargets === true && morphAttributes.position ) geometry.addAttribute( 'morphTarget' + i, morphAttributes.position[ index ] ); - if ( material.morphNormals === true && morphAttributes.normal ) geometry.addAttribute( 'morphNormal' + i, morphAttributes.normal[ index ] ); + material.program = undefined; - } else { + if ( programInfo !== undefined ) { - if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i ); - if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i ); + programCache.releaseProgram( programInfo ); - } + } - } + } - program.getUniforms().setValue( - _gl, 'morphTargetInfluences', morphInfluences ); + // Buffer rendering - updateBuffers = true; + this.renderBufferImmediate = function ( object, program, material ) { - } + state.initAttributes(); - // + var buffers = properties.get( object ); - var index = geometry.index; - var position = geometry.attributes.position; + if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer(); + if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer(); + if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer(); + if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer(); - if ( material.wireframe === true ) { + var attributes = program.getAttributes(); - index = objects.getWireframeAttribute( geometry ); + if ( object.hasPositions ) { - } + _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position ); + _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW ); - var renderer; + state.enableAttribute( attributes.position ); + _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 ); - if ( index !== null ) { + } - renderer = indexedBufferRenderer; - renderer.setIndex( index ); + if ( object.hasNormals ) { - } else { + _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal ); - renderer = bufferRenderer; + if ( material.type !== 'MeshPhongMaterial' && material.type !== 'MeshStandardMaterial' && material.type !== 'MeshPhysicalMaterial' && material.shading === FlatShading ) { - } + for ( var i = 0, l = object.count * 3; i < l; i += 9 ) { - if ( updateBuffers ) { + var array = object.normalArray; - setupVertexAttributes( material, program, geometry ); + var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3; + var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3; + var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3; - if ( index !== null ) { + array[ i + 0 ] = nx; + array[ i + 1 ] = ny; + array[ i + 2 ] = nz; - _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, objects.getAttributeBuffer( index ) ); + array[ i + 3 ] = nx; + array[ i + 4 ] = ny; + array[ i + 5 ] = nz; - } + array[ i + 6 ] = nx; + array[ i + 7 ] = ny; + array[ i + 8 ] = nz; - } + } - // + } - var dataStart = 0; - var dataCount = Infinity; + _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW ); - if ( index !== null ) { + state.enableAttribute( attributes.normal ); - dataCount = index.count; + _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 ); - } else if ( position !== undefined ) { + } - dataCount = position.count; + if ( object.hasUvs && material.map ) { - } + _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv ); + _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW ); - var rangeStart = geometry.drawRange.start; - var rangeCount = geometry.drawRange.count; + state.enableAttribute( attributes.uv ); - var groupStart = group !== null ? group.start : 0; - var groupCount = group !== null ? group.count : Infinity; + _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 ); - var drawStart = Math.max( dataStart, rangeStart, groupStart ); - var drawEnd = Math.min( dataStart + dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1; + } - var drawCount = Math.max( 0, drawEnd - drawStart + 1 ); + if ( object.hasColors && material.vertexColors !== NoColors ) { - // + _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color ); + _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW ); - if ( object && object.isMesh ) { + state.enableAttribute( attributes.color ); - if ( material.wireframe === true ) { + _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 ); - state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() ); - renderer.setMode( _gl.LINES ); + } - } else { + state.disableUnusedAttributes(); - switch ( object.drawMode ) { + _gl.drawArrays( _gl.TRIANGLES, 0, object.count ); - case TrianglesDrawMode: - renderer.setMode( _gl.TRIANGLES ); - break; + object.count = 0; - case TriangleStripDrawMode: - renderer.setMode( _gl.TRIANGLE_STRIP ); - break; + }; - case TriangleFanDrawMode: - renderer.setMode( _gl.TRIANGLE_FAN ); - break; + this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) { - } + setMaterial( material ); - } + var program = setProgram( camera, fog, material, object ); + var updateBuffers = false; + var geometryProgram = geometry.id + '_' + program.id + '_' + material.wireframe; - } else if ( object && object.isLine ) { + if ( geometryProgram !== _currentGeometryProgram ) { - var lineWidth = material.linewidth; + _currentGeometryProgram = geometryProgram; + updateBuffers = true; - if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material + } - state.setLineWidth( lineWidth * getTargetPixelRatio() ); + // morph targets - if ( object && object.isLineSegments ) { + var morphTargetInfluences = object.morphTargetInfluences; - renderer.setMode( _gl.LINES ); + if ( morphTargetInfluences !== undefined ) { - } else { + var activeInfluences = []; - renderer.setMode( _gl.LINE_STRIP ); + for ( var i = 0, l = morphTargetInfluences.length; i < l; i ++ ) { - } + var influence = morphTargetInfluences[ i ]; + activeInfluences.push( [ influence, i ] ); - } else if ( object && object.isPoints ) { + } - renderer.setMode( _gl.POINTS ); + activeInfluences.sort( absNumericalSort ); - } + if ( activeInfluences.length > 8 ) { - if ( geometry && geometry.isInstancedBufferGeometry ) { + activeInfluences.length = 8; - if ( geometry.maxInstancedCount > 0 ) { + } - renderer.renderInstances( geometry, drawStart, drawCount ); + var morphAttributes = geometry.morphAttributes; - } + for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) { - } else { + var influence = activeInfluences[ i ]; + morphInfluences[ i ] = influence[ 0 ]; - renderer.render( drawStart, drawCount ); + if ( influence[ 0 ] !== 0 ) { - } + var index = influence[ 1 ]; - }; + if ( material.morphTargets === true && morphAttributes.position ) geometry.addAttribute( 'morphTarget' + i, morphAttributes.position[ index ] ); + if ( material.morphNormals === true && morphAttributes.normal ) geometry.addAttribute( 'morphNormal' + i, morphAttributes.normal[ index ] ); - function setupVertexAttributes( material, program, geometry, startIndex ) { + } else { - var extension; + if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i ); + if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i ); - if ( geometry && geometry.isInstancedBufferGeometry ) { + } - extension = extensions.get( 'ANGLE_instanced_arrays' ); + } - if ( extension === null ) { + program.getUniforms().setValue( + _gl, 'morphTargetInfluences', morphInfluences ); - console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); - return; + updateBuffers = true; - } + } - } + // - if ( startIndex === undefined ) startIndex = 0; + var index = geometry.index; + var position = geometry.attributes.position; - state.initAttributes(); + if ( material.wireframe === true ) { - var geometryAttributes = geometry.attributes; + index = objects.getWireframeAttribute( geometry ); - var programAttributes = program.getAttributes(); + } - var materialDefaultAttributeValues = material.defaultAttributeValues; + var renderer; - for ( var name in programAttributes ) { + if ( index !== null ) { - var programAttribute = programAttributes[ name ]; + renderer = indexedBufferRenderer; + renderer.setIndex( index ); - if ( programAttribute >= 0 ) { + } else { - var geometryAttribute = geometryAttributes[ name ]; + renderer = bufferRenderer; - if ( geometryAttribute !== undefined ) { + } - var type = _gl.FLOAT; - var array = geometryAttribute.array; - var normalized = geometryAttribute.normalized; + if ( updateBuffers ) { - if ( array instanceof Float32Array ) { + setupVertexAttributes( material, program, geometry ); - type = _gl.FLOAT; + if ( index !== null ) { - } else if ( array instanceof Float64Array ) { + _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, objects.getAttributeBuffer( index ) ); - console.warn( "Unsupported data buffer format: Float64Array" ); + } - } else if ( array instanceof Uint16Array ) { + } - type = _gl.UNSIGNED_SHORT; + // - } else if ( array instanceof Int16Array ) { + var dataStart = 0; + var dataCount = Infinity; - type = _gl.SHORT; + if ( index !== null ) { - } else if ( array instanceof Uint32Array ) { + dataCount = index.count; - type = _gl.UNSIGNED_INT; + } else if ( position !== undefined ) { - } else if ( array instanceof Int32Array ) { + dataCount = position.count; - type = _gl.INT; + } - } else if ( array instanceof Int8Array ) { + var rangeStart = geometry.drawRange.start; + var rangeCount = geometry.drawRange.count; - type = _gl.BYTE; + var groupStart = group !== null ? group.start : 0; + var groupCount = group !== null ? group.count : Infinity; - } else if ( array instanceof Uint8Array ) { + var drawStart = Math.max( dataStart, rangeStart, groupStart ); + var drawEnd = Math.min( dataStart + dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1; - type = _gl.UNSIGNED_BYTE; + var drawCount = Math.max( 0, drawEnd - drawStart + 1 ); - } + // - var size = geometryAttribute.itemSize; - var buffer = objects.getAttributeBuffer( geometryAttribute ); + if ( object.isMesh ) { - if ( geometryAttribute && geometryAttribute.isInterleavedBufferAttribute ) { + if ( material.wireframe === true ) { - var data = geometryAttribute.data; - var stride = data.stride; - var offset = geometryAttribute.offset; + state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() ); + renderer.setMode( _gl.LINES ); - if ( data && data.isInstancedInterleavedBuffer ) { + } else { - state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute, extension ); + switch ( object.drawMode ) { - if ( geometry.maxInstancedCount === undefined ) { + case TrianglesDrawMode: + renderer.setMode( _gl.TRIANGLES ); + break; - geometry.maxInstancedCount = data.meshPerAttribute * data.count; + case TriangleStripDrawMode: + renderer.setMode( _gl.TRIANGLE_STRIP ); + break; - } + case TriangleFanDrawMode: + renderer.setMode( _gl.TRIANGLE_FAN ); + break; - } else { + } - state.enableAttribute( programAttribute ); + } - } - _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer ); - _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * data.array.BYTES_PER_ELEMENT, ( startIndex * stride + offset ) * data.array.BYTES_PER_ELEMENT ); + } else if ( object.isLine ) { - } else { + var lineWidth = material.linewidth; - if ( geometryAttribute && geometryAttribute.isInstancedBufferAttribute ) { + if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material - state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute, extension ); + state.setLineWidth( lineWidth * getTargetPixelRatio() ); - if ( geometry.maxInstancedCount === undefined ) { + if ( object.isLineSegments ) { - geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count; + renderer.setMode( _gl.LINES ); - } + } else { - } else { + renderer.setMode( _gl.LINE_STRIP ); - state.enableAttribute( programAttribute ); + } - } + } else if ( object.isPoints ) { - _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer ); - _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, startIndex * size * geometryAttribute.array.BYTES_PER_ELEMENT ); + renderer.setMode( _gl.POINTS ); - } + } - } else if ( materialDefaultAttributeValues !== undefined ) { + if ( geometry && geometry.isInstancedBufferGeometry ) { - var value = materialDefaultAttributeValues[ name ]; + if ( geometry.maxInstancedCount > 0 ) { - if ( value !== undefined ) { + renderer.renderInstances( geometry, drawStart, drawCount ); - switch ( value.length ) { + } - case 2: - _gl.vertexAttrib2fv( programAttribute, value ); - break; + } else { - case 3: - _gl.vertexAttrib3fv( programAttribute, value ); - break; + renderer.render( drawStart, drawCount ); - case 4: - _gl.vertexAttrib4fv( programAttribute, value ); - break; + } - default: - _gl.vertexAttrib1fv( programAttribute, value ); + }; - } + function setupVertexAttributes( material, program, geometry, startIndex ) { - } + var extension; - } + if ( geometry && geometry.isInstancedBufferGeometry ) { - } + extension = extensions.get( 'ANGLE_instanced_arrays' ); - } + if ( extension === null ) { - state.disableUnusedAttributes(); + console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); + return; - } + } - // Sorting + } - function absNumericalSort( a, b ) { + if ( startIndex === undefined ) startIndex = 0; - return Math.abs( b[ 0 ] ) - Math.abs( a[ 0 ] ); + state.initAttributes(); - } + var geometryAttributes = geometry.attributes; - function painterSortStable( a, b ) { + var programAttributes = program.getAttributes(); - if ( a.object.renderOrder !== b.object.renderOrder ) { + var materialDefaultAttributeValues = material.defaultAttributeValues; - return a.object.renderOrder - b.object.renderOrder; + for ( var name in programAttributes ) { - } else if ( a.material.program && b.material.program && a.material.program !== b.material.program ) { + var programAttribute = programAttributes[ name ]; - return a.material.program.id - b.material.program.id; + if ( programAttribute >= 0 ) { - } else if ( a.material.id !== b.material.id ) { + var geometryAttribute = geometryAttributes[ name ]; - return a.material.id - b.material.id; + if ( geometryAttribute !== undefined ) { - } else if ( a.z !== b.z ) { + var type = _gl.FLOAT; + var array = geometryAttribute.array; + var normalized = geometryAttribute.normalized; - return a.z - b.z; + if ( array instanceof Float32Array ) { - } else { + type = _gl.FLOAT; - return a.id - b.id; + } else if ( array instanceof Float64Array ) { - } + console.warn( "Unsupported data buffer format: Float64Array" ); - } + } else if ( array instanceof Uint16Array ) { - function reversePainterSortStable( a, b ) { + type = _gl.UNSIGNED_SHORT; - if ( a.object.renderOrder !== b.object.renderOrder ) { + } else if ( array instanceof Int16Array ) { - return a.object.renderOrder - b.object.renderOrder; + type = _gl.SHORT; - } if ( a.z !== b.z ) { + } else if ( array instanceof Uint32Array ) { - return b.z - a.z; + type = _gl.UNSIGNED_INT; - } else { + } else if ( array instanceof Int32Array ) { - return a.id - b.id; + type = _gl.INT; - } + } else if ( array instanceof Int8Array ) { - } + type = _gl.BYTE; - // Rendering + } else if ( array instanceof Uint8Array ) { - this.render = function ( scene, camera, renderTarget, forceClear ) { + type = _gl.UNSIGNED_BYTE; - if ( ( camera && camera.isCamera ) === false ) { + } - console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' ); - return; + var size = geometryAttribute.itemSize; + var buffer = objects.getAttributeBuffer( geometryAttribute ); - } + if ( geometryAttribute && geometryAttribute.isInterleavedBufferAttribute ) { - var fog = scene.fog; + var data = geometryAttribute.data; + var stride = data.stride; + var offset = geometryAttribute.offset; - // reset caching for this frame + if ( data && data.isInstancedInterleavedBuffer ) { - _currentGeometryProgram = ''; - _currentMaterialId = - 1; - _currentCamera = null; + state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute, extension ); - // update scene graph + if ( geometry.maxInstancedCount === undefined ) { - if ( scene.autoUpdate === true ) scene.updateMatrixWorld(); + geometry.maxInstancedCount = data.meshPerAttribute * data.count; - // update camera matrices and frustum + } - if ( camera.parent === null ) camera.updateMatrixWorld(); + } else { - camera.matrixWorldInverse.getInverse( camera.matrixWorld ); + state.enableAttribute( programAttribute ); - _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); - _frustum.setFromMatrix( _projScreenMatrix ); + } - lights.length = 0; + _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer ); + _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * data.array.BYTES_PER_ELEMENT, ( startIndex * stride + offset ) * data.array.BYTES_PER_ELEMENT ); - opaqueObjectsLastIndex = - 1; - transparentObjectsLastIndex = - 1; + } else { - sprites.length = 0; - lensFlares.length = 0; + if ( geometryAttribute && geometryAttribute.isInstancedBufferAttribute ) { - _localClippingEnabled = this.localClippingEnabled; - _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera ); + state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute, extension ); - projectObject( scene, camera ); + if ( geometry.maxInstancedCount === undefined ) { - opaqueObjects.length = opaqueObjectsLastIndex + 1; - transparentObjects.length = transparentObjectsLastIndex + 1; + geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count; - if ( _this.sortObjects === true ) { + } - opaqueObjects.sort( painterSortStable ); - transparentObjects.sort( reversePainterSortStable ); + } else { - } + state.enableAttribute( programAttribute ); - // + } - if ( _clippingEnabled ) _clipping.beginShadows(); + _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer ); + _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, startIndex * size * geometryAttribute.array.BYTES_PER_ELEMENT ); - setupShadows( lights ); + } - shadowMap.render( scene, camera ); + } else if ( materialDefaultAttributeValues !== undefined ) { - setupLights( lights, camera ); + var value = materialDefaultAttributeValues[ name ]; - if ( _clippingEnabled ) _clipping.endShadows(); + if ( value !== undefined ) { - // + switch ( value.length ) { - _infoRender.calls = 0; - _infoRender.vertices = 0; - _infoRender.faces = 0; - _infoRender.points = 0; + case 2: + _gl.vertexAttrib2fv( programAttribute, value ); + break; - if ( renderTarget === undefined ) { + case 3: + _gl.vertexAttrib3fv( programAttribute, value ); + break; - renderTarget = null; + case 4: + _gl.vertexAttrib4fv( programAttribute, value ); + break; - } + default: + _gl.vertexAttrib1fv( programAttribute, value ); - this.setRenderTarget( renderTarget ); + } - // + } - var background = scene.background; + } - if ( background === null ) { + } - glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); + } - } else if ( background && background.isColor ) { + state.disableUnusedAttributes(); - glClearColor( background.r, background.g, background.b, 1 ); + } - } + // Sorting - if ( this.autoClear || forceClear ) { + function absNumericalSort( a, b ) { - this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil ); + return Math.abs( b[ 0 ] ) - Math.abs( a[ 0 ] ); - } + } - if ( background && background.isCubeTexture ) { + function painterSortStable( a, b ) { - backgroundCamera2.projectionMatrix.copy( camera.projectionMatrix ); + if ( a.object.renderOrder !== b.object.renderOrder ) { - backgroundCamera2.matrixWorld.extractRotation( camera.matrixWorld ); - backgroundCamera2.matrixWorldInverse.getInverse( backgroundCamera2.matrixWorld ); + return a.object.renderOrder - b.object.renderOrder; - backgroundBoxMesh.material.uniforms[ "tCube" ].value = background; - backgroundBoxMesh.modelViewMatrix.multiplyMatrices( backgroundCamera2.matrixWorldInverse, backgroundBoxMesh.matrixWorld ); + } else if ( a.material.program && b.material.program && a.material.program !== b.material.program ) { - objects.update( backgroundBoxMesh ); + return a.material.program.id - b.material.program.id; - _this.renderBufferDirect( backgroundCamera2, null, backgroundBoxMesh.geometry, backgroundBoxMesh.material, backgroundBoxMesh, null ); + } else if ( a.material.id !== b.material.id ) { - } else if ( background && background.isTexture ) { + return a.material.id - b.material.id; - backgroundPlaneMesh.material.map = background; + } else if ( a.z !== b.z ) { - objects.update( backgroundPlaneMesh ); + return a.z - b.z; - _this.renderBufferDirect( backgroundCamera, null, backgroundPlaneMesh.geometry, backgroundPlaneMesh.material, backgroundPlaneMesh, null ); + } else { - } + return a.id - b.id; - // + } - if ( scene.overrideMaterial ) { + } - var overrideMaterial = scene.overrideMaterial; + function reversePainterSortStable( a, b ) { - renderObjects( opaqueObjects, camera, fog, overrideMaterial ); - renderObjects( transparentObjects, camera, fog, overrideMaterial ); + if ( a.object.renderOrder !== b.object.renderOrder ) { - } else { + return a.object.renderOrder - b.object.renderOrder; - // opaque pass (front-to-back order) + } if ( a.z !== b.z ) { - state.setBlending( NoBlending ); - renderObjects( opaqueObjects, camera, fog ); + return b.z - a.z; - // transparent pass (back-to-front order) + } else { - renderObjects( transparentObjects, camera, fog ); + return a.id - b.id; - } + } - // custom render plugins (post pass) + } - spritePlugin.render( scene, camera ); - lensFlarePlugin.render( scene, camera, _currentViewport ); + // Rendering - // Generate mipmap if we're using any kind of mipmap filtering + this.render = function ( scene, camera, renderTarget, forceClear ) { - if ( renderTarget ) { + if ( ( camera && camera.isCamera ) === false ) { - textures.updateRenderTargetMipmap( renderTarget ); + console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' ); + return; - } + } - // Ensure depth buffer writing is enabled so it can be cleared on next render + var fog = scene.fog; - state.setDepthTest( true ); - state.setDepthWrite( true ); - state.setColorWrite( true ); + // reset caching for this frame - // _gl.finish(); + _currentGeometryProgram = ''; + _currentMaterialId = - 1; + _currentCamera = null; - }; + // update scene graph - function pushRenderItem( object, geometry, material, z, group ) { + if ( scene.autoUpdate === true ) scene.updateMatrixWorld(); - var array, index; + // update camera matrices and frustum - // allocate the next position in the appropriate array + if ( camera.parent === null ) camera.updateMatrixWorld(); - if ( material.transparent ) { + camera.matrixWorldInverse.getInverse( camera.matrixWorld ); - array = transparentObjects; - index = ++ transparentObjectsLastIndex; + _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); + _frustum.setFromMatrix( _projScreenMatrix ); - } else { + lights.length = 0; - array = opaqueObjects; - index = ++ opaqueObjectsLastIndex; + opaqueObjectsLastIndex = - 1; + transparentObjectsLastIndex = - 1; - } + sprites.length = 0; + lensFlares.length = 0; - // recycle existing render item or grow the array + _localClippingEnabled = this.localClippingEnabled; + _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera ); - var renderItem = array[ index ]; + projectObject( scene, camera ); - if ( renderItem !== undefined ) { + opaqueObjects.length = opaqueObjectsLastIndex + 1; + transparentObjects.length = transparentObjectsLastIndex + 1; - renderItem.id = object.id; - renderItem.object = object; - renderItem.geometry = geometry; - renderItem.material = material; - renderItem.z = _vector3.z; - renderItem.group = group; + if ( _this.sortObjects === true ) { - } else { + opaqueObjects.sort( painterSortStable ); + transparentObjects.sort( reversePainterSortStable ); - renderItem = { - id: object.id, - object: object, - geometry: geometry, - material: material, - z: _vector3.z, - group: group - }; + } - // assert( index === array.length ); - array.push( renderItem ); + // - } + if ( _clippingEnabled ) _clipping.beginShadows(); - } + setupShadows( lights ); - // TODO Duplicated code (Frustum) + shadowMap.render( scene, camera ); - function isObjectViewable( object ) { + setupLights( lights, camera ); - var geometry = object.geometry; + if ( _clippingEnabled ) _clipping.endShadows(); - if ( geometry.boundingSphere === null ) - geometry.computeBoundingSphere(); + // - _sphere.copy( geometry.boundingSphere ). - applyMatrix4( object.matrixWorld ); + _infoRender.calls = 0; + _infoRender.vertices = 0; + _infoRender.faces = 0; + _infoRender.points = 0; - return isSphereViewable( _sphere ); + if ( renderTarget === undefined ) { - } + renderTarget = null; - function isSpriteViewable( sprite ) { + } - _sphere.center.set( 0, 0, 0 ); - _sphere.radius = 0.7071067811865476; - _sphere.applyMatrix4( sprite.matrixWorld ); + this.setRenderTarget( renderTarget ); - return isSphereViewable( _sphere ); + // - } + var background = scene.background; - function isSphereViewable( sphere ) { + if ( background === null ) { - if ( ! _frustum.intersectsSphere( sphere ) ) return false; + glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); - var numPlanes = _clipping.numPlanes; + } else if ( background && background.isColor ) { - if ( numPlanes === 0 ) return true; + glClearColor( background.r, background.g, background.b, 1 ); + forceClear = true; - var planes = _this.clippingPlanes, + } - center = sphere.center, - negRad = - sphere.radius, - i = 0; + if ( this.autoClear || forceClear ) { - do { + this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil ); - // out when deeper than radius in the negative halfspace - if ( planes[ i ].distanceToPoint( center ) < negRad ) return false; + } - } while ( ++ i !== numPlanes ); + if ( background && background.isCubeTexture ) { - return true; + backgroundCamera2.projectionMatrix.copy( camera.projectionMatrix ); - } + backgroundCamera2.matrixWorld.extractRotation( camera.matrixWorld ); + backgroundCamera2.matrixWorldInverse.getInverse( backgroundCamera2.matrixWorld ); - function projectObject( object, camera ) { + backgroundBoxMesh.material.uniforms[ "tCube" ].value = background; + backgroundBoxMesh.modelViewMatrix.multiplyMatrices( backgroundCamera2.matrixWorldInverse, backgroundBoxMesh.matrixWorld ); - if ( object.visible === false ) return; + objects.update( backgroundBoxMesh ); - if ( object.layers.test( camera.layers ) ) { + _this.renderBufferDirect( backgroundCamera2, null, backgroundBoxMesh.geometry, backgroundBoxMesh.material, backgroundBoxMesh, null ); - if ( object && object.isLight ) { + } else if ( background && background.isTexture ) { - lights.push( object ); + backgroundPlaneMesh.material.map = background; - } else if ( object && object.isSprite ) { + objects.update( backgroundPlaneMesh ); - if ( object.frustumCulled === false || isSpriteViewable( object ) === true ) { + _this.renderBufferDirect( backgroundCamera, null, backgroundPlaneMesh.geometry, backgroundPlaneMesh.material, backgroundPlaneMesh, null ); - sprites.push( object ); + } - } + // - } else if ( object && object.isLensFlare ) { + if ( scene.overrideMaterial ) { - lensFlares.push( object ); + var overrideMaterial = scene.overrideMaterial; - } else if ( object && object.isImmediateRenderObject ) { + renderObjects( opaqueObjects, camera, fog, overrideMaterial ); + renderObjects( transparentObjects, camera, fog, overrideMaterial ); - if ( _this.sortObjects === true ) { + } else { - _vector3.setFromMatrixPosition( object.matrixWorld ); - _vector3.applyProjection( _projScreenMatrix ); + // opaque pass (front-to-back order) - } + state.setBlending( NoBlending ); + renderObjects( opaqueObjects, camera, fog ); - pushRenderItem( object, null, object.material, _vector3.z, null ); + // transparent pass (back-to-front order) - } else if ( ( object && object.isMesh ) || ( object && object.isLine ) || ( object && object.isPoints ) ) { + renderObjects( transparentObjects, camera, fog ); - if ( object && object.isSkinnedMesh ) { + } - object.skeleton.update(); + // custom render plugins (post pass) - } + spritePlugin.render( scene, camera ); + lensFlarePlugin.render( scene, camera, _currentViewport ); - if ( object.frustumCulled === false || isObjectViewable( object ) === true ) { + // Generate mipmap if we're using any kind of mipmap filtering - var material = object.material; + if ( renderTarget ) { - if ( material.visible === true ) { + textures.updateRenderTargetMipmap( renderTarget ); - if ( _this.sortObjects === true ) { + } - _vector3.setFromMatrixPosition( object.matrixWorld ); - _vector3.applyProjection( _projScreenMatrix ); + // Ensure depth buffer writing is enabled so it can be cleared on next render - } + state.setDepthTest( true ); + state.setDepthWrite( true ); + state.setColorWrite( true ); - var geometry = objects.update( object ); + // _gl.finish(); - if ( material && material.isMultiMaterial ) { + }; - var groups = geometry.groups; - var materials = material.materials; + function pushRenderItem( object, geometry, material, z, group ) { - for ( var i = 0, l = groups.length; i < l; i ++ ) { + var array, index; - var group = groups[ i ]; - var groupMaterial = materials[ group.materialIndex ]; + // allocate the next position in the appropriate array - if ( groupMaterial.visible === true ) { + if ( material.transparent ) { - pushRenderItem( object, geometry, groupMaterial, _vector3.z, group ); + array = transparentObjects; + index = ++ transparentObjectsLastIndex; - } + } else { - } + array = opaqueObjects; + index = ++ opaqueObjectsLastIndex; - } else { + } - pushRenderItem( object, geometry, material, _vector3.z, null ); + // recycle existing render item or grow the array - } + var renderItem = array[ index ]; - } + if ( renderItem !== undefined ) { - } + renderItem.id = object.id; + renderItem.object = object; + renderItem.geometry = geometry; + renderItem.material = material; + renderItem.z = _vector3.z; + renderItem.group = group; - } + } else { - } + renderItem = { + id: object.id, + object: object, + geometry: geometry, + material: material, + z: _vector3.z, + group: group + }; - var children = object.children; + // assert( index === array.length ); + array.push( renderItem ); - for ( var i = 0, l = children.length; i < l; i ++ ) { + } - projectObject( children[ i ], camera ); + } - } + // TODO Duplicated code (Frustum) - } + function isObjectViewable( object ) { - function renderObjects( renderList, camera, fog, overrideMaterial ) { + var geometry = object.geometry; - for ( var i = 0, l = renderList.length; i < l; i ++ ) { + if ( geometry.boundingSphere === null ) + geometry.computeBoundingSphere(); - var renderItem = renderList[ i ]; + _sphere.copy( geometry.boundingSphere ). + applyMatrix4( object.matrixWorld ); - var object = renderItem.object; - var geometry = renderItem.geometry; - var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial; - var group = renderItem.group; + return isSphereViewable( _sphere ); - object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld ); - object.normalMatrix.getNormalMatrix( object.modelViewMatrix ); + } - if ( object && object.isImmediateRenderObject ) { + function isSpriteViewable( sprite ) { - setMaterial( material ); + _sphere.center.set( 0, 0, 0 ); + _sphere.radius = 0.7071067811865476; + _sphere.applyMatrix4( sprite.matrixWorld ); - var program = setProgram( camera, fog, material, object ); + return isSphereViewable( _sphere ); - _currentGeometryProgram = ''; + } - object.render( function ( object ) { + function isSphereViewable( sphere ) { - _this.renderBufferImmediate( object, program, material ); + if ( ! _frustum.intersectsSphere( sphere ) ) return false; - } ); + var numPlanes = _clipping.numPlanes; - } else { + if ( numPlanes === 0 ) return true; - _this.renderBufferDirect( camera, fog, geometry, material, object, group ); + var planes = _this.clippingPlanes, - } + center = sphere.center, + negRad = - sphere.radius, + i = 0; - } + do { - } + // out when deeper than radius in the negative halfspace + if ( planes[ i ].distanceToPoint( center ) < negRad ) return false; - function initMaterial( material, fog, object ) { + } while ( ++ i !== numPlanes ); - var materialProperties = properties.get( material ); + return true; - var parameters = programCache.getParameters( - material, _lights, fog, _clipping.numPlanes, object ); + } - var code = programCache.getProgramCode( material, parameters ); + function projectObject( object, camera ) { - var program = materialProperties.program; - var programChange = true; + if ( object.visible === false ) return; - if ( program === undefined ) { + var visible = ( object.layers.mask & camera.layers.mask ) !== 0; - // new material - material.addEventListener( 'dispose', onMaterialDispose ); + if ( visible ) { - } else if ( program.code !== code ) { + if ( object.isLight ) { - // changed glsl or parameters - releaseMaterialProgramReference( material ); + lights.push( object ); - } else if ( parameters.shaderID !== undefined ) { + } else if ( object.isSprite ) { - // same glsl and uniform list - return; + if ( object.frustumCulled === false || isSpriteViewable( object ) === true ) { - } else { + sprites.push( object ); - // only rebuild uniform list - programChange = false; + } - } + } else if ( object.isLensFlare ) { - if ( programChange ) { + lensFlares.push( object ); - if ( parameters.shaderID ) { + } else if ( object.isImmediateRenderObject ) { - var shader = exports.ShaderLib[ parameters.shaderID ]; + if ( _this.sortObjects === true ) { - materialProperties.__webglShader = { - name: material.type, - uniforms: exports.UniformsUtils.clone( shader.uniforms ), - vertexShader: shader.vertexShader, - fragmentShader: shader.fragmentShader - }; + _vector3.setFromMatrixPosition( object.matrixWorld ); + _vector3.applyProjection( _projScreenMatrix ); - } else { + } - materialProperties.__webglShader = { - name: material.type, - uniforms: material.uniforms, - vertexShader: material.vertexShader, - fragmentShader: material.fragmentShader - }; + pushRenderItem( object, null, object.material, _vector3.z, null ); - } + } else if ( object.isMesh || object.isLine || object.isPoints ) { - material.__webglShader = materialProperties.__webglShader; + if ( object.isSkinnedMesh ) { - program = programCache.acquireProgram( material, parameters, code ); + object.skeleton.update(); - materialProperties.program = program; - material.program = program; + } - } + if ( object.frustumCulled === false || isObjectViewable( object ) === true ) { - var attributes = program.getAttributes(); + var material = object.material; - if ( material.morphTargets ) { + if ( material.visible === true ) { - material.numSupportedMorphTargets = 0; + if ( _this.sortObjects === true ) { - for ( var i = 0; i < _this.maxMorphTargets; i ++ ) { + _vector3.setFromMatrixPosition( object.matrixWorld ); + _vector3.applyProjection( _projScreenMatrix ); - if ( attributes[ 'morphTarget' + i ] >= 0 ) { + } - material.numSupportedMorphTargets ++; + var geometry = objects.update( object ); - } + if ( material && material.isMultiMaterial ) { - } + var groups = geometry.groups; + var materials = material.materials; - } + for ( var i = 0, l = groups.length; i < l; i ++ ) { - if ( material.morphNormals ) { + var group = groups[ i ]; + var groupMaterial = materials[ group.materialIndex ]; - material.numSupportedMorphNormals = 0; + if ( groupMaterial.visible === true ) { - for ( var i = 0; i < _this.maxMorphNormals; i ++ ) { + pushRenderItem( object, geometry, groupMaterial, _vector3.z, group ); - if ( attributes[ 'morphNormal' + i ] >= 0 ) { + } - material.numSupportedMorphNormals ++; + } - } + } else { - } + pushRenderItem( object, geometry, material, _vector3.z, null ); - } + } - var uniforms = materialProperties.__webglShader.uniforms; + } - if ( ! ( material && material.isShaderMaterial ) && - ! ( material && material.isRawShaderMaterial ) || - material.clipping === true ) { + } - materialProperties.numClippingPlanes = _clipping.numPlanes; - uniforms.clippingPlanes = _clipping.uniform; + } - } + } - if ( material.lights ) { + var children = object.children; - // store the light setup it was created for + for ( var i = 0, l = children.length; i < l; i ++ ) { - materialProperties.lightsHash = _lights.hash; + projectObject( children[ i ], camera ); - // wire up the material to this renderer's lighting state + } - uniforms.ambientLightColor.value = _lights.ambient; - uniforms.directionalLights.value = _lights.directional; - uniforms.spotLights.value = _lights.spot; - uniforms.pointLights.value = _lights.point; - uniforms.hemisphereLights.value = _lights.hemi; + } - uniforms.directionalShadowMap.value = _lights.directionalShadowMap; - uniforms.directionalShadowMatrix.value = _lights.directionalShadowMatrix; - uniforms.spotShadowMap.value = _lights.spotShadowMap; - uniforms.spotShadowMatrix.value = _lights.spotShadowMatrix; - uniforms.pointShadowMap.value = _lights.pointShadowMap; - uniforms.pointShadowMatrix.value = _lights.pointShadowMatrix; + function renderObjects( renderList, camera, fog, overrideMaterial ) { - } + for ( var i = 0, l = renderList.length; i < l; i ++ ) { - var progUniforms = materialProperties.program.getUniforms(), - uniformsList = - exports.WebGLUniforms.seqWithValue( progUniforms.seq, uniforms ); + var renderItem = renderList[ i ]; - materialProperties.uniformsList = uniformsList; - materialProperties.dynamicUniforms = - exports.WebGLUniforms.splitDynamic( uniformsList, uniforms ); + var object = renderItem.object; + var geometry = renderItem.geometry; + var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial; + var group = renderItem.group; - } + object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld ); + object.normalMatrix.getNormalMatrix( object.modelViewMatrix ); - function setMaterial( material ) { + if ( object.isImmediateRenderObject ) { - if ( material.side !== DoubleSide ) - state.enable( _gl.CULL_FACE ); - else - state.disable( _gl.CULL_FACE ); + setMaterial( material ); - state.setFlipSided( material.side === BackSide ); + var program = setProgram( camera, fog, material, object ); - if ( material.transparent === true ) { + _currentGeometryProgram = ''; - state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha ); + object.render( function ( object ) { - } else { + _this.renderBufferImmediate( object, program, material ); - state.setBlending( NoBlending ); + } ); - } + } else { - state.setDepthFunc( material.depthFunc ); - state.setDepthTest( material.depthTest ); - state.setDepthWrite( material.depthWrite ); - state.setColorWrite( material.colorWrite ); - state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits ); + _this.renderBufferDirect( camera, fog, geometry, material, object, group ); - } + } - function setProgram( camera, fog, material, object ) { + } - _usedTextureUnits = 0; + } - var materialProperties = properties.get( material ); + function initMaterial( material, fog, object ) { - if ( _clippingEnabled ) { + var materialProperties = properties.get( material ); - if ( _localClippingEnabled || camera !== _currentCamera ) { + var parameters = programCache.getParameters( + material, _lights, fog, _clipping.numPlanes, object ); - var useCache = - camera === _currentCamera && - material.id === _currentMaterialId; + var code = programCache.getProgramCode( material, parameters ); - // we might want to call this function with some ClippingGroup - // object instead of the material, once it becomes feasible - // (#8465, #8379) - _clipping.setState( - material.clippingPlanes, material.clipShadows, - camera, materialProperties, useCache ); + var program = materialProperties.program; + var programChange = true; - } + if ( program === undefined ) { - if ( materialProperties.numClippingPlanes !== undefined && - materialProperties.numClippingPlanes !== _clipping.numPlanes ) { + // new material + material.addEventListener( 'dispose', onMaterialDispose ); - material.needsUpdate = true; + } else if ( program.code !== code ) { - } + // changed glsl or parameters + releaseMaterialProgramReference( material ); - } + } else if ( parameters.shaderID !== undefined ) { - if ( materialProperties.program === undefined ) { + // same glsl and uniform list + return; - material.needsUpdate = true; + } else { - } + // only rebuild uniform list + programChange = false; - if ( materialProperties.lightsHash !== undefined && - materialProperties.lightsHash !== _lights.hash ) { + } - material.needsUpdate = true; + if ( programChange ) { - } + if ( parameters.shaderID ) { - if ( material.needsUpdate ) { + var shader = exports.ShaderLib[ parameters.shaderID ]; - initMaterial( material, fog, object ); - material.needsUpdate = false; + materialProperties.__webglShader = { + name: material.type, + uniforms: exports.UniformsUtils.clone( shader.uniforms ), + vertexShader: shader.vertexShader, + fragmentShader: shader.fragmentShader + }; - } + } else { - var refreshProgram = false; - var refreshMaterial = false; - var refreshLights = false; + materialProperties.__webglShader = { + name: material.type, + uniforms: material.uniforms, + vertexShader: material.vertexShader, + fragmentShader: material.fragmentShader + }; - var program = materialProperties.program, - p_uniforms = program.getUniforms(), - m_uniforms = materialProperties.__webglShader.uniforms; + } - if ( program.id !== _currentProgram ) { + material.__webglShader = materialProperties.__webglShader; - _gl.useProgram( program.program ); - _currentProgram = program.id; + program = programCache.acquireProgram( material, parameters, code ); - refreshProgram = true; - refreshMaterial = true; - refreshLights = true; + materialProperties.program = program; + material.program = program; - } + } - if ( material.id !== _currentMaterialId ) { + var attributes = program.getAttributes(); - _currentMaterialId = material.id; + if ( material.morphTargets ) { - refreshMaterial = true; + material.numSupportedMorphTargets = 0; - } + for ( var i = 0; i < _this.maxMorphTargets; i ++ ) { - if ( refreshProgram || camera !== _currentCamera ) { + if ( attributes[ 'morphTarget' + i ] >= 0 ) { - p_uniforms.set( _gl, camera, 'projectionMatrix' ); + material.numSupportedMorphTargets ++; - if ( capabilities.logarithmicDepthBuffer ) { + } - p_uniforms.setValue( _gl, 'logDepthBufFC', - 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) ); + } - } + } + if ( material.morphNormals ) { - if ( camera !== _currentCamera ) { + material.numSupportedMorphNormals = 0; - _currentCamera = camera; + for ( var i = 0; i < _this.maxMorphNormals; i ++ ) { - // lighting uniforms depend on the camera so enforce an update - // now, in case this material supports lights - or later, when - // the next material that does gets activated: + if ( attributes[ 'morphNormal' + i ] >= 0 ) { - refreshMaterial = true; // set to true on material change - refreshLights = true; // remains set until update done + material.numSupportedMorphNormals ++; - } + } - // load material specific uniforms - // (shader material also gets them for the sake of genericity) + } - if ( ( material && material.isShaderMaterial ) || - ( material && material.isMeshPhongMaterial ) || - ( material && material.isMeshStandardMaterial ) || - material.envMap ) { + } - var uCamPos = p_uniforms.map.cameraPosition; + var uniforms = materialProperties.__webglShader.uniforms; - if ( uCamPos !== undefined ) { + if ( ! ( material && material.isShaderMaterial ) && + ! ( material && material.isRawShaderMaterial ) || + material.clipping === true ) { - uCamPos.setValue( _gl, - _vector3.setFromMatrixPosition( camera.matrixWorld ) ); + materialProperties.numClippingPlanes = _clipping.numPlanes; + uniforms.clippingPlanes = _clipping.uniform; - } + } - } + materialProperties.fog = fog; - if ( ( material && material.isMeshPhongMaterial ) || - ( material && material.isMeshLambertMaterial ) || - ( material && material.isMeshBasicMaterial ) || - ( material && material.isMeshStandardMaterial ) || - ( material && material.isShaderMaterial ) || - material.skinning ) { + // store the light setup it was created for - p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse ); + materialProperties.lightsHash = _lights.hash; - } + if ( material.lights ) { - p_uniforms.set( _gl, _this, 'toneMappingExposure' ); - p_uniforms.set( _gl, _this, 'toneMappingWhitePoint' ); + // wire up the material to this renderer's lighting state - } + uniforms.ambientLightColor.value = _lights.ambient; + uniforms.directionalLights.value = _lights.directional; + uniforms.spotLights.value = _lights.spot; + uniforms.pointLights.value = _lights.point; + uniforms.hemisphereLights.value = _lights.hemi; - // skinning uniforms must be set even if material didn't change - // auto-setting of texture unit for bone texture must go before other textures - // not sure why, but otherwise weird things happen + uniforms.directionalShadowMap.value = _lights.directionalShadowMap; + uniforms.directionalShadowMatrix.value = _lights.directionalShadowMatrix; + uniforms.spotShadowMap.value = _lights.spotShadowMap; + uniforms.spotShadowMatrix.value = _lights.spotShadowMatrix; + uniforms.pointShadowMap.value = _lights.pointShadowMap; + uniforms.pointShadowMatrix.value = _lights.pointShadowMatrix; - if ( material.skinning ) { + } - p_uniforms.setOptional( _gl, object, 'bindMatrix' ); - p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' ); + var progUniforms = materialProperties.program.getUniforms(), + uniformsList = + exports.WebGLUniforms.seqWithValue( progUniforms.seq, uniforms ); - var skeleton = object.skeleton; + materialProperties.uniformsList = uniformsList; + materialProperties.dynamicUniforms = + exports.WebGLUniforms.splitDynamic( uniformsList, uniforms ); - if ( skeleton ) { + } - if ( capabilities.floatVertexTextures && skeleton.useVertexTexture ) { + function setMaterial( material ) { - p_uniforms.set( _gl, skeleton, 'boneTexture' ); - p_uniforms.set( _gl, skeleton, 'boneTextureWidth' ); - p_uniforms.set( _gl, skeleton, 'boneTextureHeight' ); + if ( material.side !== DoubleSide ) + state.enable( _gl.CULL_FACE ); + else + state.disable( _gl.CULL_FACE ); - } else { + state.setFlipSided( material.side === BackSide ); - p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' ); + if ( material.transparent === true ) { - } + state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha ); - } + } else { - } + state.setBlending( NoBlending ); - if ( refreshMaterial ) { + } - if ( material.lights ) { + state.setDepthFunc( material.depthFunc ); + state.setDepthTest( material.depthTest ); + state.setDepthWrite( material.depthWrite ); + state.setColorWrite( material.colorWrite ); + state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits ); - // the current material requires lighting info + } - // note: all lighting uniforms are always set correctly - // they simply reference the renderer's state for their - // values - // - // use the current material's .needsUpdate flags to set - // the GL state when required + function setProgram( camera, fog, material, object ) { - markUniformsLightsNeedsUpdate( m_uniforms, refreshLights ); + _usedTextureUnits = 0; - } + var materialProperties = properties.get( material ); - // refresh uniforms common to several materials + if ( _clippingEnabled ) { - if ( fog && material.fog ) { + if ( _localClippingEnabled || camera !== _currentCamera ) { - refreshUniformsFog( m_uniforms, fog ); + var useCache = + camera === _currentCamera && + material.id === _currentMaterialId; - } + // we might want to call this function with some ClippingGroup + // object instead of the material, once it becomes feasible + // (#8465, #8379) + _clipping.setState( + material.clippingPlanes, material.clipShadows, + camera, materialProperties, useCache ); - if ( ( material && material.isMeshBasicMaterial ) || - ( material && material.isMeshLambertMaterial ) || - ( material && material.isMeshPhongMaterial ) || - ( material && material.isMeshStandardMaterial ) || - ( material && material.isMeshDepthMaterial ) ) { + } - refreshUniformsCommon( m_uniforms, material ); + if ( materialProperties.numClippingPlanes !== undefined && + materialProperties.numClippingPlanes !== _clipping.numPlanes ) { - } + material.needsUpdate = true; - // refresh single material specific uniforms + } - if ( material && material.isLineBasicMaterial ) { + } - refreshUniformsLine( m_uniforms, material ); + if ( material.needsUpdate === false ) { - } else if ( material && material.isLineDashedMaterial ) { + if ( materialProperties.program === undefined ) { - refreshUniformsLine( m_uniforms, material ); - refreshUniformsDash( m_uniforms, material ); + material.needsUpdate = true; - } else if ( material && material.isPointsMaterial ) { + } else if ( material.fog && materialProperties.fog !== fog ) { - refreshUniformsPoints( m_uniforms, material ); + material.needsUpdate = true; - } else if ( material && material.isMeshLambertMaterial ) { + } else if ( material.lights && materialProperties.lightsHash !== _lights.hash ) { - refreshUniformsLambert( m_uniforms, material ); + material.needsUpdate = true; - } else if ( material && material.isMeshPhongMaterial ) { + } - refreshUniformsPhong( m_uniforms, material ); + } - } else if ( material && material.isMeshPhysicalMaterial ) { + if ( material.needsUpdate ) { - refreshUniformsPhysical( m_uniforms, material ); + initMaterial( material, fog, object ); + material.needsUpdate = false; - } else if ( material && material.isMeshStandardMaterial ) { + } - refreshUniformsStandard( m_uniforms, material ); + var refreshProgram = false; + var refreshMaterial = false; + var refreshLights = false; - } else if ( material && material.isMeshDepthMaterial ) { + var program = materialProperties.program, + p_uniforms = program.getUniforms(), + m_uniforms = materialProperties.__webglShader.uniforms; - if ( material.displacementMap ) { + if ( program.id !== _currentProgram ) { - m_uniforms.displacementMap.value = material.displacementMap; - m_uniforms.displacementScale.value = material.displacementScale; - m_uniforms.displacementBias.value = material.displacementBias; + _gl.useProgram( program.program ); + _currentProgram = program.id; - } + refreshProgram = true; + refreshMaterial = true; + refreshLights = true; - } else if ( material && material.isMeshNormalMaterial ) { + } - m_uniforms.opacity.value = material.opacity; + if ( material.id !== _currentMaterialId ) { - } + _currentMaterialId = material.id; - exports.WebGLUniforms.upload( - _gl, materialProperties.uniformsList, m_uniforms, _this ); + refreshMaterial = true; - } + } + if ( refreshProgram || camera !== _currentCamera ) { - // common matrices + p_uniforms.set( _gl, camera, 'projectionMatrix' ); - p_uniforms.set( _gl, object, 'modelViewMatrix' ); - p_uniforms.set( _gl, object, 'normalMatrix' ); - p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld ); + if ( capabilities.logarithmicDepthBuffer ) { + p_uniforms.setValue( _gl, 'logDepthBufFC', + 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) ); - // dynamic uniforms + } - var dynUniforms = materialProperties.dynamicUniforms; - if ( dynUniforms !== null ) { + if ( camera !== _currentCamera ) { - exports.WebGLUniforms.evalDynamic( - dynUniforms, m_uniforms, object, camera ); + _currentCamera = camera; - exports.WebGLUniforms.upload( _gl, dynUniforms, m_uniforms, _this ); + // lighting uniforms depend on the camera so enforce an update + // now, in case this material supports lights - or later, when + // the next material that does gets activated: - } + refreshMaterial = true; // set to true on material change + refreshLights = true; // remains set until update done - return program; + } - } + // load material specific uniforms + // (shader material also gets them for the sake of genericity) - // Uniforms (refresh uniforms objects) + if ( ( material && material.isShaderMaterial ) || + ( material && material.isMeshPhongMaterial ) || + ( material && material.isMeshStandardMaterial ) || + material.envMap ) { - function refreshUniformsCommon( uniforms, material ) { + var uCamPos = p_uniforms.map.cameraPosition; - uniforms.opacity.value = material.opacity; + if ( uCamPos !== undefined ) { - uniforms.diffuse.value = material.color; + uCamPos.setValue( _gl, + _vector3.setFromMatrixPosition( camera.matrixWorld ) ); - if ( material.emissive ) { + } - uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity ); + } - } + if ( ( material && material.isMeshPhongMaterial ) || + ( material && material.isMeshLambertMaterial ) || + ( material && material.isMeshBasicMaterial ) || + ( material && material.isMeshStandardMaterial ) || + ( material && material.isShaderMaterial ) || + material.skinning ) { - uniforms.map.value = material.map; - uniforms.specularMap.value = material.specularMap; - uniforms.alphaMap.value = material.alphaMap; + p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse ); - if ( material.aoMap ) { + } - uniforms.aoMap.value = material.aoMap; - uniforms.aoMapIntensity.value = material.aoMapIntensity; + p_uniforms.set( _gl, _this, 'toneMappingExposure' ); + p_uniforms.set( _gl, _this, 'toneMappingWhitePoint' ); - } + } - // uv repeat and offset setting priorities - // 1. color map - // 2. specular map - // 3. normal map - // 4. bump map - // 5. alpha map - // 6. emissive map + // skinning uniforms must be set even if material didn't change + // auto-setting of texture unit for bone texture must go before other textures + // not sure why, but otherwise weird things happen - var uvScaleMap; + if ( material.skinning ) { - if ( material.map ) { + p_uniforms.setOptional( _gl, object, 'bindMatrix' ); + p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' ); - uvScaleMap = material.map; + var skeleton = object.skeleton; - } else if ( material.specularMap ) { + if ( skeleton ) { - uvScaleMap = material.specularMap; + if ( capabilities.floatVertexTextures && skeleton.useVertexTexture ) { - } else if ( material.displacementMap ) { + p_uniforms.set( _gl, skeleton, 'boneTexture' ); + p_uniforms.set( _gl, skeleton, 'boneTextureWidth' ); + p_uniforms.set( _gl, skeleton, 'boneTextureHeight' ); - uvScaleMap = material.displacementMap; + } else { - } else if ( material.normalMap ) { + p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' ); - uvScaleMap = material.normalMap; + } - } else if ( material.bumpMap ) { + } - uvScaleMap = material.bumpMap; + } - } else if ( material.roughnessMap ) { + if ( refreshMaterial ) { - uvScaleMap = material.roughnessMap; + if ( material.lights ) { - } else if ( material.metalnessMap ) { + // the current material requires lighting info - uvScaleMap = material.metalnessMap; + // note: all lighting uniforms are always set correctly + // they simply reference the renderer's state for their + // values + // + // use the current material's .needsUpdate flags to set + // the GL state when required - } else if ( material.alphaMap ) { + markUniformsLightsNeedsUpdate( m_uniforms, refreshLights ); - uvScaleMap = material.alphaMap; + } - } else if ( material.emissiveMap ) { + // refresh uniforms common to several materials - uvScaleMap = material.emissiveMap; + if ( fog && material.fog ) { - } + refreshUniformsFog( m_uniforms, fog ); - if ( uvScaleMap !== undefined ) { + } - // backwards compatibility - if ( (uvScaleMap && uvScaleMap.isWebGLRenderTarget) ) { + if ( ( material && material.isMeshBasicMaterial ) || + ( material && material.isMeshLambertMaterial ) || + ( material && material.isMeshPhongMaterial ) || + ( material && material.isMeshStandardMaterial ) || + ( material && material.isMeshDepthMaterial ) ) { - uvScaleMap = uvScaleMap.texture; + refreshUniformsCommon( m_uniforms, material ); - } + } - var offset = uvScaleMap.offset; - var repeat = uvScaleMap.repeat; + // refresh single material specific uniforms - uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y ); + if ( material && material.isLineBasicMaterial ) { - } + refreshUniformsLine( m_uniforms, material ); - uniforms.envMap.value = material.envMap; + } else if ( material && material.isLineDashedMaterial ) { - // don't flip CubeTexture envMaps, flip everything else: - // WebGLRenderTargetCube will be flipped for backwards compatibility - // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture - // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future - uniforms.flipEnvMap.value = ( ! ( material.envMap && material.envMap.isCubeTexture ) ) ? 1 : - 1; + refreshUniformsLine( m_uniforms, material ); + refreshUniformsDash( m_uniforms, material ); - uniforms.reflectivity.value = material.reflectivity; - uniforms.refractionRatio.value = material.refractionRatio; + } else if ( material && material.isPointsMaterial ) { - } + refreshUniformsPoints( m_uniforms, material ); - function refreshUniformsLine( uniforms, material ) { + } else if ( material && material.isMeshLambertMaterial ) { - uniforms.diffuse.value = material.color; - uniforms.opacity.value = material.opacity; + refreshUniformsLambert( m_uniforms, material ); - } + } else if ( material && material.isMeshPhongMaterial ) { - function refreshUniformsDash( uniforms, material ) { + refreshUniformsPhong( m_uniforms, material ); - uniforms.dashSize.value = material.dashSize; - uniforms.totalSize.value = material.dashSize + material.gapSize; - uniforms.scale.value = material.scale; + } else if ( material && material.isMeshPhysicalMaterial ) { - } + refreshUniformsPhysical( m_uniforms, material ); - function refreshUniformsPoints( uniforms, material ) { + } else if ( material && material.isMeshStandardMaterial ) { - uniforms.diffuse.value = material.color; - uniforms.opacity.value = material.opacity; - uniforms.size.value = material.size * _pixelRatio; - uniforms.scale.value = _canvas.clientHeight * 0.5; + refreshUniformsStandard( m_uniforms, material ); - uniforms.map.value = material.map; + } else if ( material && material.isMeshDepthMaterial ) { - if ( material.map !== null ) { + if ( material.displacementMap ) { - var offset = material.map.offset; - var repeat = material.map.repeat; + m_uniforms.displacementMap.value = material.displacementMap; + m_uniforms.displacementScale.value = material.displacementScale; + m_uniforms.displacementBias.value = material.displacementBias; - uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y ); + } - } + } else if ( material && material.isMeshNormalMaterial ) { - } + m_uniforms.opacity.value = material.opacity; - function refreshUniformsFog( uniforms, fog ) { + } - uniforms.fogColor.value = fog.color; + exports.WebGLUniforms.upload( + _gl, materialProperties.uniformsList, m_uniforms, _this ); - if ( fog && fog.isFog ) { + } - uniforms.fogNear.value = fog.near; - uniforms.fogFar.value = fog.far; - } else if ( fog && fog.isFogExp2 ) { + // common matrices - uniforms.fogDensity.value = fog.density; + p_uniforms.set( _gl, object, 'modelViewMatrix' ); + p_uniforms.set( _gl, object, 'normalMatrix' ); + p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld ); - } - } + // dynamic uniforms - function refreshUniformsLambert( uniforms, material ) { + var dynUniforms = materialProperties.dynamicUniforms; - if ( material.lightMap ) { + if ( dynUniforms !== null ) { - uniforms.lightMap.value = material.lightMap; - uniforms.lightMapIntensity.value = material.lightMapIntensity; + exports.WebGLUniforms.evalDynamic( + dynUniforms, m_uniforms, object, camera ); - } + exports.WebGLUniforms.upload( _gl, dynUniforms, m_uniforms, _this ); - if ( material.emissiveMap ) { + } - uniforms.emissiveMap.value = material.emissiveMap; + return program; - } + } - } + // Uniforms (refresh uniforms objects) - function refreshUniformsPhong( uniforms, material ) { + function refreshUniformsCommon( uniforms, material ) { - uniforms.specular.value = material.specular; - uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 ) + uniforms.opacity.value = material.opacity; - if ( material.lightMap ) { + uniforms.diffuse.value = material.color; - uniforms.lightMap.value = material.lightMap; - uniforms.lightMapIntensity.value = material.lightMapIntensity; + if ( material.emissive ) { - } + uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity ); - if ( material.emissiveMap ) { + } - uniforms.emissiveMap.value = material.emissiveMap; + uniforms.map.value = material.map; + uniforms.specularMap.value = material.specularMap; + uniforms.alphaMap.value = material.alphaMap; - } + if ( material.aoMap ) { - if ( material.bumpMap ) { + uniforms.aoMap.value = material.aoMap; + uniforms.aoMapIntensity.value = material.aoMapIntensity; - uniforms.bumpMap.value = material.bumpMap; - uniforms.bumpScale.value = material.bumpScale; + } - } + // uv repeat and offset setting priorities + // 1. color map + // 2. specular map + // 3. normal map + // 4. bump map + // 5. alpha map + // 6. emissive map - if ( material.normalMap ) { + var uvScaleMap; - uniforms.normalMap.value = material.normalMap; - uniforms.normalScale.value.copy( material.normalScale ); + if ( material.map ) { - } + uvScaleMap = material.map; - if ( material.displacementMap ) { + } else if ( material.specularMap ) { - uniforms.displacementMap.value = material.displacementMap; - uniforms.displacementScale.value = material.displacementScale; - uniforms.displacementBias.value = material.displacementBias; + uvScaleMap = material.specularMap; - } + } else if ( material.displacementMap ) { - } + uvScaleMap = material.displacementMap; - function refreshUniformsStandard( uniforms, material ) { + } else if ( material.normalMap ) { - uniforms.roughness.value = material.roughness; - uniforms.metalness.value = material.metalness; + uvScaleMap = material.normalMap; - if ( material.roughnessMap ) { + } else if ( material.bumpMap ) { - uniforms.roughnessMap.value = material.roughnessMap; + uvScaleMap = material.bumpMap; - } + } else if ( material.roughnessMap ) { - if ( material.metalnessMap ) { + uvScaleMap = material.roughnessMap; - uniforms.metalnessMap.value = material.metalnessMap; + } else if ( material.metalnessMap ) { - } + uvScaleMap = material.metalnessMap; - if ( material.lightMap ) { + } else if ( material.alphaMap ) { - uniforms.lightMap.value = material.lightMap; - uniforms.lightMapIntensity.value = material.lightMapIntensity; + uvScaleMap = material.alphaMap; - } + } else if ( material.emissiveMap ) { - if ( material.emissiveMap ) { + uvScaleMap = material.emissiveMap; - uniforms.emissiveMap.value = material.emissiveMap; + } - } + if ( uvScaleMap !== undefined ) { - if ( material.bumpMap ) { + // backwards compatibility + if ( (uvScaleMap && uvScaleMap.isWebGLRenderTarget) ) { - uniforms.bumpMap.value = material.bumpMap; - uniforms.bumpScale.value = material.bumpScale; + uvScaleMap = uvScaleMap.texture; - } + } - if ( material.normalMap ) { + var offset = uvScaleMap.offset; + var repeat = uvScaleMap.repeat; - uniforms.normalMap.value = material.normalMap; - uniforms.normalScale.value.copy( material.normalScale ); + uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y ); - } + } - if ( material.displacementMap ) { + uniforms.envMap.value = material.envMap; - uniforms.displacementMap.value = material.displacementMap; - uniforms.displacementScale.value = material.displacementScale; - uniforms.displacementBias.value = material.displacementBias; + // don't flip CubeTexture envMaps, flip everything else: + // WebGLRenderTargetCube will be flipped for backwards compatibility + // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture + // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future + uniforms.flipEnvMap.value = ( ! ( material.envMap && material.envMap.isCubeTexture ) ) ? 1 : - 1; - } + uniforms.reflectivity.value = material.reflectivity; + uniforms.refractionRatio.value = material.refractionRatio; - if ( material.envMap ) { + } - //uniforms.envMap.value = material.envMap; // part of uniforms common - uniforms.envMapIntensity.value = material.envMapIntensity; + function refreshUniformsLine( uniforms, material ) { - } + uniforms.diffuse.value = material.color; + uniforms.opacity.value = material.opacity; - } + } - function refreshUniformsPhysical( uniforms, material ) { + function refreshUniformsDash( uniforms, material ) { - uniforms.clearCoat.value = material.clearCoat; - uniforms.clearCoatRoughness.value = material.clearCoatRoughness; + uniforms.dashSize.value = material.dashSize; + uniforms.totalSize.value = material.dashSize + material.gapSize; + uniforms.scale.value = material.scale; - refreshUniformsStandard( uniforms, material ); + } - } + function refreshUniformsPoints( uniforms, material ) { - // If uniforms are marked as clean, they don't need to be loaded to the GPU. + uniforms.diffuse.value = material.color; + uniforms.opacity.value = material.opacity; + uniforms.size.value = material.size * _pixelRatio; + uniforms.scale.value = _canvas.clientHeight * 0.5; - function markUniformsLightsNeedsUpdate( uniforms, value ) { + uniforms.map.value = material.map; - uniforms.ambientLightColor.needsUpdate = value; + if ( material.map !== null ) { - uniforms.directionalLights.needsUpdate = value; - uniforms.pointLights.needsUpdate = value; - uniforms.spotLights.needsUpdate = value; - uniforms.hemisphereLights.needsUpdate = value; + var offset = material.map.offset; + var repeat = material.map.repeat; - } + uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y ); - // Lighting + } - function setupShadows( lights ) { + } - var lightShadowsLength = 0; + function refreshUniformsFog( uniforms, fog ) { - for ( var i = 0, l = lights.length; i < l; i ++ ) { + uniforms.fogColor.value = fog.color; - var light = lights[ i ]; + if ( fog && fog.isFog ) { - if ( light.castShadow ) { + uniforms.fogNear.value = fog.near; + uniforms.fogFar.value = fog.far; - _lights.shadows[ lightShadowsLength ++ ] = light; + } else if ( fog && fog.isFogExp2 ) { - } + uniforms.fogDensity.value = fog.density; - } + } - _lights.shadows.length = lightShadowsLength; + } - } + function refreshUniformsLambert( uniforms, material ) { - function setupLights( lights, camera ) { + if ( material.lightMap ) { - var l, ll, light, - r = 0, g = 0, b = 0, - color, - intensity, - distance, - shadowMap, + uniforms.lightMap.value = material.lightMap; + uniforms.lightMapIntensity.value = material.lightMapIntensity; - viewMatrix = camera.matrixWorldInverse, + } - directionalLength = 0, - pointLength = 0, - spotLength = 0, - hemiLength = 0; + if ( material.emissiveMap ) { - for ( l = 0, ll = lights.length; l < ll; l ++ ) { + uniforms.emissiveMap.value = material.emissiveMap; - light = lights[ l ]; + } - color = light.color; - intensity = light.intensity; - distance = light.distance; + } - shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null; + function refreshUniformsPhong( uniforms, material ) { - if ( light && light.isAmbientLight ) { + uniforms.specular.value = material.specular; + uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 ) - r += color.r * intensity; - g += color.g * intensity; - b += color.b * intensity; + if ( material.lightMap ) { - } else if ( light && light.isDirectionalLight ) { + uniforms.lightMap.value = material.lightMap; + uniforms.lightMapIntensity.value = material.lightMapIntensity; - var uniforms = lightCache.get( light ); + } - uniforms.color.copy( light.color ).multiplyScalar( light.intensity ); - uniforms.direction.setFromMatrixPosition( light.matrixWorld ); - _vector3.setFromMatrixPosition( light.target.matrixWorld ); - uniforms.direction.sub( _vector3 ); - uniforms.direction.transformDirection( viewMatrix ); + if ( material.emissiveMap ) { - uniforms.shadow = light.castShadow; + uniforms.emissiveMap.value = material.emissiveMap; - if ( light.castShadow ) { + } - uniforms.shadowBias = light.shadow.bias; - uniforms.shadowRadius = light.shadow.radius; - uniforms.shadowMapSize = light.shadow.mapSize; + if ( material.bumpMap ) { - } + uniforms.bumpMap.value = material.bumpMap; + uniforms.bumpScale.value = material.bumpScale; - _lights.directionalShadowMap[ directionalLength ] = shadowMap; - _lights.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix; - _lights.directional[ directionalLength ++ ] = uniforms; + } - } else if ( light && light.isSpotLight ) { + if ( material.normalMap ) { - var uniforms = lightCache.get( light ); + uniforms.normalMap.value = material.normalMap; + uniforms.normalScale.value.copy( material.normalScale ); - uniforms.position.setFromMatrixPosition( light.matrixWorld ); - uniforms.position.applyMatrix4( viewMatrix ); + } - uniforms.color.copy( color ).multiplyScalar( intensity ); - uniforms.distance = distance; + if ( material.displacementMap ) { - uniforms.direction.setFromMatrixPosition( light.matrixWorld ); - _vector3.setFromMatrixPosition( light.target.matrixWorld ); - uniforms.direction.sub( _vector3 ); - uniforms.direction.transformDirection( viewMatrix ); + uniforms.displacementMap.value = material.displacementMap; + uniforms.displacementScale.value = material.displacementScale; + uniforms.displacementBias.value = material.displacementBias; - uniforms.coneCos = Math.cos( light.angle ); - uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) ); - uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay; + } - uniforms.shadow = light.castShadow; + } - if ( light.castShadow ) { + function refreshUniformsStandard( uniforms, material ) { - uniforms.shadowBias = light.shadow.bias; - uniforms.shadowRadius = light.shadow.radius; - uniforms.shadowMapSize = light.shadow.mapSize; + uniforms.roughness.value = material.roughness; + uniforms.metalness.value = material.metalness; - } + if ( material.roughnessMap ) { - _lights.spotShadowMap[ spotLength ] = shadowMap; - _lights.spotShadowMatrix[ spotLength ] = light.shadow.matrix; - _lights.spot[ spotLength ++ ] = uniforms; + uniforms.roughnessMap.value = material.roughnessMap; - } else if ( light && light.isPointLight ) { + } - var uniforms = lightCache.get( light ); + if ( material.metalnessMap ) { - uniforms.position.setFromMatrixPosition( light.matrixWorld ); - uniforms.position.applyMatrix4( viewMatrix ); + uniforms.metalnessMap.value = material.metalnessMap; - uniforms.color.copy( light.color ).multiplyScalar( light.intensity ); - uniforms.distance = light.distance; - uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay; + } - uniforms.shadow = light.castShadow; + if ( material.lightMap ) { - if ( light.castShadow ) { + uniforms.lightMap.value = material.lightMap; + uniforms.lightMapIntensity.value = material.lightMapIntensity; - uniforms.shadowBias = light.shadow.bias; - uniforms.shadowRadius = light.shadow.radius; - uniforms.shadowMapSize = light.shadow.mapSize; + } - } + if ( material.emissiveMap ) { - _lights.pointShadowMap[ pointLength ] = shadowMap; + uniforms.emissiveMap.value = material.emissiveMap; - if ( _lights.pointShadowMatrix[ pointLength ] === undefined ) { + } - _lights.pointShadowMatrix[ pointLength ] = new Matrix4(); + if ( material.bumpMap ) { - } + uniforms.bumpMap.value = material.bumpMap; + uniforms.bumpScale.value = material.bumpScale; - // for point lights we set the shadow matrix to be a translation-only matrix - // equal to inverse of the light's position - _vector3.setFromMatrixPosition( light.matrixWorld ).negate(); - _lights.pointShadowMatrix[ pointLength ].identity().setPosition( _vector3 ); + } - _lights.point[ pointLength ++ ] = uniforms; + if ( material.normalMap ) { - } else if ( light && light.isHemisphereLight ) { + uniforms.normalMap.value = material.normalMap; + uniforms.normalScale.value.copy( material.normalScale ); - var uniforms = lightCache.get( light ); + } - uniforms.direction.setFromMatrixPosition( light.matrixWorld ); - uniforms.direction.transformDirection( viewMatrix ); - uniforms.direction.normalize(); + if ( material.displacementMap ) { - uniforms.skyColor.copy( light.color ).multiplyScalar( intensity ); - uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity ); + uniforms.displacementMap.value = material.displacementMap; + uniforms.displacementScale.value = material.displacementScale; + uniforms.displacementBias.value = material.displacementBias; - _lights.hemi[ hemiLength ++ ] = uniforms; + } - } + if ( material.envMap ) { - } + //uniforms.envMap.value = material.envMap; // part of uniforms common + uniforms.envMapIntensity.value = material.envMapIntensity; - _lights.ambient[ 0 ] = r; - _lights.ambient[ 1 ] = g; - _lights.ambient[ 2 ] = b; + } - _lights.directional.length = directionalLength; - _lights.spot.length = spotLength; - _lights.point.length = pointLength; - _lights.hemi.length = hemiLength; + } - _lights.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + hemiLength + ',' + _lights.shadows.length; + function refreshUniformsPhysical( uniforms, material ) { - } + uniforms.clearCoat.value = material.clearCoat; + uniforms.clearCoatRoughness.value = material.clearCoatRoughness; - // GL state setting + refreshUniformsStandard( uniforms, material ); - this.setFaceCulling = function ( cullFace, frontFaceDirection ) { + } - state.setCullFace( cullFace ); - state.setFlipSided( frontFaceDirection === FrontFaceDirectionCW ); + // If uniforms are marked as clean, they don't need to be loaded to the GPU. - }; + function markUniformsLightsNeedsUpdate( uniforms, value ) { - // Textures + uniforms.ambientLightColor.needsUpdate = value; - function allocTextureUnit() { + uniforms.directionalLights.needsUpdate = value; + uniforms.pointLights.needsUpdate = value; + uniforms.spotLights.needsUpdate = value; + uniforms.hemisphereLights.needsUpdate = value; - var textureUnit = _usedTextureUnits; + } - if ( textureUnit >= capabilities.maxTextures ) { + // Lighting - console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures ); + function setupShadows( lights ) { - } + var lightShadowsLength = 0; - _usedTextureUnits += 1; + for ( var i = 0, l = lights.length; i < l; i ++ ) { - return textureUnit; + var light = lights[ i ]; - } + if ( light.castShadow ) { - this.allocTextureUnit = allocTextureUnit; + _lights.shadows[ lightShadowsLength ++ ] = light; - // this.setTexture2D = setTexture2D; - this.setTexture2D = ( function() { + } - var warned = false; + } - // backwards compatibility: peel texture.texture - return function setTexture2D( texture, slot ) { + _lights.shadows.length = lightShadowsLength; - if ( texture && texture.isWebGLRenderTarget ) { + } - if ( ! warned ) { + function setupLights( lights, camera ) { - console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." ); - warned = true; + var l, ll, light, + r = 0, g = 0, b = 0, + color, + intensity, + distance, + shadowMap, - } + viewMatrix = camera.matrixWorldInverse, - texture = texture.texture; + directionalLength = 0, + pointLength = 0, + spotLength = 0, + hemiLength = 0; - } + for ( l = 0, ll = lights.length; l < ll; l ++ ) { - textures.setTexture2D( texture, slot ); + light = lights[ l ]; - }; + color = light.color; + intensity = light.intensity; + distance = light.distance; - }() ); + shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null; - this.setTexture = ( function() { + if ( light && light.isAmbientLight ) { - var warned = false; + r += color.r * intensity; + g += color.g * intensity; + b += color.b * intensity; - return function setTexture( texture, slot ) { + } else if ( light && light.isDirectionalLight ) { - if ( ! warned ) { + var uniforms = lightCache.get( light ); - console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead." ); - warned = true; + uniforms.color.copy( light.color ).multiplyScalar( light.intensity ); + uniforms.direction.setFromMatrixPosition( light.matrixWorld ); + _vector3.setFromMatrixPosition( light.target.matrixWorld ); + uniforms.direction.sub( _vector3 ); + uniforms.direction.transformDirection( viewMatrix ); - } + uniforms.shadow = light.castShadow; - textures.setTexture2D( texture, slot ); + if ( light.castShadow ) { - }; + uniforms.shadowBias = light.shadow.bias; + uniforms.shadowRadius = light.shadow.radius; + uniforms.shadowMapSize = light.shadow.mapSize; - }() ); + } - this.setTextureCube = ( function() { + _lights.directionalShadowMap[ directionalLength ] = shadowMap; + _lights.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix; + _lights.directional[ directionalLength ++ ] = uniforms; - var warned = false; + } else if ( light && light.isSpotLight ) { - return function setTextureCube( texture, slot ) { + var uniforms = lightCache.get( light ); - // backwards compatibility: peel texture.texture - if ( texture && texture.isWebGLRenderTargetCube ) { + uniforms.position.setFromMatrixPosition( light.matrixWorld ); + uniforms.position.applyMatrix4( viewMatrix ); - if ( ! warned ) { + uniforms.color.copy( color ).multiplyScalar( intensity ); + uniforms.distance = distance; - console.warn( "THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead." ); - warned = true; + uniforms.direction.setFromMatrixPosition( light.matrixWorld ); + _vector3.setFromMatrixPosition( light.target.matrixWorld ); + uniforms.direction.sub( _vector3 ); + uniforms.direction.transformDirection( viewMatrix ); - } + uniforms.coneCos = Math.cos( light.angle ); + uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) ); + uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay; - texture = texture.texture; + uniforms.shadow = light.castShadow; - } + if ( light.castShadow ) { - // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture - // TODO: unify these code paths - if ( ( texture && texture.isCubeTexture ) || - ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) { + uniforms.shadowBias = light.shadow.bias; + uniforms.shadowRadius = light.shadow.radius; + uniforms.shadowMapSize = light.shadow.mapSize; - // CompressedTexture can have Array in image :/ + } - // this function alone should take care of cube textures - textures.setTextureCube( texture, slot ); + _lights.spotShadowMap[ spotLength ] = shadowMap; + _lights.spotShadowMatrix[ spotLength ] = light.shadow.matrix; + _lights.spot[ spotLength ++ ] = uniforms; - } else { + } else if ( light && light.isPointLight ) { - // assumed: texture property of THREE.WebGLRenderTargetCube + var uniforms = lightCache.get( light ); - textures.setTextureCubeDynamic( texture, slot ); + uniforms.position.setFromMatrixPosition( light.matrixWorld ); + uniforms.position.applyMatrix4( viewMatrix ); - } + uniforms.color.copy( light.color ).multiplyScalar( light.intensity ); + uniforms.distance = light.distance; + uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay; - }; + uniforms.shadow = light.castShadow; - }() ); + if ( light.castShadow ) { - this.getCurrentRenderTarget = function() { + uniforms.shadowBias = light.shadow.bias; + uniforms.shadowRadius = light.shadow.radius; + uniforms.shadowMapSize = light.shadow.mapSize; - return _currentRenderTarget; + } - }; + _lights.pointShadowMap[ pointLength ] = shadowMap; - this.setRenderTarget = function ( renderTarget ) { + if ( _lights.pointShadowMatrix[ pointLength ] === undefined ) { - _currentRenderTarget = renderTarget; + _lights.pointShadowMatrix[ pointLength ] = new Matrix4(); - if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) { + } - textures.setupRenderTarget( renderTarget ); + // for point lights we set the shadow matrix to be a translation-only matrix + // equal to inverse of the light's position + _vector3.setFromMatrixPosition( light.matrixWorld ).negate(); + _lights.pointShadowMatrix[ pointLength ].identity().setPosition( _vector3 ); - } + _lights.point[ pointLength ++ ] = uniforms; - var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube ); - var framebuffer; + } else if ( light && light.isHemisphereLight ) { - if ( renderTarget ) { + var uniforms = lightCache.get( light ); - var renderTargetProperties = properties.get( renderTarget ); + uniforms.direction.setFromMatrixPosition( light.matrixWorld ); + uniforms.direction.transformDirection( viewMatrix ); + uniforms.direction.normalize(); - if ( isCube ) { + uniforms.skyColor.copy( light.color ).multiplyScalar( intensity ); + uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity ); - framebuffer = renderTargetProperties.__webglFramebuffer[ renderTarget.activeCubeFace ]; + _lights.hemi[ hemiLength ++ ] = uniforms; - } else { + } - framebuffer = renderTargetProperties.__webglFramebuffer; + } - } + _lights.ambient[ 0 ] = r; + _lights.ambient[ 1 ] = g; + _lights.ambient[ 2 ] = b; - _currentScissor.copy( renderTarget.scissor ); - _currentScissorTest = renderTarget.scissorTest; + _lights.directional.length = directionalLength; + _lights.spot.length = spotLength; + _lights.point.length = pointLength; + _lights.hemi.length = hemiLength; - _currentViewport.copy( renderTarget.viewport ); + _lights.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + hemiLength + ',' + _lights.shadows.length; - } else { + } - framebuffer = null; + // GL state setting - _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ); - _currentScissorTest = _scissorTest; + this.setFaceCulling = function ( cullFace, frontFaceDirection ) { - _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ); + state.setCullFace( cullFace ); + state.setFlipSided( frontFaceDirection === FrontFaceDirectionCW ); - } + }; - if ( _currentFramebuffer !== framebuffer ) { + // Textures - _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); - _currentFramebuffer = framebuffer; + function allocTextureUnit() { - } + var textureUnit = _usedTextureUnits; - state.scissor( _currentScissor ); - state.setScissorTest( _currentScissorTest ); + if ( textureUnit >= capabilities.maxTextures ) { - state.viewport( _currentViewport ); + console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures ); - if ( isCube ) { + } - var textureProperties = properties.get( renderTarget.texture ); - _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel ); + _usedTextureUnits += 1; - } + return textureUnit; - }; + } - this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) { + this.allocTextureUnit = allocTextureUnit; - if ( ( renderTarget && renderTarget.isWebGLRenderTarget ) === false ) { + // this.setTexture2D = setTexture2D; + this.setTexture2D = ( function() { - console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' ); - return; + var warned = false; - } + // backwards compatibility: peel texture.texture + return function setTexture2D( texture, slot ) { - var framebuffer = properties.get( renderTarget ).__webglFramebuffer; + if ( texture && texture.isWebGLRenderTarget ) { - if ( framebuffer ) { + if ( ! warned ) { - var restore = false; + console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." ); + warned = true; - if ( framebuffer !== _currentFramebuffer ) { + } - _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + texture = texture.texture; - restore = true; + } - } + textures.setTexture2D( texture, slot ); - try { + }; - var texture = renderTarget.texture; + }() ); - if ( texture.format !== RGBAFormat && paramThreeToGL( texture.format ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) { + this.setTexture = ( function() { - console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' ); - return; + var warned = false; - } + return function setTexture( texture, slot ) { - if ( texture.type !== UnsignedByteType && - paramThreeToGL( texture.type ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && - ! ( texture.type === FloatType && extensions.get( 'WEBGL_color_buffer_float' ) ) && - ! ( texture.type === HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) { + if ( ! warned ) { - console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' ); - return; + console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead." ); + warned = true; - } + } - if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) { + textures.setTexture2D( texture, slot ); - // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604) + }; - if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) { + }() ); - _gl.readPixels( x, y, width, height, paramThreeToGL( texture.format ), paramThreeToGL( texture.type ), buffer ); + this.setTextureCube = ( function() { - } + var warned = false; - } else { + return function setTextureCube( texture, slot ) { - console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' ); + // backwards compatibility: peel texture.texture + if ( texture && texture.isWebGLRenderTargetCube ) { - } + if ( ! warned ) { - } finally { + console.warn( "THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead." ); + warned = true; - if ( restore ) { + } - _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer ); + texture = texture.texture; - } + } - } + // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture + // TODO: unify these code paths + if ( ( texture && texture.isCubeTexture ) || + ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) { - } + // CompressedTexture can have Array in image :/ - }; + // this function alone should take care of cube textures + textures.setTextureCube( texture, slot ); - // Map three.js constants to WebGL constants + } else { - function paramThreeToGL( p ) { + // assumed: texture property of THREE.WebGLRenderTargetCube - var extension; + textures.setTextureCubeDynamic( texture, slot ); - if ( p === RepeatWrapping ) return _gl.REPEAT; - if ( p === ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE; - if ( p === MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT; + } - if ( p === NearestFilter ) return _gl.NEAREST; - if ( p === NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST; - if ( p === NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR; + }; - if ( p === LinearFilter ) return _gl.LINEAR; - if ( p === LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST; - if ( p === LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR; + }() ); - if ( p === UnsignedByteType ) return _gl.UNSIGNED_BYTE; - if ( p === UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4; - if ( p === UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1; - if ( p === UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5; + this.getCurrentRenderTarget = function() { - if ( p === ByteType ) return _gl.BYTE; - if ( p === ShortType ) return _gl.SHORT; - if ( p === UnsignedShortType ) return _gl.UNSIGNED_SHORT; - if ( p === IntType ) return _gl.INT; - if ( p === UnsignedIntType ) return _gl.UNSIGNED_INT; - if ( p === FloatType ) return _gl.FLOAT; + return _currentRenderTarget; - extension = extensions.get( 'OES_texture_half_float' ); + }; - if ( extension !== null ) { + this.setRenderTarget = function ( renderTarget ) { - if ( p === HalfFloatType ) return extension.HALF_FLOAT_OES; + _currentRenderTarget = renderTarget; - } + if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) { - if ( p === AlphaFormat ) return _gl.ALPHA; - if ( p === RGBFormat ) return _gl.RGB; - if ( p === RGBAFormat ) return _gl.RGBA; - if ( p === LuminanceFormat ) return _gl.LUMINANCE; - if ( p === LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA; - if ( p === DepthFormat ) return _gl.DEPTH_COMPONENT; - if ( p === DepthStencilFormat ) return _gl.DEPTH_STENCIL; + textures.setupRenderTarget( renderTarget ); - if ( p === AddEquation ) return _gl.FUNC_ADD; - if ( p === SubtractEquation ) return _gl.FUNC_SUBTRACT; - if ( p === ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT; + } - if ( p === ZeroFactor ) return _gl.ZERO; - if ( p === OneFactor ) return _gl.ONE; - if ( p === SrcColorFactor ) return _gl.SRC_COLOR; - if ( p === OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR; - if ( p === SrcAlphaFactor ) return _gl.SRC_ALPHA; - if ( p === OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA; - if ( p === DstAlphaFactor ) return _gl.DST_ALPHA; - if ( p === OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA; + var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube ); + var framebuffer; - if ( p === DstColorFactor ) return _gl.DST_COLOR; - if ( p === OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR; - if ( p === SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE; + if ( renderTarget ) { - extension = extensions.get( 'WEBGL_compressed_texture_s3tc' ); + var renderTargetProperties = properties.get( renderTarget ); - if ( extension !== null ) { + if ( isCube ) { - if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT; - if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT; - if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT; - if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT; + framebuffer = renderTargetProperties.__webglFramebuffer[ renderTarget.activeCubeFace ]; - } + } else { - extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' ); + framebuffer = renderTargetProperties.__webglFramebuffer; - if ( extension !== null ) { + } - if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; - if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; - if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; - if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; + _currentScissor.copy( renderTarget.scissor ); + _currentScissorTest = renderTarget.scissorTest; - } + _currentViewport.copy( renderTarget.viewport ); - extension = extensions.get( 'WEBGL_compressed_texture_etc1' ); + } else { - if ( extension !== null ) { + framebuffer = null; - if ( p === RGB_ETC1_Format ) return extension.COMPRESSED_RGB_ETC1_WEBGL; + _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ); + _currentScissorTest = _scissorTest; - } + _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ); - extension = extensions.get( 'EXT_blend_minmax' ); + } - if ( extension !== null ) { + if ( _currentFramebuffer !== framebuffer ) { - if ( p === MinEquation ) return extension.MIN_EXT; - if ( p === MaxEquation ) return extension.MAX_EXT; + _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + _currentFramebuffer = framebuffer; - } + } - extension = extensions.get( 'WEBGL_depth_texture' ); + state.scissor( _currentScissor ); + state.setScissorTest( _currentScissorTest ); - if ( extension !== null ){ + state.viewport( _currentViewport ); - if ( p === THREE.UnsignedInt248Type ) return extension.UNSIGNED_INT_24_8_WEBGL; + if ( isCube ) { - } + var textureProperties = properties.get( renderTarget.texture ); + _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel ); - return 0; + } - } + }; - }; + this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) { - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + if ( ( renderTarget && renderTarget.isWebGLRenderTarget ) === false ) { - function FogExp2 ( color, density ) { + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' ); + return; - this.name = ''; + } - this.color = new Color( color ); - this.density = ( density !== undefined ) ? density : 0.00025; + var framebuffer = properties.get( renderTarget ).__webglFramebuffer; - } + if ( framebuffer ) { - FogExp2.prototype.isFogExp2 = true; + var restore = false; - FogExp2.prototype.clone = function () { + if ( framebuffer !== _currentFramebuffer ) { - return new FogExp2( this.color.getHex(), this.density ); + _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); - }; + restore = true; - FogExp2.prototype.toJSON = function ( meta ) { + } - return { - type: 'FogExp2', - color: this.color.getHex(), - density: this.density - }; + try { - }; + var texture = renderTarget.texture; - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + if ( texture.format !== RGBAFormat && paramThreeToGL( texture.format ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) { - function Fog ( color, near, far ) { + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' ); + return; - this.name = ''; + } - this.color = new Color( color ); + if ( texture.type !== UnsignedByteType && + paramThreeToGL( texture.type ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && + ! ( texture.type === FloatType && extensions.get( 'WEBGL_color_buffer_float' ) ) && + ! ( texture.type === HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) { - this.near = ( near !== undefined ) ? near : 1; - this.far = ( far !== undefined ) ? far : 1000; + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' ); + return; - } + } - Fog.prototype.isFog = true; + if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) { - Fog.prototype.clone = function () { + // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604) - return new Fog( this.color.getHex(), this.near, this.far ); + if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) { - }; + _gl.readPixels( x, y, width, height, paramThreeToGL( texture.format ), paramThreeToGL( texture.type ), buffer ); - Fog.prototype.toJSON = function ( meta ) { + } - return { - type: 'Fog', - color: this.color.getHex(), - near: this.near, - far: this.far - }; + } else { - }; + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' ); - /** - * @author mrdoob / http://mrdoob.com/ - */ + } - function Scene () { - - Object3D.call( this ); + } finally { - this.type = 'Scene'; + if ( restore ) { - this.background = null; - this.fog = null; - this.overrideMaterial = null; + _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer ); - this.autoUpdate = true; // checked by the renderer + } - } + } - Scene.prototype = Object.create( Object3D.prototype ); + } - Scene.prototype.constructor = Scene; + }; - Scene.prototype.copy = function ( source, recursive ) { + // Map three.js constants to WebGL constants - Object3D.prototype.copy.call( this, source, recursive ); + function paramThreeToGL( p ) { - if ( source.background !== null ) this.background = source.background.clone(); - if ( source.fog !== null ) this.fog = source.fog.clone(); - if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone(); + var extension; - this.autoUpdate = source.autoUpdate; - this.matrixAutoUpdate = source.matrixAutoUpdate; + if ( p === RepeatWrapping ) return _gl.REPEAT; + if ( p === ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE; + if ( p === MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT; - return this; + if ( p === NearestFilter ) return _gl.NEAREST; + if ( p === NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST; + if ( p === NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR; - }; + if ( p === LinearFilter ) return _gl.LINEAR; + if ( p === LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST; + if ( p === LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR; - Scene.prototype.toJSON = function ( meta ) { + if ( p === UnsignedByteType ) return _gl.UNSIGNED_BYTE; + if ( p === UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4; + if ( p === UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1; + if ( p === UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5; - var data = Object3D.prototype.toJSON.call( this, meta ); - - if ( this.fog != null ) { - - data.object.fog = this.fog.toJSON(); + if ( p === ByteType ) return _gl.BYTE; + if ( p === ShortType ) return _gl.SHORT; + if ( p === UnsignedShortType ) return _gl.UNSIGNED_SHORT; + if ( p === IntType ) return _gl.INT; + if ( p === UnsignedIntType ) return _gl.UNSIGNED_INT; + if ( p === FloatType ) return _gl.FLOAT; - } + extension = extensions.get( 'OES_texture_half_float' ); - return data; + if ( extension !== null ) { - }; + if ( p === HalfFloatType ) return extension.HALF_FLOAT_OES; - /** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - */ + } - function LensFlare( texture, size, distance, blending, color ) { + if ( p === AlphaFormat ) return _gl.ALPHA; + if ( p === RGBFormat ) return _gl.RGB; + if ( p === RGBAFormat ) return _gl.RGBA; + if ( p === LuminanceFormat ) return _gl.LUMINANCE; + if ( p === LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA; + if ( p === DepthFormat ) return _gl.DEPTH_COMPONENT; + if ( p === DepthStencilFormat ) return _gl.DEPTH_STENCIL; - Object3D.call( this ); + if ( p === AddEquation ) return _gl.FUNC_ADD; + if ( p === SubtractEquation ) return _gl.FUNC_SUBTRACT; + if ( p === ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT; - this.lensFlares = []; + if ( p === ZeroFactor ) return _gl.ZERO; + if ( p === OneFactor ) return _gl.ONE; + if ( p === SrcColorFactor ) return _gl.SRC_COLOR; + if ( p === OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR; + if ( p === SrcAlphaFactor ) return _gl.SRC_ALPHA; + if ( p === OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA; + if ( p === DstAlphaFactor ) return _gl.DST_ALPHA; + if ( p === OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA; - this.positionScreen = new Vector3(); - this.customUpdateCallback = undefined; + if ( p === DstColorFactor ) return _gl.DST_COLOR; + if ( p === OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR; + if ( p === SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE; - if ( texture !== undefined ) { + extension = extensions.get( 'WEBGL_compressed_texture_s3tc' ); - this.add( texture, size, distance, blending, color ); + if ( extension !== null ) { - } + if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT; + if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT; + if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT; + if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT; - }; + } - LensFlare.prototype = Object.assign( Object.create( Object3D.prototype ), { + extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' ); - constructor: LensFlare, + if ( extension !== null ) { - isLensFlare: true, + if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; + if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; + if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; + if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; - copy: function ( source ) { + } - Object3D.prototype.copy.call( this, source ); + extension = extensions.get( 'WEBGL_compressed_texture_etc1' ); - this.positionScreen.copy( source.positionScreen ); - this.customUpdateCallback = source.customUpdateCallback; + if ( extension !== null ) { - for ( var i = 0, l = source.lensFlares.length; i < l; i ++ ) { + if ( p === RGB_ETC1_Format ) return extension.COMPRESSED_RGB_ETC1_WEBGL; - this.lensFlares.push( source.lensFlares[ i ] ); + } - } + extension = extensions.get( 'EXT_blend_minmax' ); - return this; + if ( extension !== null ) { - }, + if ( p === MinEquation ) return extension.MIN_EXT; + if ( p === MaxEquation ) return extension.MAX_EXT; - add: function ( texture, size, distance, blending, color, opacity ) { + } - if ( size === undefined ) size = - 1; - if ( distance === undefined ) distance = 0; - if ( opacity === undefined ) opacity = 1; - if ( color === undefined ) color = new Color( 0xffffff ); - if ( blending === undefined ) blending = NormalBlending; + extension = extensions.get( 'WEBGL_depth_texture' ); - distance = Math.min( distance, Math.max( 0, distance ) ); + if ( extension !== null ){ - this.lensFlares.push( { - texture: texture, // THREE.Texture - size: size, // size in pixels (-1 = use texture.width) - distance: distance, // distance (0-1) from light source (0=at light source) - x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is in front z = 1 is back - scale: 1, // scale - rotation: 0, // rotation - opacity: opacity, // opacity - color: color, // color - blending: blending // blending - } ); + if ( p === THREE.UnsignedInt248Type ) return extension.UNSIGNED_INT_24_8_WEBGL; - }, + } - /* - * Update lens flares update positions on all flares based on the screen position - * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way. - */ + return 0; - updateLensFlares: function () { + } - var f, fl = this.lensFlares.length; - var flare; - var vecX = - this.positionScreen.x * 2; - var vecY = - this.positionScreen.y * 2; + } - for ( f = 0; f < fl; f ++ ) { + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - flare = this.lensFlares[ f ]; + function FogExp2 ( color, density ) { - flare.x = this.positionScreen.x + vecX * flare.distance; - flare.y = this.positionScreen.y + vecY * flare.distance; + this.name = ''; - flare.wantedRotation = flare.x * Math.PI * 0.25; - flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25; + this.color = new Color( color ); + this.density = ( density !== undefined ) ? density : 0.00025; - } + } - } + FogExp2.prototype.isFogExp2 = true; - } ); + FogExp2.prototype.clone = function () { - /** - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * opacity: , - * map: new THREE.Texture( ), - * - * uvOffset: new THREE.Vector2(), - * uvScale: new THREE.Vector2() - * } - */ + return new FogExp2( this.color.getHex(), this.density ); - function SpriteMaterial( parameters ) { + }; - Material.call( this ); + FogExp2.prototype.toJSON = function ( meta ) { - this.type = 'SpriteMaterial'; + return { + type: 'FogExp2', + color: this.color.getHex(), + density: this.density + }; - this.color = new Color( 0xffffff ); - this.map = null; + }; - this.rotation = 0; + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - this.fog = false; - this.lights = false; + function Fog ( color, near, far ) { - this.setValues( parameters ); + this.name = ''; - }; + this.color = new Color( color ); - SpriteMaterial.prototype = Object.create( Material.prototype ); - SpriteMaterial.prototype.constructor = SpriteMaterial; + this.near = ( near !== undefined ) ? near : 1; + this.far = ( far !== undefined ) ? far : 1000; - SpriteMaterial.prototype.copy = function ( source ) { + } - Material.prototype.copy.call( this, source ); + Fog.prototype.isFog = true; - this.color.copy( source.color ); - this.map = source.map; + Fog.prototype.clone = function () { - this.rotation = source.rotation; + return new Fog( this.color.getHex(), this.near, this.far ); - return this; + }; - }; + Fog.prototype.toJSON = function ( meta ) { - /** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - */ + return { + type: 'Fog', + color: this.color.getHex(), + near: this.near, + far: this.far + }; - function Sprite( material ) { + }; - Object3D.call( this ); + /** + * @author mrdoob / http://mrdoob.com/ + */ - this.type = 'Sprite'; + function Scene () { - this.material = ( material !== undefined ) ? material : new SpriteMaterial(); + Object3D.call( this ); - }; + this.type = 'Scene'; - Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), { + this.background = null; + this.fog = null; + this.overrideMaterial = null; - constructor: Sprite, + this.autoUpdate = true; // checked by the renderer - isSprite: true, + } - raycast: ( function () { + Scene.prototype = Object.create( Object3D.prototype ); - var matrixPosition = new Vector3(); + Scene.prototype.constructor = Scene; - return function raycast( raycaster, intersects ) { + Scene.prototype.copy = function ( source, recursive ) { - matrixPosition.setFromMatrixPosition( this.matrixWorld ); + Object3D.prototype.copy.call( this, source, recursive ); - var distanceSq = raycaster.ray.distanceSqToPoint( matrixPosition ); - var guessSizeSq = this.scale.x * this.scale.y / 4; + if ( source.background !== null ) this.background = source.background.clone(); + if ( source.fog !== null ) this.fog = source.fog.clone(); + if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone(); - if ( distanceSq > guessSizeSq ) { + this.autoUpdate = source.autoUpdate; + this.matrixAutoUpdate = source.matrixAutoUpdate; - return; + return this; - } + }; - intersects.push( { + Scene.prototype.toJSON = function ( meta ) { - distance: Math.sqrt( distanceSq ), - point: this.position, - face: null, - object: this + var data = Object3D.prototype.toJSON.call( this, meta ); - } ); + if ( this.background !== null ) data.object.background = this.background.toJSON( meta ); + if ( this.fog !== null ) data.object.fog = this.fog.toJSON(); - }; + return data; - }() ), + }; - clone: function () { + /** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + */ - return new this.constructor( this.material ).copy( this ); + function LensFlare( texture, size, distance, blending, color ) { - } + Object3D.call( this ); - } ); + this.lensFlares = []; - /** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - */ + this.positionScreen = new Vector3(); + this.customUpdateCallback = undefined; - function LOD() { + if ( texture !== undefined ) { - Object3D.call( this ); + this.add( texture, size, distance, blending, color ); - this.type = 'LOD'; + } - Object.defineProperties( this, { - levels: { - enumerable: true, - value: [] - } - } ); + } - }; + LensFlare.prototype = Object.assign( Object.create( Object3D.prototype ), { + constructor: LensFlare, - LOD.prototype = Object.assign( Object.create( Object3D.prototype ), { + isLensFlare: true, - constructor: LOD, + copy: function ( source ) { - copy: function ( source ) { + Object3D.prototype.copy.call( this, source ); - Object3D.prototype.copy.call( this, source, false ); + this.positionScreen.copy( source.positionScreen ); + this.customUpdateCallback = source.customUpdateCallback; - var levels = source.levels; + for ( var i = 0, l = source.lensFlares.length; i < l; i ++ ) { - for ( var i = 0, l = levels.length; i < l; i ++ ) { + this.lensFlares.push( source.lensFlares[ i ] ); - var level = levels[ i ]; + } - this.addLevel( level.object.clone(), level.distance ); + return this; - } + }, - return this; + add: function ( texture, size, distance, blending, color, opacity ) { - }, + if ( size === undefined ) size = - 1; + if ( distance === undefined ) distance = 0; + if ( opacity === undefined ) opacity = 1; + if ( color === undefined ) color = new Color( 0xffffff ); + if ( blending === undefined ) blending = NormalBlending; - addLevel: function ( object, distance ) { + distance = Math.min( distance, Math.max( 0, distance ) ); - if ( distance === undefined ) distance = 0; + this.lensFlares.push( { + texture: texture, // THREE.Texture + size: size, // size in pixels (-1 = use texture.width) + distance: distance, // distance (0-1) from light source (0=at light source) + x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is in front z = 1 is back + scale: 1, // scale + rotation: 0, // rotation + opacity: opacity, // opacity + color: color, // color + blending: blending // blending + } ); - distance = Math.abs( distance ); + }, - var levels = this.levels; + /* + * Update lens flares update positions on all flares based on the screen position + * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way. + */ - for ( var l = 0; l < levels.length; l ++ ) { + updateLensFlares: function () { - if ( distance < levels[ l ].distance ) { + var f, fl = this.lensFlares.length; + var flare; + var vecX = - this.positionScreen.x * 2; + var vecY = - this.positionScreen.y * 2; - break; + for ( f = 0; f < fl; f ++ ) { - } + flare = this.lensFlares[ f ]; - } + flare.x = this.positionScreen.x + vecX * flare.distance; + flare.y = this.positionScreen.y + vecY * flare.distance; - levels.splice( l, 0, { distance: distance, object: object } ); + flare.wantedRotation = flare.x * Math.PI * 0.25; + flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25; - this.add( object ); + } - }, + } - getObjectForDistance: function ( distance ) { + } ); - var levels = this.levels; + /** + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * color: , + * opacity: , + * map: new THREE.Texture( ), + * + * uvOffset: new THREE.Vector2(), + * uvScale: new THREE.Vector2() + * } + */ - for ( var i = 1, l = levels.length; i < l; i ++ ) { + function SpriteMaterial( parameters ) { - if ( distance < levels[ i ].distance ) { + Material.call( this ); - break; + this.type = 'SpriteMaterial'; - } + this.color = new Color( 0xffffff ); + this.map = null; - } + this.rotation = 0; - return levels[ i - 1 ].object; + this.fog = false; + this.lights = false; - }, + this.setValues( parameters ); - raycast: ( function () { + } - var matrixPosition = new Vector3(); + SpriteMaterial.prototype = Object.create( Material.prototype ); + SpriteMaterial.prototype.constructor = SpriteMaterial; - return function raycast( raycaster, intersects ) { + SpriteMaterial.prototype.copy = function ( source ) { - matrixPosition.setFromMatrixPosition( this.matrixWorld ); + Material.prototype.copy.call( this, source ); - var distance = raycaster.ray.origin.distanceTo( matrixPosition ); + this.color.copy( source.color ); + this.map = source.map; - this.getObjectForDistance( distance ).raycast( raycaster, intersects ); + this.rotation = source.rotation; - }; + return this; - }() ), + }; - update: function () { + /** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + */ - var v1 = new Vector3(); - var v2 = new Vector3(); + function Sprite( material ) { - return function update( camera ) { + Object3D.call( this ); - var levels = this.levels; + this.type = 'Sprite'; - if ( levels.length > 1 ) { + this.material = ( material !== undefined ) ? material : new SpriteMaterial(); - v1.setFromMatrixPosition( camera.matrixWorld ); - v2.setFromMatrixPosition( this.matrixWorld ); + } - var distance = v1.distanceTo( v2 ); + Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), { - levels[ 0 ].object.visible = true; + constructor: Sprite, - for ( var i = 1, l = levels.length; i < l; i ++ ) { + isSprite: true, - if ( distance >= levels[ i ].distance ) { + raycast: ( function () { - levels[ i - 1 ].object.visible = false; - levels[ i ].object.visible = true; + var matrixPosition = new Vector3(); - } else { + return function raycast( raycaster, intersects ) { - break; + matrixPosition.setFromMatrixPosition( this.matrixWorld ); - } + var distanceSq = raycaster.ray.distanceSqToPoint( matrixPosition ); + var guessSizeSq = this.scale.x * this.scale.y / 4; - } + if ( distanceSq > guessSizeSq ) { - for ( ; i < l; i ++ ) { + return; - levels[ i ].object.visible = false; + } - } + intersects.push( { - } + distance: Math.sqrt( distanceSq ), + point: this.position, + face: null, + object: this - }; + } ); - }(), + }; - toJSON: function ( meta ) { + }() ), - var data = Object3D.prototype.toJSON.call( this, meta ); + clone: function () { - data.object.levels = []; + return new this.constructor( this.material ).copy( this ); - var levels = this.levels; + } - for ( var i = 0, l = levels.length; i < l; i ++ ) { + } ); - var level = levels[ i ]; + /** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + */ - data.object.levels.push( { - object: level.object.uuid, - distance: level.distance - } ); + function LOD() { - } + Object3D.call( this ); - return data; + this.type = 'LOD'; - } + Object.defineProperties( this, { + levels: { + enumerable: true, + value: [] + } + } ); - } ); + } - /** - * @author alteredq / http://alteredqualia.com/ - */ - function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) { + LOD.prototype = Object.assign( Object.create( Object3D.prototype ), { - Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); + constructor: LOD, - this.image = { data: data, width: width, height: height }; + copy: function ( source ) { - this.magFilter = magFilter !== undefined ? magFilter : NearestFilter; - this.minFilter = minFilter !== undefined ? minFilter : NearestFilter; + Object3D.prototype.copy.call( this, source, false ); - this.flipY = false; - this.generateMipmaps = false; + var levels = source.levels; - }; + for ( var i = 0, l = levels.length; i < l; i ++ ) { - DataTexture.prototype = Object.create( Texture.prototype ); - DataTexture.prototype.constructor = DataTexture; + var level = levels[ i ]; - DataTexture.prototype.isDataTexture = true; + this.addLevel( level.object.clone(), level.distance ); - /** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author michael guerrero / http://realitymeltdown.com - * @author ikerr / http://verold.com - */ + } - function Skeleton( bones, boneInverses, useVertexTexture ) { + return this; - this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true; + }, - this.identityMatrix = new Matrix4(); + addLevel: function ( object, distance ) { - // copy the bone array + if ( distance === undefined ) distance = 0; - bones = bones || []; + distance = Math.abs( distance ); - this.bones = bones.slice( 0 ); + var levels = this.levels; - // create a bone texture or an array of floats + for ( var l = 0; l < levels.length; l ++ ) { - if ( this.useVertexTexture ) { + if ( distance < levels[ l ].distance ) { - // layout (1 matrix = 4 pixels) - // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4) - // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8) - // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16) - // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32) - // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64) + break; + } - var size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix - size = exports.Math.nextPowerOfTwo( Math.ceil( size ) ); - size = Math.max( size, 4 ); + } - this.boneTextureWidth = size; - this.boneTextureHeight = size; + levels.splice( l, 0, { distance: distance, object: object } ); - this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel - this.boneTexture = new DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, RGBAFormat, FloatType ); + this.add( object ); - } else { + }, - this.boneMatrices = new Float32Array( 16 * this.bones.length ); + getObjectForDistance: function ( distance ) { - } + var levels = this.levels; - // use the supplied bone inverses or calculate the inverses + for ( var i = 1, l = levels.length; i < l; i ++ ) { - if ( boneInverses === undefined ) { + if ( distance < levels[ i ].distance ) { - this.calculateInverses(); + break; - } else { + } - if ( this.bones.length === boneInverses.length ) { + } - this.boneInverses = boneInverses.slice( 0 ); + return levels[ i - 1 ].object; - } else { + }, - console.warn( 'THREE.Skeleton bonInverses is the wrong length.' ); + raycast: ( function () { - this.boneInverses = []; + var matrixPosition = new Vector3(); - for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { + return function raycast( raycaster, intersects ) { - this.boneInverses.push( new Matrix4() ); + matrixPosition.setFromMatrixPosition( this.matrixWorld ); - } + var distance = raycaster.ray.origin.distanceTo( matrixPosition ); - } + this.getObjectForDistance( distance ).raycast( raycaster, intersects ); - } + }; - }; + }() ), - Object.assign( Skeleton.prototype, { + update: function () { - calculateInverses: function () { + var v1 = new Vector3(); + var v2 = new Vector3(); - this.boneInverses = []; + return function update( camera ) { - for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { + var levels = this.levels; - var inverse = new Matrix4(); + if ( levels.length > 1 ) { - if ( this.bones[ b ] ) { + v1.setFromMatrixPosition( camera.matrixWorld ); + v2.setFromMatrixPosition( this.matrixWorld ); - inverse.getInverse( this.bones[ b ].matrixWorld ); + var distance = v1.distanceTo( v2 ); - } + levels[ 0 ].object.visible = true; - this.boneInverses.push( inverse ); + for ( var i = 1, l = levels.length; i < l; i ++ ) { - } + if ( distance >= levels[ i ].distance ) { - }, + levels[ i - 1 ].object.visible = false; + levels[ i ].object.visible = true; - pose: function () { + } else { - var bone; + break; - // recover the bind-time world matrices + } - for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { + } - bone = this.bones[ b ]; + for ( ; i < l; i ++ ) { - if ( bone ) { + levels[ i ].object.visible = false; - bone.matrixWorld.getInverse( this.boneInverses[ b ] ); + } - } + } - } + }; - // compute the local matrices, positions, rotations and scales + }(), - for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { + toJSON: function ( meta ) { - bone = this.bones[ b ]; + var data = Object3D.prototype.toJSON.call( this, meta ); - if ( bone ) { + data.object.levels = []; - if ( (bone.parent && bone.parent.isBone) ) { + var levels = this.levels; - bone.matrix.getInverse( bone.parent.matrixWorld ); - bone.matrix.multiply( bone.matrixWorld ); + for ( var i = 0, l = levels.length; i < l; i ++ ) { - } else { + var level = levels[ i ]; - bone.matrix.copy( bone.matrixWorld ); + data.object.levels.push( { + object: level.object.uuid, + distance: level.distance + } ); - } + } - bone.matrix.decompose( bone.position, bone.quaternion, bone.scale ); + return data; - } + } - } + } ); - }, + /** + * @author alteredq / http://alteredqualia.com/ + */ - update: ( function () { + function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) { - var offsetMatrix = new Matrix4(); + Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); - return function update() { + this.image = { data: data, width: width, height: height }; - // flatten bone matrices to array + this.magFilter = magFilter !== undefined ? magFilter : NearestFilter; + this.minFilter = minFilter !== undefined ? minFilter : NearestFilter; - for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { + this.flipY = false; + this.generateMipmaps = false; - // compute the offset between the current and the original transform + } - var matrix = this.bones[ b ] ? this.bones[ b ].matrixWorld : this.identityMatrix; + DataTexture.prototype = Object.create( Texture.prototype ); + DataTexture.prototype.constructor = DataTexture; - offsetMatrix.multiplyMatrices( matrix, this.boneInverses[ b ] ); - offsetMatrix.toArray( this.boneMatrices, b * 16 ); + DataTexture.prototype.isDataTexture = true; - } + /** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + * @author michael guerrero / http://realitymeltdown.com + * @author ikerr / http://verold.com + */ - if ( this.useVertexTexture ) { + function Skeleton( bones, boneInverses, useVertexTexture ) { - this.boneTexture.needsUpdate = true; + this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true; - } + this.identityMatrix = new Matrix4(); - }; + // copy the bone array - } )(), + bones = bones || []; - clone: function () { + this.bones = bones.slice( 0 ); - return new Skeleton( this.bones, this.boneInverses, this.useVertexTexture ); + // create a bone texture or an array of floats - } + if ( this.useVertexTexture ) { - } ); + // layout (1 matrix = 4 pixels) + // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4) + // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8) + // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16) + // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32) + // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64) - /** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author ikerr / http://verold.com - */ - function Bone( skin ) { + var size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix + size = exports.Math.nextPowerOfTwo( Math.ceil( size ) ); + size = Math.max( size, 4 ); - Object3D.call( this ); + this.boneTextureWidth = size; + this.boneTextureHeight = size; - this.type = 'Bone'; + this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel + this.boneTexture = new DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, RGBAFormat, FloatType ); - this.skin = skin; + } else { - }; + this.boneMatrices = new Float32Array( 16 * this.bones.length ); - Bone.prototype = Object.assign( Object.create( Object3D.prototype ), { + } - constructor: Bone, + // use the supplied bone inverses or calculate the inverses - isBone: true, + if ( boneInverses === undefined ) { - copy: function ( source ) { + this.calculateInverses(); - Object3D.prototype.copy.call( this, source ); + } else { - this.skin = source.skin; + if ( this.bones.length === boneInverses.length ) { - return this; + this.boneInverses = boneInverses.slice( 0 ); - } + } else { - } ); + console.warn( 'THREE.Skeleton bonInverses is the wrong length.' ); - /** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author ikerr / http://verold.com - */ + this.boneInverses = []; - function SkinnedMesh( geometry, material, useVertexTexture ) { + for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { - Mesh.call( this, geometry, material ); + this.boneInverses.push( new Matrix4() ); - this.type = 'SkinnedMesh'; + } - this.bindMode = "attached"; - this.bindMatrix = new Matrix4(); - this.bindMatrixInverse = new Matrix4(); + } - // init bones + } - // TODO: remove bone creation as there is no reason (other than - // convenience) for THREE.SkinnedMesh to do this. + } - var bones = []; + Object.assign( Skeleton.prototype, { - if ( this.geometry && this.geometry.bones !== undefined ) { + calculateInverses: function () { - var bone, gbone; + this.boneInverses = []; - for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) { + for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { - gbone = this.geometry.bones[ b ]; + var inverse = new Matrix4(); - bone = new Bone( this ); - bones.push( bone ); + if ( this.bones[ b ] ) { - bone.name = gbone.name; - bone.position.fromArray( gbone.pos ); - bone.quaternion.fromArray( gbone.rotq ); - if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl ); + inverse.getInverse( this.bones[ b ].matrixWorld ); - } + } - for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) { + this.boneInverses.push( inverse ); - gbone = this.geometry.bones[ b ]; + } - if ( gbone.parent !== - 1 && gbone.parent !== null && - bones[ gbone.parent ] !== undefined ) { + }, - bones[ gbone.parent ].add( bones[ b ] ); + pose: function () { - } else { + var bone; - this.add( bones[ b ] ); + // recover the bind-time world matrices - } + for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { - } + bone = this.bones[ b ]; - } + if ( bone ) { - this.normalizeSkinWeights(); + bone.matrixWorld.getInverse( this.boneInverses[ b ] ); - this.updateMatrixWorld( true ); - this.bind( new Skeleton( bones, undefined, useVertexTexture ), this.matrixWorld ); + } - }; + } + // compute the local matrices, positions, rotations and scales - SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), { + for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { - constructor: SkinnedMesh, + bone = this.bones[ b ]; - isSkinnedMesh: true, + if ( bone ) { - bind: function( skeleton, bindMatrix ) { + if ( (bone.parent && bone.parent.isBone) ) { - this.skeleton = skeleton; + bone.matrix.getInverse( bone.parent.matrixWorld ); + bone.matrix.multiply( bone.matrixWorld ); - if ( bindMatrix === undefined ) { + } else { - this.updateMatrixWorld( true ); + bone.matrix.copy( bone.matrixWorld ); - this.skeleton.calculateInverses(); + } - bindMatrix = this.matrixWorld; + bone.matrix.decompose( bone.position, bone.quaternion, bone.scale ); - } + } - this.bindMatrix.copy( bindMatrix ); - this.bindMatrixInverse.getInverse( bindMatrix ); + } - }, + }, - pose: function () { + update: ( function () { - this.skeleton.pose(); + var offsetMatrix = new Matrix4(); - }, + return function update() { - normalizeSkinWeights: function () { + // flatten bone matrices to array - if ( (this.geometry && this.geometry.isGeometry) ) { + for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { - for ( var i = 0; i < this.geometry.skinWeights.length; i ++ ) { + // compute the offset between the current and the original transform - var sw = this.geometry.skinWeights[ i ]; + var matrix = this.bones[ b ] ? this.bones[ b ].matrixWorld : this.identityMatrix; - var scale = 1.0 / sw.lengthManhattan(); + offsetMatrix.multiplyMatrices( matrix, this.boneInverses[ b ] ); + offsetMatrix.toArray( this.boneMatrices, b * 16 ); - if ( scale !== Infinity ) { + } - sw.multiplyScalar( scale ); + if ( this.useVertexTexture ) { - } else { + this.boneTexture.needsUpdate = true; - sw.set( 1, 0, 0, 0 ); // do something reasonable + } - } + }; - } + } )(), - } else if ( (this.geometry && this.geometry.isBufferGeometry) ) { + clone: function () { - var vec = new Vector4(); + return new Skeleton( this.bones, this.boneInverses, this.useVertexTexture ); - var skinWeight = this.geometry.attributes.skinWeight; + } - for ( var i = 0; i < skinWeight.count; i ++ ) { + } ); - vec.x = skinWeight.getX( i ); - vec.y = skinWeight.getY( i ); - vec.z = skinWeight.getZ( i ); - vec.w = skinWeight.getW( i ); + /** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + * @author ikerr / http://verold.com + */ - var scale = 1.0 / vec.lengthManhattan(); + function Bone( skin ) { - if ( scale !== Infinity ) { + Object3D.call( this ); - vec.multiplyScalar( scale ); + this.type = 'Bone'; - } else { + this.skin = skin; - vec.set( 1, 0, 0, 0 ); // do something reasonable + } - } + Bone.prototype = Object.assign( Object.create( Object3D.prototype ), { - skinWeight.setXYZW( i, vec.x, vec.y, vec.z, vec.w ); + constructor: Bone, - } + isBone: true, - } + copy: function ( source ) { - }, + Object3D.prototype.copy.call( this, source ); - updateMatrixWorld: function( force ) { + this.skin = source.skin; - Mesh.prototype.updateMatrixWorld.call( this, true ); + return this; - if ( this.bindMode === "attached" ) { + } - this.bindMatrixInverse.getInverse( this.matrixWorld ); + } ); - } else if ( this.bindMode === "detached" ) { + /** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + * @author ikerr / http://verold.com + */ - this.bindMatrixInverse.getInverse( this.bindMatrix ); + function SkinnedMesh( geometry, material, useVertexTexture ) { - } else { + Mesh.call( this, geometry, material ); - console.warn( 'THREE.SkinnedMesh unrecognized bindMode: ' + this.bindMode ); + this.type = 'SkinnedMesh'; - } + this.bindMode = "attached"; + this.bindMatrix = new Matrix4(); + this.bindMatrixInverse = new Matrix4(); - }, + // init bones - clone: function() { + // TODO: remove bone creation as there is no reason (other than + // convenience) for THREE.SkinnedMesh to do this. - return new this.constructor( this.geometry, this.material, this.skeleton.useVertexTexture ).copy( this ); + var bones = []; - } + if ( this.geometry && this.geometry.bones !== undefined ) { - } ); + var bone, gbone; - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * opacity: , - * - * linewidth: , - * linecap: "round", - * linejoin: "round" - * } - */ + for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) { - function LineBasicMaterial( parameters ) { + gbone = this.geometry.bones[ b ]; - Material.call( this ); + bone = new Bone( this ); + bones.push( bone ); - this.type = 'LineBasicMaterial'; + bone.name = gbone.name; + bone.position.fromArray( gbone.pos ); + bone.quaternion.fromArray( gbone.rotq ); + if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl ); - this.color = new Color( 0xffffff ); + } - this.linewidth = 1; - this.linecap = 'round'; - this.linejoin = 'round'; + for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) { - this.lights = false; + gbone = this.geometry.bones[ b ]; - this.setValues( parameters ); + if ( gbone.parent !== - 1 && gbone.parent !== null && + bones[ gbone.parent ] !== undefined ) { - }; + bones[ gbone.parent ].add( bones[ b ] ); - LineBasicMaterial.prototype = Object.create( Material.prototype ); - LineBasicMaterial.prototype.constructor = LineBasicMaterial; + } else { - LineBasicMaterial.prototype.isLineBasicMaterial = true; + this.add( bones[ b ] ); - LineBasicMaterial.prototype.copy = function ( source ) { + } - Material.prototype.copy.call( this, source ); + } - this.color.copy( source.color ); + } - this.linewidth = source.linewidth; - this.linecap = source.linecap; - this.linejoin = source.linejoin; + this.normalizeSkinWeights(); - return this; + this.updateMatrixWorld( true ); + this.bind( new Skeleton( bones, undefined, useVertexTexture ), this.matrixWorld ); - }; + } - /** - * @author mrdoob / http://mrdoob.com/ - */ - function Line( geometry, material, mode ) { + SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), { - if ( mode === 1 ) { + constructor: SkinnedMesh, - console.warn( 'THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.' ); - return new LineSegments( geometry, material ); + isSkinnedMesh: true, - } + bind: function( skeleton, bindMatrix ) { - Object3D.call( this ); + this.skeleton = skeleton; - this.type = 'Line'; + if ( bindMatrix === undefined ) { - this.geometry = geometry !== undefined ? geometry : new BufferGeometry(); - this.material = material !== undefined ? material : new LineBasicMaterial( { color: Math.random() * 0xffffff } ); + this.updateMatrixWorld( true ); - }; + this.skeleton.calculateInverses(); - Line.prototype = Object.assign( Object.create( Object3D.prototype ), { + bindMatrix = this.matrixWorld; - constructor: Line, + } - isLine: true, + this.bindMatrix.copy( bindMatrix ); + this.bindMatrixInverse.getInverse( bindMatrix ); - raycast: ( function () { + }, - var inverseMatrix = new Matrix4(); - var ray = new Ray(); - var sphere = new Sphere(); + pose: function () { - return function raycast( raycaster, intersects ) { + this.skeleton.pose(); - var precision = raycaster.linePrecision; - var precisionSq = precision * precision; + }, - var geometry = this.geometry; - var matrixWorld = this.matrixWorld; + normalizeSkinWeights: function () { - // Checking boundingSphere distance to ray + if ( (this.geometry && this.geometry.isGeometry) ) { - if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + for ( var i = 0; i < this.geometry.skinWeights.length; i ++ ) { - sphere.copy( geometry.boundingSphere ); - sphere.applyMatrix4( matrixWorld ); + var sw = this.geometry.skinWeights[ i ]; - if ( raycaster.ray.intersectsSphere( sphere ) === false ) return; + var scale = 1.0 / sw.lengthManhattan(); - // + if ( scale !== Infinity ) { - inverseMatrix.getInverse( matrixWorld ); - ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); + sw.multiplyScalar( scale ); - var vStart = new Vector3(); - var vEnd = new Vector3(); - var interSegment = new Vector3(); - var interRay = new Vector3(); - var step = (this && this.isLineSegments) ? 2 : 1; + } else { - if ( (geometry && geometry.isBufferGeometry) ) { + sw.set( 1, 0, 0, 0 ); // do something reasonable - var index = geometry.index; - var attributes = geometry.attributes; - var positions = attributes.position.array; + } - if ( index !== null ) { + } - var indices = index.array; + } else if ( (this.geometry && this.geometry.isBufferGeometry) ) { - for ( var i = 0, l = indices.length - 1; i < l; i += step ) { + var vec = new Vector4(); - var a = indices[ i ]; - var b = indices[ i + 1 ]; + var skinWeight = this.geometry.attributes.skinWeight; - vStart.fromArray( positions, a * 3 ); - vEnd.fromArray( positions, b * 3 ); + for ( var i = 0; i < skinWeight.count; i ++ ) { - var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); + vec.x = skinWeight.getX( i ); + vec.y = skinWeight.getY( i ); + vec.z = skinWeight.getZ( i ); + vec.w = skinWeight.getW( i ); - if ( distSq > precisionSq ) continue; + var scale = 1.0 / vec.lengthManhattan(); - interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation + if ( scale !== Infinity ) { - var distance = raycaster.ray.origin.distanceTo( interRay ); + vec.multiplyScalar( scale ); - if ( distance < raycaster.near || distance > raycaster.far ) continue; + } else { - intersects.push( { + vec.set( 1, 0, 0, 0 ); // do something reasonable - distance: distance, - // What do we want? intersection point on the ray or on the segment?? - // point: raycaster.ray.at( distance ), - point: interSegment.clone().applyMatrix4( this.matrixWorld ), - index: i, - face: null, - faceIndex: null, - object: this + } - } ); + skinWeight.setXYZW( i, vec.x, vec.y, vec.z, vec.w ); - } + } - } else { + } - for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) { + }, - vStart.fromArray( positions, 3 * i ); - vEnd.fromArray( positions, 3 * i + 3 ); + updateMatrixWorld: function( force ) { - var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); + Mesh.prototype.updateMatrixWorld.call( this, true ); - if ( distSq > precisionSq ) continue; + if ( this.bindMode === "attached" ) { - interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation + this.bindMatrixInverse.getInverse( this.matrixWorld ); - var distance = raycaster.ray.origin.distanceTo( interRay ); + } else if ( this.bindMode === "detached" ) { - if ( distance < raycaster.near || distance > raycaster.far ) continue; + this.bindMatrixInverse.getInverse( this.bindMatrix ); - intersects.push( { + } else { - distance: distance, - // What do we want? intersection point on the ray or on the segment?? - // point: raycaster.ray.at( distance ), - point: interSegment.clone().applyMatrix4( this.matrixWorld ), - index: i, - face: null, - faceIndex: null, - object: this + console.warn( 'THREE.SkinnedMesh unrecognized bindMode: ' + this.bindMode ); - } ); + } - } + }, - } + clone: function() { - } else if ( (geometry && geometry.isGeometry) ) { + return new this.constructor( this.geometry, this.material, this.skeleton.useVertexTexture ).copy( this ); - var vertices = geometry.vertices; - var nbVertices = vertices.length; + } - for ( var i = 0; i < nbVertices - 1; i += step ) { + } ); - var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment ); + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * color: , + * opacity: , + * + * linewidth: , + * linecap: "round", + * linejoin: "round" + * } + */ - if ( distSq > precisionSq ) continue; + function LineBasicMaterial( parameters ) { - interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation + Material.call( this ); - var distance = raycaster.ray.origin.distanceTo( interRay ); + this.type = 'LineBasicMaterial'; - if ( distance < raycaster.near || distance > raycaster.far ) continue; + this.color = new Color( 0xffffff ); - intersects.push( { + this.linewidth = 1; + this.linecap = 'round'; + this.linejoin = 'round'; - distance: distance, - // What do we want? intersection point on the ray or on the segment?? - // point: raycaster.ray.at( distance ), - point: interSegment.clone().applyMatrix4( this.matrixWorld ), - index: i, - face: null, - faceIndex: null, - object: this + this.lights = false; - } ); + this.setValues( parameters ); - } + } - } + LineBasicMaterial.prototype = Object.create( Material.prototype ); + LineBasicMaterial.prototype.constructor = LineBasicMaterial; - }; + LineBasicMaterial.prototype.isLineBasicMaterial = true; - }() ), + LineBasicMaterial.prototype.copy = function ( source ) { - clone: function () { + Material.prototype.copy.call( this, source ); - return new this.constructor( this.geometry, this.material ).copy( this ); + this.color.copy( source.color ); - } + this.linewidth = source.linewidth; + this.linecap = source.linecap; + this.linejoin = source.linejoin; - } ); + return this; - /** - * @author mrdoob / http://mrdoob.com/ - */ + }; - function LineSegments( geometry, material ) { + /** + * @author mrdoob / http://mrdoob.com/ + */ - Line.call( this, geometry, material ); + function Line( geometry, material, mode ) { - this.type = 'LineSegments'; + if ( mode === 1 ) { - }; + console.warn( 'THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.' ); + return new LineSegments( geometry, material ); - LineSegments.prototype = Object.assign( Object.create( Line.prototype ), { + } - constructor: LineSegments, + Object3D.call( this ); - isLineSegments: true + this.type = 'Line'; - } ); + this.geometry = geometry !== undefined ? geometry : new BufferGeometry(); + this.material = material !== undefined ? material : new LineBasicMaterial( { color: Math.random() * 0xffffff } ); - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * opacity: , - * map: new THREE.Texture( ), - * - * size: , - * sizeAttenuation: - * } - */ + } - function PointsMaterial( parameters ) { + Line.prototype = Object.assign( Object.create( Object3D.prototype ), { - Material.call( this ); + constructor: Line, - this.type = 'PointsMaterial'; + isLine: true, - this.color = new Color( 0xffffff ); + raycast: ( function () { - this.map = null; + var inverseMatrix = new Matrix4(); + var ray = new Ray(); + var sphere = new Sphere(); - this.size = 1; - this.sizeAttenuation = true; + return function raycast( raycaster, intersects ) { - this.lights = false; + var precision = raycaster.linePrecision; + var precisionSq = precision * precision; - this.setValues( parameters ); + var geometry = this.geometry; + var matrixWorld = this.matrixWorld; - }; + // Checking boundingSphere distance to ray - PointsMaterial.prototype = Object.create( Material.prototype ); - PointsMaterial.prototype.constructor = PointsMaterial; + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); - PointsMaterial.prototype.isPointsMaterial = true; + sphere.copy( geometry.boundingSphere ); + sphere.applyMatrix4( matrixWorld ); - PointsMaterial.prototype.copy = function ( source ) { + if ( raycaster.ray.intersectsSphere( sphere ) === false ) return; - Material.prototype.copy.call( this, source ); + // - this.color.copy( source.color ); + inverseMatrix.getInverse( matrixWorld ); + ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); - this.map = source.map; + var vStart = new Vector3(); + var vEnd = new Vector3(); + var interSegment = new Vector3(); + var interRay = new Vector3(); + var step = (this && this.isLineSegments) ? 2 : 1; - this.size = source.size; - this.sizeAttenuation = source.sizeAttenuation; + if ( (geometry && geometry.isBufferGeometry) ) { - return this; + var index = geometry.index; + var attributes = geometry.attributes; + var positions = attributes.position.array; - }; + if ( index !== null ) { - /** - * @author alteredq / http://alteredqualia.com/ - */ + var indices = index.array; - function Points( geometry, material ) { + for ( var i = 0, l = indices.length - 1; i < l; i += step ) { - Object3D.call( this ); + var a = indices[ i ]; + var b = indices[ i + 1 ]; - this.type = 'Points'; + vStart.fromArray( positions, a * 3 ); + vEnd.fromArray( positions, b * 3 ); - this.geometry = geometry !== undefined ? geometry : new BufferGeometry(); - this.material = material !== undefined ? material : new PointsMaterial( { color: Math.random() * 0xffffff } ); + var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); - }; + if ( distSq > precisionSq ) continue; - Points.prototype = Object.assign( Object.create( Object3D.prototype ), { + interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation - constructor: Points, + var distance = raycaster.ray.origin.distanceTo( interRay ); - isPoints: true, + if ( distance < raycaster.near || distance > raycaster.far ) continue; - raycast: ( function () { + intersects.push( { - var inverseMatrix = new Matrix4(); - var ray = new Ray(); - var sphere = new Sphere(); + distance: distance, + // What do we want? intersection point on the ray or on the segment?? + // point: raycaster.ray.at( distance ), + point: interSegment.clone().applyMatrix4( this.matrixWorld ), + index: i, + face: null, + faceIndex: null, + object: this - return function raycast( raycaster, intersects ) { + } ); - var object = this; - var geometry = this.geometry; - var matrixWorld = this.matrixWorld; - var threshold = raycaster.params.Points.threshold; + } - // Checking boundingSphere distance to ray + } else { - if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) { - sphere.copy( geometry.boundingSphere ); - sphere.applyMatrix4( matrixWorld ); + vStart.fromArray( positions, 3 * i ); + vEnd.fromArray( positions, 3 * i + 3 ); - if ( raycaster.ray.intersectsSphere( sphere ) === false ) return; + var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); - // + if ( distSq > precisionSq ) continue; - inverseMatrix.getInverse( matrixWorld ); - ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); + interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation - var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 ); - var localThresholdSq = localThreshold * localThreshold; - var position = new Vector3(); + var distance = raycaster.ray.origin.distanceTo( interRay ); - function testPoint( point, index ) { + if ( distance < raycaster.near || distance > raycaster.far ) continue; - var rayPointDistanceSq = ray.distanceSqToPoint( point ); + intersects.push( { - if ( rayPointDistanceSq < localThresholdSq ) { + distance: distance, + // What do we want? intersection point on the ray or on the segment?? + // point: raycaster.ray.at( distance ), + point: interSegment.clone().applyMatrix4( this.matrixWorld ), + index: i, + face: null, + faceIndex: null, + object: this - var intersectPoint = ray.closestPointToPoint( point ); - intersectPoint.applyMatrix4( matrixWorld ); + } ); - var distance = raycaster.ray.origin.distanceTo( intersectPoint ); + } - if ( distance < raycaster.near || distance > raycaster.far ) return; + } - intersects.push( { + } else if ( (geometry && geometry.isGeometry) ) { - distance: distance, - distanceToRay: Math.sqrt( rayPointDistanceSq ), - point: intersectPoint.clone(), - index: index, - face: null, - object: object + var vertices = geometry.vertices; + var nbVertices = vertices.length; - } ); + for ( var i = 0; i < nbVertices - 1; i += step ) { - } + var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment ); - } + if ( distSq > precisionSq ) continue; - if ( (geometry && geometry.isBufferGeometry) ) { + interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation - var index = geometry.index; - var attributes = geometry.attributes; - var positions = attributes.position.array; + var distance = raycaster.ray.origin.distanceTo( interRay ); - if ( index !== null ) { + if ( distance < raycaster.near || distance > raycaster.far ) continue; - var indices = index.array; + intersects.push( { - for ( var i = 0, il = indices.length; i < il; i ++ ) { + distance: distance, + // What do we want? intersection point on the ray or on the segment?? + // point: raycaster.ray.at( distance ), + point: interSegment.clone().applyMatrix4( this.matrixWorld ), + index: i, + face: null, + faceIndex: null, + object: this - var a = indices[ i ]; + } ); - position.fromArray( positions, a * 3 ); + } - testPoint( position, a ); + } - } + }; - } else { + }() ), - for ( var i = 0, l = positions.length / 3; i < l; i ++ ) { + clone: function () { - position.fromArray( positions, i * 3 ); + return new this.constructor( this.geometry, this.material ).copy( this ); - testPoint( position, i ); + } - } + } ); - } + /** + * @author mrdoob / http://mrdoob.com/ + */ - } else { + function LineSegments( geometry, material ) { - var vertices = geometry.vertices; + Line.call( this, geometry, material ); - for ( var i = 0, l = vertices.length; i < l; i ++ ) { + this.type = 'LineSegments'; - testPoint( vertices[ i ], i ); + } - } + LineSegments.prototype = Object.assign( Object.create( Line.prototype ), { - } + constructor: LineSegments, - }; + isLineSegments: true - }() ), + } ); - clone: function () { + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * color: , + * opacity: , + * map: new THREE.Texture( ), + * + * size: , + * sizeAttenuation: + * } + */ - return new this.constructor( this.geometry, this.material ).copy( this ); + function PointsMaterial( parameters ) { - } + Material.call( this ); - } ); + this.type = 'PointsMaterial'; - /** - * @author mrdoob / http://mrdoob.com/ - */ + this.color = new Color( 0xffffff ); - function Group() { + this.map = null; - Object3D.call( this ); + this.size = 1; + this.sizeAttenuation = true; - this.type = 'Group'; + this.lights = false; - }; + this.setValues( parameters ); - Group.prototype = Object.assign( Object.create( Object3D.prototype ), { + } - constructor: Group + PointsMaterial.prototype = Object.create( Material.prototype ); + PointsMaterial.prototype.constructor = PointsMaterial; - } ); + PointsMaterial.prototype.isPointsMaterial = true; - /** - * @author mrdoob / http://mrdoob.com/ - */ + PointsMaterial.prototype.copy = function ( source ) { - function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { + Material.prototype.copy.call( this, source ); - Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + this.color.copy( source.color ); - this.generateMipmaps = false; + this.map = source.map; - var scope = this; + this.size = source.size; + this.sizeAttenuation = source.sizeAttenuation; - function update() { + return this; - requestAnimationFrame( update ); + }; - if ( video.readyState >= video.HAVE_CURRENT_DATA ) { + /** + * @author alteredq / http://alteredqualia.com/ + */ - scope.needsUpdate = true; + function Points( geometry, material ) { - } + Object3D.call( this ); - } + this.type = 'Points'; - update(); + this.geometry = geometry !== undefined ? geometry : new BufferGeometry(); + this.material = material !== undefined ? material : new PointsMaterial( { color: Math.random() * 0xffffff } ); - }; + } - VideoTexture.prototype = Object.create( Texture.prototype ); - VideoTexture.prototype.constructor = VideoTexture; + Points.prototype = Object.assign( Object.create( Object3D.prototype ), { - /** - * @author alteredq / http://alteredqualia.com/ - */ + constructor: Points, - function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) { + isPoints: true, - Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); + raycast: ( function () { - this.image = { width: width, height: height }; - this.mipmaps = mipmaps; + var inverseMatrix = new Matrix4(); + var ray = new Ray(); + var sphere = new Sphere(); - // no flipping for cube textures - // (also flipping doesn't work for compressed textures ) + return function raycast( raycaster, intersects ) { - this.flipY = false; + var object = this; + var geometry = this.geometry; + var matrixWorld = this.matrixWorld; + var threshold = raycaster.params.Points.threshold; - // can't generate mipmaps for compressed textures - // mips must be embedded in DDS files + // Checking boundingSphere distance to ray - this.generateMipmaps = false; + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); - }; + sphere.copy( geometry.boundingSphere ); + sphere.applyMatrix4( matrixWorld ); - CompressedTexture.prototype = Object.create( Texture.prototype ); - CompressedTexture.prototype.constructor = CompressedTexture; + if ( raycaster.ray.intersectsSphere( sphere ) === false ) return; - CompressedTexture.prototype.isCompressedTexture = true; + // - /** - * @author mrdoob / http://mrdoob.com/ - */ + inverseMatrix.getInverse( matrixWorld ); + ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); - function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { + var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 ); + var localThresholdSq = localThreshold * localThreshold; + var position = new Vector3(); - Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + function testPoint( point, index ) { - this.needsUpdate = true; + var rayPointDistanceSq = ray.distanceSqToPoint( point ); - }; + if ( rayPointDistanceSq < localThresholdSq ) { - CanvasTexture.prototype = Object.create( Texture.prototype ); - CanvasTexture.prototype.constructor = CanvasTexture; + var intersectPoint = ray.closestPointToPoint( point ); + intersectPoint.applyMatrix4( matrixWorld ); - /** - * @author Matt DesLauriers / @mattdesl - * @author atix / arthursilber.de - */ + var distance = raycaster.ray.origin.distanceTo( intersectPoint ); - function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) { + if ( distance < raycaster.near || distance > raycaster.far ) return; - format = format !== undefined ? format : DepthFormat; + intersects.push( { - if ( format !== DepthFormat && format !== DepthStencilFormat ) { + distance: distance, + distanceToRay: Math.sqrt( rayPointDistanceSq ), + point: intersectPoint.clone(), + index: index, + face: null, + object: object - throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' ) + } ); - } + } - Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + } - this.image = { width: width, height: height }; + if ( (geometry && geometry.isBufferGeometry) ) { - this.type = type !== undefined ? type : UnsignedShortType; + var index = geometry.index; + var attributes = geometry.attributes; + var positions = attributes.position.array; - this.magFilter = magFilter !== undefined ? magFilter : NearestFilter; - this.minFilter = minFilter !== undefined ? minFilter : NearestFilter; + if ( index !== null ) { - this.flipY = false; - this.generateMipmaps = false; + var indices = index.array; - }; + for ( var i = 0, il = indices.length; i < il; i ++ ) { - DepthTexture.prototype = Object.create( Texture.prototype ); - DepthTexture.prototype.constructor = DepthTexture; - DepthTexture.prototype.isDepthTexture = true; + var a = indices[ i ]; - /** - * @author mrdoob / http://mrdoob.com/ - */ + position.fromArray( positions, a * 3 ); - function ShadowMaterial() { + testPoint( position, a ); - ShaderMaterial.call( this, { - uniforms: exports.UniformsUtils.merge( [ - exports.UniformsLib[ "lights" ], - { - opacity: { value: 1.0 } - } - ] ), - vertexShader: ShaderChunk[ 'shadow_vert' ], - fragmentShader: ShaderChunk[ 'shadow_frag' ] - } ); + } - this.lights = true; - this.transparent = true; + } else { - Object.defineProperties( this, { - opacity: { - enumerable: true, - get: function () { - return this.uniforms.opacity.value; - }, - set: function ( value ) { - this.uniforms.opacity.value = value; - } - } - } ); + for ( var i = 0, l = positions.length / 3; i < l; i ++ ) { - }; + position.fromArray( positions, i * 3 ); - ShadowMaterial.prototype = Object.create( ShaderMaterial.prototype ); - ShadowMaterial.prototype.constructor = ShadowMaterial; + testPoint( position, i ); - ShadowMaterial.prototype.isShadowMaterial = true; + } - /** - * @author mrdoob / http://mrdoob.com/ - */ + } - function RawShaderMaterial( parameters ) { + } else { - ShaderMaterial.call( this, parameters ); + var vertices = geometry.vertices; - this.type = 'RawShaderMaterial'; + for ( var i = 0, l = vertices.length; i < l; i ++ ) { - }; + testPoint( vertices[ i ], i ); - RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype ); - RawShaderMaterial.prototype.constructor = RawShaderMaterial; + } - RawShaderMaterial.prototype.isRawShaderMaterial = true; + } - /** - * @author mrdoob / http://mrdoob.com/ - */ + }; - function MultiMaterial( materials ) { + }() ), - this.uuid = exports.Math.generateUUID(); + clone: function () { - this.type = 'MultiMaterial'; + return new this.constructor( this.geometry, this.material ).copy( this ); - this.materials = materials instanceof Array ? materials : []; + } - this.visible = true; + } ); - }; + /** + * @author mrdoob / http://mrdoob.com/ + */ - MultiMaterial.prototype = { + function Group() { - constructor: MultiMaterial, + Object3D.call( this ); - isMultiMaterial: true, + this.type = 'Group'; - toJSON: function ( meta ) { + } - var output = { - metadata: { - version: 4.2, - type: 'material', - generator: 'MaterialExporter' - }, - uuid: this.uuid, - type: this.type, - materials: [] - }; + Group.prototype = Object.assign( Object.create( Object3D.prototype ), { - var materials = this.materials; + constructor: Group - for ( var i = 0, l = materials.length; i < l; i ++ ) { + } ); - var material = materials[ i ].toJSON( meta ); - delete material.metadata; + /** + * @author mrdoob / http://mrdoob.com/ + */ - output.materials.push( material ); + function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { - } + Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); - output.visible = this.visible; + this.generateMipmaps = false; - return output; + var scope = this; - }, + function update() { - clone: function () { + requestAnimationFrame( update ); - var material = new this.constructor(); + if ( video.readyState >= video.HAVE_CURRENT_DATA ) { - for ( var i = 0; i < this.materials.length; i ++ ) { + scope.needsUpdate = true; - material.materials.push( this.materials[ i ].clone() ); + } - } + } - material.visible = this.visible; + update(); - return material; + } - } + VideoTexture.prototype = Object.create( Texture.prototype ); + VideoTexture.prototype.constructor = VideoTexture; - }; + /** + * @author alteredq / http://alteredqualia.com/ + */ - /** - * @author WestLangley / http://github.com/WestLangley - * - * parameters = { - * color: , - * roughness: , - * metalness: , - * opacity: , - * - * map: new THREE.Texture( ), - * - * lightMap: new THREE.Texture( ), - * lightMapIntensity: - * - * aoMap: new THREE.Texture( ), - * aoMapIntensity: - * - * emissive: , - * emissiveIntensity: - * emissiveMap: new THREE.Texture( ), - * - * bumpMap: new THREE.Texture( ), - * bumpScale: , - * - * normalMap: new THREE.Texture( ), - * normalScale: , - * - * displacementMap: new THREE.Texture( ), - * displacementScale: , - * displacementBias: , - * - * roughnessMap: new THREE.Texture( ), - * - * metalnessMap: new THREE.Texture( ), - * - * alphaMap: new THREE.Texture( ), - * - * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ), - * envMapIntensity: - * - * refractionRatio: , - * - * wireframe: , - * wireframeLinewidth: , - * - * skinning: , - * morphTargets: , - * morphNormals: - * } - */ + function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) { - function MeshStandardMaterial( parameters ) { + Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); - Material.call( this ); + this.image = { width: width, height: height }; + this.mipmaps = mipmaps; - this.defines = { 'STANDARD': '' }; + // no flipping for cube textures + // (also flipping doesn't work for compressed textures ) - this.type = 'MeshStandardMaterial'; + this.flipY = false; - this.color = new Color( 0xffffff ); // diffuse - this.roughness = 0.5; - this.metalness = 0.5; + // can't generate mipmaps for compressed textures + // mips must be embedded in DDS files - this.map = null; + this.generateMipmaps = false; - this.lightMap = null; - this.lightMapIntensity = 1.0; + } - this.aoMap = null; - this.aoMapIntensity = 1.0; + CompressedTexture.prototype = Object.create( Texture.prototype ); + CompressedTexture.prototype.constructor = CompressedTexture; - this.emissive = new Color( 0x000000 ); - this.emissiveIntensity = 1.0; - this.emissiveMap = null; + CompressedTexture.prototype.isCompressedTexture = true; - this.bumpMap = null; - this.bumpScale = 1; + /** + * @author mrdoob / http://mrdoob.com/ + */ - this.normalMap = null; - this.normalScale = new Vector2( 1, 1 ); + function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { - this.displacementMap = null; - this.displacementScale = 1; - this.displacementBias = 0; + Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); - this.roughnessMap = null; + this.needsUpdate = true; - this.metalnessMap = null; + } - this.alphaMap = null; + CanvasTexture.prototype = Object.create( Texture.prototype ); + CanvasTexture.prototype.constructor = CanvasTexture; - this.envMap = null; - this.envMapIntensity = 1.0; + /** + * @author Matt DesLauriers / @mattdesl + * @author atix / arthursilber.de + */ - this.refractionRatio = 0.98; + function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) { - this.wireframe = false; - this.wireframeLinewidth = 1; - this.wireframeLinecap = 'round'; - this.wireframeLinejoin = 'round'; + format = format !== undefined ? format : DepthFormat; - this.skinning = false; - this.morphTargets = false; - this.morphNormals = false; + if ( format !== DepthFormat && format !== DepthStencilFormat ) { - this.setValues( parameters ); + throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' ) - }; + } - MeshStandardMaterial.prototype = Object.create( Material.prototype ); - MeshStandardMaterial.prototype.constructor = MeshStandardMaterial; + Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); - MeshStandardMaterial.prototype.isMeshStandardMaterial = true; + this.image = { width: width, height: height }; - MeshStandardMaterial.prototype.copy = function ( source ) { + this.type = type !== undefined ? type : UnsignedShortType; - Material.prototype.copy.call( this, source ); + this.magFilter = magFilter !== undefined ? magFilter : NearestFilter; + this.minFilter = minFilter !== undefined ? minFilter : NearestFilter; - this.defines = { 'STANDARD': '' }; + this.flipY = false; + this.generateMipmaps = false; - this.color.copy( source.color ); - this.roughness = source.roughness; - this.metalness = source.metalness; + } - this.map = source.map; + DepthTexture.prototype = Object.create( Texture.prototype ); + DepthTexture.prototype.constructor = DepthTexture; + DepthTexture.prototype.isDepthTexture = true; + + /** + * @author mrdoob / http://mrdoob.com/ + */ + + function ShadowMaterial() { + + ShaderMaterial.call( this, { + uniforms: exports.UniformsUtils.merge( [ + exports.UniformsLib[ "lights" ], + { + opacity: { value: 1.0 } + } + ] ), + vertexShader: ShaderChunk[ 'shadow_vert' ], + fragmentShader: ShaderChunk[ 'shadow_frag' ] + } ); - this.lightMap = source.lightMap; - this.lightMapIntensity = source.lightMapIntensity; + this.lights = true; + this.transparent = true; + + Object.defineProperties( this, { + opacity: { + enumerable: true, + get: function () { + return this.uniforms.opacity.value; + }, + set: function ( value ) { + this.uniforms.opacity.value = value; + } + } + } ); - this.aoMap = source.aoMap; - this.aoMapIntensity = source.aoMapIntensity; + } - this.emissive.copy( source.emissive ); - this.emissiveMap = source.emissiveMap; - this.emissiveIntensity = source.emissiveIntensity; + ShadowMaterial.prototype = Object.create( ShaderMaterial.prototype ); + ShadowMaterial.prototype.constructor = ShadowMaterial; - this.bumpMap = source.bumpMap; - this.bumpScale = source.bumpScale; + ShadowMaterial.prototype.isShadowMaterial = true; - this.normalMap = source.normalMap; - this.normalScale.copy( source.normalScale ); + /** + * @author mrdoob / http://mrdoob.com/ + */ - this.displacementMap = source.displacementMap; - this.displacementScale = source.displacementScale; - this.displacementBias = source.displacementBias; + function RawShaderMaterial( parameters ) { - this.roughnessMap = source.roughnessMap; + ShaderMaterial.call( this, parameters ); - this.metalnessMap = source.metalnessMap; + this.type = 'RawShaderMaterial'; - this.alphaMap = source.alphaMap; + } - this.envMap = source.envMap; - this.envMapIntensity = source.envMapIntensity; + RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype ); + RawShaderMaterial.prototype.constructor = RawShaderMaterial; - this.refractionRatio = source.refractionRatio; + RawShaderMaterial.prototype.isRawShaderMaterial = true; - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; - this.wireframeLinecap = source.wireframeLinecap; - this.wireframeLinejoin = source.wireframeLinejoin; + /** + * @author mrdoob / http://mrdoob.com/ + */ - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; - this.morphNormals = source.morphNormals; + function MultiMaterial( materials ) { - return this; + this.uuid = exports.Math.generateUUID(); - }; + this.type = 'MultiMaterial'; - /** - * @author WestLangley / http://github.com/WestLangley - * - * parameters = { - * reflectivity: - * } - */ + this.materials = materials instanceof Array ? materials : []; - function MeshPhysicalMaterial( parameters ) { + this.visible = true; - MeshStandardMaterial.call( this ); + } - this.defines = { 'PHYSICAL': '' }; + MultiMaterial.prototype = { - this.type = 'MeshPhysicalMaterial'; + constructor: MultiMaterial, - this.reflectivity = 0.5; // maps to F0 = 0.04 + isMultiMaterial: true, - this.clearCoat = 0.0; - this.clearCoatRoughness = 0.0; + toJSON: function ( meta ) { - this.setValues( parameters ); + var output = { + metadata: { + version: 4.2, + type: 'material', + generator: 'MaterialExporter' + }, + uuid: this.uuid, + type: this.type, + materials: [] + }; - }; + var materials = this.materials; - MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype ); - MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial; + for ( var i = 0, l = materials.length; i < l; i ++ ) { - MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true; + var material = materials[ i ].toJSON( meta ); + delete material.metadata; - MeshPhysicalMaterial.prototype.copy = function ( source ) { + output.materials.push( material ); - MeshStandardMaterial.prototype.copy.call( this, source ); + } - this.defines = { 'PHYSICAL': '' }; + output.visible = this.visible; - this.reflectivity = source.reflectivity; + return output; - this.clearCoat = source.clearCoat; - this.clearCoatRoughness = source.clearCoatRoughness; + }, - return this; + clone: function () { - }; + var material = new this.constructor(); - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * specular: , - * shininess: , - * opacity: , - * - * map: new THREE.Texture( ), - * - * lightMap: new THREE.Texture( ), - * lightMapIntensity: - * - * aoMap: new THREE.Texture( ), - * aoMapIntensity: - * - * emissive: , - * emissiveIntensity: - * emissiveMap: new THREE.Texture( ), - * - * bumpMap: new THREE.Texture( ), - * bumpScale: , - * - * normalMap: new THREE.Texture( ), - * normalScale: , - * - * displacementMap: new THREE.Texture( ), - * displacementScale: , - * displacementBias: , - * - * specularMap: new THREE.Texture( ), - * - * alphaMap: new THREE.Texture( ), - * - * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ), - * combine: THREE.Multiply, - * reflectivity: , - * refractionRatio: , - * - * wireframe: , - * wireframeLinewidth: , - * - * skinning: , - * morphTargets: , - * morphNormals: - * } - */ + for ( var i = 0; i < this.materials.length; i ++ ) { - function MeshPhongMaterial( parameters ) { + material.materials.push( this.materials[ i ].clone() ); - Material.call( this ); + } - this.type = 'MeshPhongMaterial'; + material.visible = this.visible; - this.color = new Color( 0xffffff ); // diffuse - this.specular = new Color( 0x111111 ); - this.shininess = 30; + return material; - this.map = null; + } - this.lightMap = null; - this.lightMapIntensity = 1.0; + }; - this.aoMap = null; - this.aoMapIntensity = 1.0; + /** + * @author WestLangley / http://github.com/WestLangley + * + * parameters = { + * color: , + * roughness: , + * metalness: , + * opacity: , + * + * map: new THREE.Texture( ), + * + * lightMap: new THREE.Texture( ), + * lightMapIntensity: + * + * aoMap: new THREE.Texture( ), + * aoMapIntensity: + * + * emissive: , + * emissiveIntensity: + * emissiveMap: new THREE.Texture( ), + * + * bumpMap: new THREE.Texture( ), + * bumpScale: , + * + * normalMap: new THREE.Texture( ), + * normalScale: , + * + * displacementMap: new THREE.Texture( ), + * displacementScale: , + * displacementBias: , + * + * roughnessMap: new THREE.Texture( ), + * + * metalnessMap: new THREE.Texture( ), + * + * alphaMap: new THREE.Texture( ), + * + * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ), + * envMapIntensity: + * + * refractionRatio: , + * + * wireframe: , + * wireframeLinewidth: , + * + * skinning: , + * morphTargets: , + * morphNormals: + * } + */ + + function MeshStandardMaterial( parameters ) { + + Material.call( this ); + + this.defines = { 'STANDARD': '' }; + + this.type = 'MeshStandardMaterial'; + + this.color = new Color( 0xffffff ); // diffuse + this.roughness = 0.5; + this.metalness = 0.5; + + this.map = null; + + this.lightMap = null; + this.lightMapIntensity = 1.0; + + this.aoMap = null; + this.aoMapIntensity = 1.0; + + this.emissive = new Color( 0x000000 ); + this.emissiveIntensity = 1.0; + this.emissiveMap = null; + + this.bumpMap = null; + this.bumpScale = 1; + + this.normalMap = null; + this.normalScale = new Vector2( 1, 1 ); + + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + + this.roughnessMap = null; + + this.metalnessMap = null; + + this.alphaMap = null; + + this.envMap = null; + this.envMapIntensity = 1.0; + + this.refractionRatio = 0.98; + + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; + + this.skinning = false; + this.morphTargets = false; + this.morphNormals = false; + + this.setValues( parameters ); - this.emissive = new Color( 0x000000 ); - this.emissiveIntensity = 1.0; - this.emissiveMap = null; + } - this.bumpMap = null; - this.bumpScale = 1; + MeshStandardMaterial.prototype = Object.create( Material.prototype ); + MeshStandardMaterial.prototype.constructor = MeshStandardMaterial; - this.normalMap = null; - this.normalScale = new Vector2( 1, 1 ); + MeshStandardMaterial.prototype.isMeshStandardMaterial = true; - this.displacementMap = null; - this.displacementScale = 1; - this.displacementBias = 0; + MeshStandardMaterial.prototype.copy = function ( source ) { - this.specularMap = null; + Material.prototype.copy.call( this, source ); - this.alphaMap = null; + this.defines = { 'STANDARD': '' }; - this.envMap = null; - this.combine = MultiplyOperation; - this.reflectivity = 1; - this.refractionRatio = 0.98; + this.color.copy( source.color ); + this.roughness = source.roughness; + this.metalness = source.metalness; - this.wireframe = false; - this.wireframeLinewidth = 1; - this.wireframeLinecap = 'round'; - this.wireframeLinejoin = 'round'; + this.map = source.map; - this.skinning = false; - this.morphTargets = false; - this.morphNormals = false; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; - this.setValues( parameters ); + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; - }; + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; - MeshPhongMaterial.prototype = Object.create( Material.prototype ); - MeshPhongMaterial.prototype.constructor = MeshPhongMaterial; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; - MeshPhongMaterial.prototype.isMeshPhongMaterial = true; + this.normalMap = source.normalMap; + this.normalScale.copy( source.normalScale ); - MeshPhongMaterial.prototype.copy = function ( source ) { + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; - Material.prototype.copy.call( this, source ); + this.roughnessMap = source.roughnessMap; - this.color.copy( source.color ); - this.specular.copy( source.specular ); - this.shininess = source.shininess; + this.metalnessMap = source.metalnessMap; - this.map = source.map; + this.alphaMap = source.alphaMap; - this.lightMap = source.lightMap; - this.lightMapIntensity = source.lightMapIntensity; + this.envMap = source.envMap; + this.envMapIntensity = source.envMapIntensity; - this.aoMap = source.aoMap; - this.aoMapIntensity = source.aoMapIntensity; + this.refractionRatio = source.refractionRatio; - this.emissive.copy( source.emissive ); - this.emissiveMap = source.emissiveMap; - this.emissiveIntensity = source.emissiveIntensity; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; - this.bumpMap = source.bumpMap; - this.bumpScale = source.bumpScale; + this.skinning = source.skinning; + this.morphTargets = source.morphTargets; + this.morphNormals = source.morphNormals; - this.normalMap = source.normalMap; - this.normalScale.copy( source.normalScale ); + return this; - this.displacementMap = source.displacementMap; - this.displacementScale = source.displacementScale; - this.displacementBias = source.displacementBias; + }; - this.specularMap = source.specularMap; + /** + * @author WestLangley / http://github.com/WestLangley + * + * parameters = { + * reflectivity: + * } + */ - this.alphaMap = source.alphaMap; + function MeshPhysicalMaterial( parameters ) { - this.envMap = source.envMap; - this.combine = source.combine; - this.reflectivity = source.reflectivity; - this.refractionRatio = source.refractionRatio; + MeshStandardMaterial.call( this ); - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; - this.wireframeLinecap = source.wireframeLinecap; - this.wireframeLinejoin = source.wireframeLinejoin; + this.defines = { 'PHYSICAL': '' }; - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; - this.morphNormals = source.morphNormals; + this.type = 'MeshPhysicalMaterial'; - return this; + this.reflectivity = 0.5; // maps to F0 = 0.04 - }; + this.clearCoat = 0.0; + this.clearCoatRoughness = 0.0; - /** - * @author mrdoob / http://mrdoob.com/ - * - * parameters = { - * opacity: , - * - * wireframe: , - * wireframeLinewidth: - * } - */ + this.setValues( parameters ); - function MeshNormalMaterial( parameters ) { + } - Material.call( this, parameters ); + MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype ); + MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial; - this.type = 'MeshNormalMaterial'; + MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true; - this.wireframe = false; - this.wireframeLinewidth = 1; + MeshPhysicalMaterial.prototype.copy = function ( source ) { - this.fog = false; - this.lights = false; - this.morphTargets = false; + MeshStandardMaterial.prototype.copy.call( this, source ); - this.setValues( parameters ); + this.defines = { 'PHYSICAL': '' }; - }; + this.reflectivity = source.reflectivity; - MeshNormalMaterial.prototype = Object.create( Material.prototype ); - MeshNormalMaterial.prototype.constructor = MeshNormalMaterial; + this.clearCoat = source.clearCoat; + this.clearCoatRoughness = source.clearCoatRoughness; - MeshNormalMaterial.prototype.isMeshNormalMaterial = true; + return this; - MeshNormalMaterial.prototype.copy = function ( source ) { + }; - Material.prototype.copy.call( this, source ); + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * color: , + * specular: , + * shininess: , + * opacity: , + * + * map: new THREE.Texture( ), + * + * lightMap: new THREE.Texture( ), + * lightMapIntensity: + * + * aoMap: new THREE.Texture( ), + * aoMapIntensity: + * + * emissive: , + * emissiveIntensity: + * emissiveMap: new THREE.Texture( ), + * + * bumpMap: new THREE.Texture( ), + * bumpScale: , + * + * normalMap: new THREE.Texture( ), + * normalScale: , + * + * displacementMap: new THREE.Texture( ), + * displacementScale: , + * displacementBias: , + * + * specularMap: new THREE.Texture( ), + * + * alphaMap: new THREE.Texture( ), + * + * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ), + * combine: THREE.Multiply, + * reflectivity: , + * refractionRatio: , + * + * wireframe: , + * wireframeLinewidth: , + * + * skinning: , + * morphTargets: , + * morphNormals: + * } + */ + + function MeshPhongMaterial( parameters ) { + + Material.call( this ); + + this.type = 'MeshPhongMaterial'; + + this.color = new Color( 0xffffff ); // diffuse + this.specular = new Color( 0x111111 ); + this.shininess = 30; + + this.map = null; + + this.lightMap = null; + this.lightMapIntensity = 1.0; + + this.aoMap = null; + this.aoMapIntensity = 1.0; + + this.emissive = new Color( 0x000000 ); + this.emissiveIntensity = 1.0; + this.emissiveMap = null; + + this.bumpMap = null; + this.bumpScale = 1; + + this.normalMap = null; + this.normalScale = new Vector2( 1, 1 ); + + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + + this.specularMap = null; + + this.alphaMap = null; + + this.envMap = null; + this.combine = MultiplyOperation; + this.reflectivity = 1; + this.refractionRatio = 0.98; + + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; + + this.skinning = false; + this.morphTargets = false; + this.morphNormals = false; + + this.setValues( parameters ); - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; + } - return this; + MeshPhongMaterial.prototype = Object.create( Material.prototype ); + MeshPhongMaterial.prototype.constructor = MeshPhongMaterial; - }; + MeshPhongMaterial.prototype.isMeshPhongMaterial = true; - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * opacity: , - * - * map: new THREE.Texture( ), - * - * lightMap: new THREE.Texture( ), - * lightMapIntensity: - * - * aoMap: new THREE.Texture( ), - * aoMapIntensity: - * - * emissive: , - * emissiveIntensity: - * emissiveMap: new THREE.Texture( ), - * - * specularMap: new THREE.Texture( ), - * - * alphaMap: new THREE.Texture( ), - * - * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ), - * combine: THREE.Multiply, - * reflectivity: , - * refractionRatio: , - * - * wireframe: , - * wireframeLinewidth: , - * - * skinning: , - * morphTargets: , - * morphNormals: - * } - */ + MeshPhongMaterial.prototype.copy = function ( source ) { - function MeshLambertMaterial( parameters ) { + Material.prototype.copy.call( this, source ); - Material.call( this ); + this.color.copy( source.color ); + this.specular.copy( source.specular ); + this.shininess = source.shininess; - this.type = 'MeshLambertMaterial'; + this.map = source.map; - this.color = new Color( 0xffffff ); // diffuse + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; - this.map = null; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; - this.lightMap = null; - this.lightMapIntensity = 1.0; + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; - this.aoMap = null; - this.aoMapIntensity = 1.0; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; - this.emissive = new Color( 0x000000 ); - this.emissiveIntensity = 1.0; - this.emissiveMap = null; + this.normalMap = source.normalMap; + this.normalScale.copy( source.normalScale ); - this.specularMap = null; + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; - this.alphaMap = null; + this.specularMap = source.specularMap; - this.envMap = null; - this.combine = MultiplyOperation; - this.reflectivity = 1; - this.refractionRatio = 0.98; + this.alphaMap = source.alphaMap; - this.wireframe = false; - this.wireframeLinewidth = 1; - this.wireframeLinecap = 'round'; - this.wireframeLinejoin = 'round'; + this.envMap = source.envMap; + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; - this.skinning = false; - this.morphTargets = false; - this.morphNormals = false; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; - this.setValues( parameters ); + this.skinning = source.skinning; + this.morphTargets = source.morphTargets; + this.morphNormals = source.morphNormals; - }; + return this; - MeshLambertMaterial.prototype = Object.create( Material.prototype ); - MeshLambertMaterial.prototype.constructor = MeshLambertMaterial; + }; - MeshLambertMaterial.prototype.isMeshLambertMaterial = true; + /** + * @author mrdoob / http://mrdoob.com/ + * + * parameters = { + * opacity: , + * + * wireframe: , + * wireframeLinewidth: + * } + */ - MeshLambertMaterial.prototype.copy = function ( source ) { + function MeshNormalMaterial( parameters ) { - Material.prototype.copy.call( this, source ); + Material.call( this, parameters ); - this.color.copy( source.color ); + this.type = 'MeshNormalMaterial'; - this.map = source.map; + this.wireframe = false; + this.wireframeLinewidth = 1; - this.lightMap = source.lightMap; - this.lightMapIntensity = source.lightMapIntensity; + this.fog = false; + this.lights = false; + this.morphTargets = false; - this.aoMap = source.aoMap; - this.aoMapIntensity = source.aoMapIntensity; + this.setValues( parameters ); - this.emissive.copy( source.emissive ); - this.emissiveMap = source.emissiveMap; - this.emissiveIntensity = source.emissiveIntensity; + } - this.specularMap = source.specularMap; + MeshNormalMaterial.prototype = Object.create( Material.prototype ); + MeshNormalMaterial.prototype.constructor = MeshNormalMaterial; - this.alphaMap = source.alphaMap; + MeshNormalMaterial.prototype.isMeshNormalMaterial = true; - this.envMap = source.envMap; - this.combine = source.combine; - this.reflectivity = source.reflectivity; - this.refractionRatio = source.refractionRatio; + MeshNormalMaterial.prototype.copy = function ( source ) { - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; - this.wireframeLinecap = source.wireframeLinecap; - this.wireframeLinejoin = source.wireframeLinejoin; + Material.prototype.copy.call( this, source ); - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; - this.morphNormals = source.morphNormals; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; - return this; + return this; - }; + }; - /** - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * opacity: , - * - * linewidth: , - * - * scale: , - * dashSize: , - * gapSize: - * } - */ + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * color: , + * opacity: , + * + * map: new THREE.Texture( ), + * + * lightMap: new THREE.Texture( ), + * lightMapIntensity: + * + * aoMap: new THREE.Texture( ), + * aoMapIntensity: + * + * emissive: , + * emissiveIntensity: + * emissiveMap: new THREE.Texture( ), + * + * specularMap: new THREE.Texture( ), + * + * alphaMap: new THREE.Texture( ), + * + * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ), + * combine: THREE.Multiply, + * reflectivity: , + * refractionRatio: , + * + * wireframe: , + * wireframeLinewidth: , + * + * skinning: , + * morphTargets: , + * morphNormals: + * } + */ + + function MeshLambertMaterial( parameters ) { + + Material.call( this ); + + this.type = 'MeshLambertMaterial'; + + this.color = new Color( 0xffffff ); // diffuse + + this.map = null; + + this.lightMap = null; + this.lightMapIntensity = 1.0; + + this.aoMap = null; + this.aoMapIntensity = 1.0; + + this.emissive = new Color( 0x000000 ); + this.emissiveIntensity = 1.0; + this.emissiveMap = null; + + this.specularMap = null; + + this.alphaMap = null; + + this.envMap = null; + this.combine = MultiplyOperation; + this.reflectivity = 1; + this.refractionRatio = 0.98; + + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; + + this.skinning = false; + this.morphTargets = false; + this.morphNormals = false; + + this.setValues( parameters ); - function LineDashedMaterial( parameters ) { + } - Material.call( this ); + MeshLambertMaterial.prototype = Object.create( Material.prototype ); + MeshLambertMaterial.prototype.constructor = MeshLambertMaterial; - this.type = 'LineDashedMaterial'; + MeshLambertMaterial.prototype.isMeshLambertMaterial = true; - this.color = new Color( 0xffffff ); + MeshLambertMaterial.prototype.copy = function ( source ) { - this.linewidth = 1; + Material.prototype.copy.call( this, source ); - this.scale = 1; - this.dashSize = 3; - this.gapSize = 1; + this.color.copy( source.color ); - this.lights = false; + this.map = source.map; - this.setValues( parameters ); + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; - }; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; - LineDashedMaterial.prototype = Object.create( Material.prototype ); - LineDashedMaterial.prototype.constructor = LineDashedMaterial; + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; - LineDashedMaterial.prototype.isLineDashedMaterial = true; + this.specularMap = source.specularMap; - LineDashedMaterial.prototype.copy = function ( source ) { + this.alphaMap = source.alphaMap; - Material.prototype.copy.call( this, source ); + this.envMap = source.envMap; + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; - this.color.copy( source.color ); + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; - this.linewidth = source.linewidth; + this.skinning = source.skinning; + this.morphTargets = source.morphTargets; + this.morphNormals = source.morphNormals; - this.scale = source.scale; - this.dashSize = source.dashSize; - this.gapSize = source.gapSize; + return this; - return this; + }; - }; + /** + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * color: , + * opacity: , + * + * linewidth: , + * + * scale: , + * dashSize: , + * gapSize: + * } + */ - /** - * @author mrdoob / http://mrdoob.com/ - */ + function LineDashedMaterial( parameters ) { - exports.Cache = { + Material.call( this ); - enabled: false, + this.type = 'LineDashedMaterial'; - files: {}, + this.color = new Color( 0xffffff ); - add: function ( key, file ) { + this.linewidth = 1; - if ( this.enabled === false ) return; + this.scale = 1; + this.dashSize = 3; + this.gapSize = 1; - // console.log( 'THREE.Cache', 'Adding key:', key ); + this.lights = false; - this.files[ key ] = file; + this.setValues( parameters ); - }, + } - get: function ( key ) { + LineDashedMaterial.prototype = Object.create( Material.prototype ); + LineDashedMaterial.prototype.constructor = LineDashedMaterial; - if ( this.enabled === false ) return; + LineDashedMaterial.prototype.isLineDashedMaterial = true; - // console.log( 'THREE.Cache', 'Checking key:', key ); + LineDashedMaterial.prototype.copy = function ( source ) { - return this.files[ key ]; + Material.prototype.copy.call( this, source ); - }, + this.color.copy( source.color ); - remove: function ( key ) { + this.linewidth = source.linewidth; - delete this.files[ key ]; + this.scale = source.scale; + this.dashSize = source.dashSize; + this.gapSize = source.gapSize; - }, + return this; - clear: function () { + }; - this.files = {}; + /** + * @author mrdoob / http://mrdoob.com/ + */ - } + exports.Cache = { - }; + enabled: false, - /** - * @author mrdoob / http://mrdoob.com/ - */ + files: {}, - function LoadingManager( onLoad, onProgress, onError ) { + add: function ( key, file ) { - var scope = this; + if ( this.enabled === false ) return; - var isLoading = false, itemsLoaded = 0, itemsTotal = 0; + // console.log( 'THREE.Cache', 'Adding key:', key ); - this.onStart = undefined; - this.onLoad = onLoad; - this.onProgress = onProgress; - this.onError = onError; + this.files[ key ] = file; - this.itemStart = function ( url ) { + }, - itemsTotal ++; + get: function ( key ) { - if ( isLoading === false ) { + if ( this.enabled === false ) return; - if ( scope.onStart !== undefined ) { + // console.log( 'THREE.Cache', 'Checking key:', key ); - scope.onStart( url, itemsLoaded, itemsTotal ); + return this.files[ key ]; - } + }, - } + remove: function ( key ) { - isLoading = true; + delete this.files[ key ]; - }; + }, - this.itemEnd = function ( url ) { + clear: function () { - itemsLoaded ++; + this.files = {}; - if ( scope.onProgress !== undefined ) { + } - scope.onProgress( url, itemsLoaded, itemsTotal ); + }; - } + /** + * @author mrdoob / http://mrdoob.com/ + */ - if ( itemsLoaded === itemsTotal ) { + function LoadingManager( onLoad, onProgress, onError ) { - isLoading = false; + var scope = this; - if ( scope.onLoad !== undefined ) { + var isLoading = false, itemsLoaded = 0, itemsTotal = 0; - scope.onLoad(); + this.onStart = undefined; + this.onLoad = onLoad; + this.onProgress = onProgress; + this.onError = onError; - } + this.itemStart = function ( url ) { - } + itemsTotal ++; - }; + if ( isLoading === false ) { - this.itemError = function ( url ) { + if ( scope.onStart !== undefined ) { - if ( scope.onError !== undefined ) { + scope.onStart( url, itemsLoaded, itemsTotal ); - scope.onError( url ); + } - } + } - }; + isLoading = true; - }; + }; - exports.DefaultLoadingManager = new LoadingManager(); + this.itemEnd = function ( url ) { - /** - * @author mrdoob / http://mrdoob.com/ - */ + itemsLoaded ++; - function XHRLoader( manager ) { + if ( scope.onProgress !== undefined ) { - this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; + scope.onProgress( url, itemsLoaded, itemsTotal ); - }; + } - Object.assign( XHRLoader.prototype, { + if ( itemsLoaded === itemsTotal ) { - load: function ( url, onLoad, onProgress, onError ) { + isLoading = false; - if ( this.path !== undefined ) url = this.path + url; + if ( scope.onLoad !== undefined ) { - var scope = this; + scope.onLoad(); - var cached = exports.Cache.get( url ); + } - if ( cached !== undefined ) { + } - scope.manager.itemStart( url ); + }; - setTimeout( function () { + this.itemError = function ( url ) { - if ( onLoad ) onLoad( cached ); + if ( scope.onError !== undefined ) { - scope.manager.itemEnd( url ); + scope.onError( url ); - }, 0 ); + } - return cached; + }; - } + } - var request = new XMLHttpRequest(); - request.overrideMimeType( 'text/plain' ); - request.open( 'GET', url, true ); + exports.DefaultLoadingManager = new LoadingManager(); - request.addEventListener( 'load', function ( event ) { + /** + * @author mrdoob / http://mrdoob.com/ + */ - var response = event.target.response; + function XHRLoader( manager ) { - exports.Cache.add( url, response ); + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; - if ( this.status === 200 ) { + } - if ( onLoad ) onLoad( response ); + Object.assign( XHRLoader.prototype, { - scope.manager.itemEnd( url ); + load: function ( url, onLoad, onProgress, onError ) { - } else if ( this.status === 0 ) { + if ( this.path !== undefined ) url = this.path + url; - // Some browsers return HTTP Status 0 when using non-http protocol - // e.g. 'file://' or 'data://'. Handle as success. + var scope = this; - console.warn( 'THREE.XHRLoader: HTTP Status 0 received.' ); + var cached = exports.Cache.get( url ); - if ( onLoad ) onLoad( response ); + if ( cached !== undefined ) { - scope.manager.itemEnd( url ); + scope.manager.itemStart( url ); - } else { + setTimeout( function () { - if ( onError ) onError( event ); + if ( onLoad ) onLoad( cached ); - scope.manager.itemError( url ); + scope.manager.itemEnd( url ); - } + }, 0 ); - }, false ); + return cached; - if ( onProgress !== undefined ) { + } - request.addEventListener( 'progress', function ( event ) { + var request = new XMLHttpRequest(); + request.open( 'GET', url, true ); - onProgress( event ); + request.addEventListener( 'load', function ( event ) { - }, false ); + var response = event.target.response; - } + exports.Cache.add( url, response ); - request.addEventListener( 'error', function ( event ) { + if ( this.status === 200 ) { - if ( onError ) onError( event ); + if ( onLoad ) onLoad( response ); - scope.manager.itemError( url ); + scope.manager.itemEnd( url ); - }, false ); + } else if ( this.status === 0 ) { - if ( this.responseType !== undefined ) request.responseType = this.responseType; - if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials; + // Some browsers return HTTP Status 0 when using non-http protocol + // e.g. 'file://' or 'data://'. Handle as success. - request.send( null ); + console.warn( 'THREE.XHRLoader: HTTP Status 0 received.' ); - scope.manager.itemStart( url ); + if ( onLoad ) onLoad( response ); - return request; + scope.manager.itemEnd( url ); - }, + } else { - setPath: function ( value ) { + if ( onError ) onError( event ); - this.path = value; - return this; + scope.manager.itemError( url ); - }, + } - setResponseType: function ( value ) { + }, false ); - this.responseType = value; - return this; + if ( onProgress !== undefined ) { - }, + request.addEventListener( 'progress', function ( event ) { - setWithCredentials: function ( value ) { + onProgress( event ); - this.withCredentials = value; - return this; + }, false ); - } + } - } ); + request.addEventListener( 'error', function ( event ) { - /** - * @author mrdoob / http://mrdoob.com/ - * - * Abstract Base class to block based textures loader (dds, pvr, ...) - */ + if ( onError ) onError( event ); - function CompressedTextureLoader( manager ) { + scope.manager.itemError( url ); - this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; + }, false ); - // override in sub classes - this._parser = null; + if ( this.responseType !== undefined ) request.responseType = this.responseType; + if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials; - }; + if ( request.overrideMimeType ) request.overrideMimeType( 'text/plain' ); - Object.assign( CompressedTextureLoader.prototype, { + request.send( null ); - load: function ( url, onLoad, onProgress, onError ) { + scope.manager.itemStart( url ); - var scope = this; + return request; - var images = []; + }, - var texture = new CompressedTexture(); - texture.image = images; + setPath: function ( value ) { - var loader = new XHRLoader( this.manager ); - loader.setPath( this.path ); - loader.setResponseType( 'arraybuffer' ); + this.path = value; + return this; - function loadTexture( i ) { + }, - loader.load( url[ i ], function ( buffer ) { + setResponseType: function ( value ) { - var texDatas = scope._parser( buffer, true ); + this.responseType = value; + return this; - images[ i ] = { - width: texDatas.width, - height: texDatas.height, - format: texDatas.format, - mipmaps: texDatas.mipmaps - }; + }, - loaded += 1; + setWithCredentials: function ( value ) { - if ( loaded === 6 ) { + this.withCredentials = value; + return this; - if ( texDatas.mipmapCount === 1 ) - texture.minFilter = LinearFilter; + } - texture.format = texDatas.format; - texture.needsUpdate = true; + } ); - if ( onLoad ) onLoad( texture ); + /** + * @author mrdoob / http://mrdoob.com/ + * + * Abstract Base class to block based textures loader (dds, pvr, ...) + */ - } + function CompressedTextureLoader( manager ) { - }, onProgress, onError ); + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; - } + // override in sub classes + this._parser = null; - if ( Array.isArray( url ) ) { + } - var loaded = 0; + Object.assign( CompressedTextureLoader.prototype, { - for ( var i = 0, il = url.length; i < il; ++ i ) { + load: function ( url, onLoad, onProgress, onError ) { - loadTexture( i ); + var scope = this; - } + var images = []; - } else { + var texture = new CompressedTexture(); + texture.image = images; - // compressed cubemap texture stored in a single DDS file + var loader = new XHRLoader( this.manager ); + loader.setPath( this.path ); + loader.setResponseType( 'arraybuffer' ); - loader.load( url, function ( buffer ) { + function loadTexture( i ) { - var texDatas = scope._parser( buffer, true ); + loader.load( url[ i ], function ( buffer ) { - if ( texDatas.isCubemap ) { + var texDatas = scope._parser( buffer, true ); - var faces = texDatas.mipmaps.length / texDatas.mipmapCount; + images[ i ] = { + width: texDatas.width, + height: texDatas.height, + format: texDatas.format, + mipmaps: texDatas.mipmaps + }; - for ( var f = 0; f < faces; f ++ ) { + loaded += 1; - images[ f ] = { mipmaps : [] }; + if ( loaded === 6 ) { - for ( var i = 0; i < texDatas.mipmapCount; i ++ ) { + if ( texDatas.mipmapCount === 1 ) + texture.minFilter = LinearFilter; - images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] ); - images[ f ].format = texDatas.format; - images[ f ].width = texDatas.width; - images[ f ].height = texDatas.height; + texture.format = texDatas.format; + texture.needsUpdate = true; - } + if ( onLoad ) onLoad( texture ); - } + } - } else { + }, onProgress, onError ); - texture.image.width = texDatas.width; - texture.image.height = texDatas.height; - texture.mipmaps = texDatas.mipmaps; + } - } + if ( Array.isArray( url ) ) { - if ( texDatas.mipmapCount === 1 ) { + var loaded = 0; - texture.minFilter = LinearFilter; + for ( var i = 0, il = url.length; i < il; ++ i ) { - } + loadTexture( i ); - texture.format = texDatas.format; - texture.needsUpdate = true; + } - if ( onLoad ) onLoad( texture ); + } else { - }, onProgress, onError ); + // compressed cubemap texture stored in a single DDS file - } + loader.load( url, function ( buffer ) { - return texture; + var texDatas = scope._parser( buffer, true ); - }, + if ( texDatas.isCubemap ) { - setPath: function ( value ) { + var faces = texDatas.mipmaps.length / texDatas.mipmapCount; - this.path = value; - return this; + for ( var f = 0; f < faces; f ++ ) { - } + images[ f ] = { mipmaps : [] }; - } ); + for ( var i = 0; i < texDatas.mipmapCount; i ++ ) { - /** - * @author Nikos M. / https://github.com/foo123/ - * - * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...) - */ + images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] ); + images[ f ].format = texDatas.format; + images[ f ].width = texDatas.width; + images[ f ].height = texDatas.height; - var DataTextureLoader = BinaryTextureLoader; - function BinaryTextureLoader( manager ) { + } - this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; + } - // override in sub classes - this._parser = null; + } else { - }; + texture.image.width = texDatas.width; + texture.image.height = texDatas.height; + texture.mipmaps = texDatas.mipmaps; - Object.assign( BinaryTextureLoader.prototype, { + } - load: function ( url, onLoad, onProgress, onError ) { + if ( texDatas.mipmapCount === 1 ) { - var scope = this; + texture.minFilter = LinearFilter; - var texture = new DataTexture(); + } - var loader = new XHRLoader( this.manager ); - loader.setResponseType( 'arraybuffer' ); + texture.format = texDatas.format; + texture.needsUpdate = true; - loader.load( url, function ( buffer ) { + if ( onLoad ) onLoad( texture ); - var texData = scope._parser( buffer ); + }, onProgress, onError ); - if ( ! texData ) return; + } - if ( undefined !== texData.image ) { + return texture; - texture.image = texData.image; + }, - } else if ( undefined !== texData.data ) { + setPath: function ( value ) { - texture.image.width = texData.width; - texture.image.height = texData.height; - texture.image.data = texData.data; + this.path = value; + return this; - } + } - texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : ClampToEdgeWrapping; - texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : ClampToEdgeWrapping; + } ); - texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : LinearFilter; - texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : LinearMipMapLinearFilter; + /** + * @author Nikos M. / https://github.com/foo123/ + * + * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...) + */ - texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1; + var DataTextureLoader = BinaryTextureLoader; + function BinaryTextureLoader( manager ) { - if ( undefined !== texData.format ) { + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; - texture.format = texData.format; + // override in sub classes + this._parser = null; - } - if ( undefined !== texData.type ) { + } - texture.type = texData.type; + Object.assign( BinaryTextureLoader.prototype, { - } + load: function ( url, onLoad, onProgress, onError ) { - if ( undefined !== texData.mipmaps ) { + var scope = this; - texture.mipmaps = texData.mipmaps; + var texture = new DataTexture(); - } + var loader = new XHRLoader( this.manager ); + loader.setResponseType( 'arraybuffer' ); - if ( 1 === texData.mipmapCount ) { + loader.load( url, function ( buffer ) { - texture.minFilter = LinearFilter; + var texData = scope._parser( buffer ); - } + if ( ! texData ) return; - texture.needsUpdate = true; + if ( undefined !== texData.image ) { - if ( onLoad ) onLoad( texture, texData ); + texture.image = texData.image; - }, onProgress, onError ); + } else if ( undefined !== texData.data ) { + texture.image.width = texData.width; + texture.image.height = texData.height; + texture.image.data = texData.data; - return texture; + } - } + texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : ClampToEdgeWrapping; + texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : ClampToEdgeWrapping; - } ); + texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : LinearFilter; + texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : LinearMipMapLinearFilter; - /** - * @author mrdoob / http://mrdoob.com/ - */ + texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1; - function ImageLoader( manager ) { + if ( undefined !== texData.format ) { - this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; + texture.format = texData.format; - }; + } + if ( undefined !== texData.type ) { - Object.assign( ImageLoader.prototype, { + texture.type = texData.type; - load: function ( url, onLoad, onProgress, onError ) { + } - var scope = this; + if ( undefined !== texData.mipmaps ) { - var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' ); - image.onload = function () { + texture.mipmaps = texData.mipmaps; - URL.revokeObjectURL( image.src ); + } - if ( onLoad ) onLoad( image ); + if ( 1 === texData.mipmapCount ) { - scope.manager.itemEnd( url ); + texture.minFilter = LinearFilter; - }; + } - if ( url.indexOf( 'data:' ) === 0 ) { + texture.needsUpdate = true; - image.src = url; + if ( onLoad ) onLoad( texture, texData ); - } else { + }, onProgress, onError ); - var loader = new XHRLoader(); - loader.setPath( this.path ); - loader.setResponseType( 'blob' ); - loader.setWithCredentials( this.withCredentials ); - loader.load( url, function ( blob ) { - image.src = URL.createObjectURL( blob ); + return texture; - }, onProgress, onError ); + } - } + } ); - scope.manager.itemStart( url ); + /** + * @author mrdoob / http://mrdoob.com/ + */ - return image; + function ImageLoader( manager ) { - }, + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; - setCrossOrigin: function ( value ) { + } - this.crossOrigin = value; - return this; + Object.assign( ImageLoader.prototype, { - }, + load: function ( url, onLoad, onProgress, onError ) { - setWithCredentials: function ( value ) { + var scope = this; - this.withCredentials = value; - return this; + var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' ); + image.onload = function () { - }, + URL.revokeObjectURL( image.src ); - setPath: function ( value ) { + if ( onLoad ) onLoad( image ); - this.path = value; - return this; + scope.manager.itemEnd( url ); - } + }; - } ); + if ( url.indexOf( 'data:' ) === 0 ) { - /** - * @author mrdoob / http://mrdoob.com/ - */ + image.src = url; - function CubeTextureLoader( manager ) { + } else { - this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; + var loader = new XHRLoader(); + loader.setPath( this.path ); + loader.setResponseType( 'blob' ); + loader.setWithCredentials( this.withCredentials ); + loader.load( url, function ( blob ) { - }; + image.src = URL.createObjectURL( blob ); - Object.assign( CubeTextureLoader.prototype, { + }, onProgress, onError ); - load: function ( urls, onLoad, onProgress, onError ) { + } - var texture = new CubeTexture(); + scope.manager.itemStart( url ); - var loader = new ImageLoader( this.manager ); - loader.setCrossOrigin( this.crossOrigin ); - loader.setPath( this.path ); + return image; - var loaded = 0; + }, - function loadTexture( i ) { + setCrossOrigin: function ( value ) { - loader.load( urls[ i ], function ( image ) { + this.crossOrigin = value; + return this; - texture.images[ i ] = image; + }, - loaded ++; + setWithCredentials: function ( value ) { - if ( loaded === 6 ) { + this.withCredentials = value; + return this; - texture.needsUpdate = true; + }, - if ( onLoad ) onLoad( texture ); + setPath: function ( value ) { - } + this.path = value; + return this; - }, undefined, onError ); + } - } + } ); - for ( var i = 0; i < urls.length; ++ i ) { + /** + * @author mrdoob / http://mrdoob.com/ + */ - loadTexture( i ); + function CubeTextureLoader( manager ) { - } + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; - return texture; + } - }, + Object.assign( CubeTextureLoader.prototype, { - setCrossOrigin: function ( value ) { + load: function ( urls, onLoad, onProgress, onError ) { - this.crossOrigin = value; - return this; + var texture = new CubeTexture(); - }, + var loader = new ImageLoader( this.manager ); + loader.setCrossOrigin( this.crossOrigin ); + loader.setPath( this.path ); - setPath: function ( value ) { + var loaded = 0; - this.path = value; - return this; + function loadTexture( i ) { - } + loader.load( urls[ i ], function ( image ) { - } ); + texture.images[ i ] = image; - /** - * @author mrdoob / http://mrdoob.com/ - */ + loaded ++; - function TextureLoader( manager ) { + if ( loaded === 6 ) { - this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; + texture.needsUpdate = true; - }; + if ( onLoad ) onLoad( texture ); - Object.assign( TextureLoader.prototype, { + } - load: function ( url, onLoad, onProgress, onError ) { + }, undefined, onError ); - var texture = new Texture(); + } - var loader = new ImageLoader( this.manager ); - loader.setCrossOrigin( this.crossOrigin ); - loader.setWithCredentials( this.withCredentials ); - loader.setPath( this.path ); - loader.load( url, function ( image ) { + for ( var i = 0; i < urls.length; ++ i ) { - // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB. - var isJPEG = url.search( /\.(jpg|jpeg)$/ ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0; + loadTexture( i ); - texture.format = isJPEG ? RGBFormat : RGBAFormat; - texture.image = image; - texture.needsUpdate = true; + } - if ( onLoad !== undefined ) { + return texture; - onLoad( texture ); + }, - } + setCrossOrigin: function ( value ) { - }, onProgress, onError ); + this.crossOrigin = value; + return this; - return texture; + }, - }, + setPath: function ( value ) { - setCrossOrigin: function ( value ) { + this.path = value; + return this; - this.crossOrigin = value; - return this; + } - }, + } ); - setWithCredentials: function ( value ) { + /** + * @author mrdoob / http://mrdoob.com/ + */ - this.withCredentials = value; - return this; + function TextureLoader( manager ) { - }, + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; - setPath: function ( value ) { + } - this.path = value; - return this; + Object.assign( TextureLoader.prototype, { - } + load: function ( url, onLoad, onProgress, onError ) { + var texture = new Texture(); + var loader = new ImageLoader( this.manager ); + loader.setCrossOrigin( this.crossOrigin ); + loader.setWithCredentials( this.withCredentials ); + loader.setPath( this.path ); + loader.load( url, function ( image ) { - } ); + // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB. + var isJPEG = url.search( /\.(jpg|jpeg)$/ ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0; - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + texture.format = isJPEG ? RGBFormat : RGBAFormat; + texture.image = image; + texture.needsUpdate = true; - function Light( color, intensity ) { + if ( onLoad !== undefined ) { - Object3D.call( this ); + onLoad( texture ); - this.type = 'Light'; + } - this.color = new Color( color ); - this.intensity = intensity !== undefined ? intensity : 1; + }, onProgress, onError ); - this.receiveShadow = undefined; + return texture; - }; + }, - Light.prototype = Object.assign( Object.create( Object3D.prototype ), { + setCrossOrigin: function ( value ) { - constructor: Light, + this.crossOrigin = value; + return this; - isLight: true, + }, - copy: function ( source ) { + setWithCredentials: function ( value ) { - Object3D.prototype.copy.call( this, source ); + this.withCredentials = value; + return this; - this.color.copy( source.color ); - this.intensity = source.intensity; + }, - return this; + setPath: function ( value ) { - }, + this.path = value; + return this; - toJSON: function ( meta ) { + } - var data = Object3D.prototype.toJSON.call( this, meta ); - data.object.color = this.color.getHex(); - data.object.intensity = this.intensity; - if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex(); + } ); - if ( this.distance !== undefined ) data.object.distance = this.distance; - if ( this.angle !== undefined ) data.object.angle = this.angle; - if ( this.decay !== undefined ) data.object.decay = this.decay; - if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra; + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - return data; + function Light( color, intensity ) { - } + Object3D.call( this ); - } ); + this.type = 'Light'; - /** - * @author alteredq / http://alteredqualia.com/ - */ + this.color = new Color( color ); + this.intensity = intensity !== undefined ? intensity : 1; - function HemisphereLight( skyColor, groundColor, intensity ) { + this.receiveShadow = undefined; - Light.call( this, skyColor, intensity ); + } - this.type = 'HemisphereLight'; + Light.prototype = Object.assign( Object.create( Object3D.prototype ), { - this.castShadow = undefined; + constructor: Light, - this.position.copy( Object3D.DefaultUp ); - this.updateMatrix(); + isLight: true, - this.groundColor = new Color( groundColor ); + copy: function ( source ) { - }; + Object3D.prototype.copy.call( this, source ); - HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), { + this.color.copy( source.color ); + this.intensity = source.intensity; - constructor: HemisphereLight, + return this; - isHemisphereLight: true, + }, - copy: function ( source ) { + toJSON: function ( meta ) { - Light.prototype.copy.call( this, source ); + var data = Object3D.prototype.toJSON.call( this, meta ); - this.groundColor.copy( source.groundColor ); + data.object.color = this.color.getHex(); + data.object.intensity = this.intensity; - return this; + if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex(); - } + if ( this.distance !== undefined ) data.object.distance = this.distance; + if ( this.angle !== undefined ) data.object.angle = this.angle; + if ( this.decay !== undefined ) data.object.decay = this.decay; + if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra; - } ); + if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON(); - /** - * @author mrdoob / http://mrdoob.com/ - */ + return data; - function LightShadow( camera ) { + } - this.camera = camera; + } ); - this.bias = 0; - this.radius = 1; + /** + * @author alteredq / http://alteredqualia.com/ + */ - this.mapSize = new Vector2( 512, 512 ); + function HemisphereLight( skyColor, groundColor, intensity ) { - this.map = null; - this.matrix = new Matrix4(); + Light.call( this, skyColor, intensity ); - }; + this.type = 'HemisphereLight'; - Object.assign( LightShadow.prototype, { + this.castShadow = undefined; - copy: function ( source ) { + this.position.copy( Object3D.DefaultUp ); + this.updateMatrix(); - this.camera = source.camera.clone(); + this.groundColor = new Color( groundColor ); - this.bias = source.bias; - this.radius = source.radius; + } - this.mapSize.copy( source.mapSize ); + HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), { - return this; + constructor: HemisphereLight, - }, + isHemisphereLight: true, - clone: function () { + copy: function ( source ) { - return new this.constructor().copy( this ); + Light.prototype.copy.call( this, source ); - } + this.groundColor.copy( source.groundColor ); - } ); + return this; - /** - * @author mrdoob / http://mrdoob.com/ - */ + } - function SpotLightShadow() { + } ); - LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) ); + /** + * @author mrdoob / http://mrdoob.com/ + */ - }; + function LightShadow( camera ) { - SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), { + this.camera = camera; - constructor: SpotLightShadow, + this.bias = 0; + this.radius = 1; - isSpotLightShadow: true, + this.mapSize = new Vector2( 512, 512 ); - update: function ( light ) { + this.map = null; + this.matrix = new Matrix4(); - var fov = exports.Math.RAD2DEG * 2 * light.angle; - var aspect = this.mapSize.width / this.mapSize.height; - var far = light.distance || 500; + } - var camera = this.camera; + Object.assign( LightShadow.prototype, { - if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) { + copy: function ( source ) { - camera.fov = fov; - camera.aspect = aspect; - camera.far = far; - camera.updateProjectionMatrix(); + this.camera = source.camera.clone(); - } + this.bias = source.bias; + this.radius = source.radius; - } + this.mapSize.copy( source.mapSize ); - } ); + return this; - /** - * @author alteredq / http://alteredqualia.com/ - */ + }, - function SpotLight( color, intensity, distance, angle, penumbra, decay ) { + clone: function () { - Light.call( this, color, intensity ); + return new this.constructor().copy( this ); - this.type = 'SpotLight'; + }, - this.position.copy( Object3D.DefaultUp ); - this.updateMatrix(); + toJSON: function () { - this.target = new Object3D(); + var object = {}; - Object.defineProperty( this, 'power', { - get: function () { - // intensity = power per solid angle. - // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf - return this.intensity * Math.PI; - }, - set: function ( power ) { - // intensity = power per solid angle. - // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf - this.intensity = power / Math.PI; - } - } ); + if ( this.bias !== 0 ) object.bias = this.bias; + if ( this.radius !== 1 ) object.radius = this.radius; + if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray(); - this.distance = ( distance !== undefined ) ? distance : 0; - this.angle = ( angle !== undefined ) ? angle : Math.PI / 3; - this.penumbra = ( penumbra !== undefined ) ? penumbra : 0; - this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2. + object.camera = this.camera.toJSON( false ).object; + delete object.camera.matrix; - this.shadow = new SpotLightShadow(); + return object; - }; + } - SpotLight.prototype = Object.assign( Object.create( Light.prototype ), { + } ); - constructor: SpotLight, + /** + * @author mrdoob / http://mrdoob.com/ + */ - isSpotLight: true, + function SpotLightShadow() { - copy: function ( source ) { + LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) ); - Light.prototype.copy.call( this, source ); + } - this.distance = source.distance; - this.angle = source.angle; - this.penumbra = source.penumbra; - this.decay = source.decay; + SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), { - this.target = source.target.clone(); + constructor: SpotLightShadow, - this.shadow = source.shadow.clone(); + isSpotLightShadow: true, - return this; + update: function ( light ) { - } + var fov = exports.Math.RAD2DEG * 2 * light.angle; + var aspect = this.mapSize.width / this.mapSize.height; + var far = light.distance || 500; - } ); + var camera = this.camera; - /** - * @author mrdoob / http://mrdoob.com/ - */ + if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) { + camera.fov = fov; + camera.aspect = aspect; + camera.far = far; + camera.updateProjectionMatrix(); - function PointLight( color, intensity, distance, decay ) { + } - Light.call( this, color, intensity ); + } - this.type = 'PointLight'; + } ); - Object.defineProperty( this, 'power', { - get: function () { - // intensity = power per solid angle. - // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf - return this.intensity * 4 * Math.PI; + /** + * @author alteredq / http://alteredqualia.com/ + */ - }, - set: function ( power ) { - // intensity = power per solid angle. - // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf - this.intensity = power / ( 4 * Math.PI ); - } - } ); + function SpotLight( color, intensity, distance, angle, penumbra, decay ) { - this.distance = ( distance !== undefined ) ? distance : 0; - this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2. + Light.call( this, color, intensity ); - this.shadow = new LightShadow( new PerspectiveCamera( 90, 1, 0.5, 500 ) ); + this.type = 'SpotLight'; - }; + this.position.copy( Object3D.DefaultUp ); + this.updateMatrix(); - PointLight.prototype = Object.assign( Object.create( Light.prototype ), { + this.target = new Object3D(); - constructor: PointLight, + Object.defineProperty( this, 'power', { + get: function () { + // intensity = power per solid angle. + // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf + return this.intensity * Math.PI; + }, + set: function ( power ) { + // intensity = power per solid angle. + // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf + this.intensity = power / Math.PI; + } + } ); - isPointLight: true, + this.distance = ( distance !== undefined ) ? distance : 0; + this.angle = ( angle !== undefined ) ? angle : Math.PI / 3; + this.penumbra = ( penumbra !== undefined ) ? penumbra : 0; + this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2. - copy: function ( source ) { + this.shadow = new SpotLightShadow(); - Light.prototype.copy.call( this, source ); + } - this.distance = source.distance; - this.decay = source.decay; + SpotLight.prototype = Object.assign( Object.create( Light.prototype ), { - this.shadow = source.shadow.clone(); + constructor: SpotLight, - return this; + isSpotLight: true, - } + copy: function ( source ) { - } ); + Light.prototype.copy.call( this, source ); - /** - * @author mrdoob / http://mrdoob.com/ - */ + this.distance = source.distance; + this.angle = source.angle; + this.penumbra = source.penumbra; + this.decay = source.decay; - function DirectionalLightShadow( light ) { + this.target = source.target.clone(); - LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) ); + this.shadow = source.shadow.clone(); - }; + return this; - DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), { + } - constructor: DirectionalLightShadow + } ); - } ); + /** + * @author mrdoob / http://mrdoob.com/ + */ - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ - function DirectionalLight( color, intensity ) { + function PointLight( color, intensity, distance, decay ) { - Light.call( this, color, intensity ); + Light.call( this, color, intensity ); - this.type = 'DirectionalLight'; + this.type = 'PointLight'; - this.position.copy( Object3D.DefaultUp ); - this.updateMatrix(); + Object.defineProperty( this, 'power', { + get: function () { + // intensity = power per solid angle. + // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf + return this.intensity * 4 * Math.PI; - this.target = new Object3D(); + }, + set: function ( power ) { + // intensity = power per solid angle. + // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf + this.intensity = power / ( 4 * Math.PI ); + } + } ); - this.shadow = new DirectionalLightShadow(); + this.distance = ( distance !== undefined ) ? distance : 0; + this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2. - }; + this.shadow = new LightShadow( new PerspectiveCamera( 90, 1, 0.5, 500 ) ); - DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), { + } - constructor: DirectionalLight, + PointLight.prototype = Object.assign( Object.create( Light.prototype ), { - isDirectionalLight: true, + constructor: PointLight, - copy: function ( source ) { + isPointLight: true, - Light.prototype.copy.call( this, source ); + copy: function ( source ) { - this.target = source.target.clone(); + Light.prototype.copy.call( this, source ); - this.shadow = source.shadow.clone(); + this.distance = source.distance; + this.decay = source.decay; - return this; + this.shadow = source.shadow.clone(); - } + return this; - } ); + } - /** - * @author mrdoob / http://mrdoob.com/ - */ + } ); - function AmbientLight( color, intensity ) { + /** + * @author mrdoob / http://mrdoob.com/ + */ - Light.call( this, color, intensity ); + function DirectionalLightShadow( light ) { - this.type = 'AmbientLight'; + LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) ); - this.castShadow = undefined; + } - }; + DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), { - AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), { + constructor: DirectionalLightShadow - constructor: AmbientLight, + } ); - isAmbientLight: true, + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - } ); + function DirectionalLight( color, intensity ) { - /** - * @author tschw - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - */ + Light.call( this, color, intensity ); - exports.AnimationUtils = { + this.type = 'DirectionalLight'; - // same as Array.prototype.slice, but also works on typed arrays - arraySlice: function( array, from, to ) { + this.position.copy( Object3D.DefaultUp ); + this.updateMatrix(); - if ( exports.AnimationUtils.isTypedArray( array ) ) { + this.target = new Object3D(); - return new array.constructor( array.subarray( from, to ) ); + this.shadow = new DirectionalLightShadow(); - } + } - return array.slice( from, to ); + DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), { - }, + constructor: DirectionalLight, - // converts an array to a specific type - convertArray: function( array, type, forceClone ) { + isDirectionalLight: true, - if ( ! array || // let 'undefined' and 'null' pass - ! forceClone && array.constructor === type ) return array; + copy: function ( source ) { - if ( typeof type.BYTES_PER_ELEMENT === 'number' ) { + Light.prototype.copy.call( this, source ); - return new type( array ); // create typed array + this.target = source.target.clone(); - } + this.shadow = source.shadow.clone(); - return Array.prototype.slice.call( array ); // create Array + return this; - }, + } - isTypedArray: function( object ) { + } ); - return ArrayBuffer.isView( object ) && - ! ( object instanceof DataView ); + /** + * @author mrdoob / http://mrdoob.com/ + */ - }, + function AmbientLight( color, intensity ) { - // returns an array by which times and values can be sorted - getKeyframeOrder: function( times ) { + Light.call( this, color, intensity ); - function compareTime( i, j ) { + this.type = 'AmbientLight'; - return times[ i ] - times[ j ]; + this.castShadow = undefined; - } + } - var n = times.length; - var result = new Array( n ); - for ( var i = 0; i !== n; ++ i ) result[ i ] = i; + AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), { - result.sort( compareTime ); + constructor: AmbientLight, - return result; + isAmbientLight: true, - }, + } ); - // uses the array previously returned by 'getKeyframeOrder' to sort data - sortedArray: function( values, stride, order ) { + /** + * @author tschw + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + */ - var nValues = values.length; - var result = new values.constructor( nValues ); + exports.AnimationUtils = { - for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) { + // same as Array.prototype.slice, but also works on typed arrays + arraySlice: function( array, from, to ) { - var srcOffset = order[ i ] * stride; + if ( exports.AnimationUtils.isTypedArray( array ) ) { - for ( var j = 0; j !== stride; ++ j ) { + return new array.constructor( array.subarray( from, to ) ); - result[ dstOffset ++ ] = values[ srcOffset + j ]; + } - } + return array.slice( from, to ); - } + }, - return result; + // converts an array to a specific type + convertArray: function( array, type, forceClone ) { - }, + if ( ! array || // let 'undefined' and 'null' pass + ! forceClone && array.constructor === type ) return array; - // function for parsing AOS keyframe formats - flattenJSON: function( jsonKeys, times, values, valuePropertyName ) { + if ( typeof type.BYTES_PER_ELEMENT === 'number' ) { - var i = 1, key = jsonKeys[ 0 ]; + return new type( array ); // create typed array - while ( key !== undefined && key[ valuePropertyName ] === undefined ) { + } - key = jsonKeys[ i ++ ]; + return Array.prototype.slice.call( array ); // create Array - } + }, - if ( key === undefined ) return; // no data + isTypedArray: function( object ) { - var value = key[ valuePropertyName ]; - if ( value === undefined ) return; // no data + return ArrayBuffer.isView( object ) && + ! ( object instanceof DataView ); - if ( Array.isArray( value ) ) { + }, - do { + // returns an array by which times and values can be sorted + getKeyframeOrder: function( times ) { - value = key[ valuePropertyName ]; + function compareTime( i, j ) { - if ( value !== undefined ) { + return times[ i ] - times[ j ]; - times.push( key.time ); - values.push.apply( values, value ); // push all elements + } - } + var n = times.length; + var result = new Array( n ); + for ( var i = 0; i !== n; ++ i ) result[ i ] = i; - key = jsonKeys[ i ++ ]; + result.sort( compareTime ); - } while ( key !== undefined ); + return result; - } else if ( value.toArray !== undefined ) { - // ...assume THREE.Math-ish + }, - do { + // uses the array previously returned by 'getKeyframeOrder' to sort data + sortedArray: function( values, stride, order ) { - value = key[ valuePropertyName ]; + var nValues = values.length; + var result = new values.constructor( nValues ); - if ( value !== undefined ) { + for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) { - times.push( key.time ); - value.toArray( values, values.length ); + var srcOffset = order[ i ] * stride; - } + for ( var j = 0; j !== stride; ++ j ) { - key = jsonKeys[ i ++ ]; + result[ dstOffset ++ ] = values[ srcOffset + j ]; - } while ( key !== undefined ); + } - } else { - // otherwise push as-is + } - do { + return result; - value = key[ valuePropertyName ]; + }, - if ( value !== undefined ) { + // function for parsing AOS keyframe formats + flattenJSON: function( jsonKeys, times, values, valuePropertyName ) { - times.push( key.time ); - values.push( value ); + var i = 1, key = jsonKeys[ 0 ]; - } + while ( key !== undefined && key[ valuePropertyName ] === undefined ) { - key = jsonKeys[ i ++ ]; + key = jsonKeys[ i ++ ]; - } while ( key !== undefined ); + } - } + if ( key === undefined ) return; // no data - } + var value = key[ valuePropertyName ]; + if ( value === undefined ) return; // no data - }; + if ( Array.isArray( value ) ) { - /** - * Abstract base class of interpolants over parametric samples. - * - * The parameter domain is one dimensional, typically the time or a path - * along a curve defined by the data. - * - * The sample values can have any dimensionality and derived classes may - * apply special interpretations to the data. - * - * This class provides the interval seek in a Template Method, deferring - * the actual interpolation to derived classes. - * - * Time complexity is O(1) for linear access crossing at most two points - * and O(log N) for random access, where N is the number of positions. - * - * References: - * - * http://www.oodesign.com/template-method-pattern.html - * - * @author tschw - */ + do { - function Interpolant( - parameterPositions, sampleValues, sampleSize, resultBuffer ) { + value = key[ valuePropertyName ]; - this.parameterPositions = parameterPositions; - this._cachedIndex = 0; + if ( value !== undefined ) { - this.resultBuffer = resultBuffer !== undefined ? - resultBuffer : new sampleValues.constructor( sampleSize ); - this.sampleValues = sampleValues; - this.valueSize = sampleSize; + times.push( key.time ); + values.push.apply( values, value ); // push all elements - }; + } - Interpolant.prototype = { + key = jsonKeys[ i ++ ]; - constructor: Interpolant, + } while ( key !== undefined ); - evaluate: function( t ) { + } else if ( value.toArray !== undefined ) { + // ...assume THREE.Math-ish - var pp = this.parameterPositions, - i1 = this._cachedIndex, + do { - t1 = pp[ i1 ], - t0 = pp[ i1 - 1 ]; + value = key[ valuePropertyName ]; - validate_interval: { + if ( value !== undefined ) { - seek: { + times.push( key.time ); + value.toArray( values, values.length ); - var right; + } - linear_scan: { - //- See http://jsperf.com/comparison-to-undefined/3 - //- slower code: - //- - //- if ( t >= t1 || t1 === undefined ) { - forward_scan: if ( ! ( t < t1 ) ) { + key = jsonKeys[ i ++ ]; - for ( var giveUpAt = i1 + 2; ;) { + } while ( key !== undefined ); - if ( t1 === undefined ) { + } else { + // otherwise push as-is - if ( t < t0 ) break forward_scan; + do { - // after end + value = key[ valuePropertyName ]; - i1 = pp.length; - this._cachedIndex = i1; - return this.afterEnd_( i1 - 1, t, t0 ); + if ( value !== undefined ) { - } + times.push( key.time ); + values.push( value ); - if ( i1 === giveUpAt ) break; // this loop + } - t0 = t1; - t1 = pp[ ++ i1 ]; + key = jsonKeys[ i ++ ]; - if ( t < t1 ) { + } while ( key !== undefined ); - // we have arrived at the sought interval - break seek; + } - } + } - } + }; - // prepare binary search on the right side of the index - right = pp.length; - break linear_scan; + /** + * Abstract base class of interpolants over parametric samples. + * + * The parameter domain is one dimensional, typically the time or a path + * along a curve defined by the data. + * + * The sample values can have any dimensionality and derived classes may + * apply special interpretations to the data. + * + * This class provides the interval seek in a Template Method, deferring + * the actual interpolation to derived classes. + * + * Time complexity is O(1) for linear access crossing at most two points + * and O(log N) for random access, where N is the number of positions. + * + * References: + * + * http://www.oodesign.com/template-method-pattern.html + * + * @author tschw + */ + + function Interpolant( + parameterPositions, sampleValues, sampleSize, resultBuffer ) { + + this.parameterPositions = parameterPositions; + this._cachedIndex = 0; + + this.resultBuffer = resultBuffer !== undefined ? + resultBuffer : new sampleValues.constructor( sampleSize ); + this.sampleValues = sampleValues; + this.valueSize = sampleSize; - } + } - //- slower code: - //- if ( t < t0 || t0 === undefined ) { - if ( ! ( t >= t0 ) ) { + Interpolant.prototype = { - // looping? + constructor: Interpolant, - var t1global = pp[ 1 ]; + evaluate: function( t ) { - if ( t < t1global ) { + var pp = this.parameterPositions, + i1 = this._cachedIndex, - i1 = 2; // + 1, using the scan for the details - t0 = t1global; + t1 = pp[ i1 ], + t0 = pp[ i1 - 1 ]; - } + validate_interval: { - // linear reverse scan + seek: { - for ( var giveUpAt = i1 - 2; ;) { + var right; - if ( t0 === undefined ) { + linear_scan: { + //- See http://jsperf.com/comparison-to-undefined/3 + //- slower code: + //- + //- if ( t >= t1 || t1 === undefined ) { + forward_scan: if ( ! ( t < t1 ) ) { - // before start + for ( var giveUpAt = i1 + 2; ;) { - this._cachedIndex = 0; - return this.beforeStart_( 0, t, t1 ); + if ( t1 === undefined ) { - } + if ( t < t0 ) break forward_scan; - if ( i1 === giveUpAt ) break; // this loop + // after end - t1 = t0; - t0 = pp[ -- i1 - 1 ]; + i1 = pp.length; + this._cachedIndex = i1; + return this.afterEnd_( i1 - 1, t, t0 ); - if ( t >= t0 ) { + } - // we have arrived at the sought interval - break seek; + if ( i1 === giveUpAt ) break; // this loop - } + t0 = t1; + t1 = pp[ ++ i1 ]; - } + if ( t < t1 ) { - // prepare binary search on the left side of the index - right = i1; - i1 = 0; - break linear_scan; + // we have arrived at the sought interval + break seek; - } + } - // the interval is valid + } - break validate_interval; + // prepare binary search on the right side of the index + right = pp.length; + break linear_scan; - } // linear scan + } - // binary search + //- slower code: + //- if ( t < t0 || t0 === undefined ) { + if ( ! ( t >= t0 ) ) { - while ( i1 < right ) { + // looping? - var mid = ( i1 + right ) >>> 1; + var t1global = pp[ 1 ]; - if ( t < pp[ mid ] ) { + if ( t < t1global ) { - right = mid; + i1 = 2; // + 1, using the scan for the details + t0 = t1global; - } else { + } - i1 = mid + 1; + // linear reverse scan - } + for ( var giveUpAt = i1 - 2; ;) { - } + if ( t0 === undefined ) { - t1 = pp[ i1 ]; - t0 = pp[ i1 - 1 ]; + // before start - // check boundary cases, again + this._cachedIndex = 0; + return this.beforeStart_( 0, t, t1 ); - if ( t0 === undefined ) { + } - this._cachedIndex = 0; - return this.beforeStart_( 0, t, t1 ); + if ( i1 === giveUpAt ) break; // this loop - } + t1 = t0; + t0 = pp[ -- i1 - 1 ]; - if ( t1 === undefined ) { + if ( t >= t0 ) { - i1 = pp.length; - this._cachedIndex = i1; - return this.afterEnd_( i1 - 1, t0, t ); + // we have arrived at the sought interval + break seek; - } + } - } // seek + } - this._cachedIndex = i1; + // prepare binary search on the left side of the index + right = i1; + i1 = 0; + break linear_scan; - this.intervalChanged_( i1, t0, t1 ); + } - } // validate_interval + // the interval is valid - return this.interpolate_( i1, t0, t, t1 ); + break validate_interval; - }, + } // linear scan - settings: null, // optional, subclass-specific settings structure - // Note: The indirection allows central control of many interpolants. + // binary search - // --- Protected interface + while ( i1 < right ) { - DefaultSettings_: {}, + var mid = ( i1 + right ) >>> 1; - getSettings_: function() { + if ( t < pp[ mid ] ) { - return this.settings || this.DefaultSettings_; + right = mid; - }, + } else { - copySampleValue_: function( index ) { + i1 = mid + 1; - // copies a sample value to the result buffer + } - var result = this.resultBuffer, - values = this.sampleValues, - stride = this.valueSize, - offset = index * stride; + } - for ( var i = 0; i !== stride; ++ i ) { + t1 = pp[ i1 ]; + t0 = pp[ i1 - 1 ]; - result[ i ] = values[ offset + i ]; + // check boundary cases, again - } + if ( t0 === undefined ) { - return result; + this._cachedIndex = 0; + return this.beforeStart_( 0, t, t1 ); - }, + } - // Template methods for derived classes: + if ( t1 === undefined ) { - interpolate_: function( i1, t0, t, t1 ) { + i1 = pp.length; + this._cachedIndex = i1; + return this.afterEnd_( i1 - 1, t0, t ); - throw new Error( "call to abstract method" ); - // implementations shall return this.resultBuffer + } - }, + } // seek - intervalChanged_: function( i1, t0, t1 ) { + this._cachedIndex = i1; - // empty + this.intervalChanged_( i1, t0, t1 ); - } + } // validate_interval - }; + return this.interpolate_( i1, t0, t, t1 ); - Object.assign( Interpolant.prototype, { + }, - beforeStart_: //( 0, t, t0 ), returns this.resultBuffer - Interpolant.prototype.copySampleValue_, + settings: null, // optional, subclass-specific settings structure + // Note: The indirection allows central control of many interpolants. - afterEnd_: //( N-1, tN-1, t ), returns this.resultBuffer - Interpolant.prototype.copySampleValue_ + // --- Protected interface - } ); + DefaultSettings_: {}, - /** - * Fast and simple cubic spline interpolant. - * - * It was derived from a Hermitian construction setting the first derivative - * at each sample position to the linear slope between neighboring positions - * over their parameter interval. - * - * @author tschw - */ + getSettings_: function() { - function CubicInterpolant( - parameterPositions, sampleValues, sampleSize, resultBuffer ) { + return this.settings || this.DefaultSettings_; - Interpolant.call( - this, parameterPositions, sampleValues, sampleSize, resultBuffer ); + }, - this._weightPrev = -0; - this._offsetPrev = -0; - this._weightNext = -0; - this._offsetNext = -0; + copySampleValue_: function( index ) { - }; + // copies a sample value to the result buffer - CubicInterpolant.prototype = - Object.assign( Object.create( Interpolant.prototype ), { + var result = this.resultBuffer, + values = this.sampleValues, + stride = this.valueSize, + offset = index * stride; - constructor: CubicInterpolant, + for ( var i = 0; i !== stride; ++ i ) { - DefaultSettings_: { + result[ i ] = values[ offset + i ]; - endingStart: ZeroCurvatureEnding, - endingEnd: ZeroCurvatureEnding + } - }, + return result; - intervalChanged_: function( i1, t0, t1 ) { + }, - var pp = this.parameterPositions, - iPrev = i1 - 2, - iNext = i1 + 1, + // Template methods for derived classes: - tPrev = pp[ iPrev ], - tNext = pp[ iNext ]; + interpolate_: function( i1, t0, t, t1 ) { - if ( tPrev === undefined ) { + throw new Error( "call to abstract method" ); + // implementations shall return this.resultBuffer - switch ( this.getSettings_().endingStart ) { + }, - case ZeroSlopeEnding: + intervalChanged_: function( i1, t0, t1 ) { - // f'(t0) = 0 - iPrev = i1; - tPrev = 2 * t0 - t1; + // empty - break; + } - case WrapAroundEnding: + }; - // use the other end of the curve - iPrev = pp.length - 2; - tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ]; + Object.assign( Interpolant.prototype, { - break; + beforeStart_: //( 0, t, t0 ), returns this.resultBuffer + Interpolant.prototype.copySampleValue_, - default: // ZeroCurvatureEnding + afterEnd_: //( N-1, tN-1, t ), returns this.resultBuffer + Interpolant.prototype.copySampleValue_ - // f''(t0) = 0 a.k.a. Natural Spline - iPrev = i1; - tPrev = t1; + } ); - } + /** + * Fast and simple cubic spline interpolant. + * + * It was derived from a Hermitian construction setting the first derivative + * at each sample position to the linear slope between neighboring positions + * over their parameter interval. + * + * @author tschw + */ - } + function CubicInterpolant( + parameterPositions, sampleValues, sampleSize, resultBuffer ) { - if ( tNext === undefined ) { + Interpolant.call( + this, parameterPositions, sampleValues, sampleSize, resultBuffer ); - switch ( this.getSettings_().endingEnd ) { + this._weightPrev = -0; + this._offsetPrev = -0; + this._weightNext = -0; + this._offsetNext = -0; - case ZeroSlopeEnding: + } - // f'(tN) = 0 - iNext = i1; - tNext = 2 * t1 - t0; + CubicInterpolant.prototype = + Object.assign( Object.create( Interpolant.prototype ), { - break; + constructor: CubicInterpolant, - case WrapAroundEnding: + DefaultSettings_: { - // use the other end of the curve - iNext = 1; - tNext = t1 + pp[ 1 ] - pp[ 0 ]; + endingStart: ZeroCurvatureEnding, + endingEnd: ZeroCurvatureEnding - break; + }, - default: // ZeroCurvatureEnding + intervalChanged_: function( i1, t0, t1 ) { - // f''(tN) = 0, a.k.a. Natural Spline - iNext = i1 - 1; - tNext = t0; + var pp = this.parameterPositions, + iPrev = i1 - 2, + iNext = i1 + 1, - } + tPrev = pp[ iPrev ], + tNext = pp[ iNext ]; - } + if ( tPrev === undefined ) { - var halfDt = ( t1 - t0 ) * 0.5, - stride = this.valueSize; + switch ( this.getSettings_().endingStart ) { - this._weightPrev = halfDt / ( t0 - tPrev ); - this._weightNext = halfDt / ( tNext - t1 ); - this._offsetPrev = iPrev * stride; - this._offsetNext = iNext * stride; + case ZeroSlopeEnding: - }, + // f'(t0) = 0 + iPrev = i1; + tPrev = 2 * t0 - t1; - interpolate_: function( i1, t0, t, t1 ) { + break; - var result = this.resultBuffer, - values = this.sampleValues, - stride = this.valueSize, + case WrapAroundEnding: - o1 = i1 * stride, o0 = o1 - stride, - oP = this._offsetPrev, oN = this._offsetNext, - wP = this._weightPrev, wN = this._weightNext, + // use the other end of the curve + iPrev = pp.length - 2; + tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ]; - p = ( t - t0 ) / ( t1 - t0 ), - pp = p * p, - ppp = pp * p; + break; - // evaluate polynomials + default: // ZeroCurvatureEnding - var sP = - wP * ppp + 2 * wP * pp - wP * p; - var s0 = ( 1 + wP ) * ppp + (-1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1; - var s1 = (-1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p; - var sN = wN * ppp - wN * pp; + // f''(t0) = 0 a.k.a. Natural Spline + iPrev = i1; + tPrev = t1; - // combine data linearly + } - for ( var i = 0; i !== stride; ++ i ) { + } - result[ i ] = - sP * values[ oP + i ] + - s0 * values[ o0 + i ] + - s1 * values[ o1 + i ] + - sN * values[ oN + i ]; + if ( tNext === undefined ) { - } + switch ( this.getSettings_().endingEnd ) { - return result; + case ZeroSlopeEnding: - } + // f'(tN) = 0 + iNext = i1; + tNext = 2 * t1 - t0; - } ); + break; - /** - * @author tschw - */ + case WrapAroundEnding: - function LinearInterpolant( - parameterPositions, sampleValues, sampleSize, resultBuffer ) { + // use the other end of the curve + iNext = 1; + tNext = t1 + pp[ 1 ] - pp[ 0 ]; - Interpolant.call( - this, parameterPositions, sampleValues, sampleSize, resultBuffer ); + break; - }; + default: // ZeroCurvatureEnding - LinearInterpolant.prototype = - Object.assign( Object.create( Interpolant.prototype ), { + // f''(tN) = 0, a.k.a. Natural Spline + iNext = i1 - 1; + tNext = t0; - constructor: LinearInterpolant, + } - interpolate_: function( i1, t0, t, t1 ) { + } - var result = this.resultBuffer, - values = this.sampleValues, - stride = this.valueSize, + var halfDt = ( t1 - t0 ) * 0.5, + stride = this.valueSize; - offset1 = i1 * stride, - offset0 = offset1 - stride, + this._weightPrev = halfDt / ( t0 - tPrev ); + this._weightNext = halfDt / ( tNext - t1 ); + this._offsetPrev = iPrev * stride; + this._offsetNext = iNext * stride; - weight1 = ( t - t0 ) / ( t1 - t0 ), - weight0 = 1 - weight1; + }, - for ( var i = 0; i !== stride; ++ i ) { + interpolate_: function( i1, t0, t, t1 ) { - result[ i ] = - values[ offset0 + i ] * weight0 + - values[ offset1 + i ] * weight1; + var result = this.resultBuffer, + values = this.sampleValues, + stride = this.valueSize, - } + o1 = i1 * stride, o0 = o1 - stride, + oP = this._offsetPrev, oN = this._offsetNext, + wP = this._weightPrev, wN = this._weightNext, - return result; + p = ( t - t0 ) / ( t1 - t0 ), + pp = p * p, + ppp = pp * p; - } + // evaluate polynomials - } ); + var sP = - wP * ppp + 2 * wP * pp - wP * p; + var s0 = ( 1 + wP ) * ppp + (-1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1; + var s1 = (-1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p; + var sN = wN * ppp - wN * pp; - /** - * - * Interpolant that evaluates to the sample value at the position preceeding - * the parameter. - * - * @author tschw - */ + // combine data linearly - function DiscreteInterpolant( - parameterPositions, sampleValues, sampleSize, resultBuffer ) { + for ( var i = 0; i !== stride; ++ i ) { - Interpolant.call( - this, parameterPositions, sampleValues, sampleSize, resultBuffer ); + result[ i ] = + sP * values[ oP + i ] + + s0 * values[ o0 + i ] + + s1 * values[ o1 + i ] + + sN * values[ oN + i ]; - }; + } - DiscreteInterpolant.prototype = - Object.assign( Object.create( Interpolant.prototype ), { + return result; - constructor: DiscreteInterpolant, + } - interpolate_: function( i1, t0, t, t1 ) { + } ); - return this.copySampleValue_( i1 - 1 ); + /** + * @author tschw + */ - } + function LinearInterpolant( + parameterPositions, sampleValues, sampleSize, resultBuffer ) { - } ); + Interpolant.call( + this, parameterPositions, sampleValues, sampleSize, resultBuffer ); - var KeyframeTrackPrototype; + } - KeyframeTrackPrototype = { + LinearInterpolant.prototype = + Object.assign( Object.create( Interpolant.prototype ), { - TimeBufferType: Float32Array, - ValueBufferType: Float32Array, + constructor: LinearInterpolant, - DefaultInterpolation: InterpolateLinear, + interpolate_: function( i1, t0, t, t1 ) { - InterpolantFactoryMethodDiscrete: function( result ) { + var result = this.resultBuffer, + values = this.sampleValues, + stride = this.valueSize, - return new DiscreteInterpolant( - this.times, this.values, this.getValueSize(), result ); + offset1 = i1 * stride, + offset0 = offset1 - stride, - }, + weight1 = ( t - t0 ) / ( t1 - t0 ), + weight0 = 1 - weight1; - InterpolantFactoryMethodLinear: function( result ) { + for ( var i = 0; i !== stride; ++ i ) { - return new LinearInterpolant( - this.times, this.values, this.getValueSize(), result ); + result[ i ] = + values[ offset0 + i ] * weight0 + + values[ offset1 + i ] * weight1; - }, + } - InterpolantFactoryMethodSmooth: function( result ) { + return result; - return new CubicInterpolant( - this.times, this.values, this.getValueSize(), result ); + } - }, + } ); - setInterpolation: function( interpolation ) { + /** + * + * Interpolant that evaluates to the sample value at the position preceeding + * the parameter. + * + * @author tschw + */ - var factoryMethod; + function DiscreteInterpolant( + parameterPositions, sampleValues, sampleSize, resultBuffer ) { - switch ( interpolation ) { + Interpolant.call( + this, parameterPositions, sampleValues, sampleSize, resultBuffer ); - case InterpolateDiscrete: + } - factoryMethod = this.InterpolantFactoryMethodDiscrete; + DiscreteInterpolant.prototype = + Object.assign( Object.create( Interpolant.prototype ), { - break; + constructor: DiscreteInterpolant, - case InterpolateLinear: + interpolate_: function( i1, t0, t, t1 ) { - factoryMethod = this.InterpolantFactoryMethodLinear; + return this.copySampleValue_( i1 - 1 ); - break; + } - case InterpolateSmooth: + } ); - factoryMethod = this.InterpolantFactoryMethodSmooth; + var KeyframeTrackPrototype; - break; + KeyframeTrackPrototype = { - } + TimeBufferType: Float32Array, + ValueBufferType: Float32Array, - if ( factoryMethod === undefined ) { + DefaultInterpolation: InterpolateLinear, - var message = "unsupported interpolation for " + - this.ValueTypeName + " keyframe track named " + this.name; + InterpolantFactoryMethodDiscrete: function( result ) { - if ( this.createInterpolant === undefined ) { + return new DiscreteInterpolant( + this.times, this.values, this.getValueSize(), result ); - // fall back to default, unless the default itself is messed up - if ( interpolation !== this.DefaultInterpolation ) { + }, - this.setInterpolation( this.DefaultInterpolation ); + InterpolantFactoryMethodLinear: function( result ) { - } else { + return new LinearInterpolant( + this.times, this.values, this.getValueSize(), result ); - throw new Error( message ); // fatal, in this case + }, - } + InterpolantFactoryMethodSmooth: function( result ) { - } + return new CubicInterpolant( + this.times, this.values, this.getValueSize(), result ); - console.warn( message ); - return; + }, - } + setInterpolation: function( interpolation ) { - this.createInterpolant = factoryMethod; + var factoryMethod; - }, + switch ( interpolation ) { - getInterpolation: function() { + case InterpolateDiscrete: - switch ( this.createInterpolant ) { + factoryMethod = this.InterpolantFactoryMethodDiscrete; - case this.InterpolantFactoryMethodDiscrete: + break; - return InterpolateDiscrete; + case InterpolateLinear: - case this.InterpolantFactoryMethodLinear: + factoryMethod = this.InterpolantFactoryMethodLinear; - return InterpolateLinear; + break; - case this.InterpolantFactoryMethodSmooth: + case InterpolateSmooth: - return InterpolateSmooth; + factoryMethod = this.InterpolantFactoryMethodSmooth; - } + break; - }, + } - getValueSize: function() { + if ( factoryMethod === undefined ) { - return this.values.length / this.times.length; + var message = "unsupported interpolation for " + + this.ValueTypeName + " keyframe track named " + this.name; - }, + if ( this.createInterpolant === undefined ) { - // move all keyframes either forwards or backwards in time - shift: function( timeOffset ) { + // fall back to default, unless the default itself is messed up + if ( interpolation !== this.DefaultInterpolation ) { - if( timeOffset !== 0.0 ) { + this.setInterpolation( this.DefaultInterpolation ); - var times = this.times; + } else { - for( var i = 0, n = times.length; i !== n; ++ i ) { + throw new Error( message ); // fatal, in this case - times[ i ] += timeOffset; + } - } + } - } + console.warn( message ); + return; - return this; + } - }, + this.createInterpolant = factoryMethod; - // scale all keyframe times by a factor (useful for frame <-> seconds conversions) - scale: function( timeScale ) { + }, - if( timeScale !== 1.0 ) { + getInterpolation: function() { - var times = this.times; + switch ( this.createInterpolant ) { - for( var i = 0, n = times.length; i !== n; ++ i ) { + case this.InterpolantFactoryMethodDiscrete: - times[ i ] *= timeScale; + return InterpolateDiscrete; - } + case this.InterpolantFactoryMethodLinear: - } + return InterpolateLinear; - return this; + case this.InterpolantFactoryMethodSmooth: - }, + return InterpolateSmooth; - // removes keyframes before and after animation without changing any values within the range [startTime, endTime]. - // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values - trim: function( startTime, endTime ) { + } - var times = this.times, - nKeys = times.length, - from = 0, - to = nKeys - 1; + }, - while ( from !== nKeys && times[ from ] < startTime ) ++ from; - while ( to !== -1 && times[ to ] > endTime ) -- to; + getValueSize: function() { - ++ to; // inclusive -> exclusive bound + return this.values.length / this.times.length; - if( from !== 0 || to !== nKeys ) { + }, - // empty tracks are forbidden, so keep at least one keyframe - if ( from >= to ) to = Math.max( to , 1 ), from = to - 1; + // move all keyframes either forwards or backwards in time + shift: function( timeOffset ) { - var stride = this.getValueSize(); - this.times = exports.AnimationUtils.arraySlice( times, from, to ); - this.values = exports.AnimationUtils. - arraySlice( this.values, from * stride, to * stride ); + if( timeOffset !== 0.0 ) { - } + var times = this.times; - return this; + for( var i = 0, n = times.length; i !== n; ++ i ) { - }, + times[ i ] += timeOffset; - // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable - validate: function() { + } - var valid = true; + } - var valueSize = this.getValueSize(); - if ( valueSize - Math.floor( valueSize ) !== 0 ) { + return this; - console.error( "invalid value size in track", this ); - valid = false; + }, - } + // scale all keyframe times by a factor (useful for frame <-> seconds conversions) + scale: function( timeScale ) { - var times = this.times, - values = this.values, + if( timeScale !== 1.0 ) { - nKeys = times.length; + var times = this.times; - if( nKeys === 0 ) { + for( var i = 0, n = times.length; i !== n; ++ i ) { - console.error( "track is empty", this ); - valid = false; + times[ i ] *= timeScale; - } + } - var prevTime = null; + } - for( var i = 0; i !== nKeys; i ++ ) { + return this; - var currTime = times[ i ]; + }, - if ( typeof currTime === 'number' && isNaN( currTime ) ) { + // removes keyframes before and after animation without changing any values within the range [startTime, endTime]. + // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values + trim: function( startTime, endTime ) { - console.error( "time is not a valid number", this, i, currTime ); - valid = false; - break; + var times = this.times, + nKeys = times.length, + from = 0, + to = nKeys - 1; - } + while ( from !== nKeys && times[ from ] < startTime ) ++ from; + while ( to !== -1 && times[ to ] > endTime ) -- to; - if( prevTime !== null && prevTime > currTime ) { + ++ to; // inclusive -> exclusive bound - console.error( "out of order keys", this, i, currTime, prevTime ); - valid = false; - break; + if( from !== 0 || to !== nKeys ) { - } + // empty tracks are forbidden, so keep at least one keyframe + if ( from >= to ) to = Math.max( to , 1 ), from = to - 1; - prevTime = currTime; + var stride = this.getValueSize(); + this.times = exports.AnimationUtils.arraySlice( times, from, to ); + this.values = exports.AnimationUtils. + arraySlice( this.values, from * stride, to * stride ); - } + } - if ( values !== undefined ) { + return this; - if ( exports.AnimationUtils.isTypedArray( values ) ) { + }, - for ( var i = 0, n = values.length; i !== n; ++ i ) { + // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable + validate: function() { - var value = values[ i ]; + var valid = true; - if ( isNaN( value ) ) { + var valueSize = this.getValueSize(); + if ( valueSize - Math.floor( valueSize ) !== 0 ) { - console.error( "value is not a valid number", this, i, value ); - valid = false; - break; + console.error( "invalid value size in track", this ); + valid = false; - } + } - } + var times = this.times, + values = this.values, - } + nKeys = times.length; - } + if( nKeys === 0 ) { - return valid; + console.error( "track is empty", this ); + valid = false; - }, + } - // removes equivalent sequential keys as common in morph target sequences - // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0) - optimize: function() { + var prevTime = null; - var times = this.times, - values = this.values, - stride = this.getValueSize(), + for( var i = 0; i !== nKeys; i ++ ) { - writeIndex = 1; + var currTime = times[ i ]; - for( var i = 1, n = times.length - 1; i <= n; ++ i ) { + if ( typeof currTime === 'number' && isNaN( currTime ) ) { - var keep = false; + console.error( "time is not a valid number", this, i, currTime ); + valid = false; + break; - var time = times[ i ]; - var timeNext = times[ i + 1 ]; + } - // remove adjacent keyframes scheduled at the same time + if( prevTime !== null && prevTime > currTime ) { - if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) { + console.error( "out of order keys", this, i, currTime, prevTime ); + valid = false; + break; - // remove unnecessary keyframes same as their neighbors - var offset = i * stride, - offsetP = offset - stride, - offsetN = offset + stride; + } - for ( var j = 0; j !== stride; ++ j ) { + prevTime = currTime; - var value = values[ offset + j ]; + } - if ( value !== values[ offsetP + j ] || - value !== values[ offsetN + j ] ) { + if ( values !== undefined ) { - keep = true; - break; + if ( exports.AnimationUtils.isTypedArray( values ) ) { - } + for ( var i = 0, n = values.length; i !== n; ++ i ) { - } + var value = values[ i ]; - } + if ( isNaN( value ) ) { - // in-place compaction + console.error( "value is not a valid number", this, i, value ); + valid = false; + break; - if ( keep ) { + } - if ( i !== writeIndex ) { + } - times[ writeIndex ] = times[ i ]; + } - var readOffset = i * stride, - writeOffset = writeIndex * stride; + } - for ( var j = 0; j !== stride; ++ j ) { + return valid; - values[ writeOffset + j ] = values[ readOffset + j ]; + }, - } + // removes equivalent sequential keys as common in morph target sequences + // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0) + optimize: function() { + var times = this.times, + values = this.values, + stride = this.getValueSize(), - } + writeIndex = 1; - ++ writeIndex; + for( var i = 1, n = times.length - 1; i <= n; ++ i ) { - } + var keep = false; - } + var time = times[ i ]; + var timeNext = times[ i + 1 ]; - if ( writeIndex !== times.length ) { + // remove adjacent keyframes scheduled at the same time - this.times = exports.AnimationUtils.arraySlice( times, 0, writeIndex ); - this.values = exports.AnimationUtils.arraySlice( values, 0, writeIndex * stride ); + if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) { - } + // remove unnecessary keyframes same as their neighbors + var offset = i * stride, + offsetP = offset - stride, + offsetN = offset + stride; - return this; + for ( var j = 0; j !== stride; ++ j ) { - } + var value = values[ offset + j ]; - } + if ( value !== values[ offsetP + j ] || + value !== values[ offsetN + j ] ) { - function KeyframeTrackConstructor( name, times, values, interpolation ) { + keep = true; + break; - if( name === undefined ) throw new Error( "track name is undefined" ); + } - if( times === undefined || times.length === 0 ) { + } - throw new Error( "no keyframes in track named " + name ); + } - } + // in-place compaction - this.name = name; + if ( keep ) { - this.times = exports.AnimationUtils.convertArray( times, this.TimeBufferType ); - this.values = exports.AnimationUtils.convertArray( values, this.ValueBufferType ); + if ( i !== writeIndex ) { - this.setInterpolation( interpolation || this.DefaultInterpolation ); + times[ writeIndex ] = times[ i ]; - this.validate(); - this.optimize(); + var readOffset = i * stride, + writeOffset = writeIndex * stride; - } + for ( var j = 0; j !== stride; ++ j ) { - /** - * - * A Track of vectored keyframe values. - * - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + values[ writeOffset + j ] = values[ readOffset + j ]; - function VectorKeyframeTrack( name, times, values, interpolation ) { + } - KeyframeTrackConstructor.call( this, name, times, values, interpolation ); - }; + } - VectorKeyframeTrack.prototype = - Object.assign( Object.create( KeyframeTrackPrototype ), { + ++ writeIndex; - constructor: VectorKeyframeTrack, + } - ValueTypeName: 'vector' + } - // ValueBufferType is inherited + if ( writeIndex !== times.length ) { - // DefaultInterpolation is inherited + this.times = exports.AnimationUtils.arraySlice( times, 0, writeIndex ); + this.values = exports.AnimationUtils.arraySlice( values, 0, writeIndex * stride ); - } ); + } - /** - * Spherical linear unit quaternion interpolant. - * - * @author tschw - */ + return this; - function QuaternionLinearInterpolant( - parameterPositions, sampleValues, sampleSize, resultBuffer ) { + } - Interpolant.call( - this, parameterPositions, sampleValues, sampleSize, resultBuffer ); + } - }; + function KeyframeTrackConstructor( name, times, values, interpolation ) { - QuaternionLinearInterpolant.prototype = - Object.assign( Object.create( Interpolant.prototype ), { + if( name === undefined ) throw new Error( "track name is undefined" ); - constructor: QuaternionLinearInterpolant, + if( times === undefined || times.length === 0 ) { - interpolate_: function( i1, t0, t, t1 ) { + throw new Error( "no keyframes in track named " + name ); - var result = this.resultBuffer, - values = this.sampleValues, - stride = this.valueSize, + } - offset = i1 * stride, + this.name = name; - alpha = ( t - t0 ) / ( t1 - t0 ); + this.times = exports.AnimationUtils.convertArray( times, this.TimeBufferType ); + this.values = exports.AnimationUtils.convertArray( values, this.ValueBufferType ); - for ( var end = offset + stride; offset !== end; offset += 4 ) { + this.setInterpolation( interpolation || this.DefaultInterpolation ); - Quaternion.slerpFlat( result, 0, - values, offset - stride, values, offset, alpha ); + this.validate(); + this.optimize(); - } + } - return result; + /** + * + * A Track of vectored keyframe values. + * + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - } + function VectorKeyframeTrack( name, times, values, interpolation ) { - } ); + KeyframeTrackConstructor.call( this, name, times, values, interpolation ); - /** - * - * A Track of quaternion keyframe values. - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + } - function QuaternionKeyframeTrack( name, times, values, interpolation ) { + VectorKeyframeTrack.prototype = + Object.assign( Object.create( KeyframeTrackPrototype ), { - KeyframeTrackConstructor.call( this, name, times, values, interpolation ); + constructor: VectorKeyframeTrack, - }; + ValueTypeName: 'vector' - QuaternionKeyframeTrack.prototype = - Object.assign( Object.create( KeyframeTrackPrototype ), { + // ValueBufferType is inherited - constructor: QuaternionKeyframeTrack, + // DefaultInterpolation is inherited - ValueTypeName: 'quaternion', + } ); - // ValueBufferType is inherited + /** + * Spherical linear unit quaternion interpolant. + * + * @author tschw + */ - DefaultInterpolation: InterpolateLinear, + function QuaternionLinearInterpolant( + parameterPositions, sampleValues, sampleSize, resultBuffer ) { - InterpolantFactoryMethodLinear: function( result ) { + Interpolant.call( + this, parameterPositions, sampleValues, sampleSize, resultBuffer ); - return new QuaternionLinearInterpolant( - this.times, this.values, this.getValueSize(), result ); + } - }, + QuaternionLinearInterpolant.prototype = + Object.assign( Object.create( Interpolant.prototype ), { - InterpolantFactoryMethodSmooth: undefined // not yet implemented + constructor: QuaternionLinearInterpolant, - } ); + interpolate_: function( i1, t0, t, t1 ) { - /** - * - * A Track of numeric keyframe values. - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + var result = this.resultBuffer, + values = this.sampleValues, + stride = this.valueSize, - function NumberKeyframeTrack( name, times, values, interpolation ) { + offset = i1 * stride, - KeyframeTrackConstructor.call( this, name, times, values, interpolation ); + alpha = ( t - t0 ) / ( t1 - t0 ); - }; + for ( var end = offset + stride; offset !== end; offset += 4 ) { - NumberKeyframeTrack.prototype = - Object.assign( Object.create( KeyframeTrackPrototype ), { + Quaternion.slerpFlat( result, 0, + values, offset - stride, values, offset, alpha ); - constructor: NumberKeyframeTrack, + } - ValueTypeName: 'number', + return result; - // ValueBufferType is inherited + } - // DefaultInterpolation is inherited + } ); - } ); + /** + * + * A Track of quaternion keyframe values. + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - /** - * - * A Track that interpolates Strings - * - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + function QuaternionKeyframeTrack( name, times, values, interpolation ) { - function StringKeyframeTrack( name, times, values, interpolation ) { + KeyframeTrackConstructor.call( this, name, times, values, interpolation ); - KeyframeTrackConstructor.call( this, name, times, values, interpolation ); + } - }; + QuaternionKeyframeTrack.prototype = + Object.assign( Object.create( KeyframeTrackPrototype ), { - StringKeyframeTrack.prototype = - Object.assign( Object.create( KeyframeTrackPrototype ), { + constructor: QuaternionKeyframeTrack, - constructor: StringKeyframeTrack, + ValueTypeName: 'quaternion', - ValueTypeName: 'string', - ValueBufferType: Array, + // ValueBufferType is inherited - DefaultInterpolation: InterpolateDiscrete, + DefaultInterpolation: InterpolateLinear, - InterpolantFactoryMethodLinear: undefined, + InterpolantFactoryMethodLinear: function( result ) { - InterpolantFactoryMethodSmooth: undefined + return new QuaternionLinearInterpolant( + this.times, this.values, this.getValueSize(), result ); - } ); + }, - /** - * - * A Track of Boolean keyframe values. - * - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + InterpolantFactoryMethodSmooth: undefined // not yet implemented - function BooleanKeyframeTrack( name, times, values ) { + } ); - KeyframeTrackConstructor.call( this, name, times, values ); + /** + * + * A Track of numeric keyframe values. + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - }; + function NumberKeyframeTrack( name, times, values, interpolation ) { - BooleanKeyframeTrack.prototype = - Object.assign( Object.create( KeyframeTrackPrototype ), { + KeyframeTrackConstructor.call( this, name, times, values, interpolation ); - constructor: BooleanKeyframeTrack, + } - ValueTypeName: 'bool', - ValueBufferType: Array, + NumberKeyframeTrack.prototype = + Object.assign( Object.create( KeyframeTrackPrototype ), { - DefaultInterpolation: InterpolateDiscrete, + constructor: NumberKeyframeTrack, - InterpolantFactoryMethodLinear: undefined, - InterpolantFactoryMethodSmooth: undefined + ValueTypeName: 'number', - // Note: Actually this track could have a optimized / compressed - // representation of a single value and a custom interpolant that - // computes "firstValue ^ isOdd( index )". + // ValueBufferType is inherited - } ); + // DefaultInterpolation is inherited - /** - * - * A Track of keyframe values that represent color. - * - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + } ); - function ColorKeyframeTrack( name, times, values, interpolation ) { + /** + * + * A Track that interpolates Strings + * + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - KeyframeTrackConstructor.call( this, name, times, values, interpolation ); + function StringKeyframeTrack( name, times, values, interpolation ) { - }; + KeyframeTrackConstructor.call( this, name, times, values, interpolation ); - ColorKeyframeTrack.prototype = - Object.assign( Object.create( KeyframeTrackPrototype ), { + } - constructor: ColorKeyframeTrack, + StringKeyframeTrack.prototype = + Object.assign( Object.create( KeyframeTrackPrototype ), { - ValueTypeName: 'color' + constructor: StringKeyframeTrack, - // ValueBufferType is inherited + ValueTypeName: 'string', + ValueBufferType: Array, - // DefaultInterpolation is inherited + DefaultInterpolation: InterpolateDiscrete, + InterpolantFactoryMethodLinear: undefined, - // Note: Very basic implementation and nothing special yet. - // However, this is the place for color space parameterization. + InterpolantFactoryMethodSmooth: undefined - } ); + } ); - /** - * - * A timed sequence of keyframes for a specific property. - * - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + /** + * + * A Track of Boolean keyframe values. + * + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - function KeyframeTrack( name, times, values, interpolation ) { - KeyframeTrackConstructor.apply( this, arguments ); - }; + function BooleanKeyframeTrack( name, times, values ) { - KeyframeTrack.prototype = KeyframeTrackPrototype; - KeyframeTrackPrototype.constructor = KeyframeTrack; + KeyframeTrackConstructor.call( this, name, times, values ); - // Static methods: + } - Object.assign( KeyframeTrack, { + BooleanKeyframeTrack.prototype = + Object.assign( Object.create( KeyframeTrackPrototype ), { - // Serialization (in static context, because of constructor invocation - // and automatic invocation of .toJSON): + constructor: BooleanKeyframeTrack, - parse: function( json ) { + ValueTypeName: 'bool', + ValueBufferType: Array, - if( json.type === undefined ) { + DefaultInterpolation: InterpolateDiscrete, - throw new Error( "track type undefined, can not parse" ); + InterpolantFactoryMethodLinear: undefined, + InterpolantFactoryMethodSmooth: undefined - } + // Note: Actually this track could have a optimized / compressed + // representation of a single value and a custom interpolant that + // computes "firstValue ^ isOdd( index )". - var trackType = KeyframeTrack._getTrackTypeForValueTypeName( json.type ); + } ); - if ( json.times === undefined ) { + /** + * + * A Track of keyframe values that represent color. + * + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - var times = [], values = []; + function ColorKeyframeTrack( name, times, values, interpolation ) { - exports.AnimationUtils.flattenJSON( json.keys, times, values, 'value' ); + KeyframeTrackConstructor.call( this, name, times, values, interpolation ); - json.times = times; - json.values = values; + } - } + ColorKeyframeTrack.prototype = + Object.assign( Object.create( KeyframeTrackPrototype ), { - // derived classes can define a static parse method - if ( trackType.parse !== undefined ) { + constructor: ColorKeyframeTrack, - return trackType.parse( json ); + ValueTypeName: 'color' - } else { + // ValueBufferType is inherited - // by default, we asssume a constructor compatible with the base - return new trackType( - json.name, json.times, json.values, json.interpolation ); + // DefaultInterpolation is inherited - } - }, + // Note: Very basic implementation and nothing special yet. + // However, this is the place for color space parameterization. - toJSON: function( track ) { + } ); - var trackType = track.constructor; + /** + * + * A timed sequence of keyframes for a specific property. + * + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - var json; + function KeyframeTrack( name, times, values, interpolation ) { - // derived classes can define a static toJSON method - if ( trackType.toJSON !== undefined ) { + KeyframeTrackConstructor.apply( this, arguments ); - json = trackType.toJSON( track ); + } - } else { + KeyframeTrack.prototype = KeyframeTrackPrototype; + KeyframeTrackPrototype.constructor = KeyframeTrack; - // by default, we assume the data can be serialized as-is - json = { + // Static methods: - 'name': track.name, - 'times': exports.AnimationUtils.convertArray( track.times, Array ), - 'values': exports.AnimationUtils.convertArray( track.values, Array ) + Object.assign( KeyframeTrack, { - }; + // Serialization (in static context, because of constructor invocation + // and automatic invocation of .toJSON): - var interpolation = track.getInterpolation(); + parse: function( json ) { - if ( interpolation !== track.DefaultInterpolation ) { + if( json.type === undefined ) { - json.interpolation = interpolation; + throw new Error( "track type undefined, can not parse" ); - } + } - } + var trackType = KeyframeTrack._getTrackTypeForValueTypeName( json.type ); - json.type = track.ValueTypeName; // mandatory + if ( json.times === undefined ) { - return json; + var times = [], values = []; - }, + exports.AnimationUtils.flattenJSON( json.keys, times, values, 'value' ); - _getTrackTypeForValueTypeName: function( typeName ) { + json.times = times; + json.values = values; - switch( typeName.toLowerCase() ) { + } - case "scalar": - case "double": - case "float": - case "number": - case "integer": + // derived classes can define a static parse method + if ( trackType.parse !== undefined ) { - return NumberKeyframeTrack; + return trackType.parse( json ); - case "vector": - case "vector2": - case "vector3": - case "vector4": + } else { - return VectorKeyframeTrack; + // by default, we asssume a constructor compatible with the base + return new trackType( + json.name, json.times, json.values, json.interpolation ); - case "color": + } - return ColorKeyframeTrack; + }, - case "quaternion": + toJSON: function( track ) { - return QuaternionKeyframeTrack; + var trackType = track.constructor; - case "bool": - case "boolean": + var json; - return BooleanKeyframeTrack; + // derived classes can define a static toJSON method + if ( trackType.toJSON !== undefined ) { - case "string": + json = trackType.toJSON( track ); - return StringKeyframeTrack; + } else { - } + // by default, we assume the data can be serialized as-is + json = { - throw new Error( "Unsupported typeName: " + typeName ); + 'name': track.name, + 'times': exports.AnimationUtils.convertArray( track.times, Array ), + 'values': exports.AnimationUtils.convertArray( track.values, Array ) - } + }; - } ); + var interpolation = track.getInterpolation(); - /** - * - * Reusable set of Tracks that represent an animation. - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - */ + if ( interpolation !== track.DefaultInterpolation ) { - function AnimationClip( name, duration, tracks ) { + json.interpolation = interpolation; - this.name = name; - this.tracks = tracks; - this.duration = ( duration !== undefined ) ? duration : -1; + } - this.uuid = exports.Math.generateUUID(); + } - // this means it should figure out its duration by scanning the tracks - if ( this.duration < 0 ) { + json.type = track.ValueTypeName; // mandatory - this.resetDuration(); + return json; - } + }, - // maybe only do these on demand, as doing them here could potentially slow down loading - // but leaving these here during development as this ensures a lot of testing of these functions - this.trim(); - this.optimize(); + _getTrackTypeForValueTypeName: function( typeName ) { - }; + switch( typeName.toLowerCase() ) { - AnimationClip.prototype = { + case "scalar": + case "double": + case "float": + case "number": + case "integer": - constructor: AnimationClip, + return NumberKeyframeTrack; - resetDuration: function() { + case "vector": + case "vector2": + case "vector3": + case "vector4": - var tracks = this.tracks, - duration = 0; + return VectorKeyframeTrack; - for ( var i = 0, n = tracks.length; i !== n; ++ i ) { + case "color": - var track = this.tracks[ i ]; + return ColorKeyframeTrack; - duration = Math.max( - duration, track.times[ track.times.length - 1 ] ); + case "quaternion": - } + return QuaternionKeyframeTrack; - this.duration = duration; + case "bool": + case "boolean": - }, + return BooleanKeyframeTrack; - trim: function() { + case "string": - for ( var i = 0; i < this.tracks.length; i ++ ) { + return StringKeyframeTrack; - this.tracks[ i ].trim( 0, this.duration ); + } - } + throw new Error( "Unsupported typeName: " + typeName ); - return this; + } - }, + } ); - optimize: function() { + /** + * + * Reusable set of Tracks that represent an animation. + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + */ - for ( var i = 0; i < this.tracks.length; i ++ ) { + function AnimationClip( name, duration, tracks ) { - this.tracks[ i ].optimize(); + this.name = name; + this.tracks = tracks; + this.duration = ( duration !== undefined ) ? duration : -1; - } + this.uuid = exports.Math.generateUUID(); - return this; + // this means it should figure out its duration by scanning the tracks + if ( this.duration < 0 ) { - } + this.resetDuration(); - }; + } - // Static methods: + // maybe only do these on demand, as doing them here could potentially slow down loading + // but leaving these here during development as this ensures a lot of testing of these functions + this.trim(); + this.optimize(); - Object.assign( AnimationClip, { + } - parse: function( json ) { + AnimationClip.prototype = { - var tracks = [], - jsonTracks = json.tracks, - frameTime = 1.0 / ( json.fps || 1.0 ); + constructor: AnimationClip, - for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) { + resetDuration: function() { - tracks.push( KeyframeTrack.parse( jsonTracks[ i ] ).scale( frameTime ) ); + var tracks = this.tracks, + duration = 0; - } + for ( var i = 0, n = tracks.length; i !== n; ++ i ) { - return new AnimationClip( json.name, json.duration, tracks ); + var track = this.tracks[ i ]; - }, + duration = Math.max( + duration, track.times[ track.times.length - 1 ] ); + } - toJSON: function( clip ) { + this.duration = duration; - var tracks = [], - clipTracks = clip.tracks; + }, - var json = { + trim: function() { - 'name': clip.name, - 'duration': clip.duration, - 'tracks': tracks + for ( var i = 0; i < this.tracks.length; i ++ ) { - }; + this.tracks[ i ].trim( 0, this.duration ); - for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) { + } - tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) ); + return this; - } + }, - return json; + optimize: function() { - }, + for ( var i = 0; i < this.tracks.length; i ++ ) { + this.tracks[ i ].optimize(); - CreateFromMorphTargetSequence: function( name, morphTargetSequence, fps, noLoop ) { + } - var numMorphTargets = morphTargetSequence.length; - var tracks = []; + return this; - for ( var i = 0; i < numMorphTargets; i ++ ) { + } - var times = []; - var values = []; + }; - times.push( - ( i + numMorphTargets - 1 ) % numMorphTargets, - i, - ( i + 1 ) % numMorphTargets ); + // Static methods: - values.push( 0, 1, 0 ); + Object.assign( AnimationClip, { - var order = exports.AnimationUtils.getKeyframeOrder( times ); - times = exports.AnimationUtils.sortedArray( times, 1, order ); - values = exports.AnimationUtils.sortedArray( values, 1, order ); + parse: function( json ) { - // if there is a key at the first frame, duplicate it as the - // last frame as well for perfect loop. - if ( ! noLoop && times[ 0 ] === 0 ) { + var tracks = [], + jsonTracks = json.tracks, + frameTime = 1.0 / ( json.fps || 1.0 ); - times.push( numMorphTargets ); - values.push( values[ 0 ] ); + for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) { - } + tracks.push( KeyframeTrack.parse( jsonTracks[ i ] ).scale( frameTime ) ); - tracks.push( - new NumberKeyframeTrack( - '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']', - times, values - ).scale( 1.0 / fps ) ); - } + } - return new AnimationClip( name, -1, tracks ); + return new AnimationClip( json.name, json.duration, tracks ); - }, + }, - findByName: function( objectOrClipArray, name ) { - var clipArray = objectOrClipArray; + toJSON: function( clip ) { - if ( ! Array.isArray( objectOrClipArray ) ) { + var tracks = [], + clipTracks = clip.tracks; - var o = objectOrClipArray; - clipArray = o.geometry && o.geometry.animations || o.animations; + var json = { - } + 'name': clip.name, + 'duration': clip.duration, + 'tracks': tracks - for ( var i = 0; i < clipArray.length; i ++ ) { + }; - if ( clipArray[ i ].name === name ) { + for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) { - return clipArray[ i ]; + tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) ); - } - } + } - return null; + return json; - }, + }, - CreateClipsFromMorphTargetSequences: function( morphTargets, fps, noLoop ) { - var animationToMorphTargets = {}; + CreateFromMorphTargetSequence: function( name, morphTargetSequence, fps, noLoop ) { - // tested with https://regex101.com/ on trick sequences - // such flamingo_flyA_003, flamingo_run1_003, crdeath0059 - var pattern = /^([\w-]*?)([\d]+)$/; + var numMorphTargets = morphTargetSequence.length; + var tracks = []; - // sort morph target names into animation groups based - // patterns like Walk_001, Walk_002, Run_001, Run_002 - for ( var i = 0, il = morphTargets.length; i < il; i ++ ) { + for ( var i = 0; i < numMorphTargets; i ++ ) { - var morphTarget = morphTargets[ i ]; - var parts = morphTarget.name.match( pattern ); + var times = []; + var values = []; - if ( parts && parts.length > 1 ) { + times.push( + ( i + numMorphTargets - 1 ) % numMorphTargets, + i, + ( i + 1 ) % numMorphTargets ); - var name = parts[ 1 ]; + values.push( 0, 1, 0 ); - var animationMorphTargets = animationToMorphTargets[ name ]; - if ( ! animationMorphTargets ) { + var order = exports.AnimationUtils.getKeyframeOrder( times ); + times = exports.AnimationUtils.sortedArray( times, 1, order ); + values = exports.AnimationUtils.sortedArray( values, 1, order ); - animationToMorphTargets[ name ] = animationMorphTargets = []; + // if there is a key at the first frame, duplicate it as the + // last frame as well for perfect loop. + if ( ! noLoop && times[ 0 ] === 0 ) { - } + times.push( numMorphTargets ); + values.push( values[ 0 ] ); - animationMorphTargets.push( morphTarget ); + } - } + tracks.push( + new NumberKeyframeTrack( + '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']', + times, values + ).scale( 1.0 / fps ) ); + } - } + return new AnimationClip( name, -1, tracks ); - var clips = []; + }, - for ( var name in animationToMorphTargets ) { + findByName: function( objectOrClipArray, name ) { - clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) ); + var clipArray = objectOrClipArray; - } + if ( ! Array.isArray( objectOrClipArray ) ) { - return clips; + var o = objectOrClipArray; + clipArray = o.geometry && o.geometry.animations || o.animations; - }, + } - // parse the animation.hierarchy format - parseAnimation: function( animation, bones, nodeName ) { + for ( var i = 0; i < clipArray.length; i ++ ) { - if ( ! animation ) { + if ( clipArray[ i ].name === name ) { - console.error( " no animation in JSONLoader data" ); - return null; + return clipArray[ i ]; - } + } + } - var addNonemptyTrack = function( - trackType, trackName, animationKeys, propertyName, destTracks ) { + return null; - // only return track if there are actually keys. - if ( animationKeys.length !== 0 ) { + }, - var times = []; - var values = []; + CreateClipsFromMorphTargetSequences: function( morphTargets, fps, noLoop ) { - exports.AnimationUtils.flattenJSON( - animationKeys, times, values, propertyName ); + var animationToMorphTargets = {}; - // empty keys are filtered out, so check again - if ( times.length !== 0 ) { + // tested with https://regex101.com/ on trick sequences + // such flamingo_flyA_003, flamingo_run1_003, crdeath0059 + var pattern = /^([\w-]*?)([\d]+)$/; - destTracks.push( new trackType( trackName, times, values ) ); + // sort morph target names into animation groups based + // patterns like Walk_001, Walk_002, Run_001, Run_002 + for ( var i = 0, il = morphTargets.length; i < il; i ++ ) { - } + var morphTarget = morphTargets[ i ]; + var parts = morphTarget.name.match( pattern ); - } + if ( parts && parts.length > 1 ) { - }; + var name = parts[ 1 ]; - var tracks = []; + var animationMorphTargets = animationToMorphTargets[ name ]; + if ( ! animationMorphTargets ) { - var clipName = animation.name || 'default'; - // automatic length determination in AnimationClip. - var duration = animation.length || -1; - var fps = animation.fps || 30; + animationToMorphTargets[ name ] = animationMorphTargets = []; - var hierarchyTracks = animation.hierarchy || []; + } - for ( var h = 0; h < hierarchyTracks.length; h ++ ) { + animationMorphTargets.push( morphTarget ); - var animationKeys = hierarchyTracks[ h ].keys; + } - // skip empty tracks - if ( ! animationKeys || animationKeys.length === 0 ) continue; + } - // process morph targets in a way exactly compatible - // with AnimationHandler.init( animation ) - if ( animationKeys[0].morphTargets ) { + var clips = []; - // figure out all morph targets used in this track - var morphTargetNames = {}; - for ( var k = 0; k < animationKeys.length; k ++ ) { + for ( var name in animationToMorphTargets ) { - if ( animationKeys[k].morphTargets ) { + clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) ); - for ( var m = 0; m < animationKeys[k].morphTargets.length; m ++ ) { + } - morphTargetNames[ animationKeys[k].morphTargets[m] ] = -1; - } + return clips; - } + }, - } + // parse the animation.hierarchy format + parseAnimation: function( animation, bones, nodeName ) { - // create a track for each morph target with all zero - // morphTargetInfluences except for the keys in which - // the morphTarget is named. - for ( var morphTargetName in morphTargetNames ) { + if ( ! animation ) { - var times = []; - var values = []; + console.error( " no animation in JSONLoader data" ); + return null; - for ( var m = 0; - m !== animationKeys[k].morphTargets.length; ++ m ) { + } - var animationKey = animationKeys[k]; + var addNonemptyTrack = function( + trackType, trackName, animationKeys, propertyName, destTracks ) { - times.push( animationKey.time ); - values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 ); + // only return track if there are actually keys. + if ( animationKeys.length !== 0 ) { - } + var times = []; + var values = []; - tracks.push( new NumberKeyframeTrack( - '.morphTargetInfluence[' + morphTargetName + ']', times, values ) ); + exports.AnimationUtils.flattenJSON( + animationKeys, times, values, propertyName ); - } + // empty keys are filtered out, so check again + if ( times.length !== 0 ) { - duration = morphTargetNames.length * ( fps || 1.0 ); + destTracks.push( new trackType( trackName, times, values ) ); - } else { - // ...assume skeletal animation + } - var boneName = '.bones[' + bones[ h ].name + ']'; + } - addNonemptyTrack( - VectorKeyframeTrack, boneName + '.position', - animationKeys, 'pos', tracks ); + }; - addNonemptyTrack( - QuaternionKeyframeTrack, boneName + '.quaternion', - animationKeys, 'rot', tracks ); + var tracks = []; - addNonemptyTrack( - VectorKeyframeTrack, boneName + '.scale', - animationKeys, 'scl', tracks ); + var clipName = animation.name || 'default'; + // automatic length determination in AnimationClip. + var duration = animation.length || -1; + var fps = animation.fps || 30; - } + var hierarchyTracks = animation.hierarchy || []; - } + for ( var h = 0; h < hierarchyTracks.length; h ++ ) { - if ( tracks.length === 0 ) { + var animationKeys = hierarchyTracks[ h ].keys; - return null; + // skip empty tracks + if ( ! animationKeys || animationKeys.length === 0 ) continue; - } + // process morph targets in a way exactly compatible + // with AnimationHandler.init( animation ) + if ( animationKeys[0].morphTargets ) { - var clip = new AnimationClip( clipName, duration, tracks ); + // figure out all morph targets used in this track + var morphTargetNames = {}; + for ( var k = 0; k < animationKeys.length; k ++ ) { - return clip; + if ( animationKeys[k].morphTargets ) { - } + for ( var m = 0; m < animationKeys[k].morphTargets.length; m ++ ) { - } ); + morphTargetNames[ animationKeys[k].morphTargets[m] ] = -1; + } - /** - * @author mrdoob / http://mrdoob.com/ - */ + } - function MaterialLoader( manager ) { + } - this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; - this.textures = {}; + // create a track for each morph target with all zero + // morphTargetInfluences except for the keys in which + // the morphTarget is named. + for ( var morphTargetName in morphTargetNames ) { - }; + var times = []; + var values = []; - Object.assign( MaterialLoader.prototype, { + for ( var m = 0; + m !== animationKeys[k].morphTargets.length; ++ m ) { - load: function ( url, onLoad, onProgress, onError ) { + var animationKey = animationKeys[k]; - var scope = this; + times.push( animationKey.time ); + values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 ); - var loader = new XHRLoader( scope.manager ); - loader.load( url, function ( text ) { + } - onLoad( scope.parse( JSON.parse( text ) ) ); + tracks.push( new NumberKeyframeTrack( + '.morphTargetInfluence[' + morphTargetName + ']', times, values ) ); - }, onProgress, onError ); + } - }, + duration = morphTargetNames.length * ( fps || 1.0 ); - setTextures: function ( value ) { + } else { + // ...assume skeletal animation - this.textures = value; + var boneName = '.bones[' + bones[ h ].name + ']'; - }, + addNonemptyTrack( + VectorKeyframeTrack, boneName + '.position', + animationKeys, 'pos', tracks ); - getTexture: function ( name ) { + addNonemptyTrack( + QuaternionKeyframeTrack, boneName + '.quaternion', + animationKeys, 'rot', tracks ); - var textures = this.textures; + addNonemptyTrack( + VectorKeyframeTrack, boneName + '.scale', + animationKeys, 'scl', tracks ); - if ( textures[ name ] === undefined ) { + } - console.warn( 'THREE.MaterialLoader: Undefined texture', name ); + } - } + if ( tracks.length === 0 ) { - return textures[ name ]; + return null; - }, + } - parse: function ( json ) { + var clip = new AnimationClip( clipName, duration, tracks ); - var material = new THREE[ json.type ]; + return clip; - if ( json.uuid !== undefined ) material.uuid = json.uuid; - if ( json.name !== undefined ) material.name = json.name; - if ( json.color !== undefined ) material.color.setHex( json.color ); - if ( json.roughness !== undefined ) material.roughness = json.roughness; - if ( json.metalness !== undefined ) material.metalness = json.metalness; - if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive ); - if ( json.specular !== undefined ) material.specular.setHex( json.specular ); - if ( json.shininess !== undefined ) material.shininess = json.shininess; - if ( json.uniforms !== undefined ) material.uniforms = json.uniforms; - if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader; - if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader; - if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors; - if ( json.fog !== undefined ) material.fog = json.fog; - if ( json.shading !== undefined ) material.shading = json.shading; - if ( json.blending !== undefined ) material.blending = json.blending; - if ( json.side !== undefined ) material.side = json.side; - if ( json.opacity !== undefined ) material.opacity = json.opacity; - if ( json.transparent !== undefined ) material.transparent = json.transparent; - if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest; - if ( json.depthTest !== undefined ) material.depthTest = json.depthTest; - if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite; - if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite; - if ( json.wireframe !== undefined ) material.wireframe = json.wireframe; - if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth; + } - // for PointsMaterial - if ( json.size !== undefined ) material.size = json.size; - if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation; + } ); - // maps + /** + * @author mrdoob / http://mrdoob.com/ + */ - if ( json.map !== undefined ) material.map = this.getTexture( json.map ); + function MaterialLoader( manager ) { - if ( json.alphaMap !== undefined ) { + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; + this.textures = {}; - material.alphaMap = this.getTexture( json.alphaMap ); - material.transparent = true; + } - } + Object.assign( MaterialLoader.prototype, { - if ( json.bumpMap !== undefined ) material.bumpMap = this.getTexture( json.bumpMap ); - if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale; + load: function ( url, onLoad, onProgress, onError ) { - if ( json.normalMap !== undefined ) material.normalMap = this.getTexture( json.normalMap ); - if ( json.normalScale !== undefined ) { + var scope = this; - var normalScale = json.normalScale; + var loader = new XHRLoader( scope.manager ); + loader.load( url, function ( text ) { - if ( Array.isArray( normalScale ) === false ) { + onLoad( scope.parse( JSON.parse( text ) ) ); - // Blender exporter used to export a scalar. See #7459 + }, onProgress, onError ); - normalScale = [ normalScale, normalScale ]; + }, - } + setTextures: function ( value ) { - material.normalScale = new Vector2().fromArray( normalScale ); + this.textures = value; - } + }, - if ( json.displacementMap !== undefined ) material.displacementMap = this.getTexture( json.displacementMap ); - if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale; - if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias; + parse: function ( json ) { - if ( json.roughnessMap !== undefined ) material.roughnessMap = this.getTexture( json.roughnessMap ); - if ( json.metalnessMap !== undefined ) material.metalnessMap = this.getTexture( json.metalnessMap ); + var textures = this.textures; - if ( json.emissiveMap !== undefined ) material.emissiveMap = this.getTexture( json.emissiveMap ); - if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity; + function getTexture( name ) { - if ( json.specularMap !== undefined ) material.specularMap = this.getTexture( json.specularMap ); + if ( textures[ name ] === undefined ) { - if ( json.envMap !== undefined ) { + console.warn( 'THREE.MaterialLoader: Undefined texture', name ); - material.envMap = this.getTexture( json.envMap ); - material.combine = MultiplyOperation; + } - } + return textures[ name ]; - if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity; + } - if ( json.lightMap !== undefined ) material.lightMap = this.getTexture( json.lightMap ); - if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity; + var material = new THREE[ json.type ](); - if ( json.aoMap !== undefined ) material.aoMap = this.getTexture( json.aoMap ); - if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity; + if ( json.uuid !== undefined ) material.uuid = json.uuid; + if ( json.name !== undefined ) material.name = json.name; + if ( json.color !== undefined ) material.color.setHex( json.color ); + if ( json.roughness !== undefined ) material.roughness = json.roughness; + if ( json.metalness !== undefined ) material.metalness = json.metalness; + if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive ); + if ( json.specular !== undefined ) material.specular.setHex( json.specular ); + if ( json.shininess !== undefined ) material.shininess = json.shininess; + if ( json.uniforms !== undefined ) material.uniforms = json.uniforms; + if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader; + if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader; + if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors; + if ( json.fog !== undefined ) material.fog = json.fog; + if ( json.shading !== undefined ) material.shading = json.shading; + if ( json.blending !== undefined ) material.blending = json.blending; + if ( json.side !== undefined ) material.side = json.side; + if ( json.opacity !== undefined ) material.opacity = json.opacity; + if ( json.transparent !== undefined ) material.transparent = json.transparent; + if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest; + if ( json.depthTest !== undefined ) material.depthTest = json.depthTest; + if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite; + if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite; + if ( json.wireframe !== undefined ) material.wireframe = json.wireframe; + if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth; + if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap; + if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin; + if ( json.skinning !== undefined ) material.skinning = json.skinning; + if ( json.morphTargets !== undefined ) material.morphTargets = json.morphTargets; - // MultiMaterial + // for PointsMaterial - if ( json.materials !== undefined ) { + if ( json.size !== undefined ) material.size = json.size; + if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation; - for ( var i = 0, l = json.materials.length; i < l; i ++ ) { + // maps - material.materials.push( this.parse( json.materials[ i ] ) ); + if ( json.map !== undefined ) material.map = getTexture( json.map ); - } + if ( json.alphaMap !== undefined ) { - } + material.alphaMap = getTexture( json.alphaMap ); + material.transparent = true; - return material; + } - } + if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap ); + if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale; - } ); + if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap ); + if ( json.normalScale !== undefined ) { - /** - * @author mrdoob / http://mrdoob.com/ - */ + var normalScale = json.normalScale; - function BufferGeometryLoader( manager ) { + if ( Array.isArray( normalScale ) === false ) { - this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; + // Blender exporter used to export a scalar. See #7459 - }; + normalScale = [ normalScale, normalScale ]; - Object.assign( BufferGeometryLoader.prototype, { + } - load: function ( url, onLoad, onProgress, onError ) { + material.normalScale = new Vector2().fromArray( normalScale ); - var scope = this; + } - var loader = new XHRLoader( scope.manager ); - loader.load( url, function ( text ) { + if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap ); + if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale; + if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias; - onLoad( scope.parse( JSON.parse( text ) ) ); + if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap ); + if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap ); - }, onProgress, onError ); + if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap ); + if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity; - }, + if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap ); - parse: function ( json ) { + if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap ); - var geometry = new BufferGeometry(); + if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity; - var index = json.data.index; + if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap ); + if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity; - var TYPED_ARRAYS = { - 'Int8Array': Int8Array, - 'Uint8Array': Uint8Array, - 'Uint8ClampedArray': Uint8ClampedArray, - 'Int16Array': Int16Array, - 'Uint16Array': Uint16Array, - 'Int32Array': Int32Array, - 'Uint32Array': Uint32Array, - 'Float32Array': Float32Array, - 'Float64Array': Float64Array - }; + if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap ); + if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity; - if ( index !== undefined ) { + // MultiMaterial - var typedArray = new TYPED_ARRAYS[ index.type ]( index.array ); - geometry.setIndex( new BufferAttribute( typedArray, 1 ) ); + if ( json.materials !== undefined ) { - } + for ( var i = 0, l = json.materials.length; i < l; i ++ ) { - var attributes = json.data.attributes; + material.materials.push( this.parse( json.materials[ i ] ) ); - for ( var key in attributes ) { + } - var attribute = attributes[ key ]; - var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array ); + } - geometry.addAttribute( key, new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ) ); + return material; - } + } - var groups = json.data.groups || json.data.drawcalls || json.data.offsets; + } ); - if ( groups !== undefined ) { + /** + * @author mrdoob / http://mrdoob.com/ + */ - for ( var i = 0, n = groups.length; i !== n; ++ i ) { + function BufferGeometryLoader( manager ) { - var group = groups[ i ]; + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; - geometry.addGroup( group.start, group.count, group.materialIndex ); + } - } + Object.assign( BufferGeometryLoader.prototype, { - } + load: function ( url, onLoad, onProgress, onError ) { - var boundingSphere = json.data.boundingSphere; + var scope = this; - if ( boundingSphere !== undefined ) { + var loader = new XHRLoader( scope.manager ); + loader.load( url, function ( text ) { - var center = new Vector3(); + onLoad( scope.parse( JSON.parse( text ) ) ); - if ( boundingSphere.center !== undefined ) { + }, onProgress, onError ); - center.fromArray( boundingSphere.center ); + }, - } + parse: function ( json ) { - geometry.boundingSphere = new Sphere( center, boundingSphere.radius ); + var geometry = new BufferGeometry(); - } + var index = json.data.index; - return geometry; + var TYPED_ARRAYS = { + 'Int8Array': Int8Array, + 'Uint8Array': Uint8Array, + 'Uint8ClampedArray': Uint8ClampedArray, + 'Int16Array': Int16Array, + 'Uint16Array': Uint16Array, + 'Int32Array': Int32Array, + 'Uint32Array': Uint32Array, + 'Float32Array': Float32Array, + 'Float64Array': Float64Array + }; - } + if ( index !== undefined ) { - } ); + var typedArray = new TYPED_ARRAYS[ index.type ]( index.array ); + geometry.setIndex( new BufferAttribute( typedArray, 1 ) ); - /** - * @author alteredq / http://alteredqualia.com/ - */ + } - function Loader() { + var attributes = json.data.attributes; - this.onLoadStart = function () {}; - this.onLoadProgress = function () {}; - this.onLoadComplete = function () {}; + for ( var key in attributes ) { - }; + var attribute = attributes[ key ]; + var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array ); - Loader.prototype = { + geometry.addAttribute( key, new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ) ); - constructor: Loader, + } - crossOrigin: undefined, + var groups = json.data.groups || json.data.drawcalls || json.data.offsets; - extractUrlBase: function ( url ) { + if ( groups !== undefined ) { - var parts = url.split( '/' ); + for ( var i = 0, n = groups.length; i !== n; ++ i ) { - if ( parts.length === 1 ) return './'; + var group = groups[ i ]; - parts.pop(); + geometry.addGroup( group.start, group.count, group.materialIndex ); - return parts.join( '/' ) + '/'; + } - }, + } - initMaterials: function ( materials, texturePath, crossOrigin ) { + var boundingSphere = json.data.boundingSphere; - var array = []; + if ( boundingSphere !== undefined ) { - for ( var i = 0; i < materials.length; ++ i ) { + var center = new Vector3(); - array[ i ] = this.createMaterial( materials[ i ], texturePath, crossOrigin ); + if ( boundingSphere.center !== undefined ) { - } + center.fromArray( boundingSphere.center ); - return array; + } - }, + geometry.boundingSphere = new Sphere( center, boundingSphere.radius ); - createMaterial: ( function () { + } - var color, textureLoader, materialLoader; + return geometry; - return function createMaterial( m, texturePath, crossOrigin ) { + } - if ( color === undefined ) color = new Color(); - if ( textureLoader === undefined ) textureLoader = new TextureLoader(); - if ( materialLoader === undefined ) materialLoader = new MaterialLoader(); + } ); - // convert from old material format + /** + * @author alteredq / http://alteredqualia.com/ + */ - var textures = {}; + function Loader() { - function loadTexture( path, repeat, offset, wrap, anisotropy ) { + this.onLoadStart = function () {}; + this.onLoadProgress = function () {}; + this.onLoadComplete = function () {}; - var fullPath = texturePath + path; - var loader = Loader.Handlers.get( fullPath ); + } - var texture; + Loader.prototype = { - if ( loader !== null ) { + constructor: Loader, - texture = loader.load( fullPath ); + crossOrigin: undefined, - } else { + extractUrlBase: function ( url ) { - textureLoader.setCrossOrigin( crossOrigin ); - texture = textureLoader.load( fullPath ); + var parts = url.split( '/' ); - } + if ( parts.length === 1 ) return './'; - if ( repeat !== undefined ) { + parts.pop(); - texture.repeat.fromArray( repeat ); + return parts.join( '/' ) + '/'; - if ( repeat[ 0 ] !== 1 ) texture.wrapS = RepeatWrapping; - if ( repeat[ 1 ] !== 1 ) texture.wrapT = RepeatWrapping; + }, - } + initMaterials: function ( materials, texturePath, crossOrigin ) { - if ( offset !== undefined ) { + var array = []; - texture.offset.fromArray( offset ); + for ( var i = 0; i < materials.length; ++ i ) { - } + array[ i ] = this.createMaterial( materials[ i ], texturePath, crossOrigin ); - if ( wrap !== undefined ) { + } - if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = RepeatWrapping; - if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = MirroredRepeatWrapping; + return array; - if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = RepeatWrapping; - if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = MirroredRepeatWrapping; + }, - } + createMaterial: ( function () { - if ( anisotropy !== undefined ) { + var color, textureLoader, materialLoader; - texture.anisotropy = anisotropy; + return function createMaterial( m, texturePath, crossOrigin ) { - } + if ( color === undefined ) color = new Color(); + if ( textureLoader === undefined ) textureLoader = new TextureLoader(); + if ( materialLoader === undefined ) materialLoader = new MaterialLoader(); - var uuid = exports.Math.generateUUID(); + // convert from old material format - textures[ uuid ] = texture; + var textures = {}; - return uuid; + function loadTexture( path, repeat, offset, wrap, anisotropy ) { - } + var fullPath = texturePath + path; + var loader = Loader.Handlers.get( fullPath ); - // + var texture; - var json = { - uuid: exports.Math.generateUUID(), - type: 'MeshLambertMaterial' - }; - - for ( var name in m ) { - - var value = m[ name ]; - - switch ( name ) { - case 'DbgColor': - case 'DbgIndex': - case 'opticalDensity': - case 'illumination': - break; - case 'DbgName': - json.name = value; - break; - case 'blending': - json.blending = THREE[ value ]; - break; - case 'colorAmbient': - case 'mapAmbient': - console.warn( 'THREE.Loader.createMaterial:', name, 'is no longer supported.' ); - break; - case 'colorDiffuse': - json.color = color.fromArray( value ).getHex(); - break; - case 'colorSpecular': - json.specular = color.fromArray( value ).getHex(); - break; - case 'colorEmissive': - json.emissive = color.fromArray( value ).getHex(); - break; - case 'specularCoef': - json.shininess = value; - break; - case 'shading': - if ( value.toLowerCase() === 'basic' ) json.type = 'MeshBasicMaterial'; - if ( value.toLowerCase() === 'phong' ) json.type = 'MeshPhongMaterial'; - if ( value.toLowerCase() === 'standard' ) json.type = 'MeshStandardMaterial'; - break; - case 'mapDiffuse': - json.map = loadTexture( value, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy ); - break; - case 'mapDiffuseRepeat': - case 'mapDiffuseOffset': - case 'mapDiffuseWrap': - case 'mapDiffuseAnisotropy': - break; - case 'mapEmissive': - json.emissiveMap = loadTexture( value, m.mapEmissiveRepeat, m.mapEmissiveOffset, m.mapEmissiveWrap, m.mapEmissiveAnisotropy ); - break; - case 'mapEmissiveRepeat': - case 'mapEmissiveOffset': - case 'mapEmissiveWrap': - case 'mapEmissiveAnisotropy': - break; - case 'mapLight': - json.lightMap = loadTexture( value, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy ); - break; - case 'mapLightRepeat': - case 'mapLightOffset': - case 'mapLightWrap': - case 'mapLightAnisotropy': - break; - case 'mapAO': - json.aoMap = loadTexture( value, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy ); - break; - case 'mapAORepeat': - case 'mapAOOffset': - case 'mapAOWrap': - case 'mapAOAnisotropy': - break; - case 'mapBump': - json.bumpMap = loadTexture( value, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy ); - break; - case 'mapBumpScale': - json.bumpScale = value; - break; - case 'mapBumpRepeat': - case 'mapBumpOffset': - case 'mapBumpWrap': - case 'mapBumpAnisotropy': - break; - case 'mapNormal': - json.normalMap = loadTexture( value, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy ); - break; - case 'mapNormalFactor': - json.normalScale = [ value, value ]; - break; - case 'mapNormalRepeat': - case 'mapNormalOffset': - case 'mapNormalWrap': - case 'mapNormalAnisotropy': - break; - case 'mapSpecular': - json.specularMap = loadTexture( value, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy ); - break; - case 'mapSpecularRepeat': - case 'mapSpecularOffset': - case 'mapSpecularWrap': - case 'mapSpecularAnisotropy': - break; - case 'mapMetalness': - json.metalnessMap = loadTexture( value, m.mapMetalnessRepeat, m.mapMetalnessOffset, m.mapMetalnessWrap, m.mapMetalnessAnisotropy ); - break; - case 'mapMetalnessRepeat': - case 'mapMetalnessOffset': - case 'mapMetalnessWrap': - case 'mapMetalnessAnisotropy': - break; - case 'mapRoughness': - json.roughnessMap = loadTexture( value, m.mapRoughnessRepeat, m.mapRoughnessOffset, m.mapRoughnessWrap, m.mapRoughnessAnisotropy ); - break; - case 'mapRoughnessRepeat': - case 'mapRoughnessOffset': - case 'mapRoughnessWrap': - case 'mapRoughnessAnisotropy': - break; - case 'mapAlpha': - json.alphaMap = loadTexture( value, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy ); - break; - case 'mapAlphaRepeat': - case 'mapAlphaOffset': - case 'mapAlphaWrap': - case 'mapAlphaAnisotropy': - break; - case 'flipSided': - json.side = BackSide; - break; - case 'doubleSided': - json.side = DoubleSide; - break; - case 'transparency': - console.warn( 'THREE.Loader.createMaterial: transparency has been renamed to opacity' ); - json.opacity = value; - break; - case 'depthTest': - case 'depthWrite': - case 'colorWrite': - case 'opacity': - case 'reflectivity': - case 'transparent': - case 'visible': - case 'wireframe': - json[ name ] = value; - break; - case 'vertexColors': - if ( value === true ) json.vertexColors = VertexColors; - if ( value === 'face' ) json.vertexColors = FaceColors; - break; - default: - console.error( 'THREE.Loader.createMaterial: Unsupported', name, value ); - break; - } - - } - - if ( json.type === 'MeshBasicMaterial' ) delete json.emissive; - if ( json.type !== 'MeshPhongMaterial' ) delete json.specular; - - if ( json.opacity < 1 ) json.transparent = true; - - materialLoader.setTextures( textures ); + if ( loader !== null ) { - return materialLoader.parse( json ); + texture = loader.load( fullPath ); - }; + } else { - } )() + textureLoader.setCrossOrigin( crossOrigin ); + texture = textureLoader.load( fullPath ); - }; + } - Loader.Handlers = { + if ( repeat !== undefined ) { - handlers: [], + texture.repeat.fromArray( repeat ); - add: function ( regex, loader ) { + if ( repeat[ 0 ] !== 1 ) texture.wrapS = RepeatWrapping; + if ( repeat[ 1 ] !== 1 ) texture.wrapT = RepeatWrapping; - this.handlers.push( regex, loader ); + } - }, + if ( offset !== undefined ) { - get: function ( file ) { + texture.offset.fromArray( offset ); - var handlers = this.handlers; + } - for ( var i = 0, l = handlers.length; i < l; i += 2 ) { + if ( wrap !== undefined ) { - var regex = handlers[ i ]; - var loader = handlers[ i + 1 ]; + if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = RepeatWrapping; + if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = MirroredRepeatWrapping; + + if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = RepeatWrapping; + if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = MirroredRepeatWrapping; + + } + + if ( anisotropy !== undefined ) { + + texture.anisotropy = anisotropy; + + } + + var uuid = exports.Math.generateUUID(); + + textures[ uuid ] = texture; + + return uuid; + + } + + // + + var json = { + uuid: exports.Math.generateUUID(), + type: 'MeshLambertMaterial' + }; + + for ( var name in m ) { + + var value = m[ name ]; + + switch ( name ) { + case 'DbgColor': + case 'DbgIndex': + case 'opticalDensity': + case 'illumination': + break; + case 'DbgName': + json.name = value; + break; + case 'blending': + json.blending = THREE[ value ]; + break; + case 'colorAmbient': + case 'mapAmbient': + console.warn( 'THREE.Loader.createMaterial:', name, 'is no longer supported.' ); + break; + case 'colorDiffuse': + json.color = color.fromArray( value ).getHex(); + break; + case 'colorSpecular': + json.specular = color.fromArray( value ).getHex(); + break; + case 'colorEmissive': + json.emissive = color.fromArray( value ).getHex(); + break; + case 'specularCoef': + json.shininess = value; + break; + case 'shading': + if ( value.toLowerCase() === 'basic' ) json.type = 'MeshBasicMaterial'; + if ( value.toLowerCase() === 'phong' ) json.type = 'MeshPhongMaterial'; + if ( value.toLowerCase() === 'standard' ) json.type = 'MeshStandardMaterial'; + break; + case 'mapDiffuse': + json.map = loadTexture( value, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy ); + break; + case 'mapDiffuseRepeat': + case 'mapDiffuseOffset': + case 'mapDiffuseWrap': + case 'mapDiffuseAnisotropy': + break; + case 'mapEmissive': + json.emissiveMap = loadTexture( value, m.mapEmissiveRepeat, m.mapEmissiveOffset, m.mapEmissiveWrap, m.mapEmissiveAnisotropy ); + break; + case 'mapEmissiveRepeat': + case 'mapEmissiveOffset': + case 'mapEmissiveWrap': + case 'mapEmissiveAnisotropy': + break; + case 'mapLight': + json.lightMap = loadTexture( value, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy ); + break; + case 'mapLightRepeat': + case 'mapLightOffset': + case 'mapLightWrap': + case 'mapLightAnisotropy': + break; + case 'mapAO': + json.aoMap = loadTexture( value, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy ); + break; + case 'mapAORepeat': + case 'mapAOOffset': + case 'mapAOWrap': + case 'mapAOAnisotropy': + break; + case 'mapBump': + json.bumpMap = loadTexture( value, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy ); + break; + case 'mapBumpScale': + json.bumpScale = value; + break; + case 'mapBumpRepeat': + case 'mapBumpOffset': + case 'mapBumpWrap': + case 'mapBumpAnisotropy': + break; + case 'mapNormal': + json.normalMap = loadTexture( value, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy ); + break; + case 'mapNormalFactor': + json.normalScale = [ value, value ]; + break; + case 'mapNormalRepeat': + case 'mapNormalOffset': + case 'mapNormalWrap': + case 'mapNormalAnisotropy': + break; + case 'mapSpecular': + json.specularMap = loadTexture( value, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy ); + break; + case 'mapSpecularRepeat': + case 'mapSpecularOffset': + case 'mapSpecularWrap': + case 'mapSpecularAnisotropy': + break; + case 'mapMetalness': + json.metalnessMap = loadTexture( value, m.mapMetalnessRepeat, m.mapMetalnessOffset, m.mapMetalnessWrap, m.mapMetalnessAnisotropy ); + break; + case 'mapMetalnessRepeat': + case 'mapMetalnessOffset': + case 'mapMetalnessWrap': + case 'mapMetalnessAnisotropy': + break; + case 'mapRoughness': + json.roughnessMap = loadTexture( value, m.mapRoughnessRepeat, m.mapRoughnessOffset, m.mapRoughnessWrap, m.mapRoughnessAnisotropy ); + break; + case 'mapRoughnessRepeat': + case 'mapRoughnessOffset': + case 'mapRoughnessWrap': + case 'mapRoughnessAnisotropy': + break; + case 'mapAlpha': + json.alphaMap = loadTexture( value, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy ); + break; + case 'mapAlphaRepeat': + case 'mapAlphaOffset': + case 'mapAlphaWrap': + case 'mapAlphaAnisotropy': + break; + case 'flipSided': + json.side = BackSide; + break; + case 'doubleSided': + json.side = DoubleSide; + break; + case 'transparency': + console.warn( 'THREE.Loader.createMaterial: transparency has been renamed to opacity' ); + json.opacity = value; + break; + case 'depthTest': + case 'depthWrite': + case 'colorWrite': + case 'opacity': + case 'reflectivity': + case 'transparent': + case 'visible': + case 'wireframe': + json[ name ] = value; + break; + case 'vertexColors': + if ( value === true ) json.vertexColors = VertexColors; + if ( value === 'face' ) json.vertexColors = FaceColors; + break; + default: + console.error( 'THREE.Loader.createMaterial: Unsupported', name, value ); + break; + } + + } + + if ( json.type === 'MeshBasicMaterial' ) delete json.emissive; + if ( json.type !== 'MeshPhongMaterial' ) delete json.specular; + + if ( json.opacity < 1 ) json.transparent = true; + + materialLoader.setTextures( textures ); + + return materialLoader.parse( json ); + + }; + + } )() - if ( regex.test( file ) ) { + }; - return loader; + Loader.Handlers = { - } + handlers: [], - } + add: function ( regex, loader ) { - return null; + this.handlers.push( regex, loader ); - } + }, - }; + get: function ( file ) { - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + var handlers = this.handlers; - function JSONLoader( manager ) { + for ( var i = 0, l = handlers.length; i < l; i += 2 ) { - if ( typeof manager === 'boolean' ) { + var regex = handlers[ i ]; + var loader = handlers[ i + 1 ]; - console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' ); - manager = undefined; + if ( regex.test( file ) ) { - } + return loader; - this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; + } - this.withCredentials = false; + } - }; + return null; - Object.assign( JSONLoader.prototype, { + } - load: function( url, onLoad, onProgress, onError ) { + }; - var scope = this; + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - var texturePath = this.texturePath && ( typeof this.texturePath === "string" ) ? this.texturePath : Loader.prototype.extractUrlBase( url ); + function JSONLoader( manager ) { - var loader = new XHRLoader( this.manager ); - loader.setWithCredentials( this.withCredentials ); - loader.load( url, function ( text ) { + if ( typeof manager === 'boolean' ) { - var json = JSON.parse( text ); - var metadata = json.metadata; + console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' ); + manager = undefined; - if ( metadata !== undefined ) { + } - var type = metadata.type; + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; - if ( type !== undefined ) { + this.withCredentials = false; - if ( type.toLowerCase() === 'object' ) { + } - console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' ); - return; + Object.assign( JSONLoader.prototype, { - } + load: function( url, onLoad, onProgress, onError ) { - if ( type.toLowerCase() === 'scene' ) { + var scope = this; - console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.SceneLoader instead.' ); - return; + var texturePath = this.texturePath && ( typeof this.texturePath === "string" ) ? this.texturePath : Loader.prototype.extractUrlBase( url ); - } + var loader = new XHRLoader( this.manager ); + loader.setWithCredentials( this.withCredentials ); + loader.load( url, function ( text ) { - } + var json = JSON.parse( text ); + var metadata = json.metadata; - } + if ( metadata !== undefined ) { - var object = scope.parse( json, texturePath ); - onLoad( object.geometry, object.materials ); + var type = metadata.type; - }, onProgress, onError ); + if ( type !== undefined ) { - }, + if ( type.toLowerCase() === 'object' ) { - setTexturePath: function ( value ) { + console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' ); + return; - this.texturePath = value; + } - }, + if ( type.toLowerCase() === 'scene' ) { - parse: function ( json, texturePath ) { + console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.SceneLoader instead.' ); + return; - var geometry = new Geometry(), - scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0; + } - parseModel( scale ); + } - parseSkin(); - parseMorphing( scale ); - parseAnimations(); + } - geometry.computeFaceNormals(); - geometry.computeBoundingSphere(); + var object = scope.parse( json, texturePath ); + onLoad( object.geometry, object.materials ); - function parseModel( scale ) { + }, onProgress, onError ); - function isBitSet( value, position ) { + }, - return value & ( 1 << position ); + setTexturePath: function ( value ) { - } + this.texturePath = value; - var i, j, fi, + }, - offset, zLength, + parse: function ( json, texturePath ) { - colorIndex, normalIndex, uvIndex, materialIndex, + var geometry = new Geometry(), + scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0; - type, - isQuad, - hasMaterial, - hasFaceVertexUv, - hasFaceNormal, hasFaceVertexNormal, - hasFaceColor, hasFaceVertexColor, + parseModel( scale ); - vertex, face, faceA, faceB, hex, normal, + parseSkin(); + parseMorphing( scale ); + parseAnimations(); - uvLayer, uv, u, v, + geometry.computeFaceNormals(); + geometry.computeBoundingSphere(); - faces = json.faces, - vertices = json.vertices, - normals = json.normals, - colors = json.colors, + function parseModel( scale ) { - nUvLayers = 0; + function isBitSet( value, position ) { - if ( json.uvs !== undefined ) { + return value & ( 1 << position ); - // disregard empty arrays + } - for ( i = 0; i < json.uvs.length; i ++ ) { + var i, j, fi, - if ( json.uvs[ i ].length ) nUvLayers ++; + offset, zLength, - } + colorIndex, normalIndex, uvIndex, materialIndex, - for ( i = 0; i < nUvLayers; i ++ ) { + type, + isQuad, + hasMaterial, + hasFaceVertexUv, + hasFaceNormal, hasFaceVertexNormal, + hasFaceColor, hasFaceVertexColor, - geometry.faceVertexUvs[ i ] = []; + vertex, face, faceA, faceB, hex, normal, - } + uvLayer, uv, u, v, - } + faces = json.faces, + vertices = json.vertices, + normals = json.normals, + colors = json.colors, - offset = 0; - zLength = vertices.length; + nUvLayers = 0; - while ( offset < zLength ) { + if ( json.uvs !== undefined ) { - vertex = new Vector3(); + // disregard empty arrays - vertex.x = vertices[ offset ++ ] * scale; - vertex.y = vertices[ offset ++ ] * scale; - vertex.z = vertices[ offset ++ ] * scale; + for ( i = 0; i < json.uvs.length; i ++ ) { - geometry.vertices.push( vertex ); + if ( json.uvs[ i ].length ) nUvLayers ++; - } + } - offset = 0; - zLength = faces.length; + for ( i = 0; i < nUvLayers; i ++ ) { - while ( offset < zLength ) { + geometry.faceVertexUvs[ i ] = []; - type = faces[ offset ++ ]; + } + } - isQuad = isBitSet( type, 0 ); - hasMaterial = isBitSet( type, 1 ); - hasFaceVertexUv = isBitSet( type, 3 ); - hasFaceNormal = isBitSet( type, 4 ); - hasFaceVertexNormal = isBitSet( type, 5 ); - hasFaceColor = isBitSet( type, 6 ); - hasFaceVertexColor = isBitSet( type, 7 ); + offset = 0; + zLength = vertices.length; - // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor); + while ( offset < zLength ) { - if ( isQuad ) { + vertex = new Vector3(); - faceA = new Face3(); - faceA.a = faces[ offset ]; - faceA.b = faces[ offset + 1 ]; - faceA.c = faces[ offset + 3 ]; + vertex.x = vertices[ offset ++ ] * scale; + vertex.y = vertices[ offset ++ ] * scale; + vertex.z = vertices[ offset ++ ] * scale; - faceB = new Face3(); - faceB.a = faces[ offset + 1 ]; - faceB.b = faces[ offset + 2 ]; - faceB.c = faces[ offset + 3 ]; + geometry.vertices.push( vertex ); - offset += 4; + } - if ( hasMaterial ) { + offset = 0; + zLength = faces.length; - materialIndex = faces[ offset ++ ]; - faceA.materialIndex = materialIndex; - faceB.materialIndex = materialIndex; + while ( offset < zLength ) { - } + type = faces[ offset ++ ]; - // to get face <=> uv index correspondence - fi = geometry.faces.length; + isQuad = isBitSet( type, 0 ); + hasMaterial = isBitSet( type, 1 ); + hasFaceVertexUv = isBitSet( type, 3 ); + hasFaceNormal = isBitSet( type, 4 ); + hasFaceVertexNormal = isBitSet( type, 5 ); + hasFaceColor = isBitSet( type, 6 ); + hasFaceVertexColor = isBitSet( type, 7 ); - if ( hasFaceVertexUv ) { + // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor); - for ( i = 0; i < nUvLayers; i ++ ) { + if ( isQuad ) { - uvLayer = json.uvs[ i ]; + faceA = new Face3(); + faceA.a = faces[ offset ]; + faceA.b = faces[ offset + 1 ]; + faceA.c = faces[ offset + 3 ]; - geometry.faceVertexUvs[ i ][ fi ] = []; - geometry.faceVertexUvs[ i ][ fi + 1 ] = []; + faceB = new Face3(); + faceB.a = faces[ offset + 1 ]; + faceB.b = faces[ offset + 2 ]; + faceB.c = faces[ offset + 3 ]; - for ( j = 0; j < 4; j ++ ) { + offset += 4; - uvIndex = faces[ offset ++ ]; + if ( hasMaterial ) { - u = uvLayer[ uvIndex * 2 ]; - v = uvLayer[ uvIndex * 2 + 1 ]; + materialIndex = faces[ offset ++ ]; + faceA.materialIndex = materialIndex; + faceB.materialIndex = materialIndex; - uv = new Vector2( u, v ); + } - if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv ); - if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv ); + // to get face <=> uv index correspondence - } + fi = geometry.faces.length; - } + if ( hasFaceVertexUv ) { - } + for ( i = 0; i < nUvLayers; i ++ ) { - if ( hasFaceNormal ) { + uvLayer = json.uvs[ i ]; - normalIndex = faces[ offset ++ ] * 3; + geometry.faceVertexUvs[ i ][ fi ] = []; + geometry.faceVertexUvs[ i ][ fi + 1 ] = []; - faceA.normal.set( - normals[ normalIndex ++ ], - normals[ normalIndex ++ ], - normals[ normalIndex ] - ); + for ( j = 0; j < 4; j ++ ) { - faceB.normal.copy( faceA.normal ); + uvIndex = faces[ offset ++ ]; - } + u = uvLayer[ uvIndex * 2 ]; + v = uvLayer[ uvIndex * 2 + 1 ]; - if ( hasFaceVertexNormal ) { + uv = new Vector2( u, v ); - for ( i = 0; i < 4; i ++ ) { + if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv ); + if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv ); - normalIndex = faces[ offset ++ ] * 3; + } - normal = new Vector3( - normals[ normalIndex ++ ], - normals[ normalIndex ++ ], - normals[ normalIndex ] - ); + } + } - if ( i !== 2 ) faceA.vertexNormals.push( normal ); - if ( i !== 0 ) faceB.vertexNormals.push( normal ); + if ( hasFaceNormal ) { - } + normalIndex = faces[ offset ++ ] * 3; - } + faceA.normal.set( + normals[ normalIndex ++ ], + normals[ normalIndex ++ ], + normals[ normalIndex ] + ); + faceB.normal.copy( faceA.normal ); - if ( hasFaceColor ) { + } - colorIndex = faces[ offset ++ ]; - hex = colors[ colorIndex ]; + if ( hasFaceVertexNormal ) { - faceA.color.setHex( hex ); - faceB.color.setHex( hex ); + for ( i = 0; i < 4; i ++ ) { - } + normalIndex = faces[ offset ++ ] * 3; + normal = new Vector3( + normals[ normalIndex ++ ], + normals[ normalIndex ++ ], + normals[ normalIndex ] + ); - if ( hasFaceVertexColor ) { - for ( i = 0; i < 4; i ++ ) { + if ( i !== 2 ) faceA.vertexNormals.push( normal ); + if ( i !== 0 ) faceB.vertexNormals.push( normal ); - colorIndex = faces[ offset ++ ]; - hex = colors[ colorIndex ]; + } - if ( i !== 2 ) faceA.vertexColors.push( new Color( hex ) ); - if ( i !== 0 ) faceB.vertexColors.push( new Color( hex ) ); + } - } - } + if ( hasFaceColor ) { - geometry.faces.push( faceA ); - geometry.faces.push( faceB ); + colorIndex = faces[ offset ++ ]; + hex = colors[ colorIndex ]; - } else { + faceA.color.setHex( hex ); + faceB.color.setHex( hex ); - face = new Face3(); - face.a = faces[ offset ++ ]; - face.b = faces[ offset ++ ]; - face.c = faces[ offset ++ ]; + } - if ( hasMaterial ) { - materialIndex = faces[ offset ++ ]; - face.materialIndex = materialIndex; + if ( hasFaceVertexColor ) { - } + for ( i = 0; i < 4; i ++ ) { - // to get face <=> uv index correspondence + colorIndex = faces[ offset ++ ]; + hex = colors[ colorIndex ]; - fi = geometry.faces.length; + if ( i !== 2 ) faceA.vertexColors.push( new Color( hex ) ); + if ( i !== 0 ) faceB.vertexColors.push( new Color( hex ) ); - if ( hasFaceVertexUv ) { + } - for ( i = 0; i < nUvLayers; i ++ ) { + } - uvLayer = json.uvs[ i ]; + geometry.faces.push( faceA ); + geometry.faces.push( faceB ); - geometry.faceVertexUvs[ i ][ fi ] = []; + } else { - for ( j = 0; j < 3; j ++ ) { + face = new Face3(); + face.a = faces[ offset ++ ]; + face.b = faces[ offset ++ ]; + face.c = faces[ offset ++ ]; - uvIndex = faces[ offset ++ ]; + if ( hasMaterial ) { - u = uvLayer[ uvIndex * 2 ]; - v = uvLayer[ uvIndex * 2 + 1 ]; + materialIndex = faces[ offset ++ ]; + face.materialIndex = materialIndex; - uv = new Vector2( u, v ); + } - geometry.faceVertexUvs[ i ][ fi ].push( uv ); + // to get face <=> uv index correspondence - } + fi = geometry.faces.length; - } + if ( hasFaceVertexUv ) { - } + for ( i = 0; i < nUvLayers; i ++ ) { - if ( hasFaceNormal ) { + uvLayer = json.uvs[ i ]; - normalIndex = faces[ offset ++ ] * 3; + geometry.faceVertexUvs[ i ][ fi ] = []; - face.normal.set( - normals[ normalIndex ++ ], - normals[ normalIndex ++ ], - normals[ normalIndex ] - ); + for ( j = 0; j < 3; j ++ ) { - } + uvIndex = faces[ offset ++ ]; - if ( hasFaceVertexNormal ) { + u = uvLayer[ uvIndex * 2 ]; + v = uvLayer[ uvIndex * 2 + 1 ]; - for ( i = 0; i < 3; i ++ ) { + uv = new Vector2( u, v ); - normalIndex = faces[ offset ++ ] * 3; + geometry.faceVertexUvs[ i ][ fi ].push( uv ); - normal = new Vector3( - normals[ normalIndex ++ ], - normals[ normalIndex ++ ], - normals[ normalIndex ] - ); + } - face.vertexNormals.push( normal ); + } - } + } - } + if ( hasFaceNormal ) { + normalIndex = faces[ offset ++ ] * 3; - if ( hasFaceColor ) { + face.normal.set( + normals[ normalIndex ++ ], + normals[ normalIndex ++ ], + normals[ normalIndex ] + ); - colorIndex = faces[ offset ++ ]; - face.color.setHex( colors[ colorIndex ] ); + } - } + if ( hasFaceVertexNormal ) { + for ( i = 0; i < 3; i ++ ) { - if ( hasFaceVertexColor ) { + normalIndex = faces[ offset ++ ] * 3; - for ( i = 0; i < 3; i ++ ) { + normal = new Vector3( + normals[ normalIndex ++ ], + normals[ normalIndex ++ ], + normals[ normalIndex ] + ); - colorIndex = faces[ offset ++ ]; - face.vertexColors.push( new Color( colors[ colorIndex ] ) ); + face.vertexNormals.push( normal ); - } + } - } + } - geometry.faces.push( face ); - } + if ( hasFaceColor ) { - } + colorIndex = faces[ offset ++ ]; + face.color.setHex( colors[ colorIndex ] ); - } + } - function parseSkin() { - var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2; + if ( hasFaceVertexColor ) { - if ( json.skinWeights ) { + for ( i = 0; i < 3; i ++ ) { - for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) { + colorIndex = faces[ offset ++ ]; + face.vertexColors.push( new Color( colors[ colorIndex ] ) ); - var x = json.skinWeights[ i ]; - var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0; - var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0; - var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0; + } - geometry.skinWeights.push( new Vector4( x, y, z, w ) ); + } - } + geometry.faces.push( face ); - } + } - if ( json.skinIndices ) { + } - for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) { + } - var a = json.skinIndices[ i ]; - var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0; - var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0; - var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0; + function parseSkin() { - geometry.skinIndices.push( new Vector4( a, b, c, d ) ); + var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2; - } + if ( json.skinWeights ) { - } + for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) { - geometry.bones = json.bones; + var x = json.skinWeights[ i ]; + var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0; + var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0; + var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0; - if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) { + geometry.skinWeights.push( new Vector4( x, y, z, w ) ); - console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' + - geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' ); + } - } + } - } + if ( json.skinIndices ) { - function parseMorphing( scale ) { + for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) { - if ( json.morphTargets !== undefined ) { + var a = json.skinIndices[ i ]; + var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0; + var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0; + var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0; - for ( var i = 0, l = json.morphTargets.length; i < l; i ++ ) { + geometry.skinIndices.push( new Vector4( a, b, c, d ) ); - geometry.morphTargets[ i ] = {}; - geometry.morphTargets[ i ].name = json.morphTargets[ i ].name; - geometry.morphTargets[ i ].vertices = []; + } - var dstVertices = geometry.morphTargets[ i ].vertices; - var srcVertices = json.morphTargets[ i ].vertices; + } - for ( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) { + geometry.bones = json.bones; - var vertex = new Vector3(); - vertex.x = srcVertices[ v ] * scale; - vertex.y = srcVertices[ v + 1 ] * scale; - vertex.z = srcVertices[ v + 2 ] * scale; + if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) { - dstVertices.push( vertex ); + console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' + + geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' ); - } + } - } + } - } + function parseMorphing( scale ) { - if ( json.morphColors !== undefined && json.morphColors.length > 0 ) { + if ( json.morphTargets !== undefined ) { - console.warn( 'THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.' ); + for ( var i = 0, l = json.morphTargets.length; i < l; i ++ ) { - var faces = geometry.faces; - var morphColors = json.morphColors[ 0 ].colors; + geometry.morphTargets[ i ] = {}; + geometry.morphTargets[ i ].name = json.morphTargets[ i ].name; + geometry.morphTargets[ i ].vertices = []; - for ( var i = 0, l = faces.length; i < l; i ++ ) { + var dstVertices = geometry.morphTargets[ i ].vertices; + var srcVertices = json.morphTargets[ i ].vertices; - faces[ i ].color.fromArray( morphColors, i * 3 ); + for ( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) { - } + var vertex = new Vector3(); + vertex.x = srcVertices[ v ] * scale; + vertex.y = srcVertices[ v + 1 ] * scale; + vertex.z = srcVertices[ v + 2 ] * scale; - } + dstVertices.push( vertex ); - } + } - function parseAnimations() { + } - var outputAnimations = []; + } - // parse old style Bone/Hierarchy animations - var animations = []; + if ( json.morphColors !== undefined && json.morphColors.length > 0 ) { - if ( json.animation !== undefined ) { + console.warn( 'THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.' ); - animations.push( json.animation ); + var faces = geometry.faces; + var morphColors = json.morphColors[ 0 ].colors; - } + for ( var i = 0, l = faces.length; i < l; i ++ ) { - if ( json.animations !== undefined ) { + faces[ i ].color.fromArray( morphColors, i * 3 ); - if ( json.animations.length ) { + } - animations = animations.concat( json.animations ); + } - } else { + } - animations.push( json.animations ); + function parseAnimations() { - } + var outputAnimations = []; - } + // parse old style Bone/Hierarchy animations + var animations = []; - for ( var i = 0; i < animations.length; i ++ ) { + if ( json.animation !== undefined ) { - var clip = AnimationClip.parseAnimation( animations[ i ], geometry.bones ); - if ( clip ) outputAnimations.push( clip ); + animations.push( json.animation ); - } + } - // parse implicit morph animations - if ( geometry.morphTargets ) { + if ( json.animations !== undefined ) { - // TODO: Figure out what an appropraite FPS is for morph target animations -- defaulting to 10, but really it is completely arbitrary. - var morphAnimationClips = AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 ); - outputAnimations = outputAnimations.concat( morphAnimationClips ); + if ( json.animations.length ) { - } + animations = animations.concat( json.animations ); - if ( outputAnimations.length > 0 ) geometry.animations = outputAnimations; + } else { - } + animations.push( json.animations ); - if ( json.materials === undefined || json.materials.length === 0 ) { + } - return { geometry: geometry }; + } - } else { + for ( var i = 0; i < animations.length; i ++ ) { - var materials = Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin ); + var clip = AnimationClip.parseAnimation( animations[ i ], geometry.bones ); + if ( clip ) outputAnimations.push( clip ); - return { geometry: geometry, materials: materials }; + } - } + // parse implicit morph animations + if ( geometry.morphTargets ) { - } + // TODO: Figure out what an appropraite FPS is for morph target animations -- defaulting to 10, but really it is completely arbitrary. + var morphAnimationClips = AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 ); + outputAnimations = outputAnimations.concat( morphAnimationClips ); - } ); + } - /** - * @author mrdoob / http://mrdoob.com/ - */ + if ( outputAnimations.length > 0 ) geometry.animations = outputAnimations; - function ObjectLoader ( manager ) { + } - this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; - this.texturePath = ''; + if ( json.materials === undefined || json.materials.length === 0 ) { - } + return { geometry: geometry }; - Object.assign( ObjectLoader.prototype, { + } else { - load: function ( url, onLoad, onProgress, onError ) { + var materials = Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin ); - if ( this.texturePath === '' ) { + return { geometry: geometry, materials: materials }; - this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 ); + } - } + } - var scope = this; + } ); - var loader = new XHRLoader( scope.manager ); - loader.load( url, function ( text ) { + /** + * @author mrdoob / http://mrdoob.com/ + */ - scope.parse( JSON.parse( text ), onLoad ); + function ObjectLoader ( manager ) { - }, onProgress, onError ); + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; + this.texturePath = ''; - }, + } - setTexturePath: function ( value ) { + Object.assign( ObjectLoader.prototype, { - this.texturePath = value; + load: function ( url, onLoad, onProgress, onError ) { - }, + if ( this.texturePath === '' ) { - setCrossOrigin: function ( value ) { + this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 ); - this.crossOrigin = value; + } - }, + var scope = this; - parse: function ( json, onLoad ) { + var loader = new XHRLoader( scope.manager ); + loader.load( url, function ( text ) { - var geometries = this.parseGeometries( json.geometries ); + scope.parse( JSON.parse( text ), onLoad ); - var images = this.parseImages( json.images, function () { + }, onProgress, onError ); - if ( onLoad !== undefined ) onLoad( object ); + }, - } ); + setTexturePath: function ( value ) { - var textures = this.parseTextures( json.textures, images ); - var materials = this.parseMaterials( json.materials, textures ); + this.texturePath = value; - var object = this.parseObject( json.object, geometries, materials ); + }, - if ( json.animations ) { + setCrossOrigin: function ( value ) { - object.animations = this.parseAnimations( json.animations ); + this.crossOrigin = value; - } + }, - if ( json.images === undefined || json.images.length === 0 ) { + parse: function ( json, onLoad ) { - if ( onLoad !== undefined ) onLoad( object ); + var geometries = this.parseGeometries( json.geometries ); - } + var images = this.parseImages( json.images, function () { - return object; + if ( onLoad !== undefined ) onLoad( object ); - }, + } ); - parseGeometries: function ( json ) { + var textures = this.parseTextures( json.textures, images ); + var materials = this.parseMaterials( json.materials, textures ); - var geometries = {}; + var object = this.parseObject( json.object, geometries, materials ); - if ( json !== undefined ) { + if ( json.animations ) { - var geometryLoader = new JSONLoader(); - var bufferGeometryLoader = new BufferGeometryLoader(); + object.animations = this.parseAnimations( json.animations ); - for ( var i = 0, l = json.length; i < l; i ++ ) { + } - var geometry; - var data = json[ i ]; + if ( json.images === undefined || json.images.length === 0 ) { - switch ( data.type ) { + if ( onLoad !== undefined ) onLoad( object ); - case 'PlaneGeometry': - case 'PlaneBufferGeometry': + } - geometry = new THREE[ data.type ]( - data.width, - data.height, - data.widthSegments, - data.heightSegments - ); + return object; - break; + }, - case 'BoxGeometry': - case 'BoxBufferGeometry': - case 'CubeGeometry': // backwards compatible + parseGeometries: function ( json ) { - geometry = new THREE[ data.type ]( - data.width, - data.height, - data.depth, - data.widthSegments, - data.heightSegments, - data.depthSegments - ); + var geometries = {}; - break; + if ( json !== undefined ) { - case 'CircleGeometry': - case 'CircleBufferGeometry': + var geometryLoader = new JSONLoader(); + var bufferGeometryLoader = new BufferGeometryLoader(); - geometry = new THREE[ data.type ]( - data.radius, - data.segments, - data.thetaStart, - data.thetaLength - ); + for ( var i = 0, l = json.length; i < l; i ++ ) { - break; + var geometry; + var data = json[ i ]; - case 'CylinderGeometry': - case 'CylinderBufferGeometry': + switch ( data.type ) { - geometry = new THREE[ data.type ]( - data.radiusTop, - data.radiusBottom, - data.height, - data.radialSegments, - data.heightSegments, - data.openEnded, - data.thetaStart, - data.thetaLength - ); + case 'PlaneGeometry': + case 'PlaneBufferGeometry': - break; + geometry = new THREE[ data.type ]( + data.width, + data.height, + data.widthSegments, + data.heightSegments + ); - case 'ConeGeometry': - case 'ConeBufferGeometry': + break; - geometry = new THREE [ data.type ]( - data.radius, - data.height, - data.radialSegments, - data.heightSegments, - data.openEnded, - data.thetaStart, - data.thetaLength - ); + case 'BoxGeometry': + case 'BoxBufferGeometry': + case 'CubeGeometry': // backwards compatible - break; + geometry = new THREE[ data.type ]( + data.width, + data.height, + data.depth, + data.widthSegments, + data.heightSegments, + data.depthSegments + ); - case 'SphereGeometry': - case 'SphereBufferGeometry': + break; - geometry = new THREE[ data.type ]( - data.radius, - data.widthSegments, - data.heightSegments, - data.phiStart, - data.phiLength, - data.thetaStart, - data.thetaLength - ); + case 'CircleGeometry': + case 'CircleBufferGeometry': - break; + geometry = new THREE[ data.type ]( + data.radius, + data.segments, + data.thetaStart, + data.thetaLength + ); + + break; + + case 'CylinderGeometry': + case 'CylinderBufferGeometry': - case 'DodecahedronGeometry': - case 'IcosahedronGeometry': - case 'OctahedronGeometry': - case 'TetrahedronGeometry': + geometry = new THREE[ data.type ]( + data.radiusTop, + data.radiusBottom, + data.height, + data.radialSegments, + data.heightSegments, + data.openEnded, + data.thetaStart, + data.thetaLength + ); - geometry = new THREE[ data.type ]( - data.radius, - data.detail - ); + break; - break; + case 'ConeGeometry': + case 'ConeBufferGeometry': - case 'RingGeometry': - case 'RingBufferGeometry': + geometry = new THREE [ data.type ]( + data.radius, + data.height, + data.radialSegments, + data.heightSegments, + data.openEnded, + data.thetaStart, + data.thetaLength + ); - geometry = new THREE[ data.type ]( - data.innerRadius, - data.outerRadius, - data.thetaSegments, - data.phiSegments, - data.thetaStart, - data.thetaLength - ); + break; - break; + case 'SphereGeometry': + case 'SphereBufferGeometry': - case 'TorusGeometry': - case 'TorusBufferGeometry': + geometry = new THREE[ data.type ]( + data.radius, + data.widthSegments, + data.heightSegments, + data.phiStart, + data.phiLength, + data.thetaStart, + data.thetaLength + ); - geometry = new THREE[ data.type ]( - data.radius, - data.tube, - data.radialSegments, - data.tubularSegments, - data.arc - ); + break; - break; + case 'DodecahedronGeometry': + case 'IcosahedronGeometry': + case 'OctahedronGeometry': + case 'TetrahedronGeometry': - case 'TorusKnotGeometry': - case 'TorusKnotBufferGeometry': + geometry = new THREE[ data.type ]( + data.radius, + data.detail + ); - geometry = new THREE[ data.type ]( - data.radius, - data.tube, - data.tubularSegments, - data.radialSegments, - data.p, - data.q - ); + break; - break; + case 'RingGeometry': + case 'RingBufferGeometry': - case 'LatheGeometry': - case 'LatheBufferGeometry': + geometry = new THREE[ data.type ]( + data.innerRadius, + data.outerRadius, + data.thetaSegments, + data.phiSegments, + data.thetaStart, + data.thetaLength + ); - geometry = new THREE[ data.type ]( - data.points, - data.segments, - data.phiStart, - data.phiLength - ); + break; - break; + case 'TorusGeometry': + case 'TorusBufferGeometry': - case 'BufferGeometry': + geometry = new THREE[ data.type ]( + data.radius, + data.tube, + data.radialSegments, + data.tubularSegments, + data.arc + ); - geometry = bufferGeometryLoader.parse( data ); + break; - break; + case 'TorusKnotGeometry': + case 'TorusKnotBufferGeometry': - case 'Geometry': + geometry = new THREE[ data.type ]( + data.radius, + data.tube, + data.tubularSegments, + data.radialSegments, + data.p, + data.q + ); - geometry = geometryLoader.parse( data.data, this.texturePath ).geometry; + break; - break; + case 'LatheGeometry': + case 'LatheBufferGeometry': - default: + geometry = new THREE[ data.type ]( + data.points, + data.segments, + data.phiStart, + data.phiLength + ); - console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' ); + break; - continue; + case 'BufferGeometry': - } + geometry = bufferGeometryLoader.parse( data ); - geometry.uuid = data.uuid; + break; - if ( data.name !== undefined ) geometry.name = data.name; + case 'Geometry': - geometries[ data.uuid ] = geometry; + geometry = geometryLoader.parse( data.data, this.texturePath ).geometry; - } + break; - } + default: - return geometries; + console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' ); - }, + continue; - parseMaterials: function ( json, textures ) { + } - var materials = {}; + geometry.uuid = data.uuid; - if ( json !== undefined ) { + if ( data.name !== undefined ) geometry.name = data.name; - var loader = new MaterialLoader(); - loader.setTextures( textures ); + geometries[ data.uuid ] = geometry; - for ( var i = 0, l = json.length; i < l; i ++ ) { + } - var material = loader.parse( json[ i ] ); - materials[ material.uuid ] = material; + } - } + return geometries; - } + }, - return materials; + parseMaterials: function ( json, textures ) { - }, + var materials = {}; - parseAnimations: function ( json ) { + if ( json !== undefined ) { - var animations = []; + var loader = new MaterialLoader(); + loader.setTextures( textures ); - for ( var i = 0; i < json.length; i ++ ) { + for ( var i = 0, l = json.length; i < l; i ++ ) { - var clip = AnimationClip.parse( json[ i ] ); + var material = loader.parse( json[ i ] ); + materials[ material.uuid ] = material; - animations.push( clip ); + } - } + } - return animations; + return materials; - }, + }, - parseImages: function ( json, onLoad ) { + parseAnimations: function ( json ) { - var scope = this; - var images = {}; + var animations = []; - function loadImage( url ) { + for ( var i = 0; i < json.length; i ++ ) { - scope.manager.itemStart( url ); + var clip = AnimationClip.parse( json[ i ] ); - return loader.load( url, function () { + animations.push( clip ); - scope.manager.itemEnd( url ); + } - } ); + return animations; - } + }, - if ( json !== undefined && json.length > 0 ) { + parseImages: function ( json, onLoad ) { - var manager = new LoadingManager( onLoad ); + var scope = this; + var images = {}; - var loader = new ImageLoader( manager ); - loader.setCrossOrigin( this.crossOrigin ); + function loadImage( url ) { - for ( var i = 0, l = json.length; i < l; i ++ ) { + scope.manager.itemStart( url ); - var image = json[ i ]; - var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url; + return loader.load( url, function () { - images[ image.uuid ] = loadImage( path ); + scope.manager.itemEnd( url ); - } + }, undefined, function () { - } + scope.manager.itemError( url ); - return images; + } ); - }, + } - parseTextures: function ( json, images ) { + if ( json !== undefined && json.length > 0 ) { - function parseConstant( value ) { + var manager = new LoadingManager( onLoad ); - if ( typeof( value ) === 'number' ) return value; + var loader = new ImageLoader( manager ); + loader.setCrossOrigin( this.crossOrigin ); - console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value ); + for ( var i = 0, l = json.length; i < l; i ++ ) { - return THREE[ value ]; + var image = json[ i ]; + var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url; - } + images[ image.uuid ] = loadImage( path ); - var textures = {}; + } - if ( json !== undefined ) { + } - for ( var i = 0, l = json.length; i < l; i ++ ) { + return images; - var data = json[ i ]; + }, - if ( data.image === undefined ) { + parseTextures: function ( json, images ) { - console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid ); + function parseConstant( value ) { - } + if ( typeof( value ) === 'number' ) return value; - if ( images[ data.image ] === undefined ) { + console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value ); - console.warn( 'THREE.ObjectLoader: Undefined image', data.image ); + return THREE[ value ]; - } + } - var texture = new Texture( images[ data.image ] ); - texture.needsUpdate = true; + var textures = {}; - texture.uuid = data.uuid; + if ( json !== undefined ) { - if ( data.name !== undefined ) texture.name = data.name; + for ( var i = 0, l = json.length; i < l; i ++ ) { - if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping ); + var data = json[ i ]; - if ( data.offset !== undefined ) texture.offset.fromArray( data.offset ); - if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat ); - if ( data.wrap !== undefined ) { + if ( data.image === undefined ) { - texture.wrapS = parseConstant( data.wrap[ 0 ] ); - texture.wrapT = parseConstant( data.wrap[ 1 ] ); + console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid ); - } + } - if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter ); - if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter ); - if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy; + if ( images[ data.image ] === undefined ) { - if ( data.flipY !== undefined ) texture.flipY = data.flipY; + console.warn( 'THREE.ObjectLoader: Undefined image', data.image ); - textures[ data.uuid ] = texture; + } - } + var texture = new Texture( images[ data.image ] ); + texture.needsUpdate = true; - } + texture.uuid = data.uuid; - return textures; + if ( data.name !== undefined ) texture.name = data.name; - }, + if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping ); - parseObject: function () { + if ( data.offset !== undefined ) texture.offset.fromArray( data.offset ); + if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat ); + if ( data.wrap !== undefined ) { - var matrix = new Matrix4(); + texture.wrapS = parseConstant( data.wrap[ 0 ] ); + texture.wrapT = parseConstant( data.wrap[ 1 ] ); - return function parseObject( data, geometries, materials ) { + } - var object; + if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter ); + if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter ); + if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy; - function getGeometry( name ) { + if ( data.flipY !== undefined ) texture.flipY = data.flipY; - if ( geometries[ name ] === undefined ) { + textures[ data.uuid ] = texture; - console.warn( 'THREE.ObjectLoader: Undefined geometry', name ); + } - } + } - return geometries[ name ]; + return textures; - } + }, - function getMaterial( name ) { + parseObject: function () { - if ( name === undefined ) return undefined; + var matrix = new Matrix4(); - if ( materials[ name ] === undefined ) { + return function parseObject( data, geometries, materials ) { - console.warn( 'THREE.ObjectLoader: Undefined material', name ); + var object; - } + function getGeometry( name ) { - return materials[ name ]; + if ( geometries[ name ] === undefined ) { - } + console.warn( 'THREE.ObjectLoader: Undefined geometry', name ); - switch ( data.type ) { + } - case 'Scene': + return geometries[ name ]; - object = new Scene(); + } - - if ( data.fog !== undefined ) { - - if ( data.fog.type === 'FogExp2' ) { - - object.fog = new FogExp2(data.fog.color, data.fog.density); - - } else if ( data.fog.type === 'Fog' ) { - - object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far); - - } - } + function getMaterial( name ) { - break; + if ( name === undefined ) return undefined; - case 'PerspectiveCamera': + if ( materials[ name ] === undefined ) { - object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far ); + console.warn( 'THREE.ObjectLoader: Undefined material', name ); - if ( data.focus !== undefined ) object.focus = data.focus; - if ( data.zoom !== undefined ) object.zoom = data.zoom; - if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge; - if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset; - if ( data.view !== undefined ) object.view = Object.assign( {}, data.view ); + } - break; + return materials[ name ]; - case 'OrthographicCamera': + } - object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far ); + switch ( data.type ) { - break; + case 'Scene': - case 'AmbientLight': + object = new Scene(); - object = new AmbientLight( data.color, data.intensity ); + if ( data.background !== undefined ) { - break; + if ( Number.isInteger( data.background ) ) { - case 'DirectionalLight': + object.background = new THREE.Color( data.background ); - object = new DirectionalLight( data.color, data.intensity ); + } - break; + } - case 'PointLight': + if ( data.fog !== undefined ) { - object = new PointLight( data.color, data.intensity, data.distance, data.decay ); + if ( data.fog.type === 'Fog' ) { - break; + object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far ); - case 'SpotLight': + } else if ( data.fog.type === 'FogExp2' ) { - object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay ); + object.fog = new FogExp2( data.fog.color, data.fog.density ); - break; + } - case 'HemisphereLight': + } - object = new HemisphereLight( data.color, data.groundColor, data.intensity ); + break; - break; + case 'PerspectiveCamera': - case 'Mesh': + object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far ); - var geometry = getGeometry( data.geometry ); - var material = getMaterial( data.material ); + if ( data.focus !== undefined ) object.focus = data.focus; + if ( data.zoom !== undefined ) object.zoom = data.zoom; + if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge; + if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset; + if ( data.view !== undefined ) object.view = Object.assign( {}, data.view ); - if ( geometry.bones && geometry.bones.length > 0 ) { + break; - object = new SkinnedMesh( geometry, material ); + case 'OrthographicCamera': - } else { + object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far ); - object = new Mesh( geometry, material ); + break; - } + case 'AmbientLight': - break; + object = new AmbientLight( data.color, data.intensity ); - case 'LOD': + break; - object = new LOD(); + case 'DirectionalLight': - break; + object = new DirectionalLight( data.color, data.intensity ); - case 'Line': + break; - object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode ); + case 'PointLight': - break; + object = new PointLight( data.color, data.intensity, data.distance, data.decay ); - case 'LineSegments': + break; - object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) ); + case 'SpotLight': - break; + object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay ); - case 'PointCloud': - case 'Points': + break; - object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) ); + case 'HemisphereLight': - break; + object = new HemisphereLight( data.color, data.groundColor, data.intensity ); - case 'Sprite': + break; - object = new Sprite( getMaterial( data.material ) ); + case 'Mesh': - break; + var geometry = getGeometry( data.geometry ); + var material = getMaterial( data.material ); - case 'Group': + if ( geometry.bones && geometry.bones.length > 0 ) { - object = new Group(); + object = new SkinnedMesh( geometry, material ); - break; + } else { - default: + object = new Mesh( geometry, material ); - object = new Object3D(); + } - } + break; - object.uuid = data.uuid; + case 'LOD': - if ( data.name !== undefined ) object.name = data.name; - if ( data.matrix !== undefined ) { + object = new LOD(); - matrix.fromArray( data.matrix ); - matrix.decompose( object.position, object.quaternion, object.scale ); + break; - } else { + case 'Line': - if ( data.position !== undefined ) object.position.fromArray( data.position ); - if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation ); - if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion ); - if ( data.scale !== undefined ) object.scale.fromArray( data.scale ); + object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode ); - } + break; - if ( data.castShadow !== undefined ) object.castShadow = data.castShadow; - if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow; + case 'LineSegments': - if ( data.visible !== undefined ) object.visible = data.visible; - if ( data.userData !== undefined ) object.userData = data.userData; + object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) ); - if ( data.children !== undefined ) { + break; - for ( var child in data.children ) { + case 'PointCloud': + case 'Points': - object.add( this.parseObject( data.children[ child ], geometries, materials ) ); + object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) ); - } + break; - } + case 'Sprite': - if ( data.type === 'LOD' ) { + object = new Sprite( getMaterial( data.material ) ); - var levels = data.levels; + break; - for ( var l = 0; l < levels.length; l ++ ) { + case 'Group': - var level = levels[ l ]; - var child = object.getObjectByProperty( 'uuid', level.object ); + object = new Group(); - if ( child !== undefined ) { + break; - object.addLevel( child, level.distance ); + default: - } + object = new Object3D(); - } + } - } + object.uuid = data.uuid; - return object; + if ( data.name !== undefined ) object.name = data.name; + if ( data.matrix !== undefined ) { - }; + matrix.fromArray( data.matrix ); + matrix.decompose( object.position, object.quaternion, object.scale ); - }() + } else { - } ); + if ( data.position !== undefined ) object.position.fromArray( data.position ); + if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation ); + if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion ); + if ( data.scale !== undefined ) object.scale.fromArray( data.scale ); - /** - * @author zz85 / http://www.lab4games.net/zz85/blog - */ + } - exports.ShapeUtils = { + if ( data.castShadow !== undefined ) object.castShadow = data.castShadow; + if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow; - // calculate area of the contour polygon + if ( data.shadow ) { - area: function ( contour ) { + if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias; + if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius; + if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize ); + if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera ); - var n = contour.length; - var a = 0.0; + } - for ( var p = n - 1, q = 0; q < n; p = q ++ ) { + if ( data.visible !== undefined ) object.visible = data.visible; + if ( data.userData !== undefined ) object.userData = data.userData; - a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y; + if ( data.children !== undefined ) { - } + for ( var child in data.children ) { - return a * 0.5; + object.add( this.parseObject( data.children[ child ], geometries, materials ) ); - }, + } - triangulate: ( function () { + } - /** - * This code is a quick port of code written in C++ which was submitted to - * flipcode.com by John W. Ratcliff // July 22, 2000 - * See original code and more information here: - * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml - * - * ported to actionscript by Zevan Rosser - * www.actionsnippet.com - * - * ported to javascript by Joshua Koo - * http://www.lab4games.net/zz85/blog - * - */ + if ( data.type === 'LOD' ) { - function snip( contour, u, v, w, n, verts ) { + var levels = data.levels; - var p; - var ax, ay, bx, by; - var cx, cy, px, py; + for ( var l = 0; l < levels.length; l ++ ) { - ax = contour[ verts[ u ] ].x; - ay = contour[ verts[ u ] ].y; + var level = levels[ l ]; + var child = object.getObjectByProperty( 'uuid', level.object ); - bx = contour[ verts[ v ] ].x; - by = contour[ verts[ v ] ].y; + if ( child !== undefined ) { - cx = contour[ verts[ w ] ].x; - cy = contour[ verts[ w ] ].y; + object.addLevel( child, level.distance ); - if ( Number.EPSILON > ( ( ( bx - ax ) * ( cy - ay ) ) - ( ( by - ay ) * ( cx - ax ) ) ) ) return false; + } - var aX, aY, bX, bY, cX, cY; - var apx, apy, bpx, bpy, cpx, cpy; - var cCROSSap, bCROSScp, aCROSSbp; + } - aX = cx - bx; aY = cy - by; - bX = ax - cx; bY = ay - cy; - cX = bx - ax; cY = by - ay; + } - for ( p = 0; p < n; p ++ ) { + return object; - px = contour[ verts[ p ] ].x; - py = contour[ verts[ p ] ].y; + }; - if ( ( ( px === ax ) && ( py === ay ) ) || - ( ( px === bx ) && ( py === by ) ) || - ( ( px === cx ) && ( py === cy ) ) ) continue; + }() - apx = px - ax; apy = py - ay; - bpx = px - bx; bpy = py - by; - cpx = px - cx; cpy = py - cy; + } ); - // see if p is inside triangle abc + /** + * @author zz85 / http://www.lab4games.net/zz85/blog + */ - aCROSSbp = aX * bpy - aY * bpx; - cCROSSap = cX * apy - cY * apx; - bCROSScp = bX * cpy - bY * cpx; + exports.ShapeUtils = { - if ( ( aCROSSbp >= - Number.EPSILON ) && ( bCROSScp >= - Number.EPSILON ) && ( cCROSSap >= - Number.EPSILON ) ) return false; + // calculate area of the contour polygon - } + area: function ( contour ) { - return true; + var n = contour.length; + var a = 0.0; - } + for ( var p = n - 1, q = 0; q < n; p = q ++ ) { - // takes in an contour array and returns + a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y; - return function triangulate( contour, indices ) { + } - var n = contour.length; + return a * 0.5; - if ( n < 3 ) return null; + }, - var result = [], - verts = [], - vertIndices = []; + triangulate: ( function () { - /* we want a counter-clockwise polygon in verts */ + /** + * This code is a quick port of code written in C++ which was submitted to + * flipcode.com by John W. Ratcliff // July 22, 2000 + * See original code and more information here: + * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml + * + * ported to actionscript by Zevan Rosser + * www.actionsnippet.com + * + * ported to javascript by Joshua Koo + * http://www.lab4games.net/zz85/blog + * + */ - var u, v, w; + function snip( contour, u, v, w, n, verts ) { - if ( exports.ShapeUtils.area( contour ) > 0.0 ) { + var p; + var ax, ay, bx, by; + var cx, cy, px, py; - for ( v = 0; v < n; v ++ ) verts[ v ] = v; + ax = contour[ verts[ u ] ].x; + ay = contour[ verts[ u ] ].y; - } else { + bx = contour[ verts[ v ] ].x; + by = contour[ verts[ v ] ].y; - for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v; + cx = contour[ verts[ w ] ].x; + cy = contour[ verts[ w ] ].y; - } + if ( Number.EPSILON > ( ( ( bx - ax ) * ( cy - ay ) ) - ( ( by - ay ) * ( cx - ax ) ) ) ) return false; - var nv = n; + var aX, aY, bX, bY, cX, cY; + var apx, apy, bpx, bpy, cpx, cpy; + var cCROSSap, bCROSScp, aCROSSbp; - /* remove nv - 2 vertices, creating 1 triangle every time */ + aX = cx - bx; aY = cy - by; + bX = ax - cx; bY = ay - cy; + cX = bx - ax; cY = by - ay; - var count = 2 * nv; /* error detection */ + for ( p = 0; p < n; p ++ ) { - for ( v = nv - 1; nv > 2; ) { + px = contour[ verts[ p ] ].x; + py = contour[ verts[ p ] ].y; - /* if we loop, it is probably a non-simple polygon */ + if ( ( ( px === ax ) && ( py === ay ) ) || + ( ( px === bx ) && ( py === by ) ) || + ( ( px === cx ) && ( py === cy ) ) ) continue; - if ( ( count -- ) <= 0 ) { + apx = px - ax; apy = py - ay; + bpx = px - bx; bpy = py - by; + cpx = px - cx; cpy = py - cy; - //** Triangulate: ERROR - probable bad polygon! + // see if p is inside triangle abc - //throw ( "Warning, unable to triangulate polygon!" ); - //return null; - // Sometimes warning is fine, especially polygons are triangulated in reverse. - console.warn( 'THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()' ); + aCROSSbp = aX * bpy - aY * bpx; + cCROSSap = cX * apy - cY * apx; + bCROSScp = bX * cpy - bY * cpx; - if ( indices ) return vertIndices; - return result; + if ( ( aCROSSbp >= - Number.EPSILON ) && ( bCROSScp >= - Number.EPSILON ) && ( cCROSSap >= - Number.EPSILON ) ) return false; - } + } - /* three consecutive vertices in current polygon, */ + return true; - u = v; if ( nv <= u ) u = 0; /* previous */ - v = u + 1; if ( nv <= v ) v = 0; /* new v */ - w = v + 1; if ( nv <= w ) w = 0; /* next */ + } - if ( snip( contour, u, v, w, nv, verts ) ) { + // takes in an contour array and returns - var a, b, c, s, t; + return function triangulate( contour, indices ) { - /* true names of the vertices */ + var n = contour.length; - a = verts[ u ]; - b = verts[ v ]; - c = verts[ w ]; + if ( n < 3 ) return null; - /* output Triangle */ + var result = [], + verts = [], + vertIndices = []; - result.push( [ contour[ a ], - contour[ b ], - contour[ c ] ] ); + /* we want a counter-clockwise polygon in verts */ + var u, v, w; - vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] ); + if ( exports.ShapeUtils.area( contour ) > 0.0 ) { - /* remove v from the remaining polygon */ + for ( v = 0; v < n; v ++ ) verts[ v ] = v; - for ( s = v, t = v + 1; t < nv; s ++, t ++ ) { + } else { - verts[ s ] = verts[ t ]; + for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v; - } + } - nv --; + var nv = n; - /* reset error detection counter */ + /* remove nv - 2 vertices, creating 1 triangle every time */ - count = 2 * nv; + var count = 2 * nv; /* error detection */ - } + for ( v = nv - 1; nv > 2; ) { - } + /* if we loop, it is probably a non-simple polygon */ - if ( indices ) return vertIndices; - return result; + if ( ( count -- ) <= 0 ) { - } + //** Triangulate: ERROR - probable bad polygon! - } )(), + //throw ( "Warning, unable to triangulate polygon!" ); + //return null; + // Sometimes warning is fine, especially polygons are triangulated in reverse. + console.warn( 'THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()' ); - triangulateShape: function ( contour, holes ) { + if ( indices ) return vertIndices; + return result; - function removeDupEndPts(points) { + } - var l = points.length; + /* three consecutive vertices in current polygon, */ - if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) { + u = v; if ( nv <= u ) u = 0; /* previous */ + v = u + 1; if ( nv <= v ) v = 0; /* new v */ + w = v + 1; if ( nv <= w ) w = 0; /* next */ - points.pop(); + if ( snip( contour, u, v, w, nv, verts ) ) { - } + var a, b, c, s, t; - } + /* true names of the vertices */ - removeDupEndPts( contour ); - holes.forEach( removeDupEndPts ); + a = verts[ u ]; + b = verts[ v ]; + c = verts[ w ]; - function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) { + /* output Triangle */ - // inOtherPt needs to be collinear to the inSegment - if ( inSegPt1.x !== inSegPt2.x ) { + result.push( [ contour[ a ], + contour[ b ], + contour[ c ] ] ); - if ( inSegPt1.x < inSegPt2.x ) { - return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) ); + vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] ); - } else { + /* remove v from the remaining polygon */ - return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) ); + for ( s = v, t = v + 1; t < nv; s ++, t ++ ) { - } + verts[ s ] = verts[ t ]; - } else { + } - if ( inSegPt1.y < inSegPt2.y ) { + nv --; - return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) ); + /* reset error detection counter */ - } else { + count = 2 * nv; - return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) ); + } - } + } - } + if ( indices ) return vertIndices; + return result; - } + } - function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) { + } )(), - var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y; - var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y; + triangulateShape: function ( contour, holes ) { - var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x; - var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y; + function removeDupEndPts(points) { - var limit = seg1dy * seg2dx - seg1dx * seg2dy; - var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy; + var l = points.length; - if ( Math.abs( limit ) > Number.EPSILON ) { + if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) { - // not parallel + points.pop(); - var perpSeg2; - if ( limit > 0 ) { + } - if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return []; - perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy; - if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return []; + } - } else { + removeDupEndPts( contour ); + holes.forEach( removeDupEndPts ); - if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return []; - perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy; - if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return []; + function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) { - } + // inOtherPt needs to be collinear to the inSegment + if ( inSegPt1.x !== inSegPt2.x ) { - // i.e. to reduce rounding errors - // intersection at endpoint of segment#1? - if ( perpSeg2 === 0 ) { + if ( inSegPt1.x < inSegPt2.x ) { - if ( ( inExcludeAdjacentSegs ) && - ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return []; - return [ inSeg1Pt1 ]; + return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) ); - } - if ( perpSeg2 === limit ) { + } else { - if ( ( inExcludeAdjacentSegs ) && - ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return []; - return [ inSeg1Pt2 ]; + return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) ); - } - // intersection at endpoint of segment#2? - if ( perpSeg1 === 0 ) return [ inSeg2Pt1 ]; - if ( perpSeg1 === limit ) return [ inSeg2Pt2 ]; + } - // return real intersection point - var factorSeg1 = perpSeg2 / limit; - return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx, - y: inSeg1Pt1.y + factorSeg1 * seg1dy } ]; + } else { - } else { + if ( inSegPt1.y < inSegPt2.y ) { - // parallel or collinear - if ( ( perpSeg1 !== 0 ) || - ( seg2dy * seg1seg2dx !== seg2dx * seg1seg2dy ) ) return []; + return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) ); - // they are collinear or degenerate - var seg1Pt = ( ( seg1dx === 0 ) && ( seg1dy === 0 ) ); // segment1 is just a point? - var seg2Pt = ( ( seg2dx === 0 ) && ( seg2dy === 0 ) ); // segment2 is just a point? - // both segments are points - if ( seg1Pt && seg2Pt ) { + } else { - if ( ( inSeg1Pt1.x !== inSeg2Pt1.x ) || - ( inSeg1Pt1.y !== inSeg2Pt1.y ) ) return []; // they are distinct points - return [ inSeg1Pt1 ]; // they are the same point + return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) ); - } - // segment#1 is a single point - if ( seg1Pt ) { + } - if ( ! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2 - return [ inSeg1Pt1 ]; + } - } - // segment#2 is a single point - if ( seg2Pt ) { + } - if ( ! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1 - return [ inSeg2Pt1 ]; + function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) { - } + var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y; + var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y; - // they are collinear segments, which might overlap - var seg1min, seg1max, seg1minVal, seg1maxVal; - var seg2min, seg2max, seg2minVal, seg2maxVal; - if ( seg1dx !== 0 ) { + var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x; + var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y; - // the segments are NOT on a vertical line - if ( inSeg1Pt1.x < inSeg1Pt2.x ) { + var limit = seg1dy * seg2dx - seg1dx * seg2dy; + var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy; - seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x; - seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x; + if ( Math.abs( limit ) > Number.EPSILON ) { - } else { + // not parallel - seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x; - seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x; + var perpSeg2; + if ( limit > 0 ) { - } - if ( inSeg2Pt1.x < inSeg2Pt2.x ) { + if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return []; + perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy; + if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return []; - seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x; - seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x; + } else { - } else { + if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return []; + perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy; + if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return []; - seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x; - seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x; + } - } + // i.e. to reduce rounding errors + // intersection at endpoint of segment#1? + if ( perpSeg2 === 0 ) { - } else { + if ( ( inExcludeAdjacentSegs ) && + ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return []; + return [ inSeg1Pt1 ]; - // the segments are on a vertical line - if ( inSeg1Pt1.y < inSeg1Pt2.y ) { + } + if ( perpSeg2 === limit ) { - seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y; - seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y; + if ( ( inExcludeAdjacentSegs ) && + ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return []; + return [ inSeg1Pt2 ]; - } else { + } + // intersection at endpoint of segment#2? + if ( perpSeg1 === 0 ) return [ inSeg2Pt1 ]; + if ( perpSeg1 === limit ) return [ inSeg2Pt2 ]; - seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y; - seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y; + // return real intersection point + var factorSeg1 = perpSeg2 / limit; + return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx, + y: inSeg1Pt1.y + factorSeg1 * seg1dy } ]; - } - if ( inSeg2Pt1.y < inSeg2Pt2.y ) { + } else { - seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y; - seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y; + // parallel or collinear + if ( ( perpSeg1 !== 0 ) || + ( seg2dy * seg1seg2dx !== seg2dx * seg1seg2dy ) ) return []; - } else { + // they are collinear or degenerate + var seg1Pt = ( ( seg1dx === 0 ) && ( seg1dy === 0 ) ); // segment1 is just a point? + var seg2Pt = ( ( seg2dx === 0 ) && ( seg2dy === 0 ) ); // segment2 is just a point? + // both segments are points + if ( seg1Pt && seg2Pt ) { - seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y; - seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y; + if ( ( inSeg1Pt1.x !== inSeg2Pt1.x ) || + ( inSeg1Pt1.y !== inSeg2Pt1.y ) ) return []; // they are distinct points + return [ inSeg1Pt1 ]; // they are the same point - } + } + // segment#1 is a single point + if ( seg1Pt ) { - } - if ( seg1minVal <= seg2minVal ) { + if ( ! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2 + return [ inSeg1Pt1 ]; - if ( seg1maxVal < seg2minVal ) return []; - if ( seg1maxVal === seg2minVal ) { + } + // segment#2 is a single point + if ( seg2Pt ) { - if ( inExcludeAdjacentSegs ) return []; - return [ seg2min ]; + if ( ! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1 + return [ inSeg2Pt1 ]; - } - if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ]; - return [ seg2min, seg2max ]; + } - } else { + // they are collinear segments, which might overlap + var seg1min, seg1max, seg1minVal, seg1maxVal; + var seg2min, seg2max, seg2minVal, seg2maxVal; + if ( seg1dx !== 0 ) { - if ( seg1minVal > seg2maxVal ) return []; - if ( seg1minVal === seg2maxVal ) { + // the segments are NOT on a vertical line + if ( inSeg1Pt1.x < inSeg1Pt2.x ) { - if ( inExcludeAdjacentSegs ) return []; - return [ seg1min ]; + seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x; + seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x; - } - if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ]; - return [ seg1min, seg2max ]; + } else { - } + seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x; + seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x; - } + } + if ( inSeg2Pt1.x < inSeg2Pt2.x ) { - } + seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x; + seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x; - function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) { + } else { - // The order of legs is important + seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x; + seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x; - // translation of all points, so that Vertex is at (0,0) - var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y; - var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y; - var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y; + } - // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg. - var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX; - var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX; + } else { - if ( Math.abs( from2toAngle ) > Number.EPSILON ) { + // the segments are on a vertical line + if ( inSeg1Pt1.y < inSeg1Pt2.y ) { - // angle != 180 deg. + seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y; + seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y; - var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX; - // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle ); + } else { - if ( from2toAngle > 0 ) { + seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y; + seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y; - // main angle < 180 deg. - return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) ); + } + if ( inSeg2Pt1.y < inSeg2Pt2.y ) { - } else { + seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y; + seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y; - // main angle > 180 deg. - return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) ); + } else { - } + seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y; + seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y; - } else { + } - // angle == 180 deg. - // console.log( "from2to: 180 deg., from2other: " + from2otherAngle ); - return ( from2otherAngle > 0 ); + } + if ( seg1minVal <= seg2minVal ) { - } + if ( seg1maxVal < seg2minVal ) return []; + if ( seg1maxVal === seg2minVal ) { - } + if ( inExcludeAdjacentSegs ) return []; + return [ seg2min ]; + } + if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ]; + return [ seg2min, seg2max ]; - function removeHoles( contour, holes ) { + } else { - var shape = contour.concat(); // work on this shape - var hole; + if ( seg1minVal > seg2maxVal ) return []; + if ( seg1minVal === seg2maxVal ) { - function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) { + if ( inExcludeAdjacentSegs ) return []; + return [ seg1min ]; - // Check if hole point lies within angle around shape point - var lastShapeIdx = shape.length - 1; + } + if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ]; + return [ seg1min, seg2max ]; - var prevShapeIdx = inShapeIdx - 1; - if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx; + } - var nextShapeIdx = inShapeIdx + 1; - if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0; + } - var insideAngle = isPointInsideAngle( shape[ inShapeIdx ], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[ inHoleIdx ] ); - if ( ! insideAngle ) { + } - // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y ); - return false; + function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) { - } + // The order of legs is important - // Check if shape point lies within angle around hole point - var lastHoleIdx = hole.length - 1; + // translation of all points, so that Vertex is at (0,0) + var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y; + var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y; + var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y; - var prevHoleIdx = inHoleIdx - 1; - if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx; + // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg. + var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX; + var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX; - var nextHoleIdx = inHoleIdx + 1; - if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0; + if ( Math.abs( from2toAngle ) > Number.EPSILON ) { - insideAngle = isPointInsideAngle( hole[ inHoleIdx ], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[ inShapeIdx ] ); - if ( ! insideAngle ) { + // angle != 180 deg. - // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y ); - return false; + var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX; + // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle ); - } + if ( from2toAngle > 0 ) { - return true; + // main angle < 180 deg. + return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) ); - } + } else { - function intersectsShapeEdge( inShapePt, inHolePt ) { + // main angle > 180 deg. + return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) ); - // checks for intersections with shape edges - var sIdx, nextIdx, intersection; - for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) { + } - nextIdx = sIdx + 1; nextIdx %= shape.length; - intersection = intersect_segments_2D( inShapePt, inHolePt, shape[ sIdx ], shape[ nextIdx ], true ); - if ( intersection.length > 0 ) return true; + } else { - } + // angle == 180 deg. + // console.log( "from2to: 180 deg., from2other: " + from2otherAngle ); + return ( from2otherAngle > 0 ); - return false; + } - } + } - var indepHoles = []; - function intersectsHoleEdge( inShapePt, inHolePt ) { + function removeHoles( contour, holes ) { - // checks for intersections with hole edges - var ihIdx, chkHole, - hIdx, nextIdx, intersection; - for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) { + var shape = contour.concat(); // work on this shape + var hole; - chkHole = holes[ indepHoles[ ihIdx ]]; - for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) { + function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) { - nextIdx = hIdx + 1; nextIdx %= chkHole.length; - intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[ hIdx ], chkHole[ nextIdx ], true ); - if ( intersection.length > 0 ) return true; + // Check if hole point lies within angle around shape point + var lastShapeIdx = shape.length - 1; - } + var prevShapeIdx = inShapeIdx - 1; + if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx; - } - return false; + var nextShapeIdx = inShapeIdx + 1; + if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0; - } + var insideAngle = isPointInsideAngle( shape[ inShapeIdx ], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[ inHoleIdx ] ); + if ( ! insideAngle ) { - var holeIndex, shapeIndex, - shapePt, holePt, - holeIdx, cutKey, failedCuts = [], - tmpShape1, tmpShape2, - tmpHole1, tmpHole2; + // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y ); + return false; - for ( var h = 0, hl = holes.length; h < hl; h ++ ) { + } - indepHoles.push( h ); + // Check if shape point lies within angle around hole point + var lastHoleIdx = hole.length - 1; - } + var prevHoleIdx = inHoleIdx - 1; + if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx; - var minShapeIndex = 0; - var counter = indepHoles.length * 2; - while ( indepHoles.length > 0 ) { + var nextHoleIdx = inHoleIdx + 1; + if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0; - counter --; - if ( counter < 0 ) { + insideAngle = isPointInsideAngle( hole[ inHoleIdx ], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[ inShapeIdx ] ); + if ( ! insideAngle ) { - console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" ); - break; + // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y ); + return false; - } + } - // search for shape-vertex and hole-vertex, - // which can be connected without intersections - for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) { + return true; - shapePt = shape[ shapeIndex ]; - holeIndex = - 1; + } - // search for hole which can be reached without intersections - for ( var h = 0; h < indepHoles.length; h ++ ) { + function intersectsShapeEdge( inShapePt, inHolePt ) { - holeIdx = indepHoles[ h ]; + // checks for intersections with shape edges + var sIdx, nextIdx, intersection; + for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) { - // prevent multiple checks - cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx; - if ( failedCuts[ cutKey ] !== undefined ) continue; + nextIdx = sIdx + 1; nextIdx %= shape.length; + intersection = intersect_segments_2D( inShapePt, inHolePt, shape[ sIdx ], shape[ nextIdx ], true ); + if ( intersection.length > 0 ) return true; - hole = holes[ holeIdx ]; - for ( var h2 = 0; h2 < hole.length; h2 ++ ) { + } - holePt = hole[ h2 ]; - if ( ! isCutLineInsideAngles( shapeIndex, h2 ) ) continue; - if ( intersectsShapeEdge( shapePt, holePt ) ) continue; - if ( intersectsHoleEdge( shapePt, holePt ) ) continue; + return false; - holeIndex = h2; - indepHoles.splice( h, 1 ); + } - tmpShape1 = shape.slice( 0, shapeIndex + 1 ); - tmpShape2 = shape.slice( shapeIndex ); - tmpHole1 = hole.slice( holeIndex ); - tmpHole2 = hole.slice( 0, holeIndex + 1 ); + var indepHoles = []; - shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 ); + function intersectsHoleEdge( inShapePt, inHolePt ) { - minShapeIndex = shapeIndex; + // checks for intersections with hole edges + var ihIdx, chkHole, + hIdx, nextIdx, intersection; + for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) { - // Debug only, to show the selected cuts - // glob_CutLines.push( [ shapePt, holePt ] ); + chkHole = holes[ indepHoles[ ihIdx ]]; + for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) { - break; + nextIdx = hIdx + 1; nextIdx %= chkHole.length; + intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[ hIdx ], chkHole[ nextIdx ], true ); + if ( intersection.length > 0 ) return true; - } - if ( holeIndex >= 0 ) break; // hole-vertex found + } - failedCuts[ cutKey ] = true; // remember failure + } + return false; - } - if ( holeIndex >= 0 ) break; // hole-vertex found + } - } + var holeIndex, shapeIndex, + shapePt, holePt, + holeIdx, cutKey, failedCuts = [], + tmpShape1, tmpShape2, + tmpHole1, tmpHole2; - } + for ( var h = 0, hl = holes.length; h < hl; h ++ ) { - return shape; /* shape with no holes */ + indepHoles.push( h ); - } + } + var minShapeIndex = 0; + var counter = indepHoles.length * 2; + while ( indepHoles.length > 0 ) { - var i, il, f, face, - key, index, - allPointsMap = {}; + counter --; + if ( counter < 0 ) { - // To maintain reference to old shape, one must match coordinates, or offset the indices from original arrays. It's probably easier to do the first. + console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" ); + break; - var allpoints = contour.concat(); + } - for ( var h = 0, hl = holes.length; h < hl; h ++ ) { + // search for shape-vertex and hole-vertex, + // which can be connected without intersections + for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) { - Array.prototype.push.apply( allpoints, holes[ h ] ); + shapePt = shape[ shapeIndex ]; + holeIndex = - 1; - } + // search for hole which can be reached without intersections + for ( var h = 0; h < indepHoles.length; h ++ ) { - //console.log( "allpoints",allpoints, allpoints.length ); + holeIdx = indepHoles[ h ]; - // prepare all points map + // prevent multiple checks + cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx; + if ( failedCuts[ cutKey ] !== undefined ) continue; - for ( i = 0, il = allpoints.length; i < il; i ++ ) { + hole = holes[ holeIdx ]; + for ( var h2 = 0; h2 < hole.length; h2 ++ ) { - key = allpoints[ i ].x + ":" + allpoints[ i ].y; + holePt = hole[ h2 ]; + if ( ! isCutLineInsideAngles( shapeIndex, h2 ) ) continue; + if ( intersectsShapeEdge( shapePt, holePt ) ) continue; + if ( intersectsHoleEdge( shapePt, holePt ) ) continue; - if ( allPointsMap[ key ] !== undefined ) { + holeIndex = h2; + indepHoles.splice( h, 1 ); - console.warn( "THREE.ShapeUtils: Duplicate point", key, i ); + tmpShape1 = shape.slice( 0, shapeIndex + 1 ); + tmpShape2 = shape.slice( shapeIndex ); + tmpHole1 = hole.slice( holeIndex ); + tmpHole2 = hole.slice( 0, holeIndex + 1 ); - } + shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 ); - allPointsMap[ key ] = i; + minShapeIndex = shapeIndex; - } + // Debug only, to show the selected cuts + // glob_CutLines.push( [ shapePt, holePt ] ); - // remove holes by cutting paths to holes and adding them to the shape - var shapeWithoutHoles = removeHoles( contour, holes ); + break; - var triangles = exports.ShapeUtils.triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape - //console.log( "triangles",triangles, triangles.length ); + } + if ( holeIndex >= 0 ) break; // hole-vertex found - // check all face vertices against all points map + failedCuts[ cutKey ] = true; // remember failure - for ( i = 0, il = triangles.length; i < il; i ++ ) { + } + if ( holeIndex >= 0 ) break; // hole-vertex found - face = triangles[ i ]; + } - for ( f = 0; f < 3; f ++ ) { + } - key = face[ f ].x + ":" + face[ f ].y; + return shape; /* shape with no holes */ - index = allPointsMap[ key ]; + } - if ( index !== undefined ) { - face[ f ] = index; + var i, il, f, face, + key, index, + allPointsMap = {}; - } + // To maintain reference to old shape, one must match coordinates, or offset the indices from original arrays. It's probably easier to do the first. - } + var allpoints = contour.concat(); - } + for ( var h = 0, hl = holes.length; h < hl; h ++ ) { - return triangles.concat(); + Array.prototype.push.apply( allpoints, holes[ h ] ); - }, + } - isClockWise: function ( pts ) { + //console.log( "allpoints",allpoints, allpoints.length ); - return exports.ShapeUtils.area( pts ) < 0; + // prepare all points map - }, + for ( i = 0, il = allpoints.length; i < il; i ++ ) { - // Bezier Curves formulas obtained from - // http://en.wikipedia.org/wiki/B%C3%A9zier_curve + key = allpoints[ i ].x + ":" + allpoints[ i ].y; - // Quad Bezier Functions + if ( allPointsMap[ key ] !== undefined ) { - b2: ( function () { + console.warn( "THREE.ShapeUtils: Duplicate point", key, i ); - function b2p0( t, p ) { + } - var k = 1 - t; - return k * k * p; + allPointsMap[ key ] = i; - } + } - function b2p1( t, p ) { + // remove holes by cutting paths to holes and adding them to the shape + var shapeWithoutHoles = removeHoles( contour, holes ); - return 2 * ( 1 - t ) * t * p; + var triangles = exports.ShapeUtils.triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape + //console.log( "triangles",triangles, triangles.length ); - } + // check all face vertices against all points map - function b2p2( t, p ) { + for ( i = 0, il = triangles.length; i < il; i ++ ) { - return t * t * p; + face = triangles[ i ]; - } + for ( f = 0; f < 3; f ++ ) { - return function b2( t, p0, p1, p2 ) { + key = face[ f ].x + ":" + face[ f ].y; - return b2p0( t, p0 ) + b2p1( t, p1 ) + b2p2( t, p2 ); + index = allPointsMap[ key ]; - }; + if ( index !== undefined ) { - } )(), + face[ f ] = index; - // Cubic Bezier Functions + } - b3: ( function () { + } - function b3p0( t, p ) { + } - var k = 1 - t; - return k * k * k * p; + return triangles.concat(); - } + }, - function b3p1( t, p ) { + isClockWise: function ( pts ) { - var k = 1 - t; - return 3 * k * k * t * p; + return exports.ShapeUtils.area( pts ) < 0; - } + }, - function b3p2( t, p ) { + // Bezier Curves formulas obtained from + // http://en.wikipedia.org/wiki/B%C3%A9zier_curve - var k = 1 - t; - return 3 * k * t * t * p; + // Quad Bezier Functions - } + b2: ( function () { - function b3p3( t, p ) { + function b2p0( t, p ) { - return t * t * t * p; + var k = 1 - t; + return k * k * p; - } + } - return function b3( t, p0, p1, p2, p3 ) { + function b2p1( t, p ) { - return b3p0( t, p0 ) + b3p1( t, p1 ) + b3p2( t, p2 ) + b3p3( t, p3 ); + return 2 * ( 1 - t ) * t * p; - }; + } - } )() + function b2p2( t, p ) { - }; + return t * t * p; - /** - * @author zz85 / http://www.lab4games.net/zz85/blog - * Extensible curve object - * - * Some common of Curve methods - * .getPoint(t), getTangent(t) - * .getPointAt(u), getTangentAt(u) - * .getPoints(), .getSpacedPoints() - * .getLength() - * .updateArcLengths() - * - * This following classes subclasses THREE.Curve: - * - * -- 2d classes -- - * THREE.LineCurve - * THREE.QuadraticBezierCurve - * THREE.CubicBezierCurve - * THREE.SplineCurve - * THREE.ArcCurve - * THREE.EllipseCurve - * - * -- 3d classes -- - * THREE.LineCurve3 - * THREE.QuadraticBezierCurve3 - * THREE.CubicBezierCurve3 - * THREE.SplineCurve3 - * - * A series of curves can be represented as a THREE.CurvePath - * - **/ + } - /************************************************************** - * Abstract Curve base class - **************************************************************/ + return function b2( t, p0, p1, p2 ) { - function Curve() {} + return b2p0( t, p0 ) + b2p1( t, p1 ) + b2p2( t, p2 ); - Curve.prototype = { + }; - constructor: Curve, + } )(), - // Virtual base class method to overwrite and implement in subclasses - // - t [0 .. 1] + // Cubic Bezier Functions - getPoint: function ( t ) { + b3: ( function () { - console.warn( "THREE.Curve: Warning, getPoint() not implemented!" ); - return null; + function b3p0( t, p ) { - }, + var k = 1 - t; + return k * k * k * p; - // Get point at relative position in curve according to arc length - // - u [0 .. 1] + } - getPointAt: function ( u ) { + function b3p1( t, p ) { - var t = this.getUtoTmapping( u ); - return this.getPoint( t ); + var k = 1 - t; + return 3 * k * k * t * p; - }, + } - // Get sequence of points using getPoint( t ) + function b3p2( t, p ) { - getPoints: function ( divisions ) { + var k = 1 - t; + return 3 * k * t * t * p; - if ( ! divisions ) divisions = 5; + } - var points = []; + function b3p3( t, p ) { - for ( var d = 0; d <= divisions; d ++ ) { + return t * t * t * p; - points.push( this.getPoint( d / divisions ) ); + } - } + return function b3( t, p0, p1, p2, p3 ) { - return points; + return b3p0( t, p0 ) + b3p1( t, p1 ) + b3p2( t, p2 ) + b3p3( t, p3 ); - }, + }; - // Get sequence of points using getPointAt( u ) + } )() - getSpacedPoints: function ( divisions ) { + }; - if ( ! divisions ) divisions = 5; + /** + * @author zz85 / http://www.lab4games.net/zz85/blog + * Extensible curve object + * + * Some common of Curve methods + * .getPoint(t), getTangent(t) + * .getPointAt(u), getTangentAt(u) + * .getPoints(), .getSpacedPoints() + * .getLength() + * .updateArcLengths() + * + * This following classes subclasses THREE.Curve: + * + * -- 2d classes -- + * THREE.LineCurve + * THREE.QuadraticBezierCurve + * THREE.CubicBezierCurve + * THREE.SplineCurve + * THREE.ArcCurve + * THREE.EllipseCurve + * + * -- 3d classes -- + * THREE.LineCurve3 + * THREE.QuadraticBezierCurve3 + * THREE.CubicBezierCurve3 + * THREE.SplineCurve3 + * + * A series of curves can be represented as a THREE.CurvePath + * + **/ + + /************************************************************** + * Abstract Curve base class + **************************************************************/ + + function Curve() {} + + Curve.prototype = { + + constructor: Curve, + + // Virtual base class method to overwrite and implement in subclasses + // - t [0 .. 1] + + getPoint: function ( t ) { + + console.warn( "THREE.Curve: Warning, getPoint() not implemented!" ); + return null; - var points = []; + }, - for ( var d = 0; d <= divisions; d ++ ) { + // Get point at relative position in curve according to arc length + // - u [0 .. 1] - points.push( this.getPointAt( d / divisions ) ); + getPointAt: function ( u ) { - } + var t = this.getUtoTmapping( u ); + return this.getPoint( t ); - return points; + }, - }, + // Get sequence of points using getPoint( t ) - // Get total curve arc length + getPoints: function ( divisions ) { - getLength: function () { + if ( ! divisions ) divisions = 5; - var lengths = this.getLengths(); - return lengths[ lengths.length - 1 ]; + var points = []; - }, + for ( var d = 0; d <= divisions; d ++ ) { - // Get list of cumulative segment lengths + points.push( this.getPoint( d / divisions ) ); - getLengths: function ( divisions ) { + } - if ( ! divisions ) divisions = ( this.__arcLengthDivisions ) ? ( this.__arcLengthDivisions ) : 200; + return points; - if ( this.cacheArcLengths - && ( this.cacheArcLengths.length === divisions + 1 ) - && ! this.needsUpdate ) { + }, - //console.log( "cached", this.cacheArcLengths ); - return this.cacheArcLengths; + // Get sequence of points using getPointAt( u ) - } + getSpacedPoints: function ( divisions ) { - this.needsUpdate = false; + if ( ! divisions ) divisions = 5; - var cache = []; - var current, last = this.getPoint( 0 ); - var p, sum = 0; + var points = []; - cache.push( 0 ); + for ( var d = 0; d <= divisions; d ++ ) { - for ( p = 1; p <= divisions; p ++ ) { + points.push( this.getPointAt( d / divisions ) ); - current = this.getPoint ( p / divisions ); - sum += current.distanceTo( last ); - cache.push( sum ); - last = current; + } - } + return points; - this.cacheArcLengths = cache; + }, - return cache; // { sums: cache, sum:sum }; Sum is in the last element. + // Get total curve arc length - }, + getLength: function () { - updateArcLengths: function() { + var lengths = this.getLengths(); + return lengths[ lengths.length - 1 ]; - this.needsUpdate = true; - this.getLengths(); + }, - }, + // Get list of cumulative segment lengths - // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant + getLengths: function ( divisions ) { - getUtoTmapping: function ( u, distance ) { + if ( ! divisions ) divisions = ( this.__arcLengthDivisions ) ? ( this.__arcLengthDivisions ) : 200; - var arcLengths = this.getLengths(); + if ( this.cacheArcLengths + && ( this.cacheArcLengths.length === divisions + 1 ) + && ! this.needsUpdate ) { - var i = 0, il = arcLengths.length; + //console.log( "cached", this.cacheArcLengths ); + return this.cacheArcLengths; - var targetArcLength; // The targeted u distance value to get + } - if ( distance ) { + this.needsUpdate = false; - targetArcLength = distance; + var cache = []; + var current, last = this.getPoint( 0 ); + var p, sum = 0; - } else { + cache.push( 0 ); - targetArcLength = u * arcLengths[ il - 1 ]; + for ( p = 1; p <= divisions; p ++ ) { - } + current = this.getPoint ( p / divisions ); + sum += current.distanceTo( last ); + cache.push( sum ); + last = current; - //var time = Date.now(); + } - // binary search for the index with largest value smaller than target u distance + this.cacheArcLengths = cache; - var low = 0, high = il - 1, comparison; + return cache; // { sums: cache, sum:sum }; Sum is in the last element. - while ( low <= high ) { + }, - i = Math.floor( low + ( high - low ) / 2 ); // less likely to overflow, though probably not issue here, JS doesn't really have integers, all numbers are floats + updateArcLengths: function() { - comparison = arcLengths[ i ] - targetArcLength; + this.needsUpdate = true; + this.getLengths(); - if ( comparison < 0 ) { + }, - low = i + 1; + // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant - } else if ( comparison > 0 ) { + getUtoTmapping: function ( u, distance ) { - high = i - 1; + var arcLengths = this.getLengths(); - } else { + var i = 0, il = arcLengths.length; - high = i; - break; + var targetArcLength; // The targeted u distance value to get - // DONE + if ( distance ) { - } + targetArcLength = distance; - } + } else { - i = high; + targetArcLength = u * arcLengths[ il - 1 ]; - //console.log('b' , i, low, high, Date.now()- time); + } - if ( arcLengths[ i ] === targetArcLength ) { + //var time = Date.now(); - var t = i / ( il - 1 ); - return t; + // binary search for the index with largest value smaller than target u distance - } + var low = 0, high = il - 1, comparison; - // we could get finer grain at lengths, or use simple interpolation between two points + while ( low <= high ) { - var lengthBefore = arcLengths[ i ]; - var lengthAfter = arcLengths[ i + 1 ]; + i = Math.floor( low + ( high - low ) / 2 ); // less likely to overflow, though probably not issue here, JS doesn't really have integers, all numbers are floats - var segmentLength = lengthAfter - lengthBefore; + comparison = arcLengths[ i ] - targetArcLength; - // determine where we are between the 'before' and 'after' points + if ( comparison < 0 ) { - var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength; + low = i + 1; - // add that fractional amount to t + } else if ( comparison > 0 ) { - var t = ( i + segmentFraction ) / ( il - 1 ); + high = i - 1; - return t; + } else { - }, + high = i; + break; - // Returns a unit vector tangent at t - // In case any sub curve does not implement its tangent derivation, - // 2 points a small delta apart will be used to find its gradient - // which seems to give a reasonable approximation + // DONE - getTangent: function( t ) { + } - var delta = 0.0001; - var t1 = t - delta; - var t2 = t + delta; + } - // Capping in case of danger + i = high; - if ( t1 < 0 ) t1 = 0; - if ( t2 > 1 ) t2 = 1; + //console.log('b' , i, low, high, Date.now()- time); - var pt1 = this.getPoint( t1 ); - var pt2 = this.getPoint( t2 ); + if ( arcLengths[ i ] === targetArcLength ) { - var vec = pt2.clone().sub( pt1 ); - return vec.normalize(); + var t = i / ( il - 1 ); + return t; - }, + } - getTangentAt: function ( u ) { + // we could get finer grain at lengths, or use simple interpolation between two points - var t = this.getUtoTmapping( u ); - return this.getTangent( t ); + var lengthBefore = arcLengths[ i ]; + var lengthAfter = arcLengths[ i + 1 ]; - } + var segmentLength = lengthAfter - lengthBefore; - }; + // determine where we are between the 'before' and 'after' points - // TODO: Transformation for Curves? + var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength; - /************************************************************** - * 3D Curves - **************************************************************/ + // add that fractional amount to t - // A Factory method for creating new curve subclasses + var t = ( i + segmentFraction ) / ( il - 1 ); - Curve.create = function ( constructor, getPointFunc ) { + return t; - constructor.prototype = Object.create( Curve.prototype ); - constructor.prototype.constructor = constructor; - constructor.prototype.getPoint = getPointFunc; + }, - return constructor; + // Returns a unit vector tangent at t + // In case any sub curve does not implement its tangent derivation, + // 2 points a small delta apart will be used to find its gradient + // which seems to give a reasonable approximation - }; + getTangent: function( t ) { - /************************************************************** - * Line - **************************************************************/ + var delta = 0.0001; + var t1 = t - delta; + var t2 = t + delta; - function LineCurve( v1, v2 ) { + // Capping in case of danger - this.v1 = v1; - this.v2 = v2; + if ( t1 < 0 ) t1 = 0; + if ( t2 > 1 ) t2 = 1; - }; + var pt1 = this.getPoint( t1 ); + var pt2 = this.getPoint( t2 ); - LineCurve.prototype = Object.create( Curve.prototype ); - LineCurve.prototype.constructor = LineCurve; + var vec = pt2.clone().sub( pt1 ); + return vec.normalize(); - LineCurve.prototype.isLineCurve = true; + }, - LineCurve.prototype.getPoint = function ( t ) { + getTangentAt: function ( u ) { - if ( t === 1 ) { + var t = this.getUtoTmapping( u ); + return this.getTangent( t ); - return this.v2.clone(); + } - } + }; - var point = this.v2.clone().sub( this.v1 ); - point.multiplyScalar( t ).add( this.v1 ); + // TODO: Transformation for Curves? - return point; + /************************************************************** + * 3D Curves + **************************************************************/ - }; + // A Factory method for creating new curve subclasses - // Line curve is linear, so we can overwrite default getPointAt + Curve.create = function ( constructor, getPointFunc ) { - LineCurve.prototype.getPointAt = function ( u ) { + constructor.prototype = Object.create( Curve.prototype ); + constructor.prototype.constructor = constructor; + constructor.prototype.getPoint = getPointFunc; - return this.getPoint( u ); + return constructor; - }; + }; - LineCurve.prototype.getTangent = function( t ) { + /************************************************************** + * Line + **************************************************************/ - var tangent = this.v2.clone().sub( this.v1 ); + function LineCurve( v1, v2 ) { - return tangent.normalize(); + this.v1 = v1; + this.v2 = v2; - }; + } - /** - * @author zz85 / http://www.lab4games.net/zz85/blog - * - **/ + LineCurve.prototype = Object.create( Curve.prototype ); + LineCurve.prototype.constructor = LineCurve; - /************************************************************** - * Curved Path - a curve path is simply a array of connected - * curves, but retains the api of a curve - **************************************************************/ + LineCurve.prototype.isLineCurve = true; - function CurvePath() { + LineCurve.prototype.getPoint = function ( t ) { - this.curves = []; + if ( t === 1 ) { - this.autoClose = false; // Automatically closes the path + return this.v2.clone(); - }; + } - CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), { + var point = this.v2.clone().sub( this.v1 ); + point.multiplyScalar( t ).add( this.v1 ); - constructor: CurvePath, + return point; - add: function ( curve ) { + }; - this.curves.push( curve ); + // Line curve is linear, so we can overwrite default getPointAt - }, + LineCurve.prototype.getPointAt = function ( u ) { - closePath: function () { + return this.getPoint( u ); - // Add a line curve if start and end of lines are not connected - var startPoint = this.curves[ 0 ].getPoint( 0 ); - var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 ); + }; - if ( ! startPoint.equals( endPoint ) ) { + LineCurve.prototype.getTangent = function( t ) { - this.curves.push( new LineCurve( endPoint, startPoint ) ); + var tangent = this.v2.clone().sub( this.v1 ); - } + return tangent.normalize(); - }, + }; - // To get accurate point with reference to - // entire path distance at time t, - // following has to be done: + /** + * @author zz85 / http://www.lab4games.net/zz85/blog + * + **/ - // 1. Length of each sub path have to be known - // 2. Locate and identify type of curve - // 3. Get t for the curve - // 4. Return curve.getPointAt(t') + /************************************************************** + * Curved Path - a curve path is simply a array of connected + * curves, but retains the api of a curve + **************************************************************/ - getPoint: function ( t ) { + function CurvePath() { - var d = t * this.getLength(); - var curveLengths = this.getCurveLengths(); - var i = 0; + this.curves = []; - // To think about boundaries points. + this.autoClose = false; // Automatically closes the path - while ( i < curveLengths.length ) { + } - if ( curveLengths[ i ] >= d ) { + CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), { - var diff = curveLengths[ i ] - d; - var curve = this.curves[ i ]; + constructor: CurvePath, - var segmentLength = curve.getLength(); - var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength; + add: function ( curve ) { - return curve.getPointAt( u ); + this.curves.push( curve ); - } + }, - i ++; + closePath: function () { - } + // Add a line curve if start and end of lines are not connected + var startPoint = this.curves[ 0 ].getPoint( 0 ); + var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 ); - return null; + if ( ! startPoint.equals( endPoint ) ) { - // loop where sum != 0, sum > d , sum+1 = d ) { - getCurveLengths: function () { + var diff = curveLengths[ i ] - d; + var curve = this.curves[ i ]; - // We use cache values if curves and cache array are same length + var segmentLength = curve.getLength(); + var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength; - if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) { + return curve.getPointAt( u ); - return this.cacheLengths; + } - } + i ++; - // Get length of sub-curve - // Push sums into cached array + } - var lengths = [], sums = 0; + return null; - for ( var i = 0, l = this.curves.length; i < l; i ++ ) { + // loop where sum != 0, sum > d , sum+1 1 && !points[ points.length - 1 ].equals( points[ 0 ] ) ) { + if ( this.autoClose ) { - points.push( points[ 0 ] ); + points.push( points[ 0 ] ); - } + } - return points; + return points; - }, + }, - /************************************************************** - * Create Geometries Helpers - **************************************************************/ + getPoints: function ( divisions ) { - /// Generate geometry from path points (for Line or Points objects) + divisions = divisions || 12; - createPointsGeometry: function ( divisions ) { + var points = [], last; - var pts = this.getPoints( divisions ); - return this.createGeometry( pts ); + for ( var i = 0, curves = this.curves; i < curves.length; i ++ ) { - }, + var curve = curves[ i ]; + var resolution = (curve && curve.isEllipseCurve) ? divisions * 2 + : (curve && curve.isLineCurve) ? 1 + : (curve && curve.isSplineCurve) ? divisions * curve.points.length + : divisions; - // Generate geometry from equidistant sampling along the path + var pts = curve.getPoints( resolution ); - createSpacedPointsGeometry: function ( divisions ) { + for ( var j = 0; j < pts.length; j++ ) { - var pts = this.getSpacedPoints( divisions ); - return this.createGeometry( pts ); + var point = pts[ j ]; - }, + if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates - createGeometry: function ( points ) { + points.push( point ); + last = point; - var geometry = new Geometry(); + } - for ( var i = 0, l = points.length; i < l; i ++ ) { + } - var point = points[ i ]; - geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) ); + if ( this.autoClose && points.length > 1 && !points[ points.length - 1 ].equals( points[ 0 ] ) ) { - } + points.push( points[ 0 ] ); - return geometry; + } - } + return points; - } ); + }, - /************************************************************** - * Ellipse curve - **************************************************************/ + /************************************************************** + * Create Geometries Helpers + **************************************************************/ - function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { + /// Generate geometry from path points (for Line or Points objects) - this.aX = aX; - this.aY = aY; + createPointsGeometry: function ( divisions ) { - this.xRadius = xRadius; - this.yRadius = yRadius; + var pts = this.getPoints( divisions ); + return this.createGeometry( pts ); - this.aStartAngle = aStartAngle; - this.aEndAngle = aEndAngle; + }, - this.aClockwise = aClockwise; + // Generate geometry from equidistant sampling along the path - this.aRotation = aRotation || 0; + createSpacedPointsGeometry: function ( divisions ) { - }; + var pts = this.getSpacedPoints( divisions ); + return this.createGeometry( pts ); - EllipseCurve.prototype = Object.create( Curve.prototype ); - EllipseCurve.prototype.constructor = EllipseCurve; + }, - EllipseCurve.prototype.isEllipseCurve = true; + createGeometry: function ( points ) { - EllipseCurve.prototype.getPoint = function( t ) { + var geometry = new Geometry(); - var twoPi = Math.PI * 2; - var deltaAngle = this.aEndAngle - this.aStartAngle; - var samePoints = Math.abs( deltaAngle ) < Number.EPSILON; + for ( var i = 0, l = points.length; i < l; i ++ ) { - // ensures that deltaAngle is 0 .. 2 PI - while ( deltaAngle < 0 ) deltaAngle += twoPi; - while ( deltaAngle > twoPi ) deltaAngle -= twoPi; + var point = points[ i ]; + geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) ); - if ( deltaAngle < Number.EPSILON ) { + } - if ( samePoints ) { + return geometry; - deltaAngle = 0; + } - } else { + } ); - deltaAngle = twoPi; + /************************************************************** + * Ellipse curve + **************************************************************/ - } + function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { - } + this.aX = aX; + this.aY = aY; - if ( this.aClockwise === true && ! samePoints ) { + this.xRadius = xRadius; + this.yRadius = yRadius; - if ( deltaAngle === twoPi ) { + this.aStartAngle = aStartAngle; + this.aEndAngle = aEndAngle; - deltaAngle = - twoPi; + this.aClockwise = aClockwise; - } else { + this.aRotation = aRotation || 0; - deltaAngle = deltaAngle - twoPi; + } - } + EllipseCurve.prototype = Object.create( Curve.prototype ); + EllipseCurve.prototype.constructor = EllipseCurve; - } + EllipseCurve.prototype.isEllipseCurve = true; - var angle = this.aStartAngle + t * deltaAngle; - var x = this.aX + this.xRadius * Math.cos( angle ); - var y = this.aY + this.yRadius * Math.sin( angle ); + EllipseCurve.prototype.getPoint = function( t ) { - if ( this.aRotation !== 0 ) { + var twoPi = Math.PI * 2; + var deltaAngle = this.aEndAngle - this.aStartAngle; + var samePoints = Math.abs( deltaAngle ) < Number.EPSILON; - var cos = Math.cos( this.aRotation ); - var sin = Math.sin( this.aRotation ); + // ensures that deltaAngle is 0 .. 2 PI + while ( deltaAngle < 0 ) deltaAngle += twoPi; + while ( deltaAngle > twoPi ) deltaAngle -= twoPi; - var tx = x - this.aX; - var ty = y - this.aY; + if ( deltaAngle < Number.EPSILON ) { - // Rotate the point about the center of the ellipse. - x = tx * cos - ty * sin + this.aX; - y = tx * sin + ty * cos + this.aY; + if ( samePoints ) { - } + deltaAngle = 0; - return new Vector2( x, y ); + } else { - }; + deltaAngle = twoPi; - /** - * @author zz85 / http://www.lab4games.net/zz85/blog - */ + } - exports.CurveUtils = { + } - tangentQuadraticBezier: function ( t, p0, p1, p2 ) { + if ( this.aClockwise === true && ! samePoints ) { - return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 ); + if ( deltaAngle === twoPi ) { - }, + deltaAngle = - twoPi; - // Puay Bing, thanks for helping with this derivative! + } else { - tangentCubicBezier: function ( t, p0, p1, p2, p3 ) { + deltaAngle = deltaAngle - twoPi; - return - 3 * p0 * ( 1 - t ) * ( 1 - t ) + - 3 * p1 * ( 1 - t ) * ( 1 - t ) - 6 * t * p1 * ( 1 - t ) + - 6 * t * p2 * ( 1 - t ) - 3 * t * t * p2 + - 3 * t * t * p3; + } - }, + } - tangentSpline: function ( t, p0, p1, p2, p3 ) { + var angle = this.aStartAngle + t * deltaAngle; + var x = this.aX + this.xRadius * Math.cos( angle ); + var y = this.aY + this.yRadius * Math.sin( angle ); - // To check if my formulas are correct + if ( this.aRotation !== 0 ) { - var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1 - var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t - var h01 = - 6 * t * t + 6 * t; // − 2t3 + 3t2 - var h11 = 3 * t * t - 2 * t; // t3 − t2 + var cos = Math.cos( this.aRotation ); + var sin = Math.sin( this.aRotation ); - return h00 + h10 + h01 + h11; + var tx = x - this.aX; + var ty = y - this.aY; - }, + // Rotate the point about the center of the ellipse. + x = tx * cos - ty * sin + this.aX; + y = tx * sin + ty * cos + this.aY; - // Catmull-Rom + } - interpolate: function( p0, p1, p2, p3, t ) { + return new Vector2( x, y ); - var v0 = ( p2 - p0 ) * 0.5; - var v1 = ( p3 - p1 ) * 0.5; - var t2 = t * t; - var t3 = t * t2; - return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1; + }; - } + /** + * @author zz85 / http://www.lab4games.net/zz85/blog + */ - }; + exports.CurveUtils = { - /************************************************************** - * Spline curve - **************************************************************/ + tangentQuadraticBezier: function ( t, p0, p1, p2 ) { - function SplineCurve( points /* array of Vector2 */ ) { + return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 ); - this.points = ( points == undefined ) ? [] : points; + }, - }; + // Puay Bing, thanks for helping with this derivative! - SplineCurve.prototype = Object.create( Curve.prototype ); - SplineCurve.prototype.constructor = SplineCurve; + tangentCubicBezier: function ( t, p0, p1, p2, p3 ) { - SplineCurve.prototype.isSplineCurve = true; + return - 3 * p0 * ( 1 - t ) * ( 1 - t ) + + 3 * p1 * ( 1 - t ) * ( 1 - t ) - 6 * t * p1 * ( 1 - t ) + + 6 * t * p2 * ( 1 - t ) - 3 * t * t * p2 + + 3 * t * t * p3; - SplineCurve.prototype.getPoint = function ( t ) { + }, - var points = this.points; - var point = ( points.length - 1 ) * t; + tangentSpline: function ( t, p0, p1, p2, p3 ) { - var intPoint = Math.floor( point ); - var weight = point - intPoint; + // To check if my formulas are correct - var point0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ]; - var point1 = points[ intPoint ]; - var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ]; - var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ]; + var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1 + var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t + var h01 = - 6 * t * t + 6 * t; // − 2t3 + 3t2 + var h11 = 3 * t * t - 2 * t; // t3 − t2 - var interpolate = exports.CurveUtils.interpolate; + return h00 + h10 + h01 + h11; - return new Vector2( - interpolate( point0.x, point1.x, point2.x, point3.x, weight ), - interpolate( point0.y, point1.y, point2.y, point3.y, weight ) - ); + }, - }; + // Catmull-Rom - /************************************************************** - * Cubic Bezier curve - **************************************************************/ + interpolate: function( p0, p1, p2, p3, t ) { - function CubicBezierCurve( v0, v1, v2, v3 ) { + var v0 = ( p2 - p0 ) * 0.5; + var v1 = ( p3 - p1 ) * 0.5; + var t2 = t * t; + var t3 = t * t2; + return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1; - this.v0 = v0; - this.v1 = v1; - this.v2 = v2; - this.v3 = v3; + } - }; + }; - CubicBezierCurve.prototype = Object.create( Curve.prototype ); - CubicBezierCurve.prototype.constructor = CubicBezierCurve; + /************************************************************** + * Spline curve + **************************************************************/ - CubicBezierCurve.prototype.getPoint = function ( t ) { + function SplineCurve( points /* array of Vector2 */ ) { - var b3 = exports.ShapeUtils.b3; + this.points = ( points === undefined ) ? [] : points; - return new Vector2( - b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ), - b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ) - ); + } - }; + SplineCurve.prototype = Object.create( Curve.prototype ); + SplineCurve.prototype.constructor = SplineCurve; - CubicBezierCurve.prototype.getTangent = function( t ) { + SplineCurve.prototype.isSplineCurve = true; - var tangentCubicBezier = exports.CurveUtils.tangentCubicBezier; + SplineCurve.prototype.getPoint = function ( t ) { - return new Vector2( - tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ), - tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ) - ).normalize(); + var points = this.points; + var point = ( points.length - 1 ) * t; - }; + var intPoint = Math.floor( point ); + var weight = point - intPoint; - /************************************************************** - * Quadratic Bezier curve - **************************************************************/ + var point0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ]; + var point1 = points[ intPoint ]; + var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ]; + var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ]; + var interpolate = exports.CurveUtils.interpolate; - function QuadraticBezierCurve( v0, v1, v2 ) { + return new Vector2( + interpolate( point0.x, point1.x, point2.x, point3.x, weight ), + interpolate( point0.y, point1.y, point2.y, point3.y, weight ) + ); - this.v0 = v0; - this.v1 = v1; - this.v2 = v2; + }; - }; + /************************************************************** + * Cubic Bezier curve + **************************************************************/ - QuadraticBezierCurve.prototype = Object.create( Curve.prototype ); - QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve; + function CubicBezierCurve( v0, v1, v2, v3 ) { + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + this.v3 = v3; - QuadraticBezierCurve.prototype.getPoint = function ( t ) { + } - var b2 = exports.ShapeUtils.b2; + CubicBezierCurve.prototype = Object.create( Curve.prototype ); + CubicBezierCurve.prototype.constructor = CubicBezierCurve; - return new Vector2( - b2( t, this.v0.x, this.v1.x, this.v2.x ), - b2( t, this.v0.y, this.v1.y, this.v2.y ) - ); + CubicBezierCurve.prototype.getPoint = function ( t ) { - }; + var b3 = exports.ShapeUtils.b3; + return new Vector2( + b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ), + b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ) + ); - QuadraticBezierCurve.prototype.getTangent = function( t ) { + }; - var tangentQuadraticBezier = exports.CurveUtils.tangentQuadraticBezier; + CubicBezierCurve.prototype.getTangent = function( t ) { - return new Vector2( - tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x ), - tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y ) - ).normalize(); + var tangentCubicBezier = exports.CurveUtils.tangentCubicBezier; - }; + return new Vector2( + tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ), + tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ) + ).normalize(); - var PathPrototype = Object.assign( Object.create( CurvePath.prototype ), { + }; - fromPoints: function ( vectors ) { + /************************************************************** + * Quadratic Bezier curve + **************************************************************/ - this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y ); - for ( var i = 1, l = vectors.length; i < l; i ++ ) { + function QuadraticBezierCurve( v0, v1, v2 ) { - this.lineTo( vectors[ i ].x, vectors[ i ].y ); + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; - } + } - }, + QuadraticBezierCurve.prototype = Object.create( Curve.prototype ); + QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve; - moveTo: function ( x, y ) { - this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying? + QuadraticBezierCurve.prototype.getPoint = function ( t ) { - }, + var b2 = exports.ShapeUtils.b2; - lineTo: function ( x, y ) { + return new Vector2( + b2( t, this.v0.x, this.v1.x, this.v2.x ), + b2( t, this.v0.y, this.v1.y, this.v2.y ) + ); - var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) ); - this.curves.push( curve ); + }; - this.currentPoint.set( x, y ); - }, + QuadraticBezierCurve.prototype.getTangent = function( t ) { - quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) { + var tangentQuadraticBezier = exports.CurveUtils.tangentQuadraticBezier; - var curve = new QuadraticBezierCurve( - this.currentPoint.clone(), - new Vector2( aCPx, aCPy ), - new Vector2( aX, aY ) - ); + return new Vector2( + tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x ), + tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y ) + ).normalize(); - this.curves.push( curve ); + }; - this.currentPoint.set( aX, aY ); + var PathPrototype = Object.assign( Object.create( CurvePath.prototype ), { - }, + fromPoints: function ( vectors ) { - bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) { + this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y ); - var curve = new CubicBezierCurve( - this.currentPoint.clone(), - new Vector2( aCP1x, aCP1y ), - new Vector2( aCP2x, aCP2y ), - new Vector2( aX, aY ) - ); + for ( var i = 1, l = vectors.length; i < l; i ++ ) { - this.curves.push( curve ); + this.lineTo( vectors[ i ].x, vectors[ i ].y ); - this.currentPoint.set( aX, aY ); + } - }, + }, - splineThru: function ( pts /*Array of Vector*/ ) { + moveTo: function ( x, y ) { - var npts = [ this.currentPoint.clone() ].concat( pts ); + this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying? - var curve = new SplineCurve( npts ); - this.curves.push( curve ); + }, - this.currentPoint.copy( pts[ pts.length - 1 ] ); + lineTo: function ( x, y ) { - }, + var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) ); + this.curves.push( curve ); - arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { + this.currentPoint.set( x, y ); - var x0 = this.currentPoint.x; - var y0 = this.currentPoint.y; + }, - this.absarc( aX + x0, aY + y0, aRadius, - aStartAngle, aEndAngle, aClockwise ); + quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) { - }, + var curve = new QuadraticBezierCurve( + this.currentPoint.clone(), + new Vector2( aCPx, aCPy ), + new Vector2( aX, aY ) + ); - absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { + this.curves.push( curve ); - this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); + this.currentPoint.set( aX, aY ); - }, + }, - ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { + bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) { - var x0 = this.currentPoint.x; - var y0 = this.currentPoint.y; + var curve = new CubicBezierCurve( + this.currentPoint.clone(), + new Vector2( aCP1x, aCP1y ), + new Vector2( aCP2x, aCP2y ), + new Vector2( aX, aY ) + ); - this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); + this.curves.push( curve ); - }, + this.currentPoint.set( aX, aY ); - absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { + }, - var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); + splineThru: function ( pts /*Array of Vector*/ ) { - if ( this.curves.length > 0 ) { + var npts = [ this.currentPoint.clone() ].concat( pts ); - // if a previous curve is present, attempt to join - var firstPoint = curve.getPoint( 0 ); + var curve = new SplineCurve( npts ); + this.curves.push( curve ); - if ( ! firstPoint.equals( this.currentPoint ) ) { + this.currentPoint.copy( pts[ pts.length - 1 ] ); - this.lineTo( firstPoint.x, firstPoint.y ); + }, - } + arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { - } + var x0 = this.currentPoint.x; + var y0 = this.currentPoint.y; - this.curves.push( curve ); + this.absarc( aX + x0, aY + y0, aRadius, + aStartAngle, aEndAngle, aClockwise ); - var lastPoint = curve.getPoint( 1 ); - this.currentPoint.copy( lastPoint ); + }, - } + absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { - } ) + this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); - /** - * @author WestLangley / https://github.com/WestLangley - * @author zz85 / https://github.com/zz85 - * @author miningold / https://github.com/miningold - * @author jonobr1 / https://github.com/jonobr1 - * - * Modified from the TorusKnotGeometry by @oosmoxiecode - * - * Creates a tube which extrudes along a 3d spline - * - * Uses parallel transport frames as described in - * http://www.cs.indiana.edu/pub/techreports/TR425.pdf - */ + }, - function TubeGeometry( path, segments, radius, radialSegments, closed, taper ) { + ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { - Geometry.call( this ); + var x0 = this.currentPoint.x; + var y0 = this.currentPoint.y; - this.type = 'TubeGeometry'; + this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); - this.parameters = { - path: path, - segments: segments, - radius: radius, - radialSegments: radialSegments, - closed: closed, - taper: taper - }; + }, - segments = segments || 64; - radius = radius || 1; - radialSegments = radialSegments || 8; - closed = closed || false; - taper = taper || TubeGeometry.NoTaper; + absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { - var grid = []; + var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); - var scope = this, + if ( this.curves.length > 0 ) { - tangent, - normal, - binormal, + // if a previous curve is present, attempt to join + var firstPoint = curve.getPoint( 0 ); - numpoints = segments + 1, + if ( ! firstPoint.equals( this.currentPoint ) ) { - u, v, r, + this.lineTo( firstPoint.x, firstPoint.y ); - cx, cy, - pos, pos2 = new Vector3(), - i, j, - ip, jp, - a, b, c, d, - uva, uvb, uvc, uvd; + } - var frames = new TubeGeometry.FrenetFrames( path, segments, closed ), - tangents = frames.tangents, - normals = frames.normals, - binormals = frames.binormals; + } - // proxy internals - this.tangents = tangents; - this.normals = normals; - this.binormals = binormals; + this.curves.push( curve ); - function vert( x, y, z ) { + var lastPoint = curve.getPoint( 1 ); + this.currentPoint.copy( lastPoint ); - return scope.vertices.push( new Vector3( x, y, z ) ) - 1; + } - } + } ); - // construct the grid + /** + * @author WestLangley / https://github.com/WestLangley + * @author zz85 / https://github.com/zz85 + * @author miningold / https://github.com/miningold + * @author jonobr1 / https://github.com/jonobr1 + * + * Modified from the TorusKnotGeometry by @oosmoxiecode + * + * Creates a tube which extrudes along a 3d spline + * + * Uses parallel transport frames as described in + * http://www.cs.indiana.edu/pub/techreports/TR425.pdf + */ - for ( i = 0; i < numpoints; i ++ ) { + function TubeGeometry( path, segments, radius, radialSegments, closed, taper ) { - grid[ i ] = []; + Geometry.call( this ); - u = i / ( numpoints - 1 ); + this.type = 'TubeGeometry'; - pos = path.getPointAt( u ); + this.parameters = { + path: path, + segments: segments, + radius: radius, + radialSegments: radialSegments, + closed: closed, + taper: taper + }; - tangent = tangents[ i ]; - normal = normals[ i ]; - binormal = binormals[ i ]; + segments = segments || 64; + radius = radius || 1; + radialSegments = radialSegments || 8; + closed = closed || false; + taper = taper || TubeGeometry.NoTaper; - r = radius * taper( u ); + var grid = []; - for ( j = 0; j < radialSegments; j ++ ) { + var scope = this, - v = j / radialSegments * 2 * Math.PI; + tangent, + normal, + binormal, - cx = - r * Math.cos( v ); // TODO: Hack: Negating it so it faces outside. - cy = r * Math.sin( v ); + numpoints = segments + 1, - pos2.copy( pos ); - pos2.x += cx * normal.x + cy * binormal.x; - pos2.y += cx * normal.y + cy * binormal.y; - pos2.z += cx * normal.z + cy * binormal.z; + u, v, r, - grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z ); + cx, cy, + pos, pos2 = new Vector3(), + i, j, + ip, jp, + a, b, c, d, + uva, uvb, uvc, uvd; - } + var frames = new TubeGeometry.FrenetFrames( path, segments, closed ), + tangents = frames.tangents, + normals = frames.normals, + binormals = frames.binormals; - } + // proxy internals + this.tangents = tangents; + this.normals = normals; + this.binormals = binormals; + function vert( x, y, z ) { - // construct the mesh + return scope.vertices.push( new Vector3( x, y, z ) ) - 1; - for ( i = 0; i < segments; i ++ ) { + } - for ( j = 0; j < radialSegments; j ++ ) { + // construct the grid - ip = ( closed ) ? ( i + 1 ) % segments : i + 1; - jp = ( j + 1 ) % radialSegments; + for ( i = 0; i < numpoints; i ++ ) { - a = grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! *** - b = grid[ ip ][ j ]; - c = grid[ ip ][ jp ]; - d = grid[ i ][ jp ]; + grid[ i ] = []; - uva = new Vector2( i / segments, j / radialSegments ); - uvb = new Vector2( ( i + 1 ) / segments, j / radialSegments ); - uvc = new Vector2( ( i + 1 ) / segments, ( j + 1 ) / radialSegments ); - uvd = new Vector2( i / segments, ( j + 1 ) / radialSegments ); + u = i / ( numpoints - 1 ); - this.faces.push( new Face3( a, b, d ) ); - this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] ); + pos = path.getPointAt( u ); - this.faces.push( new Face3( b, c, d ) ); - this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] ); + tangent = tangents[ i ]; + normal = normals[ i ]; + binormal = binormals[ i ]; - } + r = radius * taper( u ); - } + for ( j = 0; j < radialSegments; j ++ ) { - this.computeFaceNormals(); - this.computeVertexNormals(); + v = j / radialSegments * 2 * Math.PI; - }; + cx = - r * Math.cos( v ); // TODO: Hack: Negating it so it faces outside. + cy = r * Math.sin( v ); - TubeGeometry.prototype = Object.create( Geometry.prototype ); - TubeGeometry.prototype.constructor = TubeGeometry; + pos2.copy( pos ); + pos2.x += cx * normal.x + cy * binormal.x; + pos2.y += cx * normal.y + cy * binormal.y; + pos2.z += cx * normal.z + cy * binormal.z; - TubeGeometry.NoTaper = function ( u ) { + grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z ); - return 1; + } - }; + } - TubeGeometry.SinusoidalTaper = function ( u ) { - return Math.sin( Math.PI * u ); + // construct the mesh - }; + for ( i = 0; i < segments; i ++ ) { - // For computing of Frenet frames, exposing the tangents, normals and binormals the spline - TubeGeometry.FrenetFrames = function ( path, segments, closed ) { + for ( j = 0; j < radialSegments; j ++ ) { - var normal = new Vector3(), + ip = ( closed ) ? ( i + 1 ) % segments : i + 1; + jp = ( j + 1 ) % radialSegments; - tangents = [], - normals = [], - binormals = [], + a = grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! *** + b = grid[ ip ][ j ]; + c = grid[ ip ][ jp ]; + d = grid[ i ][ jp ]; - vec = new Vector3(), - mat = new Matrix4(), + uva = new Vector2( i / segments, j / radialSegments ); + uvb = new Vector2( ( i + 1 ) / segments, j / radialSegments ); + uvc = new Vector2( ( i + 1 ) / segments, ( j + 1 ) / radialSegments ); + uvd = new Vector2( i / segments, ( j + 1 ) / radialSegments ); - numpoints = segments + 1, - theta, - smallest, + this.faces.push( new Face3( a, b, d ) ); + this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] ); - tx, ty, tz, - i, u; + this.faces.push( new Face3( b, c, d ) ); + this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] ); + } - // expose internals - this.tangents = tangents; - this.normals = normals; - this.binormals = binormals; + } - // compute the tangent vectors for each segment on the path + this.computeFaceNormals(); + this.computeVertexNormals(); - for ( i = 0; i < numpoints; i ++ ) { + } - u = i / ( numpoints - 1 ); + TubeGeometry.prototype = Object.create( Geometry.prototype ); + TubeGeometry.prototype.constructor = TubeGeometry; - tangents[ i ] = path.getTangentAt( u ); - tangents[ i ].normalize(); + TubeGeometry.NoTaper = function ( u ) { - } + return 1; - initialNormal3(); + }; - /* - function initialNormal1(lastBinormal) { - // fixed start binormal. Has dangers of 0 vectors - normals[ 0 ] = new THREE.Vector3(); - binormals[ 0 ] = new THREE.Vector3(); - if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 ); - normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize(); - binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize(); - } + TubeGeometry.SinusoidalTaper = function ( u ) { - function initialNormal2() { + return Math.sin( Math.PI * u ); - // This uses the Frenet-Serret formula for deriving binormal - var t2 = path.getTangentAt( epsilon ); + }; - normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize(); - binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] ); + // For computing of Frenet frames, exposing the tangents, normals and binormals the spline + TubeGeometry.FrenetFrames = function ( path, segments, closed ) { - normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent - binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize(); + var normal = new Vector3(), - } - */ + tangents = [], + normals = [], + binormals = [], - function initialNormal3() { + vec = new Vector3(), + mat = new Matrix4(), - // select an initial normal vector perpendicular to the first tangent vector, - // and in the direction of the smallest tangent xyz component + numpoints = segments + 1, + theta, + smallest, - normals[ 0 ] = new Vector3(); - binormals[ 0 ] = new Vector3(); - smallest = Number.MAX_VALUE; - tx = Math.abs( tangents[ 0 ].x ); - ty = Math.abs( tangents[ 0 ].y ); - tz = Math.abs( tangents[ 0 ].z ); + tx, ty, tz, + i, u; - if ( tx <= smallest ) { - smallest = tx; - normal.set( 1, 0, 0 ); + // expose internals + this.tangents = tangents; + this.normals = normals; + this.binormals = binormals; - } + // compute the tangent vectors for each segment on the path - if ( ty <= smallest ) { + for ( i = 0; i < numpoints; i ++ ) { - smallest = ty; - normal.set( 0, 1, 0 ); + u = i / ( numpoints - 1 ); - } + tangents[ i ] = path.getTangentAt( u ); + tangents[ i ].normalize(); - if ( tz <= smallest ) { + } - normal.set( 0, 0, 1 ); + initialNormal3(); - } + /* + function initialNormal1(lastBinormal) { + // fixed start binormal. Has dangers of 0 vectors + normals[ 0 ] = new THREE.Vector3(); + binormals[ 0 ] = new THREE.Vector3(); + if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 ); + normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize(); + binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize(); + } - vec.crossVectors( tangents[ 0 ], normal ).normalize(); + function initialNormal2() { - normals[ 0 ].crossVectors( tangents[ 0 ], vec ); - binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ); + // This uses the Frenet-Serret formula for deriving binormal + var t2 = path.getTangentAt( epsilon ); - } + normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize(); + binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] ); + normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent + binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize(); - // compute the slowly-varying normal and binormal vectors for each segment on the path + } + */ - for ( i = 1; i < numpoints; i ++ ) { + function initialNormal3() { - normals[ i ] = normals[ i - 1 ].clone(); + // select an initial normal vector perpendicular to the first tangent vector, + // and in the direction of the smallest tangent xyz component - binormals[ i ] = binormals[ i - 1 ].clone(); + normals[ 0 ] = new Vector3(); + binormals[ 0 ] = new Vector3(); + smallest = Number.MAX_VALUE; + tx = Math.abs( tangents[ 0 ].x ); + ty = Math.abs( tangents[ 0 ].y ); + tz = Math.abs( tangents[ 0 ].z ); - vec.crossVectors( tangents[ i - 1 ], tangents[ i ] ); + if ( tx <= smallest ) { - if ( vec.length() > Number.EPSILON ) { + smallest = tx; + normal.set( 1, 0, 0 ); - vec.normalize(); + } - theta = Math.acos( exports.Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors + if ( ty <= smallest ) { - normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) ); + smallest = ty; + normal.set( 0, 1, 0 ); - } + } - binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); + if ( tz <= smallest ) { - } + normal.set( 0, 0, 1 ); + } - // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same + vec.crossVectors( tangents[ 0 ], normal ).normalize(); - if ( closed ) { + normals[ 0 ].crossVectors( tangents[ 0 ], vec ); + binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ); - theta = Math.acos( exports.Math.clamp( normals[ 0 ].dot( normals[ numpoints - 1 ] ), - 1, 1 ) ); - theta /= ( numpoints - 1 ); + } - if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints - 1 ] ) ) > 0 ) { - theta = - theta; + // compute the slowly-varying normal and binormal vectors for each segment on the path - } + for ( i = 1; i < numpoints; i ++ ) { - for ( i = 1; i < numpoints; i ++ ) { + normals[ i ] = normals[ i - 1 ].clone(); - // twist a little... - normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) ); - binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); + binormals[ i ] = binormals[ i - 1 ].clone(); - } + vec.crossVectors( tangents[ i - 1 ], tangents[ i ] ); - } + if ( vec.length() > Number.EPSILON ) { - }; + vec.normalize(); - /** - * @author zz85 / http://www.lab4games.net/zz85/blog - * - * Creates extruded geometry from a path shape. - * - * parameters = { - * - * curveSegments: , // number of points on the curves - * steps: , // number of points for z-side extrusions / used for subdividing segments of extrude spline too - * amount: , // Depth to extrude the shape - * - * bevelEnabled: , // turn on bevel - * bevelThickness: , // how deep into the original shape bevel goes - * bevelSize: , // how far from shape outline is bevel - * bevelSegments: , // number of bevel layers - * - * extrudePath: // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined) - * frames: // containing arrays of tangents, normals, binormals - * - * uvGenerator: // object that provides UV generator functions - * - * } - **/ + theta = Math.acos( exports.Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors - function ExtrudeGeometry( shapes, options ) { + normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) ); - if ( typeof( shapes ) === "undefined" ) { + } - shapes = []; - return; + binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); - } + } - Geometry.call( this ); - this.type = 'ExtrudeGeometry'; + // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same - shapes = Array.isArray( shapes ) ? shapes : [ shapes ]; + if ( closed ) { - this.addShapeList( shapes, options ); + theta = Math.acos( exports.Math.clamp( normals[ 0 ].dot( normals[ numpoints - 1 ] ), - 1, 1 ) ); + theta /= ( numpoints - 1 ); - this.computeFaceNormals(); + if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints - 1 ] ) ) > 0 ) { - // can't really use automatic vertex normals - // as then front and back sides get smoothed too - // should do separate smoothing just for sides + theta = - theta; - //this.computeVertexNormals(); + } - //console.log( "took", ( Date.now() - startTime ) ); + for ( i = 1; i < numpoints; i ++ ) { - }; + // twist a little... + normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) ); + binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); - ExtrudeGeometry.prototype = Object.create( Geometry.prototype ); - ExtrudeGeometry.prototype.constructor = ExtrudeGeometry; + } - ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) { + } - var sl = shapes.length; + }; - for ( var s = 0; s < sl; s ++ ) { + /** + * @author zz85 / http://www.lab4games.net/zz85/blog + * + * Creates extruded geometry from a path shape. + * + * parameters = { + * + * curveSegments: , // number of points on the curves + * steps: , // number of points for z-side extrusions / used for subdividing segments of extrude spline too + * amount: , // Depth to extrude the shape + * + * bevelEnabled: , // turn on bevel + * bevelThickness: , // how deep into the original shape bevel goes + * bevelSize: , // how far from shape outline is bevel + * bevelSegments: , // number of bevel layers + * + * extrudePath: // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined) + * frames: // containing arrays of tangents, normals, binormals + * + * uvGenerator: // object that provides UV generator functions + * + * } + **/ + + function ExtrudeGeometry( shapes, options ) { + + if ( typeof( shapes ) === "undefined" ) { + + shapes = []; + return; - var shape = shapes[ s ]; - this.addShape( shape, options ); + } - } + Geometry.call( this ); - }; + this.type = 'ExtrudeGeometry'; - ExtrudeGeometry.prototype.addShape = function ( shape, options ) { + shapes = Array.isArray( shapes ) ? shapes : [ shapes ]; - var amount = options.amount !== undefined ? options.amount : 100; + this.addShapeList( shapes, options ); - var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10 - var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8 - var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3; + this.computeFaceNormals(); - var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false + // can't really use automatic vertex normals + // as then front and back sides get smoothed too + // should do separate smoothing just for sides - var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12; + //this.computeVertexNormals(); - var steps = options.steps !== undefined ? options.steps : 1; + //console.log( "took", ( Date.now() - startTime ) ); - var extrudePath = options.extrudePath; - var extrudePts, extrudeByPath = false; + } - // Use default WorldUVGenerator if no UV generators are specified. - var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : ExtrudeGeometry.WorldUVGenerator; + ExtrudeGeometry.prototype = Object.create( Geometry.prototype ); + ExtrudeGeometry.prototype.constructor = ExtrudeGeometry; - var splineTube, binormal, normal, position2; - if ( extrudePath ) { + ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) { - extrudePts = extrudePath.getSpacedPoints( steps ); + var sl = shapes.length; - extrudeByPath = true; - bevelEnabled = false; // bevels not supported for path extrusion + for ( var s = 0; s < sl; s ++ ) { - // SETUP TNB variables + var shape = shapes[ s ]; + this.addShape( shape, options ); - // Reuse TNB from TubeGeomtry for now. - // TODO1 - have a .isClosed in spline? + } - splineTube = options.frames !== undefined ? options.frames : new TubeGeometry.FrenetFrames( extrudePath, steps, false ); + }; - // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length); + ExtrudeGeometry.prototype.addShape = function ( shape, options ) { - binormal = new Vector3(); - normal = new Vector3(); - position2 = new Vector3(); + var amount = options.amount !== undefined ? options.amount : 100; - } + var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10 + var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8 + var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3; - // Safeguards if bevels are not enabled + var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false - if ( ! bevelEnabled ) { + var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12; - bevelSegments = 0; - bevelThickness = 0; - bevelSize = 0; + var steps = options.steps !== undefined ? options.steps : 1; - } + var extrudePath = options.extrudePath; + var extrudePts, extrudeByPath = false; - // Variables initialization + // Use default WorldUVGenerator if no UV generators are specified. + var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : ExtrudeGeometry.WorldUVGenerator; - var ahole, h, hl; // looping of holes - var scope = this; + var splineTube, binormal, normal, position2; + if ( extrudePath ) { - var shapesOffset = this.vertices.length; + extrudePts = extrudePath.getSpacedPoints( steps ); - var shapePoints = shape.extractPoints( curveSegments ); + extrudeByPath = true; + bevelEnabled = false; // bevels not supported for path extrusion - var vertices = shapePoints.shape; - var holes = shapePoints.holes; + // SETUP TNB variables - var reverse = ! exports.ShapeUtils.isClockWise( vertices ); + // Reuse TNB from TubeGeomtry for now. + // TODO1 - have a .isClosed in spline? - if ( reverse ) { + splineTube = options.frames !== undefined ? options.frames : new TubeGeometry.FrenetFrames( extrudePath, steps, false ); - vertices = vertices.reverse(); + // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length); - // Maybe we should also check if holes are in the opposite direction, just to be safe ... + binormal = new Vector3(); + normal = new Vector3(); + position2 = new Vector3(); - for ( h = 0, hl = holes.length; h < hl; h ++ ) { + } - ahole = holes[ h ]; + // Safeguards if bevels are not enabled - if ( exports.ShapeUtils.isClockWise( ahole ) ) { + if ( ! bevelEnabled ) { - holes[ h ] = ahole.reverse(); + bevelSegments = 0; + bevelThickness = 0; + bevelSize = 0; - } + } - } + // Variables initialization - reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)! + var ahole, h, hl; // looping of holes + var scope = this; - } + var shapesOffset = this.vertices.length; + var shapePoints = shape.extractPoints( curveSegments ); - var faces = exports.ShapeUtils.triangulateShape( vertices, holes ); + var vertices = shapePoints.shape; + var holes = shapePoints.holes; - /* Vertices */ + var reverse = ! exports.ShapeUtils.isClockWise( vertices ); - var contour = vertices; // vertices has all points but contour has only points of circumference + if ( reverse ) { - for ( h = 0, hl = holes.length; h < hl; h ++ ) { + vertices = vertices.reverse(); - ahole = holes[ h ]; + // Maybe we should also check if holes are in the opposite direction, just to be safe ... - vertices = vertices.concat( ahole ); + for ( h = 0, hl = holes.length; h < hl; h ++ ) { - } + ahole = holes[ h ]; + if ( exports.ShapeUtils.isClockWise( ahole ) ) { - function scalePt2( pt, vec, size ) { + holes[ h ] = ahole.reverse(); - if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" ); + } - return vec.clone().multiplyScalar( size ).add( pt ); + } - } + reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)! - var b, bs, t, z, - vert, vlen = vertices.length, - face, flen = faces.length; + } - // Find directions for point movement + var faces = exports.ShapeUtils.triangulateShape( vertices, holes ); + /* Vertices */ - function getBevelVec( inPt, inPrev, inNext ) { + var contour = vertices; // vertices has all points but contour has only points of circumference - // computes for inPt the corresponding point inPt' on a new contour - // shifted by 1 unit (length of normalized vector) to the left - // if we walk along contour clockwise, this new contour is outside the old one - // - // inPt' is the intersection of the two lines parallel to the two - // adjacent edges of inPt at a distance of 1 unit on the left side. + for ( h = 0, hl = holes.length; h < hl; h ++ ) { - var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt + ahole = holes[ h ]; - // good reading for geometry algorithms (here: line-line intersection) - // http://geomalgorithms.com/a05-_intersect-1.html + vertices = vertices.concat( ahole ); - var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y; - var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y; + } - var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y ); - // check for collinear edges - var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x ); + function scalePt2( pt, vec, size ) { - if ( Math.abs( collinear0 ) > Number.EPSILON ) { + if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" ); - // not collinear + return vec.clone().multiplyScalar( size ).add( pt ); - // length of vectors for normalizing + } - var v_prev_len = Math.sqrt( v_prev_lensq ); - var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y ); + var b, bs, t, z, + vert, vlen = vertices.length, + face, flen = faces.length; - // shift adjacent points by unit vectors to the left - var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len ); - var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len ); + // Find directions for point movement - var ptNextShift_x = ( inNext.x - v_next_y / v_next_len ); - var ptNextShift_y = ( inNext.y + v_next_x / v_next_len ); - // scaling factor for v_prev to intersection point + function getBevelVec( inPt, inPrev, inNext ) { - var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y - - ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) / - ( v_prev_x * v_next_y - v_prev_y * v_next_x ); + // computes for inPt the corresponding point inPt' on a new contour + // shifted by 1 unit (length of normalized vector) to the left + // if we walk along contour clockwise, this new contour is outside the old one + // + // inPt' is the intersection of the two lines parallel to the two + // adjacent edges of inPt at a distance of 1 unit on the left side. - // vector from inPt to intersection point + var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt - v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x ); - v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y ); + // good reading for geometry algorithms (here: line-line intersection) + // http://geomalgorithms.com/a05-_intersect-1.html - // Don't normalize!, otherwise sharp corners become ugly - // but prevent crazy spikes - var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y ); - if ( v_trans_lensq <= 2 ) { + var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y; + var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y; - return new Vector2( v_trans_x, v_trans_y ); + var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y ); - } else { + // check for collinear edges + var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x ); - shrink_by = Math.sqrt( v_trans_lensq / 2 ); + if ( Math.abs( collinear0 ) > Number.EPSILON ) { - } + // not collinear - } else { + // length of vectors for normalizing - // handle special case of collinear edges + var v_prev_len = Math.sqrt( v_prev_lensq ); + var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y ); - var direction_eq = false; // assumes: opposite - if ( v_prev_x > Number.EPSILON ) { + // shift adjacent points by unit vectors to the left - if ( v_next_x > Number.EPSILON ) { + var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len ); + var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len ); - direction_eq = true; + var ptNextShift_x = ( inNext.x - v_next_y / v_next_len ); + var ptNextShift_y = ( inNext.y + v_next_x / v_next_len ); - } + // scaling factor for v_prev to intersection point - } else { + var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y - + ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) / + ( v_prev_x * v_next_y - v_prev_y * v_next_x ); - if ( v_prev_x < - Number.EPSILON ) { + // vector from inPt to intersection point - if ( v_next_x < - Number.EPSILON ) { + v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x ); + v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y ); - direction_eq = true; + // Don't normalize!, otherwise sharp corners become ugly + // but prevent crazy spikes + var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y ); + if ( v_trans_lensq <= 2 ) { - } + return new Vector2( v_trans_x, v_trans_y ); - } else { + } else { - if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) { + shrink_by = Math.sqrt( v_trans_lensq / 2 ); - direction_eq = true; + } - } + } else { - } + // handle special case of collinear edges - } + var direction_eq = false; // assumes: opposite + if ( v_prev_x > Number.EPSILON ) { - if ( direction_eq ) { + if ( v_next_x > Number.EPSILON ) { - // console.log("Warning: lines are a straight sequence"); - v_trans_x = - v_prev_y; - v_trans_y = v_prev_x; - shrink_by = Math.sqrt( v_prev_lensq ); + direction_eq = true; - } else { + } - // console.log("Warning: lines are a straight spike"); - v_trans_x = v_prev_x; - v_trans_y = v_prev_y; - shrink_by = Math.sqrt( v_prev_lensq / 2 ); + } else { - } + if ( v_prev_x < - Number.EPSILON ) { - } + if ( v_next_x < - Number.EPSILON ) { - return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by ); + direction_eq = true; - } + } + } else { - var contourMovements = []; + if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) { - for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) { + direction_eq = true; - if ( j === il ) j = 0; - if ( k === il ) k = 0; + } - // (j)---(i)---(k) - // console.log('i,j,k', i, j , k) + } - contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] ); + } - } + if ( direction_eq ) { - var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat(); + // console.log("Warning: lines are a straight sequence"); + v_trans_x = - v_prev_y; + v_trans_y = v_prev_x; + shrink_by = Math.sqrt( v_prev_lensq ); - for ( h = 0, hl = holes.length; h < hl; h ++ ) { + } else { - ahole = holes[ h ]; + // console.log("Warning: lines are a straight spike"); + v_trans_x = v_prev_x; + v_trans_y = v_prev_y; + shrink_by = Math.sqrt( v_prev_lensq / 2 ); - oneHoleMovements = []; + } - for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) { + } - if ( j === il ) j = 0; - if ( k === il ) k = 0; + return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by ); - // (j)---(i)---(k) - oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] ); + } - } - holesMovements.push( oneHoleMovements ); - verticesMovements = verticesMovements.concat( oneHoleMovements ); + var contourMovements = []; - } + for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) { + if ( j === il ) j = 0; + if ( k === il ) k = 0; - // Loop bevelSegments, 1 for the front, 1 for the back + // (j)---(i)---(k) + // console.log('i,j,k', i, j , k) - for ( b = 0; b < bevelSegments; b ++ ) { + contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] ); - //for ( b = bevelSegments; b > 0; b -- ) { + } - t = b / bevelSegments; - z = bevelThickness * Math.cos( t * Math.PI / 2 ); - bs = bevelSize * Math.sin( t * Math.PI / 2 ); + var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat(); - // contract shape + for ( h = 0, hl = holes.length; h < hl; h ++ ) { - for ( i = 0, il = contour.length; i < il; i ++ ) { + ahole = holes[ h ]; - vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); + oneHoleMovements = []; - v( vert.x, vert.y, - z ); + for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) { - } + if ( j === il ) j = 0; + if ( k === il ) k = 0; - // expand holes + // (j)---(i)---(k) + oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] ); - for ( h = 0, hl = holes.length; h < hl; h ++ ) { + } - ahole = holes[ h ]; - oneHoleMovements = holesMovements[ h ]; + holesMovements.push( oneHoleMovements ); + verticesMovements = verticesMovements.concat( oneHoleMovements ); - for ( i = 0, il = ahole.length; i < il; i ++ ) { + } - vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); - v( vert.x, vert.y, - z ); + // Loop bevelSegments, 1 for the front, 1 for the back - } + for ( b = 0; b < bevelSegments; b ++ ) { - } + //for ( b = bevelSegments; b > 0; b -- ) { - } + t = b / bevelSegments; + z = bevelThickness * Math.cos( t * Math.PI / 2 ); + bs = bevelSize * Math.sin( t * Math.PI / 2 ); - bs = bevelSize; + // contract shape - // Back facing vertices + for ( i = 0, il = contour.length; i < il; i ++ ) { - for ( i = 0; i < vlen; i ++ ) { + vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); - vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; + v( vert.x, vert.y, - z ); - if ( ! extrudeByPath ) { + } - v( vert.x, vert.y, 0 ); + // expand holes - } else { + for ( h = 0, hl = holes.length; h < hl; h ++ ) { - // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x ); + ahole = holes[ h ]; + oneHoleMovements = holesMovements[ h ]; - normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x ); - binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y ); + for ( i = 0, il = ahole.length; i < il; i ++ ) { - position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal ); + vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); - v( position2.x, position2.y, position2.z ); + v( vert.x, vert.y, - z ); - } + } - } + } - // Add stepped vertices... - // Including front facing vertices + } - var s; + bs = bevelSize; - for ( s = 1; s <= steps; s ++ ) { + // Back facing vertices - for ( i = 0; i < vlen; i ++ ) { + for ( i = 0; i < vlen; i ++ ) { - vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; + vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; - if ( ! extrudeByPath ) { + if ( ! extrudeByPath ) { - v( vert.x, vert.y, amount / steps * s ); + v( vert.x, vert.y, 0 ); - } else { + } else { - // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x ); + // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x ); - normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x ); - binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y ); + normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x ); + binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y ); - position2.copy( extrudePts[ s ] ).add( normal ).add( binormal ); + position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal ); - v( position2.x, position2.y, position2.z ); + v( position2.x, position2.y, position2.z ); - } + } - } + } - } + // Add stepped vertices... + // Including front facing vertices + var s; - // Add bevel segments planes + for ( s = 1; s <= steps; s ++ ) { - //for ( b = 1; b <= bevelSegments; b ++ ) { - for ( b = bevelSegments - 1; b >= 0; b -- ) { + for ( i = 0; i < vlen; i ++ ) { - t = b / bevelSegments; - z = bevelThickness * Math.cos ( t * Math.PI / 2 ); - bs = bevelSize * Math.sin( t * Math.PI / 2 ); + vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; - // contract shape + if ( ! extrudeByPath ) { - for ( i = 0, il = contour.length; i < il; i ++ ) { + v( vert.x, vert.y, amount / steps * s ); - vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); - v( vert.x, vert.y, amount + z ); + } else { - } + // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x ); - // expand holes + normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x ); + binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y ); - for ( h = 0, hl = holes.length; h < hl; h ++ ) { + position2.copy( extrudePts[ s ] ).add( normal ).add( binormal ); - ahole = holes[ h ]; - oneHoleMovements = holesMovements[ h ]; + v( position2.x, position2.y, position2.z ); - for ( i = 0, il = ahole.length; i < il; i ++ ) { + } - vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); + } - if ( ! extrudeByPath ) { + } - v( vert.x, vert.y, amount + z ); - } else { + // Add bevel segments planes - v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z ); + //for ( b = 1; b <= bevelSegments; b ++ ) { + for ( b = bevelSegments - 1; b >= 0; b -- ) { - } + t = b / bevelSegments; + z = bevelThickness * Math.cos ( t * Math.PI / 2 ); + bs = bevelSize * Math.sin( t * Math.PI / 2 ); - } + // contract shape - } + for ( i = 0, il = contour.length; i < il; i ++ ) { - } + vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); + v( vert.x, vert.y, amount + z ); - /* Faces */ + } - // Top and bottom faces + // expand holes - buildLidFaces(); + for ( h = 0, hl = holes.length; h < hl; h ++ ) { - // Sides faces + ahole = holes[ h ]; + oneHoleMovements = holesMovements[ h ]; - buildSideFaces(); + for ( i = 0, il = ahole.length; i < il; i ++ ) { + vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); - ///// Internal functions + if ( ! extrudeByPath ) { - function buildLidFaces() { + v( vert.x, vert.y, amount + z ); - if ( bevelEnabled ) { + } else { - var layer = 0; // steps + 1 - var offset = vlen * layer; + v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z ); - // Bottom faces + } - for ( i = 0; i < flen; i ++ ) { + } - face = faces[ i ]; - f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset ); + } - } + } - layer = steps + bevelSegments * 2; - offset = vlen * layer; + /* Faces */ - // Top faces + // Top and bottom faces - for ( i = 0; i < flen; i ++ ) { + buildLidFaces(); - face = faces[ i ]; - f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset ); + // Sides faces - } + buildSideFaces(); - } else { - // Bottom faces + ///// Internal functions - for ( i = 0; i < flen; i ++ ) { + function buildLidFaces() { - face = faces[ i ]; - f3( face[ 2 ], face[ 1 ], face[ 0 ] ); + if ( bevelEnabled ) { - } + var layer = 0; // steps + 1 + var offset = vlen * layer; - // Top faces + // Bottom faces - for ( i = 0; i < flen; i ++ ) { + for ( i = 0; i < flen; i ++ ) { - face = faces[ i ]; - f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps ); + face = faces[ i ]; + f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset ); - } + } - } + layer = steps + bevelSegments * 2; + offset = vlen * layer; - } + // Top faces - // Create faces for the z-sides of the shape + for ( i = 0; i < flen; i ++ ) { - function buildSideFaces() { + face = faces[ i ]; + f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset ); - var layeroffset = 0; - sidewalls( contour, layeroffset ); - layeroffset += contour.length; + } - for ( h = 0, hl = holes.length; h < hl; h ++ ) { + } else { - ahole = holes[ h ]; - sidewalls( ahole, layeroffset ); + // Bottom faces - //, true - layeroffset += ahole.length; + for ( i = 0; i < flen; i ++ ) { - } + face = faces[ i ]; + f3( face[ 2 ], face[ 1 ], face[ 0 ] ); - } + } - function sidewalls( contour, layeroffset ) { + // Top faces - var j, k; - i = contour.length; + for ( i = 0; i < flen; i ++ ) { - while ( -- i >= 0 ) { + face = faces[ i ]; + f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps ); - j = i; - k = i - 1; - if ( k < 0 ) k = contour.length - 1; + } - //console.log('b', i,j, i-1, k,vertices.length); + } - var s = 0, sl = steps + bevelSegments * 2; + } - for ( s = 0; s < sl; s ++ ) { + // Create faces for the z-sides of the shape - var slen1 = vlen * s; - var slen2 = vlen * ( s + 1 ); + function buildSideFaces() { - var a = layeroffset + j + slen1, - b = layeroffset + k + slen1, - c = layeroffset + k + slen2, - d = layeroffset + j + slen2; + var layeroffset = 0; + sidewalls( contour, layeroffset ); + layeroffset += contour.length; - f4( a, b, c, d, contour, s, sl, j, k ); + for ( h = 0, hl = holes.length; h < hl; h ++ ) { - } + ahole = holes[ h ]; + sidewalls( ahole, layeroffset ); - } + //, true + layeroffset += ahole.length; - } + } + } - function v( x, y, z ) { + function sidewalls( contour, layeroffset ) { - scope.vertices.push( new Vector3( x, y, z ) ); + var j, k; + i = contour.length; - } + while ( -- i >= 0 ) { - function f3( a, b, c ) { + j = i; + k = i - 1; + if ( k < 0 ) k = contour.length - 1; - a += shapesOffset; - b += shapesOffset; - c += shapesOffset; + //console.log('b', i,j, i-1, k,vertices.length); - scope.faces.push( new Face3( a, b, c, null, null, 0 ) ); + var s = 0, sl = steps + bevelSegments * 2; - var uvs = uvgen.generateTopUV( scope, a, b, c ); + for ( s = 0; s < sl; s ++ ) { - scope.faceVertexUvs[ 0 ].push( uvs ); + var slen1 = vlen * s; + var slen2 = vlen * ( s + 1 ); - } + var a = layeroffset + j + slen1, + b = layeroffset + k + slen1, + c = layeroffset + k + slen2, + d = layeroffset + j + slen2; - function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) { + f4( a, b, c, d, contour, s, sl, j, k ); - a += shapesOffset; - b += shapesOffset; - c += shapesOffset; - d += shapesOffset; + } - scope.faces.push( new Face3( a, b, d, null, null, 1 ) ); - scope.faces.push( new Face3( b, c, d, null, null, 1 ) ); + } - var uvs = uvgen.generateSideWallUV( scope, a, b, c, d ); + } - scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] ); - scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] ); - } + function v( x, y, z ) { - }; + scope.vertices.push( new Vector3( x, y, z ) ); - ExtrudeGeometry.WorldUVGenerator = { + } - generateTopUV: function ( geometry, indexA, indexB, indexC ) { + function f3( a, b, c ) { - var vertices = geometry.vertices; + a += shapesOffset; + b += shapesOffset; + c += shapesOffset; - var a = vertices[ indexA ]; - var b = vertices[ indexB ]; - var c = vertices[ indexC ]; + scope.faces.push( new Face3( a, b, c, null, null, 0 ) ); - return [ - new Vector2( a.x, a.y ), - new Vector2( b.x, b.y ), - new Vector2( c.x, c.y ) - ]; + var uvs = uvgen.generateTopUV( scope, a, b, c ); - }, + scope.faceVertexUvs[ 0 ].push( uvs ); - generateSideWallUV: function ( geometry, indexA, indexB, indexC, indexD ) { + } - var vertices = geometry.vertices; + function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) { - var a = vertices[ indexA ]; - var b = vertices[ indexB ]; - var c = vertices[ indexC ]; - var d = vertices[ indexD ]; + a += shapesOffset; + b += shapesOffset; + c += shapesOffset; + d += shapesOffset; - if ( Math.abs( a.y - b.y ) < 0.01 ) { + scope.faces.push( new Face3( a, b, d, null, null, 1 ) ); + scope.faces.push( new Face3( b, c, d, null, null, 1 ) ); - return [ - new Vector2( a.x, 1 - a.z ), - new Vector2( b.x, 1 - b.z ), - new Vector2( c.x, 1 - c.z ), - new Vector2( d.x, 1 - d.z ) - ]; + var uvs = uvgen.generateSideWallUV( scope, a, b, c, d ); - } else { + scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] ); + scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] ); - return [ - new Vector2( a.y, 1 - a.z ), - new Vector2( b.y, 1 - b.z ), - new Vector2( c.y, 1 - c.z ), - new Vector2( d.y, 1 - d.z ) - ]; + } - } + }; - } - }; + ExtrudeGeometry.WorldUVGenerator = { - /** - * @author jonobr1 / http://jonobr1.com - * - * Creates a one-sided polygonal geometry from a path shape. Similar to - * ExtrudeGeometry. - * - * parameters = { - * - * curveSegments: , // number of points on the curves. NOT USED AT THE MOMENT. - * - * material: // material index for front and back faces - * uvGenerator: // object that provides UV generator functions - * - * } - **/ + generateTopUV: function ( geometry, indexA, indexB, indexC ) { - function ShapeGeometry( shapes, options ) { + var vertices = geometry.vertices; - Geometry.call( this ); + var a = vertices[ indexA ]; + var b = vertices[ indexB ]; + var c = vertices[ indexC ]; - this.type = 'ShapeGeometry'; + return [ + new Vector2( a.x, a.y ), + new Vector2( b.x, b.y ), + new Vector2( c.x, c.y ) + ]; - if ( Array.isArray( shapes ) === false ) shapes = [ shapes ]; + }, - this.addShapeList( shapes, options ); + generateSideWallUV: function ( geometry, indexA, indexB, indexC, indexD ) { - this.computeFaceNormals(); + var vertices = geometry.vertices; - }; + var a = vertices[ indexA ]; + var b = vertices[ indexB ]; + var c = vertices[ indexC ]; + var d = vertices[ indexD ]; - ShapeGeometry.prototype = Object.create( Geometry.prototype ); - ShapeGeometry.prototype.constructor = ShapeGeometry; + if ( Math.abs( a.y - b.y ) < 0.01 ) { - /** - * Add an array of shapes to THREE.ShapeGeometry. - */ - ShapeGeometry.prototype.addShapeList = function ( shapes, options ) { + return [ + new Vector2( a.x, 1 - a.z ), + new Vector2( b.x, 1 - b.z ), + new Vector2( c.x, 1 - c.z ), + new Vector2( d.x, 1 - d.z ) + ]; - for ( var i = 0, l = shapes.length; i < l; i ++ ) { + } else { - this.addShape( shapes[ i ], options ); + return [ + new Vector2( a.y, 1 - a.z ), + new Vector2( b.y, 1 - b.z ), + new Vector2( c.y, 1 - c.z ), + new Vector2( d.y, 1 - d.z ) + ]; - } + } - return this; + } + }; - }; + /** + * @author jonobr1 / http://jonobr1.com + * + * Creates a one-sided polygonal geometry from a path shape. Similar to + * ExtrudeGeometry. + * + * parameters = { + * + * curveSegments: , // number of points on the curves. NOT USED AT THE MOMENT. + * + * material: // material index for front and back faces + * uvGenerator: // object that provides UV generator functions + * + * } + **/ - /** - * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry. - */ - ShapeGeometry.prototype.addShape = function ( shape, options ) { + function ShapeGeometry( shapes, options ) { - if ( options === undefined ) options = {}; - var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12; + Geometry.call( this ); - var material = options.material; - var uvgen = options.UVGenerator === undefined ? ExtrudeGeometry.WorldUVGenerator : options.UVGenerator; + this.type = 'ShapeGeometry'; - // + if ( Array.isArray( shapes ) === false ) shapes = [ shapes ]; - var i, l, hole; + this.addShapeList( shapes, options ); - var shapesOffset = this.vertices.length; - var shapePoints = shape.extractPoints( curveSegments ); + this.computeFaceNormals(); - var vertices = shapePoints.shape; - var holes = shapePoints.holes; + } - var reverse = ! exports.ShapeUtils.isClockWise( vertices ); + ShapeGeometry.prototype = Object.create( Geometry.prototype ); + ShapeGeometry.prototype.constructor = ShapeGeometry; - if ( reverse ) { + /** + * Add an array of shapes to THREE.ShapeGeometry. + */ + ShapeGeometry.prototype.addShapeList = function ( shapes, options ) { - vertices = vertices.reverse(); + for ( var i = 0, l = shapes.length; i < l; i ++ ) { - // Maybe we should also check if holes are in the opposite direction, just to be safe... + this.addShape( shapes[ i ], options ); - for ( i = 0, l = holes.length; i < l; i ++ ) { + } - hole = holes[ i ]; + return this; - if ( exports.ShapeUtils.isClockWise( hole ) ) { + }; - holes[ i ] = hole.reverse(); + /** + * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry. + */ + ShapeGeometry.prototype.addShape = function ( shape, options ) { - } + if ( options === undefined ) options = {}; + var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12; - } + var material = options.material; + var uvgen = options.UVGenerator === undefined ? ExtrudeGeometry.WorldUVGenerator : options.UVGenerator; - reverse = false; + // - } + var i, l, hole; - var faces = exports.ShapeUtils.triangulateShape( vertices, holes ); + var shapesOffset = this.vertices.length; + var shapePoints = shape.extractPoints( curveSegments ); - // Vertices + var vertices = shapePoints.shape; + var holes = shapePoints.holes; - for ( i = 0, l = holes.length; i < l; i ++ ) { + var reverse = ! exports.ShapeUtils.isClockWise( vertices ); - hole = holes[ i ]; - vertices = vertices.concat( hole ); + if ( reverse ) { - } + vertices = vertices.reverse(); - // + // Maybe we should also check if holes are in the opposite direction, just to be safe... - var vert, vlen = vertices.length; - var face, flen = faces.length; + for ( i = 0, l = holes.length; i < l; i ++ ) { - for ( i = 0; i < vlen; i ++ ) { + hole = holes[ i ]; - vert = vertices[ i ]; + if ( exports.ShapeUtils.isClockWise( hole ) ) { - this.vertices.push( new Vector3( vert.x, vert.y, 0 ) ); + holes[ i ] = hole.reverse(); - } + } - for ( i = 0; i < flen; i ++ ) { + } - face = faces[ i ]; + reverse = false; - var a = face[ 0 ] + shapesOffset; - var b = face[ 1 ] + shapesOffset; - var c = face[ 2 ] + shapesOffset; + } - this.faces.push( new Face3( a, b, c, null, null, material ) ); - this.faceVertexUvs[ 0 ].push( uvgen.generateTopUV( this, a, b, c ) ); + var faces = exports.ShapeUtils.triangulateShape( vertices, holes ); - } + // Vertices - }; + for ( i = 0, l = holes.length; i < l; i ++ ) { - /** - * @author zz85 / http://www.lab4games.net/zz85/blog - * Defines a 2d shape plane using paths. - **/ + hole = holes[ i ]; + vertices = vertices.concat( hole ); - // STEP 1 Create a path. - // STEP 2 Turn path into shape. - // STEP 3 ExtrudeGeometry takes in Shape/Shapes - // STEP 3a - Extract points from each shape, turn to vertices - // STEP 3b - Triangulate each shape, add faces. + } - function Shape() { + // - Path.apply( this, arguments ); + var vert, vlen = vertices.length; + var face, flen = faces.length; - this.holes = []; + for ( i = 0; i < vlen; i ++ ) { - }; + vert = vertices[ i ]; - Shape.prototype = Object.assign( Object.create( PathPrototype ), { + this.vertices.push( new Vector3( vert.x, vert.y, 0 ) ); - constructor: Shape, + } - // Convenience method to return ExtrudeGeometry + for ( i = 0; i < flen; i ++ ) { - extrude: function ( options ) { + face = faces[ i ]; - return new ExtrudeGeometry( this, options ); + var a = face[ 0 ] + shapesOffset; + var b = face[ 1 ] + shapesOffset; + var c = face[ 2 ] + shapesOffset; - }, + this.faces.push( new Face3( a, b, c, null, null, material ) ); + this.faceVertexUvs[ 0 ].push( uvgen.generateTopUV( this, a, b, c ) ); - // Convenience method to return ShapeGeometry + } - makeGeometry: function ( options ) { + }; - return new ShapeGeometry( this, options ); + /** + * @author zz85 / http://www.lab4games.net/zz85/blog + * Defines a 2d shape plane using paths. + **/ - }, + // STEP 1 Create a path. + // STEP 2 Turn path into shape. + // STEP 3 ExtrudeGeometry takes in Shape/Shapes + // STEP 3a - Extract points from each shape, turn to vertices + // STEP 3b - Triangulate each shape, add faces. - getPointsHoles: function ( divisions ) { + function Shape() { - var holesPts = []; + Path.apply( this, arguments ); - for ( var i = 0, l = this.holes.length; i < l; i ++ ) { + this.holes = []; - holesPts[ i ] = this.holes[ i ].getPoints( divisions ); + } - } + Shape.prototype = Object.assign( Object.create( PathPrototype ), { - return holesPts; + constructor: Shape, - }, + // Convenience method to return ExtrudeGeometry - // Get points of shape and holes (keypoints based on segments parameter) + extrude: function ( options ) { - extractAllPoints: function ( divisions ) { + return new ExtrudeGeometry( this, options ); - return { + }, - shape: this.getPoints( divisions ), - holes: this.getPointsHoles( divisions ) + // Convenience method to return ShapeGeometry - }; + makeGeometry: function ( options ) { - }, + return new ShapeGeometry( this, options ); - extractPoints: function ( divisions ) { + }, - return this.extractAllPoints( divisions ); + getPointsHoles: function ( divisions ) { - } + var holesPts = []; - } ); + for ( var i = 0, l = this.holes.length; i < l; i ++ ) { - /** - * @author zz85 / http://www.lab4games.net/zz85/blog - * Creates free form 2d path using series of points, lines or curves. - * - **/ + holesPts[ i ] = this.holes[ i ].getPoints( divisions ); - function Path( points ) { + } - CurvePath.call( this ); - this.currentPoint = new Vector2(); + return holesPts; - if ( points ) { + }, - this.fromPoints( points ); + // Get points of shape and holes (keypoints based on segments parameter) - } + extractAllPoints: function ( divisions ) { - }; + return { - Path.prototype = PathPrototype; - PathPrototype.constructor = Path; + shape: this.getPoints( divisions ), + holes: this.getPointsHoles( divisions ) + }; - // minimal class for proxing functions to Path. Replaces old "extractSubpaths()" - function ShapePath() { - this.subPaths = []; - this.currentPath = null; - } + }, - ShapePath.prototype = { - moveTo: function ( x, y ) { - this.currentPath = new Path(); - this.subPaths.push(this.currentPath); - this.currentPath.moveTo( x, y ); - }, - lineTo: function ( x, y ) { - this.currentPath.lineTo( x, y ); - }, - quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) { - this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY ); - }, - bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) { - this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ); - }, - splineThru: function ( pts ) { - this.currentPath.splineThru( pts ); - }, + extractPoints: function ( divisions ) { - toShapes: function ( isCCW, noHoles ) { + return this.extractAllPoints( divisions ); - function toShapesNoHoles( inSubpaths ) { + } - var shapes = []; + } ); - for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) { + /** + * @author zz85 / http://www.lab4games.net/zz85/blog + * Creates free form 2d path using series of points, lines or curves. + * + **/ - var tmpPath = inSubpaths[ i ]; + function Path( points ) { - var tmpShape = new Shape(); - tmpShape.curves = tmpPath.curves; + CurvePath.call( this ); + this.currentPoint = new Vector2(); - shapes.push( tmpShape ); + if ( points ) { - } + this.fromPoints( points ); - return shapes; + } - } + } - function isPointInsidePolygon( inPt, inPolygon ) { + Path.prototype = PathPrototype; + PathPrototype.constructor = Path; - var polyLen = inPolygon.length; - // inPt on polygon contour => immediate success or - // toggling of inside/outside at every single! intersection point of an edge - // with the horizontal line through inPt, left of inPt - // not counting lowerY endpoints of edges and whole edges on that line - var inside = false; - for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) { + // minimal class for proxing functions to Path. Replaces old "extractSubpaths()" + function ShapePath() { + this.subPaths = []; + this.currentPath = null; + } - var edgeLowPt = inPolygon[ p ]; - var edgeHighPt = inPolygon[ q ]; + ShapePath.prototype = { + moveTo: function ( x, y ) { + this.currentPath = new Path(); + this.subPaths.push(this.currentPath); + this.currentPath.moveTo( x, y ); + }, + lineTo: function ( x, y ) { + this.currentPath.lineTo( x, y ); + }, + quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) { + this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY ); + }, + bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) { + this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ); + }, + splineThru: function ( pts ) { + this.currentPath.splineThru( pts ); + }, - var edgeDx = edgeHighPt.x - edgeLowPt.x; - var edgeDy = edgeHighPt.y - edgeLowPt.y; + toShapes: function ( isCCW, noHoles ) { - if ( Math.abs( edgeDy ) > Number.EPSILON ) { + function toShapesNoHoles( inSubpaths ) { - // not parallel - if ( edgeDy < 0 ) { + var shapes = []; - edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx; - edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy; + for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) { - } - if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue; + var tmpPath = inSubpaths[ i ]; - if ( inPt.y === edgeLowPt.y ) { + var tmpShape = new Shape(); + tmpShape.curves = tmpPath.curves; - if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ? - // continue; // no intersection or edgeLowPt => doesn't count !!! + shapes.push( tmpShape ); - } else { + } - var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y ); - if ( perpEdge === 0 ) return true; // inPt is on contour ? - if ( perpEdge < 0 ) continue; - inside = ! inside; // true intersection left of inPt + return shapes; - } + } - } else { + function isPointInsidePolygon( inPt, inPolygon ) { - // parallel or collinear - if ( inPt.y !== edgeLowPt.y ) continue; // parallel - // edge lies on the same horizontal line as inPt - if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) || - ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour ! - // continue; + var polyLen = inPolygon.length; - } + // inPt on polygon contour => immediate success or + // toggling of inside/outside at every single! intersection point of an edge + // with the horizontal line through inPt, left of inPt + // not counting lowerY endpoints of edges and whole edges on that line + var inside = false; + for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) { - } + var edgeLowPt = inPolygon[ p ]; + var edgeHighPt = inPolygon[ q ]; - return inside; + var edgeDx = edgeHighPt.x - edgeLowPt.x; + var edgeDy = edgeHighPt.y - edgeLowPt.y; - } + if ( Math.abs( edgeDy ) > Number.EPSILON ) { - var isClockWise = exports.ShapeUtils.isClockWise; + // not parallel + if ( edgeDy < 0 ) { - var subPaths = this.subPaths; - if ( subPaths.length === 0 ) return []; + edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx; + edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy; - if ( noHoles === true ) return toShapesNoHoles( subPaths ); + } + if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue; + if ( inPt.y === edgeLowPt.y ) { - var solid, tmpPath, tmpShape, shapes = []; + if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ? + // continue; // no intersection or edgeLowPt => doesn't count !!! - if ( subPaths.length === 1 ) { + } else { - tmpPath = subPaths[ 0 ]; - tmpShape = new Shape(); - tmpShape.curves = tmpPath.curves; - shapes.push( tmpShape ); - return shapes; + var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y ); + if ( perpEdge === 0 ) return true; // inPt is on contour ? + if ( perpEdge < 0 ) continue; + inside = ! inside; // true intersection left of inPt - } + } - var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() ); - holesFirst = isCCW ? ! holesFirst : holesFirst; + } else { - // console.log("Holes first", holesFirst); + // parallel or collinear + if ( inPt.y !== edgeLowPt.y ) continue; // parallel + // edge lies on the same horizontal line as inPt + if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) || + ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour ! + // continue; - var betterShapeHoles = []; - var newShapes = []; - var newShapeHoles = []; - var mainIdx = 0; - var tmpPoints; + } - newShapes[ mainIdx ] = undefined; - newShapeHoles[ mainIdx ] = []; + } - for ( var i = 0, l = subPaths.length; i < l; i ++ ) { + return inside; - tmpPath = subPaths[ i ]; - tmpPoints = tmpPath.getPoints(); - solid = isClockWise( tmpPoints ); - solid = isCCW ? ! solid : solid; + } - if ( solid ) { + var isClockWise = exports.ShapeUtils.isClockWise; - if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++; + var subPaths = this.subPaths; + if ( subPaths.length === 0 ) return []; - newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints }; - newShapes[ mainIdx ].s.curves = tmpPath.curves; + if ( noHoles === true ) return toShapesNoHoles( subPaths ); - if ( holesFirst ) mainIdx ++; - newShapeHoles[ mainIdx ] = []; - //console.log('cw', i); + var solid, tmpPath, tmpShape, shapes = []; - } else { + if ( subPaths.length === 1 ) { - newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } ); + tmpPath = subPaths[ 0 ]; + tmpShape = new Shape(); + tmpShape.curves = tmpPath.curves; + shapes.push( tmpShape ); + return shapes; - //console.log('ccw', i); + } - } + var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() ); + holesFirst = isCCW ? ! holesFirst : holesFirst; - } + // console.log("Holes first", holesFirst); - // only Holes? -> probably all Shapes with wrong orientation - if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths ); + var betterShapeHoles = []; + var newShapes = []; + var newShapeHoles = []; + var mainIdx = 0; + var tmpPoints; + newShapes[ mainIdx ] = undefined; + newShapeHoles[ mainIdx ] = []; - if ( newShapes.length > 1 ) { + for ( var i = 0, l = subPaths.length; i < l; i ++ ) { - var ambiguous = false; - var toChange = []; + tmpPath = subPaths[ i ]; + tmpPoints = tmpPath.getPoints(); + solid = isClockWise( tmpPoints ); + solid = isCCW ? ! solid : solid; - for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) { + if ( solid ) { - betterShapeHoles[ sIdx ] = []; + if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++; - } + newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints }; + newShapes[ mainIdx ].s.curves = tmpPath.curves; - for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) { + if ( holesFirst ) mainIdx ++; + newShapeHoles[ mainIdx ] = []; - var sho = newShapeHoles[ sIdx ]; + //console.log('cw', i); - for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) { + } else { - var ho = sho[ hIdx ]; - var hole_unassigned = true; + newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } ); - for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) { + //console.log('ccw', i); - if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) { + } - if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } ); - if ( hole_unassigned ) { + } - hole_unassigned = false; - betterShapeHoles[ s2Idx ].push( ho ); + // only Holes? -> probably all Shapes with wrong orientation + if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths ); - } else { - ambiguous = true; + if ( newShapes.length > 1 ) { - } + var ambiguous = false; + var toChange = []; - } + for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) { - } - if ( hole_unassigned ) { + betterShapeHoles[ sIdx ] = []; - betterShapeHoles[ sIdx ].push( ho ); + } - } + for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) { - } + var sho = newShapeHoles[ sIdx ]; - } - // console.log("ambiguous: ", ambiguous); - if ( toChange.length > 0 ) { + for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) { - // console.log("to change: ", toChange); - if ( ! ambiguous ) newShapeHoles = betterShapeHoles; + var ho = sho[ hIdx ]; + var hole_unassigned = true; - } + for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) { - } + if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) { - var tmpHoles; + if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } ); + if ( hole_unassigned ) { - for ( var i = 0, il = newShapes.length; i < il; i ++ ) { + hole_unassigned = false; + betterShapeHoles[ s2Idx ].push( ho ); - tmpShape = newShapes[ i ].s; - shapes.push( tmpShape ); - tmpHoles = newShapeHoles[ i ]; + } else { - for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) { + ambiguous = true; - tmpShape.holes.push( tmpHoles[ j ].h ); + } - } + } - } + } + if ( hole_unassigned ) { - //console.log("shape", shapes); + betterShapeHoles[ sIdx ].push( ho ); - return shapes; + } - } - } + } - /** - * @author zz85 / http://www.lab4games.net/zz85/blog - * @author mrdoob / http://mrdoob.com/ - */ + } + // console.log("ambiguous: ", ambiguous); + if ( toChange.length > 0 ) { - function Font( data ) { + // console.log("to change: ", toChange); + if ( ! ambiguous ) newShapeHoles = betterShapeHoles; - this.data = data; + } - }; + } - Object.assign( Font.prototype, { + var tmpHoles; - isFont: true, + for ( var i = 0, il = newShapes.length; i < il; i ++ ) { - generateShapes: function ( text, size, divisions ) { + tmpShape = newShapes[ i ].s; + shapes.push( tmpShape ); + tmpHoles = newShapeHoles[ i ]; - function createPaths( text ) { + for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) { - var chars = String( text ).split( '' ); - var scale = size / data.resolution; - var offset = 0; + tmpShape.holes.push( tmpHoles[ j ].h ); - var paths = []; + } - for ( var i = 0; i < chars.length; i ++ ) { + } - var ret = createPath( chars[ i ], scale, offset ); - offset += ret.offset; + //console.log("shape", shapes); - paths.push( ret.path ); + return shapes; - } + } + } - return paths; + /** + * @author zz85 / http://www.lab4games.net/zz85/blog + * @author mrdoob / http://mrdoob.com/ + */ - } + function Font( data ) { - function createPath( c, scale, offset ) { + this.data = data; - var glyph = data.glyphs[ c ] || data.glyphs[ '?' ]; + } - if ( ! glyph ) return; + Object.assign( Font.prototype, { - var path = new ShapePath(); + isFont: true, - var pts = [], b2 = exports.ShapeUtils.b2, b3 = exports.ShapeUtils.b3; - var x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2, laste; + generateShapes: function ( text, size, divisions ) { - if ( glyph.o ) { + function createPaths( text ) { - var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) ); + var chars = String( text ).split( '' ); + var scale = size / data.resolution; + var offset = 0; - for ( var i = 0, l = outline.length; i < l; ) { + var paths = []; - var action = outline[ i ++ ]; + for ( var i = 0; i < chars.length; i ++ ) { - switch ( action ) { + var ret = createPath( chars[ i ], scale, offset ); + offset += ret.offset; - case 'm': // moveTo + paths.push( ret.path ); - x = outline[ i ++ ] * scale + offset; - y = outline[ i ++ ] * scale; + } - path.moveTo( x, y ); + return paths; - break; + } - case 'l': // lineTo + function createPath( c, scale, offset ) { - x = outline[ i ++ ] * scale + offset; - y = outline[ i ++ ] * scale; + var glyph = data.glyphs[ c ] || data.glyphs[ '?' ]; - path.lineTo( x, y ); + if ( ! glyph ) return; - break; + var path = new ShapePath(); - case 'q': // quadraticCurveTo + var pts = [], b2 = exports.ShapeUtils.b2, b3 = exports.ShapeUtils.b3; + var x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2, laste; - cpx = outline[ i ++ ] * scale + offset; - cpy = outline[ i ++ ] * scale; - cpx1 = outline[ i ++ ] * scale + offset; - cpy1 = outline[ i ++ ] * scale; + if ( glyph.o ) { - path.quadraticCurveTo( cpx1, cpy1, cpx, cpy ); + var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) ); - laste = pts[ pts.length - 1 ]; + for ( var i = 0, l = outline.length; i < l; ) { - if ( laste ) { + var action = outline[ i ++ ]; - cpx0 = laste.x; - cpy0 = laste.y; + switch ( action ) { - for ( var i2 = 1; i2 <= divisions; i2 ++ ) { + case 'm': // moveTo - var t = i2 / divisions; - b2( t, cpx0, cpx1, cpx ); - b2( t, cpy0, cpy1, cpy ); + x = outline[ i ++ ] * scale + offset; + y = outline[ i ++ ] * scale; - } + path.moveTo( x, y ); - } + break; - break; + case 'l': // lineTo - case 'b': // bezierCurveTo + x = outline[ i ++ ] * scale + offset; + y = outline[ i ++ ] * scale; - cpx = outline[ i ++ ] * scale + offset; - cpy = outline[ i ++ ] * scale; - cpx1 = outline[ i ++ ] * scale + offset; - cpy1 = outline[ i ++ ] * scale; - cpx2 = outline[ i ++ ] * scale + offset; - cpy2 = outline[ i ++ ] * scale; + path.lineTo( x, y ); - path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy ); + break; - laste = pts[ pts.length - 1 ]; + case 'q': // quadraticCurveTo - if ( laste ) { + cpx = outline[ i ++ ] * scale + offset; + cpy = outline[ i ++ ] * scale; + cpx1 = outline[ i ++ ] * scale + offset; + cpy1 = outline[ i ++ ] * scale; - cpx0 = laste.x; - cpy0 = laste.y; + path.quadraticCurveTo( cpx1, cpy1, cpx, cpy ); - for ( var i2 = 1; i2 <= divisions; i2 ++ ) { + laste = pts[ pts.length - 1 ]; - var t = i2 / divisions; - b3( t, cpx0, cpx1, cpx2, cpx ); - b3( t, cpy0, cpy1, cpy2, cpy ); + if ( laste ) { - } + cpx0 = laste.x; + cpy0 = laste.y; - } + for ( var i2 = 1; i2 <= divisions; i2 ++ ) { - break; + var t = i2 / divisions; + b2( t, cpx0, cpx1, cpx ); + b2( t, cpy0, cpy1, cpy ); - } + } - } + } - } + break; - return { offset: glyph.ha * scale, path: path }; + case 'b': // bezierCurveTo - } + cpx = outline[ i ++ ] * scale + offset; + cpy = outline[ i ++ ] * scale; + cpx1 = outline[ i ++ ] * scale + offset; + cpy1 = outline[ i ++ ] * scale; + cpx2 = outline[ i ++ ] * scale + offset; + cpy2 = outline[ i ++ ] * scale; - // + path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy ); - if ( size === undefined ) size = 100; - if ( divisions === undefined ) divisions = 4; + laste = pts[ pts.length - 1 ]; - var data = this.data; + if ( laste ) { - var paths = createPaths( text ); - var shapes = []; + cpx0 = laste.x; + cpy0 = laste.y; - for ( var p = 0, pl = paths.length; p < pl; p ++ ) { + for ( var i2 = 1; i2 <= divisions; i2 ++ ) { - Array.prototype.push.apply( shapes, paths[ p ].toShapes() ); + var t = i2 / divisions; + b3( t, cpx0, cpx1, cpx2, cpx ); + b3( t, cpy0, cpy1, cpy2, cpy ); - } + } - return shapes; + } - } + break; - } ); + } - /** - * @author mrdoob / http://mrdoob.com/ - */ + } - function FontLoader( manager ) { + } - this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; + return { offset: glyph.ha * scale, path: path }; - }; + } - Object.assign( FontLoader.prototype, { + // - load: function ( url, onLoad, onProgress, onError ) { + if ( size === undefined ) size = 100; + if ( divisions === undefined ) divisions = 4; - var scope = this; + var data = this.data; - var loader = new XHRLoader( this.manager ); - loader.load( url, function ( text ) { + var paths = createPaths( text ); + var shapes = []; - var json; + for ( var p = 0, pl = paths.length; p < pl; p ++ ) { - try { + Array.prototype.push.apply( shapes, paths[ p ].toShapes() ); - json = JSON.parse( text ); + } - } catch ( e ) { + return shapes; - console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' ); - json = JSON.parse( text.substring( 65, text.length - 2 ) ); + } - } + } ); - var font = scope.parse( json ); + /** + * @author mrdoob / http://mrdoob.com/ + */ - if ( onLoad ) onLoad( font ); + function FontLoader( manager ) { - }, onProgress, onError ); + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; - }, + } - parse: function ( json ) { + Object.assign( FontLoader.prototype, { - return new Font( json ); + load: function ( url, onLoad, onProgress, onError ) { - } + var scope = this; - } ); + var loader = new XHRLoader( this.manager ); + loader.load( url, function ( text ) { - var context; + var json; - function getAudioContext() { + try { - if ( context === undefined ) { + json = JSON.parse( text ); - context = new ( window.AudioContext || window.webkitAudioContext )(); + } catch ( e ) { - } + console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' ); + json = JSON.parse( text.substring( 65, text.length - 2 ) ); - return context; + } - } + var font = scope.parse( json ); - /** - * @author Reece Aaron Lecrivain / http://reecenotes.com/ - */ + if ( onLoad ) onLoad( font ); - function AudioLoader( manager ) { + }, onProgress, onError ); - this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; + }, - }; + parse: function ( json ) { - Object.assign( AudioLoader.prototype, { + return new Font( json ); - load: function ( url, onLoad, onProgress, onError ) { + } - var loader = new XHRLoader( this.manager ); - loader.setResponseType( 'arraybuffer' ); - loader.load( url, function ( buffer ) { + } ); - var context = getAudioContext(); + var context; - context.decodeAudioData( buffer, function ( audioBuffer ) { + function getAudioContext() { - onLoad( audioBuffer ); + if ( context === undefined ) { - } ); + context = new ( window.AudioContext || window.webkitAudioContext )(); - }, onProgress, onError ); + } - } + return context; - } ); + } - /** - * @author mrdoob / http://mrdoob.com/ - */ + /** + * @author Reece Aaron Lecrivain / http://reecenotes.com/ + */ - function StereoCamera() { + function AudioLoader( manager ) { - this.type = 'StereoCamera'; + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; - this.aspect = 1; + } - this.cameraL = new PerspectiveCamera(); - this.cameraL.layers.enable( 1 ); - this.cameraL.matrixAutoUpdate = false; + Object.assign( AudioLoader.prototype, { - this.cameraR = new PerspectiveCamera(); - this.cameraR.layers.enable( 2 ); - this.cameraR.matrixAutoUpdate = false; + load: function ( url, onLoad, onProgress, onError ) { - }; + var loader = new XHRLoader( this.manager ); + loader.setResponseType( 'arraybuffer' ); + loader.load( url, function ( buffer ) { - Object.assign( StereoCamera.prototype, { + var context = getAudioContext(); - update: ( function () { + context.decodeAudioData( buffer, function ( audioBuffer ) { - var focus, fov, aspect, near, far; + onLoad( audioBuffer ); - var eyeRight = new Matrix4(); - var eyeLeft = new Matrix4(); + } ); - return function update( camera ) { + }, onProgress, onError ); - var needsUpdate = focus !== camera.focus || fov !== camera.fov || - aspect !== camera.aspect * this.aspect || near !== camera.near || - far !== camera.far; + } - if ( needsUpdate ) { + } ); - focus = camera.focus; - fov = camera.fov; - aspect = camera.aspect * this.aspect; - near = camera.near; - far = camera.far; + /** + * @author mrdoob / http://mrdoob.com/ + */ - // Off-axis stereoscopic effect based on - // http://paulbourke.net/stereographics/stereorender/ + function StereoCamera() { - var projectionMatrix = camera.projectionMatrix.clone(); - var eyeSep = 0.064 / 2; - var eyeSepOnProjection = eyeSep * near / focus; - var ymax = near * Math.tan( exports.Math.DEG2RAD * fov * 0.5 ); - var xmin, xmax; + this.type = 'StereoCamera'; - // translate xOffset + this.aspect = 1; - eyeLeft.elements[ 12 ] = - eyeSep; - eyeRight.elements[ 12 ] = eyeSep; + this.eyeSep = 0.064; - // for left eye + this.cameraL = new PerspectiveCamera(); + this.cameraL.layers.enable( 1 ); + this.cameraL.matrixAutoUpdate = false; - xmin = - ymax * aspect + eyeSepOnProjection; - xmax = ymax * aspect + eyeSepOnProjection; + this.cameraR = new PerspectiveCamera(); + this.cameraR.layers.enable( 2 ); + this.cameraR.matrixAutoUpdate = false; - projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin ); - projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin ); + } - this.cameraL.projectionMatrix.copy( projectionMatrix ); + Object.assign( StereoCamera.prototype, { - // for right eye + update: ( function () { - xmin = - ymax * aspect - eyeSepOnProjection; - xmax = ymax * aspect - eyeSepOnProjection; + var focus, fov, aspect, near, far; - projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin ); - projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin ); + var eyeRight = new Matrix4(); + var eyeLeft = new Matrix4(); - this.cameraR.projectionMatrix.copy( projectionMatrix ); + return function update( camera ) { - } + var needsUpdate = focus !== camera.focus || fov !== camera.fov || + aspect !== camera.aspect * this.aspect || near !== camera.near || + far !== camera.far; - this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( eyeLeft ); - this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( eyeRight ); + if ( needsUpdate ) { - }; + focus = camera.focus; + fov = camera.fov; + aspect = camera.aspect * this.aspect; + near = camera.near; + far = camera.far; - } )() + // Off-axis stereoscopic effect based on + // http://paulbourke.net/stereographics/stereorender/ - } ); + var projectionMatrix = camera.projectionMatrix.clone(); + var eyeSep = this.eyeSep / 2; + var eyeSepOnProjection = eyeSep * near / focus; + var ymax = near * Math.tan( exports.Math.DEG2RAD * fov * 0.5 ); + var xmin, xmax; - /** - * Camera for rendering cube maps - * - renders scene into axis-aligned cube - * - * @author alteredq / http://alteredqualia.com/ - */ + // translate xOffset - function CubeCamera( near, far, cubeResolution ) { + eyeLeft.elements[ 12 ] = - eyeSep; + eyeRight.elements[ 12 ] = eyeSep; - Object3D.call( this ); + // for left eye - this.type = 'CubeCamera'; + xmin = - ymax * aspect + eyeSepOnProjection; + xmax = ymax * aspect + eyeSepOnProjection; - var fov = 90, aspect = 1; + projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin ); + projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin ); - var cameraPX = new PerspectiveCamera( fov, aspect, near, far ); - cameraPX.up.set( 0, - 1, 0 ); - cameraPX.lookAt( new Vector3( 1, 0, 0 ) ); - this.add( cameraPX ); + this.cameraL.projectionMatrix.copy( projectionMatrix ); - var cameraNX = new PerspectiveCamera( fov, aspect, near, far ); - cameraNX.up.set( 0, - 1, 0 ); - cameraNX.lookAt( new Vector3( - 1, 0, 0 ) ); - this.add( cameraNX ); + // for right eye - var cameraPY = new PerspectiveCamera( fov, aspect, near, far ); - cameraPY.up.set( 0, 0, 1 ); - cameraPY.lookAt( new Vector3( 0, 1, 0 ) ); - this.add( cameraPY ); + xmin = - ymax * aspect - eyeSepOnProjection; + xmax = ymax * aspect - eyeSepOnProjection; - var cameraNY = new PerspectiveCamera( fov, aspect, near, far ); - cameraNY.up.set( 0, 0, - 1 ); - cameraNY.lookAt( new Vector3( 0, - 1, 0 ) ); - this.add( cameraNY ); + projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin ); + projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin ); - var cameraPZ = new PerspectiveCamera( fov, aspect, near, far ); - cameraPZ.up.set( 0, - 1, 0 ); - cameraPZ.lookAt( new Vector3( 0, 0, 1 ) ); - this.add( cameraPZ ); + this.cameraR.projectionMatrix.copy( projectionMatrix ); - var cameraNZ = new PerspectiveCamera( fov, aspect, near, far ); - cameraNZ.up.set( 0, - 1, 0 ); - cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) ); - this.add( cameraNZ ); + } - var options = { format: RGBFormat, magFilter: LinearFilter, minFilter: LinearFilter }; + this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( eyeLeft ); + this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( eyeRight ); - this.renderTarget = new WebGLRenderTargetCube( cubeResolution, cubeResolution, options ); + }; - this.updateCubeMap = function ( renderer, scene ) { + } )() - if ( this.parent === null ) this.updateMatrixWorld(); + } ); - var renderTarget = this.renderTarget; - var generateMipmaps = renderTarget.texture.generateMipmaps; + /** + * Camera for rendering cube maps + * - renders scene into axis-aligned cube + * + * @author alteredq / http://alteredqualia.com/ + */ - renderTarget.texture.generateMipmaps = false; + function CubeCamera( near, far, cubeResolution ) { - renderTarget.activeCubeFace = 0; - renderer.render( scene, cameraPX, renderTarget ); + Object3D.call( this ); - renderTarget.activeCubeFace = 1; - renderer.render( scene, cameraNX, renderTarget ); + this.type = 'CubeCamera'; - renderTarget.activeCubeFace = 2; - renderer.render( scene, cameraPY, renderTarget ); + var fov = 90, aspect = 1; - renderTarget.activeCubeFace = 3; - renderer.render( scene, cameraNY, renderTarget ); + var cameraPX = new PerspectiveCamera( fov, aspect, near, far ); + cameraPX.up.set( 0, - 1, 0 ); + cameraPX.lookAt( new Vector3( 1, 0, 0 ) ); + this.add( cameraPX ); - renderTarget.activeCubeFace = 4; - renderer.render( scene, cameraPZ, renderTarget ); + var cameraNX = new PerspectiveCamera( fov, aspect, near, far ); + cameraNX.up.set( 0, - 1, 0 ); + cameraNX.lookAt( new Vector3( - 1, 0, 0 ) ); + this.add( cameraNX ); - renderTarget.texture.generateMipmaps = generateMipmaps; + var cameraPY = new PerspectiveCamera( fov, aspect, near, far ); + cameraPY.up.set( 0, 0, 1 ); + cameraPY.lookAt( new Vector3( 0, 1, 0 ) ); + this.add( cameraPY ); - renderTarget.activeCubeFace = 5; - renderer.render( scene, cameraNZ, renderTarget ); + var cameraNY = new PerspectiveCamera( fov, aspect, near, far ); + cameraNY.up.set( 0, 0, - 1 ); + cameraNY.lookAt( new Vector3( 0, - 1, 0 ) ); + this.add( cameraNY ); - renderer.setRenderTarget( null ); + var cameraPZ = new PerspectiveCamera( fov, aspect, near, far ); + cameraPZ.up.set( 0, - 1, 0 ); + cameraPZ.lookAt( new Vector3( 0, 0, 1 ) ); + this.add( cameraPZ ); - }; + var cameraNZ = new PerspectiveCamera( fov, aspect, near, far ); + cameraNZ.up.set( 0, - 1, 0 ); + cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) ); + this.add( cameraNZ ); - }; + var options = { format: RGBFormat, magFilter: LinearFilter, minFilter: LinearFilter }; - CubeCamera.prototype = Object.create( Object3D.prototype ); - CubeCamera.prototype.constructor = CubeCamera; + this.renderTarget = new WebGLRenderTargetCube( cubeResolution, cubeResolution, options ); - function AudioListener() { + this.updateCubeMap = function ( renderer, scene ) { - Object3D.call( this ); + if ( this.parent === null ) this.updateMatrixWorld(); - this.type = 'AudioListener'; + var renderTarget = this.renderTarget; + var generateMipmaps = renderTarget.texture.generateMipmaps; - this.context = getAudioContext(); + renderTarget.texture.generateMipmaps = false; - this.gain = this.context.createGain(); - this.gain.connect( this.context.destination ); + renderTarget.activeCubeFace = 0; + renderer.render( scene, cameraPX, renderTarget ); - this.filter = null; + renderTarget.activeCubeFace = 1; + renderer.render( scene, cameraNX, renderTarget ); - } + renderTarget.activeCubeFace = 2; + renderer.render( scene, cameraPY, renderTarget ); - AudioListener.prototype = Object.assign( Object.create( Object3D.prototype ), { + renderTarget.activeCubeFace = 3; + renderer.render( scene, cameraNY, renderTarget ); - constructor: AudioListener, + renderTarget.activeCubeFace = 4; + renderer.render( scene, cameraPZ, renderTarget ); - getInput: function () { + renderTarget.texture.generateMipmaps = generateMipmaps; - return this.gain; + renderTarget.activeCubeFace = 5; + renderer.render( scene, cameraNZ, renderTarget ); - }, + renderer.setRenderTarget( null ); - removeFilter: function ( ) { + }; - if ( this.filter !== null ) { + } - this.gain.disconnect( this.filter ); - this.filter.disconnect( this.context.destination ); - this.gain.connect( this.context.destination ); - this.filter = null; + CubeCamera.prototype = Object.create( Object3D.prototype ); + CubeCamera.prototype.constructor = CubeCamera; - } + function AudioListener() { - }, + Object3D.call( this ); - getFilter: function () { + this.type = 'AudioListener'; - return this.filter; + this.context = getAudioContext(); - }, + this.gain = this.context.createGain(); + this.gain.connect( this.context.destination ); - setFilter: function ( value ) { + this.filter = null; - if ( this.filter !== null ) { + } - this.gain.disconnect( this.filter ); - this.filter.disconnect( this.context.destination ); + AudioListener.prototype = Object.assign( Object.create( Object3D.prototype ), { - } else { + constructor: AudioListener, - this.gain.disconnect( this.context.destination ); + getInput: function () { - } + return this.gain; - this.filter = value; - this.gain.connect( this.filter ); - this.filter.connect( this.context.destination ); + }, - }, + removeFilter: function ( ) { - getMasterVolume: function () { + if ( this.filter !== null ) { - return this.gain.gain.value; + this.gain.disconnect( this.filter ); + this.filter.disconnect( this.context.destination ); + this.gain.connect( this.context.destination ); + this.filter = null; - }, + } - setMasterVolume: function ( value ) { + }, - this.gain.gain.value = value; + getFilter: function () { - }, + return this.filter; - updateMatrixWorld: ( function () { + }, - var position = new Vector3(); - var quaternion = new Quaternion(); - var scale = new Vector3(); + setFilter: function ( value ) { - var orientation = new Vector3(); + if ( this.filter !== null ) { - return function updateMatrixWorld( force ) { + this.gain.disconnect( this.filter ); + this.filter.disconnect( this.context.destination ); - Object3D.prototype.updateMatrixWorld.call( this, force ); + } else { - var listener = this.context.listener; - var up = this.up; + this.gain.disconnect( this.context.destination ); - this.matrixWorld.decompose( position, quaternion, scale ); + } - orientation.set( 0, 0, - 1 ).applyQuaternion( quaternion ); + this.filter = value; + this.gain.connect( this.filter ); + this.filter.connect( this.context.destination ); - listener.setPosition( position.x, position.y, position.z ); - listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z ); + }, - }; + getMasterVolume: function () { - } )() + return this.gain.gain.value; - } ); + }, - function Audio( listener ) { + setMasterVolume: function ( value ) { - Object3D.call( this ); + this.gain.gain.value = value; - this.type = 'Audio'; + }, - this.context = listener.context; - this.source = this.context.createBufferSource(); - this.source.onended = this.onEnded.bind( this ); + updateMatrixWorld: ( function () { - this.gain = this.context.createGain(); - this.gain.connect( listener.getInput() ); + var position = new Vector3(); + var quaternion = new Quaternion(); + var scale = new Vector3(); - this.autoplay = false; + var orientation = new Vector3(); - this.startTime = 0; - this.playbackRate = 1; - this.isPlaying = false; - this.hasPlaybackControl = true; - this.sourceType = 'empty'; + return function updateMatrixWorld( force ) { - this.filters = []; + Object3D.prototype.updateMatrixWorld.call( this, force ); - } + var listener = this.context.listener; + var up = this.up; - Audio.prototype = Object.assign( Object.create( Object3D.prototype ), { + this.matrixWorld.decompose( position, quaternion, scale ); - constructor: Audio, + orientation.set( 0, 0, - 1 ).applyQuaternion( quaternion ); - getOutput: function () { + listener.setPosition( position.x, position.y, position.z ); + listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z ); - return this.gain; + }; - }, + } )() - setNodeSource: function ( audioNode ) { + } ); - this.hasPlaybackControl = false; - this.sourceType = 'audioNode'; - this.source = audioNode; - this.connect(); + function Audio( listener ) { - return this; + Object3D.call( this ); - }, + this.type = 'Audio'; - setBuffer: function ( audioBuffer ) { + this.context = listener.context; + this.source = this.context.createBufferSource(); + this.source.onended = this.onEnded.bind( this ); - this.source.buffer = audioBuffer; - this.sourceType = 'buffer'; + this.gain = this.context.createGain(); + this.gain.connect( listener.getInput() ); - if ( this.autoplay ) this.play(); + this.autoplay = false; - return this; + this.startTime = 0; + this.playbackRate = 1; + this.isPlaying = false; + this.hasPlaybackControl = true; + this.sourceType = 'empty'; - }, + this.filters = []; - play: function () { + } - if ( this.isPlaying === true ) { + Audio.prototype = Object.assign( Object.create( Object3D.prototype ), { - console.warn( 'THREE.Audio: Audio is already playing.' ); - return; + constructor: Audio, - } + getOutput: function () { - if ( this.hasPlaybackControl === false ) { + return this.gain; - console.warn( 'THREE.Audio: this Audio has no playback control.' ); - return; + }, - } + setNodeSource: function ( audioNode ) { - var source = this.context.createBufferSource(); + this.hasPlaybackControl = false; + this.sourceType = 'audioNode'; + this.source = audioNode; + this.connect(); - source.buffer = this.source.buffer; - source.loop = this.source.loop; - source.onended = this.source.onended; - source.start( 0, this.startTime ); - source.playbackRate.value = this.playbackRate; + return this; - this.isPlaying = true; + }, - this.source = source; + setBuffer: function ( audioBuffer ) { - return this.connect(); + this.source.buffer = audioBuffer; + this.sourceType = 'buffer'; - }, + if ( this.autoplay ) this.play(); - pause: function () { + return this; - if ( this.hasPlaybackControl === false ) { + }, - console.warn( 'THREE.Audio: this Audio has no playback control.' ); - return; + play: function () { - } + if ( this.isPlaying === true ) { - this.source.stop(); - this.startTime = this.context.currentTime; - this.isPlaying = false; + console.warn( 'THREE.Audio: Audio is already playing.' ); + return; - return this; + } - }, + if ( this.hasPlaybackControl === false ) { - stop: function () { + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; - if ( this.hasPlaybackControl === false ) { + } - console.warn( 'THREE.Audio: this Audio has no playback control.' ); - return; + var source = this.context.createBufferSource(); - } + source.buffer = this.source.buffer; + source.loop = this.source.loop; + source.onended = this.source.onended; + source.start( 0, this.startTime ); + source.playbackRate.value = this.playbackRate; - this.source.stop(); - this.startTime = 0; - this.isPlaying = false; + this.isPlaying = true; - return this; + this.source = source; - }, + return this.connect(); - connect: function () { + }, - if ( this.filters.length > 0 ) { + pause: function () { - this.source.connect( this.filters[ 0 ] ); + if ( this.hasPlaybackControl === false ) { - for ( var i = 1, l = this.filters.length; i < l; i ++ ) { + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; - this.filters[ i - 1 ].connect( this.filters[ i ] ); + } - } + this.source.stop(); + this.startTime = this.context.currentTime; + this.isPlaying = false; - this.filters[ this.filters.length - 1 ].connect( this.getOutput() ); + return this; - } else { + }, - this.source.connect( this.getOutput() ); + stop: function () { - } + if ( this.hasPlaybackControl === false ) { - return this; + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; - }, + } - disconnect: function () { + this.source.stop(); + this.startTime = 0; + this.isPlaying = false; - if ( this.filters.length > 0 ) { + return this; - this.source.disconnect( this.filters[ 0 ] ); + }, - for ( var i = 1, l = this.filters.length; i < l; i ++ ) { + connect: function () { - this.filters[ i - 1 ].disconnect( this.filters[ i ] ); + if ( this.filters.length > 0 ) { - } + this.source.connect( this.filters[ 0 ] ); - this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() ); + for ( var i = 1, l = this.filters.length; i < l; i ++ ) { - } else { + this.filters[ i - 1 ].connect( this.filters[ i ] ); - this.source.disconnect( this.getOutput() ); + } - } + this.filters[ this.filters.length - 1 ].connect( this.getOutput() ); - return this; + } else { - }, + this.source.connect( this.getOutput() ); - getFilters: function () { + } - return this.filters; + return this; - }, + }, - setFilters: function ( value ) { + disconnect: function () { - if ( ! value ) value = []; + if ( this.filters.length > 0 ) { - if ( this.isPlaying === true ) { + this.source.disconnect( this.filters[ 0 ] ); - this.disconnect(); - this.filters = value; - this.connect(); + for ( var i = 1, l = this.filters.length; i < l; i ++ ) { - } else { + this.filters[ i - 1 ].disconnect( this.filters[ i ] ); - this.filters = value; + } - } + this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() ); - return this; + } else { - }, + this.source.disconnect( this.getOutput() ); - getFilter: function () { + } - return this.getFilters()[ 0 ]; + return this; - }, + }, - setFilter: function ( filter ) { + getFilters: function () { - return this.setFilters( filter ? [ filter ] : [] ); + return this.filters; - }, + }, - setPlaybackRate: function ( value ) { + setFilters: function ( value ) { - if ( this.hasPlaybackControl === false ) { + if ( ! value ) value = []; - console.warn( 'THREE.Audio: this Audio has no playback control.' ); - return; + if ( this.isPlaying === true ) { - } + this.disconnect(); + this.filters = value; + this.connect(); - this.playbackRate = value; + } else { - if ( this.isPlaying === true ) { + this.filters = value; - this.source.playbackRate.value = this.playbackRate; + } - } + return this; - return this; + }, - }, + getFilter: function () { - getPlaybackRate: function () { + return this.getFilters()[ 0 ]; - return this.playbackRate; + }, - }, + setFilter: function ( filter ) { - onEnded: function () { + return this.setFilters( filter ? [ filter ] : [] ); - this.isPlaying = false; + }, - }, + setPlaybackRate: function ( value ) { - getLoop: function () { + if ( this.hasPlaybackControl === false ) { - if ( this.hasPlaybackControl === false ) { + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; - console.warn( 'THREE.Audio: this Audio has no playback control.' ); - return false; + } - } + this.playbackRate = value; - return this.source.loop; + if ( this.isPlaying === true ) { - }, + this.source.playbackRate.value = this.playbackRate; - setLoop: function ( value ) { + } - if ( this.hasPlaybackControl === false ) { + return this; - console.warn( 'THREE.Audio: this Audio has no playback control.' ); - return; + }, - } + getPlaybackRate: function () { - this.source.loop = value; + return this.playbackRate; - }, + }, - getVolume: function () { + onEnded: function () { - return this.gain.gain.value; + this.isPlaying = false; - }, + }, + getLoop: function () { - setVolume: function ( value ) { + if ( this.hasPlaybackControl === false ) { - this.gain.gain.value = value; + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return false; - return this; + } - } + return this.source.loop; - } ); + }, - function PositionalAudio( listener ) { + setLoop: function ( value ) { - Audio.call( this, listener ); + if ( this.hasPlaybackControl === false ) { - this.panner = this.context.createPanner(); - this.panner.connect( this.gain ); + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; - } + } - PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), { + this.source.loop = value; - constructor: PositionalAudio, + }, - getOutput: function () { + getVolume: function () { - return this.panner; + return this.gain.gain.value; - }, + }, - getRefDistance: function () { - return this.panner.refDistance; + setVolume: function ( value ) { - }, + this.gain.gain.value = value; - setRefDistance: function ( value ) { + return this; - this.panner.refDistance = value; + } - }, + } ); - getRolloffFactor: function () { + function PositionalAudio( listener ) { - return this.panner.rolloffFactor; + Audio.call( this, listener ); - }, + this.panner = this.context.createPanner(); + this.panner.connect( this.gain ); - setRolloffFactor: function ( value ) { + } - this.panner.rolloffFactor = value; + PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), { - }, + constructor: PositionalAudio, - getDistanceModel: function () { + getOutput: function () { - return this.panner.distanceModel; + return this.panner; - }, + }, - setDistanceModel: function ( value ) { + getRefDistance: function () { - this.panner.distanceModel = value; + return this.panner.refDistance; - }, + }, - getMaxDistance: function () { + setRefDistance: function ( value ) { - return this.panner.maxDistance; + this.panner.refDistance = value; - }, + }, - setMaxDistance: function ( value ) { + getRolloffFactor: function () { - this.panner.maxDistance = value; + return this.panner.rolloffFactor; - }, + }, - updateMatrixWorld: ( function () { + setRolloffFactor: function ( value ) { - var position = new Vector3(); + this.panner.rolloffFactor = value; - return function updateMatrixWorld( force ) { + }, - Object3D.prototype.updateMatrixWorld.call( this, force ); + getDistanceModel: function () { - position.setFromMatrixPosition( this.matrixWorld ); + return this.panner.distanceModel; - this.panner.setPosition( position.x, position.y, position.z ); + }, - }; + setDistanceModel: function ( value ) { - } )() + this.panner.distanceModel = value; + }, - } ); + getMaxDistance: function () { - /** - * @author mrdoob / http://mrdoob.com/ - */ + return this.panner.maxDistance; - function AudioAnalyser( audio, fftSize ) { + }, - this.analyser = audio.context.createAnalyser(); - this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048; + setMaxDistance: function ( value ) { - this.data = new Uint8Array( this.analyser.frequencyBinCount ); + this.panner.maxDistance = value; - audio.getOutput().connect( this.analyser ); + }, - } + updateMatrixWorld: ( function () { - Object.assign( AudioAnalyser.prototype, { + var position = new Vector3(); - getFrequencyData: function () { + return function updateMatrixWorld( force ) { - this.analyser.getByteFrequencyData( this.data ); + Object3D.prototype.updateMatrixWorld.call( this, force ); - return this.data; + position.setFromMatrixPosition( this.matrixWorld ); - }, + this.panner.setPosition( position.x, position.y, position.z ); - getAverageFrequency: function () { + }; - var value = 0, data = this.getFrequencyData(); + } )() - for ( var i = 0; i < data.length; i ++ ) { - value += data[ i ]; + } ); - } + /** + * @author mrdoob / http://mrdoob.com/ + */ - return value / data.length; + function AudioAnalyser( audio, fftSize ) { - } + this.analyser = audio.context.createAnalyser(); + this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048; - } ); + this.data = new Uint8Array( this.analyser.frequencyBinCount ); - /** - * - * Buffered scene graph property that allows weighted accumulation. - * - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + audio.getOutput().connect( this.analyser ); - function PropertyMixer( binding, typeName, valueSize ) { + } - this.binding = binding; - this.valueSize = valueSize; + Object.assign( AudioAnalyser.prototype, { - var bufferType = Float64Array, - mixFunction; + getFrequencyData: function () { - switch ( typeName ) { + this.analyser.getByteFrequencyData( this.data ); - case 'quaternion': mixFunction = this._slerp; break; + return this.data; - case 'string': - case 'bool': + }, - bufferType = Array, mixFunction = this._select; break; + getAverageFrequency: function () { - default: mixFunction = this._lerp; + var value = 0, data = this.getFrequencyData(); - } + for ( var i = 0; i < data.length; i ++ ) { - this.buffer = new bufferType( valueSize * 4 ); - // layout: [ incoming | accu0 | accu1 | orig ] - // - // interpolators can use .buffer as their .result - // the data then goes to 'incoming' - // - // 'accu0' and 'accu1' are used frame-interleaved for - // the cumulative result and are compared to detect - // changes - // - // 'orig' stores the original state of the property + value += data[ i ]; - this._mixBufferRegion = mixFunction; + } - this.cumulativeWeight = 0; + return value / data.length; - this.useCount = 0; - this.referenceCount = 0; + } - }; + } ); - PropertyMixer.prototype = { + /** + * + * Buffered scene graph property that allows weighted accumulation. + * + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - constructor: PropertyMixer, + function PropertyMixer( binding, typeName, valueSize ) { - // accumulate data in the 'incoming' region into 'accu' - accumulate: function( accuIndex, weight ) { + this.binding = binding; + this.valueSize = valueSize; - // note: happily accumulating nothing when weight = 0, the caller knows - // the weight and shouldn't have made the call in the first place + var bufferType = Float64Array, + mixFunction; - var buffer = this.buffer, - stride = this.valueSize, - offset = accuIndex * stride + stride, + switch ( typeName ) { - currentWeight = this.cumulativeWeight; + case 'quaternion': mixFunction = this._slerp; break; - if ( currentWeight === 0 ) { + case 'string': + case 'bool': - // accuN := incoming * weight + bufferType = Array, mixFunction = this._select; break; - for ( var i = 0; i !== stride; ++ i ) { + default: mixFunction = this._lerp; - buffer[ offset + i ] = buffer[ i ]; + } - } + this.buffer = new bufferType( valueSize * 4 ); + // layout: [ incoming | accu0 | accu1 | orig ] + // + // interpolators can use .buffer as their .result + // the data then goes to 'incoming' + // + // 'accu0' and 'accu1' are used frame-interleaved for + // the cumulative result and are compared to detect + // changes + // + // 'orig' stores the original state of the property - currentWeight = weight; + this._mixBufferRegion = mixFunction; - } else { + this.cumulativeWeight = 0; - // accuN := accuN + incoming * weight + this.useCount = 0; + this.referenceCount = 0; - currentWeight += weight; - var mix = weight / currentWeight; - this._mixBufferRegion( buffer, offset, 0, mix, stride ); + } - } + PropertyMixer.prototype = { - this.cumulativeWeight = currentWeight; + constructor: PropertyMixer, - }, + // accumulate data in the 'incoming' region into 'accu' + accumulate: function( accuIndex, weight ) { - // apply the state of 'accu' to the binding when accus differ - apply: function( accuIndex ) { + // note: happily accumulating nothing when weight = 0, the caller knows + // the weight and shouldn't have made the call in the first place - var stride = this.valueSize, - buffer = this.buffer, - offset = accuIndex * stride + stride, + var buffer = this.buffer, + stride = this.valueSize, + offset = accuIndex * stride + stride, - weight = this.cumulativeWeight, + currentWeight = this.cumulativeWeight; - binding = this.binding; + if ( currentWeight === 0 ) { - this.cumulativeWeight = 0; + // accuN := incoming * weight - if ( weight < 1 ) { + for ( var i = 0; i !== stride; ++ i ) { - // accuN := accuN + original * ( 1 - cumulativeWeight ) + buffer[ offset + i ] = buffer[ i ]; - var originalValueOffset = stride * 3; + } - this._mixBufferRegion( - buffer, offset, originalValueOffset, 1 - weight, stride ); + currentWeight = weight; - } + } else { - for ( var i = stride, e = stride + stride; i !== e; ++ i ) { + // accuN := accuN + incoming * weight - if ( buffer[ i ] !== buffer[ i + stride ] ) { + currentWeight += weight; + var mix = weight / currentWeight; + this._mixBufferRegion( buffer, offset, 0, mix, stride ); - // value has changed -> update scene graph + } - binding.setValue( buffer, offset ); - break; + this.cumulativeWeight = currentWeight; - } + }, - } + // apply the state of 'accu' to the binding when accus differ + apply: function( accuIndex ) { - }, + var stride = this.valueSize, + buffer = this.buffer, + offset = accuIndex * stride + stride, - // remember the state of the bound property and copy it to both accus - saveOriginalState: function() { + weight = this.cumulativeWeight, - var binding = this.binding; + binding = this.binding; - var buffer = this.buffer, - stride = this.valueSize, + this.cumulativeWeight = 0; - originalValueOffset = stride * 3; + if ( weight < 1 ) { - binding.getValue( buffer, originalValueOffset ); + // accuN := accuN + original * ( 1 - cumulativeWeight ) - // accu[0..1] := orig -- initially detect changes against the original - for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) { + var originalValueOffset = stride * 3; - buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ]; + this._mixBufferRegion( + buffer, offset, originalValueOffset, 1 - weight, stride ); - } + } - this.cumulativeWeight = 0; + for ( var i = stride, e = stride + stride; i !== e; ++ i ) { - }, + if ( buffer[ i ] !== buffer[ i + stride ] ) { - // apply the state previously taken via 'saveOriginalState' to the binding - restoreOriginalState: function() { + // value has changed -> update scene graph - var originalValueOffset = this.valueSize * 3; - this.binding.setValue( this.buffer, originalValueOffset ); + binding.setValue( buffer, offset ); + break; - }, + } + } - // mix functions + }, - _select: function( buffer, dstOffset, srcOffset, t, stride ) { + // remember the state of the bound property and copy it to both accus + saveOriginalState: function() { - if ( t >= 0.5 ) { + var binding = this.binding; - for ( var i = 0; i !== stride; ++ i ) { + var buffer = this.buffer, + stride = this.valueSize, - buffer[ dstOffset + i ] = buffer[ srcOffset + i ]; + originalValueOffset = stride * 3; - } + binding.getValue( buffer, originalValueOffset ); - } + // accu[0..1] := orig -- initially detect changes against the original + for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) { - }, + buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ]; - _slerp: function( buffer, dstOffset, srcOffset, t, stride ) { + } - Quaternion.slerpFlat( buffer, dstOffset, - buffer, dstOffset, buffer, srcOffset, t ); + this.cumulativeWeight = 0; - }, + }, - _lerp: function( buffer, dstOffset, srcOffset, t, stride ) { + // apply the state previously taken via 'saveOriginalState' to the binding + restoreOriginalState: function() { - var s = 1 - t; + var originalValueOffset = this.valueSize * 3; + this.binding.setValue( this.buffer, originalValueOffset ); - for ( var i = 0; i !== stride; ++ i ) { + }, - var j = dstOffset + i; - buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t; + // mix functions - } + _select: function( buffer, dstOffset, srcOffset, t, stride ) { - } + if ( t >= 0.5 ) { - }; + for ( var i = 0; i !== stride; ++ i ) { - /** - * - * A reference to a real property in the scene graph. - * - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + buffer[ dstOffset + i ] = buffer[ srcOffset + i ]; - function PropertyBinding( rootNode, path, parsedPath ) { + } - this.path = path; - this.parsedPath = parsedPath || - PropertyBinding.parseTrackName( path ); + } - this.node = PropertyBinding.findNode( - rootNode, this.parsedPath.nodeName ) || rootNode; + }, - this.rootNode = rootNode; + _slerp: function( buffer, dstOffset, srcOffset, t, stride ) { - }; + Quaternion.slerpFlat( buffer, dstOffset, + buffer, dstOffset, buffer, srcOffset, t ); - PropertyBinding.prototype = { + }, - constructor: PropertyBinding, + _lerp: function( buffer, dstOffset, srcOffset, t, stride ) { - getValue: function getValue_unbound( targetArray, offset ) { + var s = 1 - t; - this.bind(); - this.getValue( targetArray, offset ); + for ( var i = 0; i !== stride; ++ i ) { - // Note: This class uses a State pattern on a per-method basis: - // 'bind' sets 'this.getValue' / 'setValue' and shadows the - // prototype version of these methods with one that represents - // the bound state. When the property is not found, the methods - // become no-ops. + var j = dstOffset + i; - }, + buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t; - setValue: function getValue_unbound( sourceArray, offset ) { + } - this.bind(); - this.setValue( sourceArray, offset ); + } - }, + }; - // create getter / setter pair for a property in the scene graph - bind: function() { + /** + * + * A reference to a real property in the scene graph. + * + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - var targetObject = this.node, - parsedPath = this.parsedPath, + function PropertyBinding( rootNode, path, parsedPath ) { - objectName = parsedPath.objectName, - propertyName = parsedPath.propertyName, - propertyIndex = parsedPath.propertyIndex; + this.path = path; + this.parsedPath = parsedPath || + PropertyBinding.parseTrackName( path ); - if ( ! targetObject ) { + this.node = PropertyBinding.findNode( + rootNode, this.parsedPath.nodeName ) || rootNode; - targetObject = PropertyBinding.findNode( - this.rootNode, parsedPath.nodeName ) || this.rootNode; + this.rootNode = rootNode; - this.node = targetObject; + } - } + PropertyBinding.prototype = { - // set fail state so we can just 'return' on error - this.getValue = this._getValue_unavailable; - this.setValue = this._setValue_unavailable; + constructor: PropertyBinding, - // ensure there is a value node - if ( ! targetObject ) { + getValue: function getValue_unbound( targetArray, offset ) { - console.error( " trying to update node for track: " + this.path + " but it wasn't found." ); - return; + this.bind(); + this.getValue( targetArray, offset ); - } + // Note: This class uses a State pattern on a per-method basis: + // 'bind' sets 'this.getValue' / 'setValue' and shadows the + // prototype version of these methods with one that represents + // the bound state. When the property is not found, the methods + // become no-ops. - if ( objectName ) { + }, - var objectIndex = parsedPath.objectIndex; + setValue: function getValue_unbound( sourceArray, offset ) { - // special cases were we need to reach deeper into the hierarchy to get the face materials.... - switch ( objectName ) { + this.bind(); + this.setValue( sourceArray, offset ); - case 'materials': + }, - if ( ! targetObject.material ) { + // create getter / setter pair for a property in the scene graph + bind: function() { - console.error( ' can not bind to material as node does not have a material', this ); - return; + var targetObject = this.node, + parsedPath = this.parsedPath, - } + objectName = parsedPath.objectName, + propertyName = parsedPath.propertyName, + propertyIndex = parsedPath.propertyIndex; - if ( ! targetObject.material.materials ) { + if ( ! targetObject ) { - console.error( ' can not bind to material.materials as node.material does not have a materials array', this ); - return; + targetObject = PropertyBinding.findNode( + this.rootNode, parsedPath.nodeName ) || this.rootNode; - } + this.node = targetObject; - targetObject = targetObject.material.materials; + } - break; + // set fail state so we can just 'return' on error + this.getValue = this._getValue_unavailable; + this.setValue = this._setValue_unavailable; - case 'bones': + // ensure there is a value node + if ( ! targetObject ) { - if ( ! targetObject.skeleton ) { + console.error( " trying to update node for track: " + this.path + " but it wasn't found." ); + return; - console.error( ' can not bind to bones as node does not have a skeleton', this ); - return; + } - } + if ( objectName ) { - // potential future optimization: skip this if propertyIndex is already an integer - // and convert the integer string to a true integer. + var objectIndex = parsedPath.objectIndex; - targetObject = targetObject.skeleton.bones; + // special cases were we need to reach deeper into the hierarchy to get the face materials.... + switch ( objectName ) { - // support resolving morphTarget names into indices. - for ( var i = 0; i < targetObject.length; i ++ ) { + case 'materials': - if ( targetObject[ i ].name === objectIndex ) { + if ( ! targetObject.material ) { - objectIndex = i; - break; + console.error( ' can not bind to material as node does not have a material', this ); + return; - } + } - } + if ( ! targetObject.material.materials ) { - break; + console.error( ' can not bind to material.materials as node.material does not have a materials array', this ); + return; - default: + } - if ( targetObject[ objectName ] === undefined ) { + targetObject = targetObject.material.materials; - console.error( ' can not bind to objectName of node, undefined', this ); - return; + break; - } + case 'bones': - targetObject = targetObject[ objectName ]; + if ( ! targetObject.skeleton ) { - } + console.error( ' can not bind to bones as node does not have a skeleton', this ); + return; + } - if ( objectIndex !== undefined ) { + // potential future optimization: skip this if propertyIndex is already an integer + // and convert the integer string to a true integer. - if ( targetObject[ objectIndex ] === undefined ) { + targetObject = targetObject.skeleton.bones; - console.error( " trying to bind to objectIndex of objectName, but is undefined:", this, targetObject ); - return; + // support resolving morphTarget names into indices. + for ( var i = 0; i < targetObject.length; i ++ ) { - } + if ( targetObject[ i ].name === objectIndex ) { - targetObject = targetObject[ objectIndex ]; + objectIndex = i; + break; - } + } - } + } - // resolve property - var nodeProperty = targetObject[ propertyName ]; + break; - if ( nodeProperty === undefined ) { + default: - var nodeName = parsedPath.nodeName; + if ( targetObject[ objectName ] === undefined ) { - console.error( " trying to update property for track: " + nodeName + - '.' + propertyName + " but it wasn't found.", targetObject ); - return; + console.error( ' can not bind to objectName of node, undefined', this ); + return; - } + } - // determine versioning scheme - var versioning = this.Versioning.None; + targetObject = targetObject[ objectName ]; - if ( targetObject.needsUpdate !== undefined ) { // material + } - versioning = this.Versioning.NeedsUpdate; - this.targetObject = targetObject; - } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform + if ( objectIndex !== undefined ) { - versioning = this.Versioning.MatrixWorldNeedsUpdate; - this.targetObject = targetObject; + if ( targetObject[ objectIndex ] === undefined ) { - } + console.error( " trying to bind to objectIndex of objectName, but is undefined:", this, targetObject ); + return; - // determine how the property gets bound - var bindingType = this.BindingType.Direct; + } - if ( propertyIndex !== undefined ) { - // access a sub element of the property array (only primitives are supported right now) + targetObject = targetObject[ objectIndex ]; - if ( propertyName === "morphTargetInfluences" ) { - // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer. + } - // support resolving morphTarget names into indices. - if ( ! targetObject.geometry ) { + } - console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry', this ); - return; + // resolve property + var nodeProperty = targetObject[ propertyName ]; - } + if ( nodeProperty === undefined ) { - if ( ! targetObject.geometry.morphTargets ) { + var nodeName = parsedPath.nodeName; - console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry.morphTargets', this ); - return; + console.error( " trying to update property for track: " + nodeName + + '.' + propertyName + " but it wasn't found.", targetObject ); + return; - } + } - for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) { + // determine versioning scheme + var versioning = this.Versioning.None; - if ( targetObject.geometry.morphTargets[ i ].name === propertyIndex ) { + if ( targetObject.needsUpdate !== undefined ) { // material - propertyIndex = i; - break; + versioning = this.Versioning.NeedsUpdate; + this.targetObject = targetObject; - } + } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform - } + versioning = this.Versioning.MatrixWorldNeedsUpdate; + this.targetObject = targetObject; - } + } - bindingType = this.BindingType.ArrayElement; + // determine how the property gets bound + var bindingType = this.BindingType.Direct; - this.resolvedProperty = nodeProperty; - this.propertyIndex = propertyIndex; + if ( propertyIndex !== undefined ) { + // access a sub element of the property array (only primitives are supported right now) - } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) { - // must use copy for Object3D.Euler/Quaternion + if ( propertyName === "morphTargetInfluences" ) { + // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer. - bindingType = this.BindingType.HasFromToArray; + // support resolving morphTarget names into indices. + if ( ! targetObject.geometry ) { - this.resolvedProperty = nodeProperty; + console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry', this ); + return; - } else if ( nodeProperty.length !== undefined ) { + } - bindingType = this.BindingType.EntireArray; + if ( ! targetObject.geometry.morphTargets ) { - this.resolvedProperty = nodeProperty; + console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry.morphTargets', this ); + return; - } else { + } - this.propertyName = propertyName; + for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) { - } + if ( targetObject.geometry.morphTargets[ i ].name === propertyIndex ) { - // select getter / setter - this.getValue = this.GetterByBindingType[ bindingType ]; - this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ]; + propertyIndex = i; + break; - }, + } - unbind: function() { + } - this.node = null; + } - // back to the prototype version of getValue / setValue - // note: avoiding to mutate the shape of 'this' via 'delete' - this.getValue = this._getValue_unbound; - this.setValue = this._setValue_unbound; + bindingType = this.BindingType.ArrayElement; - } + this.resolvedProperty = nodeProperty; + this.propertyIndex = propertyIndex; - }; + } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) { + // must use copy for Object3D.Euler/Quaternion - Object.assign( PropertyBinding.prototype, { // prototype, continued + bindingType = this.BindingType.HasFromToArray; - // these are used to "bind" a nonexistent property - _getValue_unavailable: function() {}, - _setValue_unavailable: function() {}, + this.resolvedProperty = nodeProperty; - // initial state of these methods that calls 'bind' - _getValue_unbound: PropertyBinding.prototype.getValue, - _setValue_unbound: PropertyBinding.prototype.setValue, + } else if ( nodeProperty.length !== undefined ) { - BindingType: { - Direct: 0, - EntireArray: 1, - ArrayElement: 2, - HasFromToArray: 3 - }, + bindingType = this.BindingType.EntireArray; - Versioning: { - None: 0, - NeedsUpdate: 1, - MatrixWorldNeedsUpdate: 2 - }, + this.resolvedProperty = nodeProperty; - GetterByBindingType: [ + } else { - function getValue_direct( buffer, offset ) { + this.propertyName = propertyName; - buffer[ offset ] = this.node[ this.propertyName ]; + } - }, + // select getter / setter + this.getValue = this.GetterByBindingType[ bindingType ]; + this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ]; - function getValue_array( buffer, offset ) { + }, - var source = this.resolvedProperty; + unbind: function() { - for ( var i = 0, n = source.length; i !== n; ++ i ) { + this.node = null; - buffer[ offset ++ ] = source[ i ]; + // back to the prototype version of getValue / setValue + // note: avoiding to mutate the shape of 'this' via 'delete' + this.getValue = this._getValue_unbound; + this.setValue = this._setValue_unbound; - } + } - }, + }; - function getValue_arrayElement( buffer, offset ) { + Object.assign( PropertyBinding.prototype, { // prototype, continued - buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ]; + // these are used to "bind" a nonexistent property + _getValue_unavailable: function() {}, + _setValue_unavailable: function() {}, - }, + // initial state of these methods that calls 'bind' + _getValue_unbound: PropertyBinding.prototype.getValue, + _setValue_unbound: PropertyBinding.prototype.setValue, - function getValue_toArray( buffer, offset ) { + BindingType: { + Direct: 0, + EntireArray: 1, + ArrayElement: 2, + HasFromToArray: 3 + }, - this.resolvedProperty.toArray( buffer, offset ); + Versioning: { + None: 0, + NeedsUpdate: 1, + MatrixWorldNeedsUpdate: 2 + }, - } + GetterByBindingType: [ - ], + function getValue_direct( buffer, offset ) { - SetterByBindingTypeAndVersioning: [ + buffer[ offset ] = this.node[ this.propertyName ]; - [ - // Direct + }, - function setValue_direct( buffer, offset ) { + function getValue_array( buffer, offset ) { - this.node[ this.propertyName ] = buffer[ offset ]; + var source = this.resolvedProperty; - }, + for ( var i = 0, n = source.length; i !== n; ++ i ) { - function setValue_direct_setNeedsUpdate( buffer, offset ) { + buffer[ offset ++ ] = source[ i ]; - this.node[ this.propertyName ] = buffer[ offset ]; - this.targetObject.needsUpdate = true; + } - }, + }, - function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) { + function getValue_arrayElement( buffer, offset ) { - this.node[ this.propertyName ] = buffer[ offset ]; - this.targetObject.matrixWorldNeedsUpdate = true; + buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ]; - } + }, - ], [ + function getValue_toArray( buffer, offset ) { - // EntireArray + this.resolvedProperty.toArray( buffer, offset ); - function setValue_array( buffer, offset ) { + } - var dest = this.resolvedProperty; + ], - for ( var i = 0, n = dest.length; i !== n; ++ i ) { + SetterByBindingTypeAndVersioning: [ - dest[ i ] = buffer[ offset ++ ]; + [ + // Direct - } + function setValue_direct( buffer, offset ) { - }, + this.node[ this.propertyName ] = buffer[ offset ]; - function setValue_array_setNeedsUpdate( buffer, offset ) { + }, - var dest = this.resolvedProperty; + function setValue_direct_setNeedsUpdate( buffer, offset ) { - for ( var i = 0, n = dest.length; i !== n; ++ i ) { + this.node[ this.propertyName ] = buffer[ offset ]; + this.targetObject.needsUpdate = true; - dest[ i ] = buffer[ offset ++ ]; + }, - } + function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) { - this.targetObject.needsUpdate = true; + this.node[ this.propertyName ] = buffer[ offset ]; + this.targetObject.matrixWorldNeedsUpdate = true; - }, + } - function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) { + ], [ - var dest = this.resolvedProperty; + // EntireArray - for ( var i = 0, n = dest.length; i !== n; ++ i ) { + function setValue_array( buffer, offset ) { - dest[ i ] = buffer[ offset ++ ]; + var dest = this.resolvedProperty; - } + for ( var i = 0, n = dest.length; i !== n; ++ i ) { - this.targetObject.matrixWorldNeedsUpdate = true; + dest[ i ] = buffer[ offset ++ ]; - } + } - ], [ + }, - // ArrayElement + function setValue_array_setNeedsUpdate( buffer, offset ) { - function setValue_arrayElement( buffer, offset ) { + var dest = this.resolvedProperty; - this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; + for ( var i = 0, n = dest.length; i !== n; ++ i ) { - }, + dest[ i ] = buffer[ offset ++ ]; - function setValue_arrayElement_setNeedsUpdate( buffer, offset ) { + } - this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; - this.targetObject.needsUpdate = true; + this.targetObject.needsUpdate = true; - }, + }, - function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) { + function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) { - this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; - this.targetObject.matrixWorldNeedsUpdate = true; + var dest = this.resolvedProperty; - } + for ( var i = 0, n = dest.length; i !== n; ++ i ) { - ], [ + dest[ i ] = buffer[ offset ++ ]; - // HasToFromArray + } - function setValue_fromArray( buffer, offset ) { + this.targetObject.matrixWorldNeedsUpdate = true; - this.resolvedProperty.fromArray( buffer, offset ); + } - }, + ], [ - function setValue_fromArray_setNeedsUpdate( buffer, offset ) { + // ArrayElement - this.resolvedProperty.fromArray( buffer, offset ); - this.targetObject.needsUpdate = true; + function setValue_arrayElement( buffer, offset ) { - }, + this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; - function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) { + }, - this.resolvedProperty.fromArray( buffer, offset ); - this.targetObject.matrixWorldNeedsUpdate = true; + function setValue_arrayElement_setNeedsUpdate( buffer, offset ) { - } + this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; + this.targetObject.needsUpdate = true; - ] + }, - ] + function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) { - } ); + this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; + this.targetObject.matrixWorldNeedsUpdate = true; - PropertyBinding.Composite = - function( targetGroup, path, optionalParsedPath ) { + } - var parsedPath = optionalParsedPath || - PropertyBinding.parseTrackName( path ); + ], [ - this._targetGroup = targetGroup; - this._bindings = targetGroup.subscribe_( path, parsedPath ); + // HasToFromArray - }; + function setValue_fromArray( buffer, offset ) { - PropertyBinding.Composite.prototype = { + this.resolvedProperty.fromArray( buffer, offset ); - constructor: PropertyBinding.Composite, + }, - getValue: function( array, offset ) { + function setValue_fromArray_setNeedsUpdate( buffer, offset ) { - this.bind(); // bind all binding + this.resolvedProperty.fromArray( buffer, offset ); + this.targetObject.needsUpdate = true; - var firstValidIndex = this._targetGroup.nCachedObjects_, - binding = this._bindings[ firstValidIndex ]; + }, - // and only call .getValue on the first - if ( binding !== undefined ) binding.getValue( array, offset ); + function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) { - }, + this.resolvedProperty.fromArray( buffer, offset ); + this.targetObject.matrixWorldNeedsUpdate = true; - setValue: function( array, offset ) { + } - var bindings = this._bindings; + ] - for ( var i = this._targetGroup.nCachedObjects_, - n = bindings.length; i !== n; ++ i ) { + ] - bindings[ i ].setValue( array, offset ); + } ); - } + PropertyBinding.Composite = + function( targetGroup, path, optionalParsedPath ) { - }, + var parsedPath = optionalParsedPath || + PropertyBinding.parseTrackName( path ); - bind: function() { + this._targetGroup = targetGroup; + this._bindings = targetGroup.subscribe_( path, parsedPath ); - var bindings = this._bindings; + }; - for ( var i = this._targetGroup.nCachedObjects_, - n = bindings.length; i !== n; ++ i ) { + PropertyBinding.Composite.prototype = { - bindings[ i ].bind(); + constructor: PropertyBinding.Composite, - } + getValue: function( array, offset ) { - }, + this.bind(); // bind all binding - unbind: function() { + var firstValidIndex = this._targetGroup.nCachedObjects_, + binding = this._bindings[ firstValidIndex ]; - var bindings = this._bindings; + // and only call .getValue on the first + if ( binding !== undefined ) binding.getValue( array, offset ); - for ( var i = this._targetGroup.nCachedObjects_, - n = bindings.length; i !== n; ++ i ) { + }, - bindings[ i ].unbind(); + setValue: function( array, offset ) { - } + var bindings = this._bindings; - } + for ( var i = this._targetGroup.nCachedObjects_, + n = bindings.length; i !== n; ++ i ) { - }; + bindings[ i ].setValue( array, offset ); - PropertyBinding.create = function( root, path, parsedPath ) { + } - if ( ! ( (root && root.isAnimationObjectGroup) ) ) { + }, - return new PropertyBinding( root, path, parsedPath ); + bind: function() { - } else { + var bindings = this._bindings; - return new PropertyBinding.Composite( root, path, parsedPath ); + for ( var i = this._targetGroup.nCachedObjects_, + n = bindings.length; i !== n; ++ i ) { - } + bindings[ i ].bind(); - }; + } - PropertyBinding.parseTrackName = function( trackName ) { + }, - // matches strings in the form of: - // nodeName.property - // nodeName.property[accessor] - // nodeName.material.property[accessor] - // uuid.property[accessor] - // uuid.objectName[objectIndex].propertyName[propertyIndex] - // parentName/nodeName.property - // parentName/parentName/nodeName.property[index] - // .bone[Armature.DEF_cog].position - // created and tested via https://regex101.com/#javascript + unbind: function() { - var re = /^(([\w]+\/)*)([\w-\d]+)?(\.([\w]+)(\[([\w\d\[\]\_.:\- ]+)\])?)?(\.([\w.]+)(\[([\w\d\[\]\_. ]+)\])?)$/; - var matches = re.exec( trackName ); + var bindings = this._bindings; - if ( ! matches ) { + for ( var i = this._targetGroup.nCachedObjects_, + n = bindings.length; i !== n; ++ i ) { - throw new Error( "cannot parse trackName at all: " + trackName ); + bindings[ i ].unbind(); - } + } - if ( matches.index === re.lastIndex ) { + } - re.lastIndex++; + }; - } + PropertyBinding.create = function( root, path, parsedPath ) { - var results = { - // directoryName: matches[ 1 ], // (tschw) currently unused - nodeName: matches[ 3 ], // allowed to be null, specified root node. - objectName: matches[ 5 ], - objectIndex: matches[ 7 ], - propertyName: matches[ 9 ], - propertyIndex: matches[ 11 ] // allowed to be null, specifies that the whole property is set. - }; + if ( ! ( (root && root.isAnimationObjectGroup) ) ) { - if ( results.propertyName === null || results.propertyName.length === 0 ) { + return new PropertyBinding( root, path, parsedPath ); - throw new Error( "can not parse propertyName from trackName: " + trackName ); + } else { - } + return new PropertyBinding.Composite( root, path, parsedPath ); - return results; + } - }; + }; - PropertyBinding.findNode = function( root, nodeName ) { + PropertyBinding.parseTrackName = function( trackName ) { - if ( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) { + // matches strings in the form of: + // nodeName.property + // nodeName.property[accessor] + // nodeName.material.property[accessor] + // uuid.property[accessor] + // uuid.objectName[objectIndex].propertyName[propertyIndex] + // parentName/nodeName.property + // parentName/parentName/nodeName.property[index] + // .bone[Armature.DEF_cog].position + // created and tested via https://regex101.com/#javascript - return root; + var re = /^((?:\w+\/)*)(\w+)?(?:\.(\w+)(?:\[(.+)\])?)?\.(\w+)(?:\[(.+)\])?$/; + var matches = re.exec( trackName ); - } + if ( ! matches ) { - // search into skeleton bones. - if ( root.skeleton ) { + throw new Error( "cannot parse trackName at all: " + trackName ); - var searchSkeleton = function( skeleton ) { + } - for( var i = 0; i < skeleton.bones.length; i ++ ) { + var results = { + // directoryName: matches[ 1 ], // (tschw) currently unused + nodeName: matches[ 2 ], // allowed to be null, specified root node. + objectName: matches[ 3 ], + objectIndex: matches[ 4 ], + propertyName: matches[ 5 ], + propertyIndex: matches[ 6 ] // allowed to be null, specifies that the whole property is set. + }; - var bone = skeleton.bones[ i ]; + if ( results.propertyName === null || results.propertyName.length === 0 ) { - if ( bone.name === nodeName ) { + throw new Error( "can not parse propertyName from trackName: " + trackName ); - return bone; + } - } - } + return results; - return null; + }; - }; + PropertyBinding.findNode = function( root, nodeName ) { - var bone = searchSkeleton( root.skeleton ); + if ( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) { - if ( bone ) { + return root; - return bone; + } - } - } + // search into skeleton bones. + if ( root.skeleton ) { - // search into node subtree. - if ( root.children ) { + var searchSkeleton = function( skeleton ) { - var searchNodeSubtree = function( children ) { + for( var i = 0; i < skeleton.bones.length; i ++ ) { - for( var i = 0; i < children.length; i ++ ) { + var bone = skeleton.bones[ i ]; - var childNode = children[ i ]; + if ( bone.name === nodeName ) { - if ( childNode.name === nodeName || childNode.uuid === nodeName ) { + return bone; - return childNode; + } + } - } + return null; - var result = searchNodeSubtree( childNode.children ); + }; - if ( result ) return result; + var bone = searchSkeleton( root.skeleton ); - } + if ( bone ) { - return null; + return bone; - }; + } + } - var subTreeNode = searchNodeSubtree( root.children ); + // search into node subtree. + if ( root.children ) { - if ( subTreeNode ) { + var searchNodeSubtree = function( children ) { - return subTreeNode; + for( var i = 0; i < children.length; i ++ ) { - } + var childNode = children[ i ]; - } + if ( childNode.name === nodeName || childNode.uuid === nodeName ) { - return null; + return childNode; - }; + } - /** - * - * A group of objects that receives a shared animation state. - * - * Usage: - * - * - Add objects you would otherwise pass as 'root' to the - * constructor or the .clipAction method of AnimationMixer. - * - * - Instead pass this object as 'root'. - * - * - You can also add and remove objects later when the mixer - * is running. - * - * Note: - * - * Objects of this class appear as one object to the mixer, - * so cache control of the individual objects must be done - * on the group. - * - * Limitation: - * - * - The animated properties must be compatible among the - * all objects in the group. - * - * - A single property can either be controlled through a - * target group or directly, but not both. - * - * @author tschw - */ + var result = searchNodeSubtree( childNode.children ); - function AnimationObjectGroup( var_args ) { + if ( result ) return result; - this.uuid = exports.Math.generateUUID(); + } - // cached objects followed by the active ones - this._objects = Array.prototype.slice.call( arguments ); + return null; - this.nCachedObjects_ = 0; // threshold - // note: read by PropertyBinding.Composite + }; - var indices = {}; - this._indicesByUUID = indices; // for bookkeeping + var subTreeNode = searchNodeSubtree( root.children ); - for ( var i = 0, n = arguments.length; i !== n; ++ i ) { + if ( subTreeNode ) { - indices[ arguments[ i ].uuid ] = i; + return subTreeNode; - } + } - this._paths = []; // inside: string - this._parsedPaths = []; // inside: { we don't care, here } - this._bindings = []; // inside: Array< PropertyBinding > - this._bindingsIndicesByPath = {}; // inside: indices in these arrays + } - var scope = this; + return null; - this.stats = { + }; - objects: { - get total() { return scope._objects.length; }, - get inUse() { return this.total - scope.nCachedObjects_; } - }, + /** + * + * A group of objects that receives a shared animation state. + * + * Usage: + * + * - Add objects you would otherwise pass as 'root' to the + * constructor or the .clipAction method of AnimationMixer. + * + * - Instead pass this object as 'root'. + * + * - You can also add and remove objects later when the mixer + * is running. + * + * Note: + * + * Objects of this class appear as one object to the mixer, + * so cache control of the individual objects must be done + * on the group. + * + * Limitation: + * + * - The animated properties must be compatible among the + * all objects in the group. + * + * - A single property can either be controlled through a + * target group or directly, but not both. + * + * @author tschw + */ + + function AnimationObjectGroup( var_args ) { + + this.uuid = exports.Math.generateUUID(); + + // cached objects followed by the active ones + this._objects = Array.prototype.slice.call( arguments ); + + this.nCachedObjects_ = 0; // threshold + // note: read by PropertyBinding.Composite + + var indices = {}; + this._indicesByUUID = indices; // for bookkeeping + + for ( var i = 0, n = arguments.length; i !== n; ++ i ) { + + indices[ arguments[ i ].uuid ] = i; - get bindingsPerObject() { return scope._bindings.length; } + } - }; + this._paths = []; // inside: string + this._parsedPaths = []; // inside: { we don't care, here } + this._bindings = []; // inside: Array< PropertyBinding > + this._bindingsIndicesByPath = {}; // inside: indices in these arrays - }; + var scope = this; - AnimationObjectGroup.prototype = { + this.stats = { - constructor: AnimationObjectGroup, + objects: { + get total() { return scope._objects.length; }, + get inUse() { return this.total - scope.nCachedObjects_; } + }, - isAnimationObjectGroup: true, + get bindingsPerObject() { return scope._bindings.length; } - add: function( var_args ) { + }; - var objects = this._objects, - nObjects = objects.length, - nCachedObjects = this.nCachedObjects_, - indicesByUUID = this._indicesByUUID, - paths = this._paths, - parsedPaths = this._parsedPaths, - bindings = this._bindings, - nBindings = bindings.length; + } - for ( var i = 0, n = arguments.length; i !== n; ++ i ) { + AnimationObjectGroup.prototype = { - var object = arguments[ i ], - uuid = object.uuid, - index = indicesByUUID[ uuid ]; + constructor: AnimationObjectGroup, - if ( index === undefined ) { + isAnimationObjectGroup: true, - // unknown object -> add it to the ACTIVE region + add: function( var_args ) { - index = nObjects ++; - indicesByUUID[ uuid ] = index; - objects.push( object ); + var objects = this._objects, + nObjects = objects.length, + nCachedObjects = this.nCachedObjects_, + indicesByUUID = this._indicesByUUID, + paths = this._paths, + parsedPaths = this._parsedPaths, + bindings = this._bindings, + nBindings = bindings.length; - // accounting is done, now do the same for all bindings + for ( var i = 0, n = arguments.length; i !== n; ++ i ) { - for ( var j = 0, m = nBindings; j !== m; ++ j ) { + var object = arguments[ i ], + uuid = object.uuid, + index = indicesByUUID[ uuid ]; - bindings[ j ].push( - new PropertyBinding( - object, paths[ j ], parsedPaths[ j ] ) ); + if ( index === undefined ) { - } + // unknown object -> add it to the ACTIVE region - } else if ( index < nCachedObjects ) { + index = nObjects ++; + indicesByUUID[ uuid ] = index; + objects.push( object ); - var knownObject = objects[ index ]; + // accounting is done, now do the same for all bindings - // move existing object to the ACTIVE region + for ( var j = 0, m = nBindings; j !== m; ++ j ) { - var firstActiveIndex = -- nCachedObjects, - lastCachedObject = objects[ firstActiveIndex ]; + bindings[ j ].push( + new PropertyBinding( + object, paths[ j ], parsedPaths[ j ] ) ); - indicesByUUID[ lastCachedObject.uuid ] = index; - objects[ index ] = lastCachedObject; + } - indicesByUUID[ uuid ] = firstActiveIndex; - objects[ firstActiveIndex ] = object; + } else if ( index < nCachedObjects ) { - // accounting is done, now do the same for all bindings + var knownObject = objects[ index ]; - for ( var j = 0, m = nBindings; j !== m; ++ j ) { + // move existing object to the ACTIVE region - var bindingsForPath = bindings[ j ], - lastCached = bindingsForPath[ firstActiveIndex ], - binding = bindingsForPath[ index ]; + var firstActiveIndex = -- nCachedObjects, + lastCachedObject = objects[ firstActiveIndex ]; - bindingsForPath[ index ] = lastCached; + indicesByUUID[ lastCachedObject.uuid ] = index; + objects[ index ] = lastCachedObject; - if ( binding === undefined ) { + indicesByUUID[ uuid ] = firstActiveIndex; + objects[ firstActiveIndex ] = object; - // since we do not bother to create new bindings - // for objects that are cached, the binding may - // or may not exist + // accounting is done, now do the same for all bindings - binding = new PropertyBinding( - object, paths[ j ], parsedPaths[ j ] ); + for ( var j = 0, m = nBindings; j !== m; ++ j ) { - } + var bindingsForPath = bindings[ j ], + lastCached = bindingsForPath[ firstActiveIndex ], + binding = bindingsForPath[ index ]; - bindingsForPath[ firstActiveIndex ] = binding; + bindingsForPath[ index ] = lastCached; - } + if ( binding === undefined ) { - } else if ( objects[ index ] !== knownObject) { + // since we do not bother to create new bindings + // for objects that are cached, the binding may + // or may not exist - console.error( "Different objects with the same UUID " + - "detected. Clean the caches or recreate your " + - "infrastructure when reloading scenes..." ); + binding = new PropertyBinding( + object, paths[ j ], parsedPaths[ j ] ); - } // else the object is already where we want it to be + } - } // for arguments + bindingsForPath[ firstActiveIndex ] = binding; - this.nCachedObjects_ = nCachedObjects; + } - }, + } else if ( objects[ index ] !== knownObject) { - remove: function( var_args ) { + console.error( "Different objects with the same UUID " + + "detected. Clean the caches or recreate your " + + "infrastructure when reloading scenes..." ); - var objects = this._objects, - nCachedObjects = this.nCachedObjects_, - indicesByUUID = this._indicesByUUID, - bindings = this._bindings, - nBindings = bindings.length; + } // else the object is already where we want it to be - for ( var i = 0, n = arguments.length; i !== n; ++ i ) { + } // for arguments - var object = arguments[ i ], - uuid = object.uuid, - index = indicesByUUID[ uuid ]; + this.nCachedObjects_ = nCachedObjects; - if ( index !== undefined && index >= nCachedObjects ) { + }, - // move existing object into the CACHED region + remove: function( var_args ) { - var lastCachedIndex = nCachedObjects ++, - firstActiveObject = objects[ lastCachedIndex ]; + var objects = this._objects, + nCachedObjects = this.nCachedObjects_, + indicesByUUID = this._indicesByUUID, + bindings = this._bindings, + nBindings = bindings.length; - indicesByUUID[ firstActiveObject.uuid ] = index; - objects[ index ] = firstActiveObject; + for ( var i = 0, n = arguments.length; i !== n; ++ i ) { - indicesByUUID[ uuid ] = lastCachedIndex; - objects[ lastCachedIndex ] = object; + var object = arguments[ i ], + uuid = object.uuid, + index = indicesByUUID[ uuid ]; - // accounting is done, now do the same for all bindings + if ( index !== undefined && index >= nCachedObjects ) { - for ( var j = 0, m = nBindings; j !== m; ++ j ) { + // move existing object into the CACHED region - var bindingsForPath = bindings[ j ], - firstActive = bindingsForPath[ lastCachedIndex ], - binding = bindingsForPath[ index ]; + var lastCachedIndex = nCachedObjects ++, + firstActiveObject = objects[ lastCachedIndex ]; - bindingsForPath[ index ] = firstActive; - bindingsForPath[ lastCachedIndex ] = binding; + indicesByUUID[ firstActiveObject.uuid ] = index; + objects[ index ] = firstActiveObject; - } + indicesByUUID[ uuid ] = lastCachedIndex; + objects[ lastCachedIndex ] = object; - } + // accounting is done, now do the same for all bindings - } // for arguments + for ( var j = 0, m = nBindings; j !== m; ++ j ) { - this.nCachedObjects_ = nCachedObjects; + var bindingsForPath = bindings[ j ], + firstActive = bindingsForPath[ lastCachedIndex ], + binding = bindingsForPath[ index ]; - }, + bindingsForPath[ index ] = firstActive; + bindingsForPath[ lastCachedIndex ] = binding; - // remove & forget - uncache: function( var_args ) { + } - var objects = this._objects, - nObjects = objects.length, - nCachedObjects = this.nCachedObjects_, - indicesByUUID = this._indicesByUUID, - bindings = this._bindings, - nBindings = bindings.length; + } - for ( var i = 0, n = arguments.length; i !== n; ++ i ) { + } // for arguments - var object = arguments[ i ], - uuid = object.uuid, - index = indicesByUUID[ uuid ]; + this.nCachedObjects_ = nCachedObjects; - if ( index !== undefined ) { + }, - delete indicesByUUID[ uuid ]; + // remove & forget + uncache: function( var_args ) { - if ( index < nCachedObjects ) { + var objects = this._objects, + nObjects = objects.length, + nCachedObjects = this.nCachedObjects_, + indicesByUUID = this._indicesByUUID, + bindings = this._bindings, + nBindings = bindings.length; - // object is cached, shrink the CACHED region + for ( var i = 0, n = arguments.length; i !== n; ++ i ) { - var firstActiveIndex = -- nCachedObjects, - lastCachedObject = objects[ firstActiveIndex ], - lastIndex = -- nObjects, - lastObject = objects[ lastIndex ]; + var object = arguments[ i ], + uuid = object.uuid, + index = indicesByUUID[ uuid ]; - // last cached object takes this object's place - indicesByUUID[ lastCachedObject.uuid ] = index; - objects[ index ] = lastCachedObject; + if ( index !== undefined ) { - // last object goes to the activated slot and pop - indicesByUUID[ lastObject.uuid ] = firstActiveIndex; - objects[ firstActiveIndex ] = lastObject; - objects.pop(); + delete indicesByUUID[ uuid ]; - // accounting is done, now do the same for all bindings + if ( index < nCachedObjects ) { - for ( var j = 0, m = nBindings; j !== m; ++ j ) { + // object is cached, shrink the CACHED region - var bindingsForPath = bindings[ j ], - lastCached = bindingsForPath[ firstActiveIndex ], - last = bindingsForPath[ lastIndex ]; + var firstActiveIndex = -- nCachedObjects, + lastCachedObject = objects[ firstActiveIndex ], + lastIndex = -- nObjects, + lastObject = objects[ lastIndex ]; - bindingsForPath[ index ] = lastCached; - bindingsForPath[ firstActiveIndex ] = last; - bindingsForPath.pop(); + // last cached object takes this object's place + indicesByUUID[ lastCachedObject.uuid ] = index; + objects[ index ] = lastCachedObject; - } + // last object goes to the activated slot and pop + indicesByUUID[ lastObject.uuid ] = firstActiveIndex; + objects[ firstActiveIndex ] = lastObject; + objects.pop(); - } else { + // accounting is done, now do the same for all bindings - // object is active, just swap with the last and pop + for ( var j = 0, m = nBindings; j !== m; ++ j ) { - var lastIndex = -- nObjects, - lastObject = objects[ lastIndex ]; + var bindingsForPath = bindings[ j ], + lastCached = bindingsForPath[ firstActiveIndex ], + last = bindingsForPath[ lastIndex ]; - indicesByUUID[ lastObject.uuid ] = index; - objects[ index ] = lastObject; - objects.pop(); + bindingsForPath[ index ] = lastCached; + bindingsForPath[ firstActiveIndex ] = last; + bindingsForPath.pop(); - // accounting is done, now do the same for all bindings + } - for ( var j = 0, m = nBindings; j !== m; ++ j ) { + } else { - var bindingsForPath = bindings[ j ]; + // object is active, just swap with the last and pop - bindingsForPath[ index ] = bindingsForPath[ lastIndex ]; - bindingsForPath.pop(); + var lastIndex = -- nObjects, + lastObject = objects[ lastIndex ]; - } + indicesByUUID[ lastObject.uuid ] = index; + objects[ index ] = lastObject; + objects.pop(); - } // cached or active + // accounting is done, now do the same for all bindings - } // if object is known + for ( var j = 0, m = nBindings; j !== m; ++ j ) { - } // for arguments + var bindingsForPath = bindings[ j ]; - this.nCachedObjects_ = nCachedObjects; + bindingsForPath[ index ] = bindingsForPath[ lastIndex ]; + bindingsForPath.pop(); - }, + } - // Internal interface used by befriended PropertyBinding.Composite: + } // cached or active - subscribe_: function( path, parsedPath ) { - // returns an array of bindings for the given path that is changed - // according to the contained objects in the group + } // if object is known - var indicesByPath = this._bindingsIndicesByPath, - index = indicesByPath[ path ], - bindings = this._bindings; + } // for arguments - if ( index !== undefined ) return bindings[ index ]; + this.nCachedObjects_ = nCachedObjects; - var paths = this._paths, - parsedPaths = this._parsedPaths, - objects = this._objects, - nObjects = objects.length, - nCachedObjects = this.nCachedObjects_, - bindingsForPath = new Array( nObjects ); + }, - index = bindings.length; + // Internal interface used by befriended PropertyBinding.Composite: - indicesByPath[ path ] = index; + subscribe_: function( path, parsedPath ) { + // returns an array of bindings for the given path that is changed + // according to the contained objects in the group - paths.push( path ); - parsedPaths.push( parsedPath ); - bindings.push( bindingsForPath ); + var indicesByPath = this._bindingsIndicesByPath, + index = indicesByPath[ path ], + bindings = this._bindings; - for ( var i = nCachedObjects, - n = objects.length; i !== n; ++ i ) { + if ( index !== undefined ) return bindings[ index ]; - var object = objects[ i ]; + var paths = this._paths, + parsedPaths = this._parsedPaths, + objects = this._objects, + nObjects = objects.length, + nCachedObjects = this.nCachedObjects_, + bindingsForPath = new Array( nObjects ); - bindingsForPath[ i ] = - new PropertyBinding( object, path, parsedPath ); + index = bindings.length; - } + indicesByPath[ path ] = index; - return bindingsForPath; + paths.push( path ); + parsedPaths.push( parsedPath ); + bindings.push( bindingsForPath ); - }, + for ( var i = nCachedObjects, + n = objects.length; i !== n; ++ i ) { - unsubscribe_: function( path ) { - // tells the group to forget about a property path and no longer - // update the array previously obtained with 'subscribe_' + var object = objects[ i ]; - var indicesByPath = this._bindingsIndicesByPath, - index = indicesByPath[ path ]; + bindingsForPath[ i ] = + new PropertyBinding( object, path, parsedPath ); - if ( index !== undefined ) { + } - var paths = this._paths, - parsedPaths = this._parsedPaths, - bindings = this._bindings, - lastBindingsIndex = bindings.length - 1, - lastBindings = bindings[ lastBindingsIndex ], - lastBindingsPath = path[ lastBindingsIndex ]; + return bindingsForPath; - indicesByPath[ lastBindingsPath ] = index; + }, - bindings[ index ] = lastBindings; - bindings.pop(); + unsubscribe_: function( path ) { + // tells the group to forget about a property path and no longer + // update the array previously obtained with 'subscribe_' - parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ]; - parsedPaths.pop(); + var indicesByPath = this._bindingsIndicesByPath, + index = indicesByPath[ path ]; - paths[ index ] = paths[ lastBindingsIndex ]; - paths.pop(); + if ( index !== undefined ) { - } + var paths = this._paths, + parsedPaths = this._parsedPaths, + bindings = this._bindings, + lastBindingsIndex = bindings.length - 1, + lastBindings = bindings[ lastBindingsIndex ], + lastBindingsPath = path[ lastBindingsIndex ]; - } + indicesByPath[ lastBindingsPath ] = index; - }; + bindings[ index ] = lastBindings; + bindings.pop(); - /** - * - * Action provided by AnimationMixer for scheduling clip playback on specific - * objects. - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - * - */ + parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ]; + parsedPaths.pop(); - function AnimationAction() { + paths[ index ] = paths[ lastBindingsIndex ]; + paths.pop(); - throw new Error( "THREE.AnimationAction: " + - "Use mixer.clipAction for construction." ); + } - }; + } - AnimationAction._new = - function AnimationAction( mixer, clip, localRoot ) { + }; - this._mixer = mixer; - this._clip = clip; - this._localRoot = localRoot || null; + /** + * + * Action provided by AnimationMixer for scheduling clip playback on specific + * objects. + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + * + */ - var tracks = clip.tracks, - nTracks = tracks.length, - interpolants = new Array( nTracks ); + function AnimationAction() { - var interpolantSettings = { - endingStart: ZeroCurvatureEnding, - endingEnd: ZeroCurvatureEnding - }; + throw new Error( "THREE.AnimationAction: " + + "Use mixer.clipAction for construction." ); - for ( var i = 0; i !== nTracks; ++ i ) { + } - var interpolant = tracks[ i ].createInterpolant( null ); - interpolants[ i ] = interpolant; - interpolant.settings = interpolantSettings; + AnimationAction._new = + function AnimationAction( mixer, clip, localRoot ) { - } + this._mixer = mixer; + this._clip = clip; + this._localRoot = localRoot || null; - this._interpolantSettings = interpolantSettings; + var tracks = clip.tracks, + nTracks = tracks.length, + interpolants = new Array( nTracks ); - this._interpolants = interpolants; // bound by the mixer + var interpolantSettings = { + endingStart: ZeroCurvatureEnding, + endingEnd: ZeroCurvatureEnding + }; - // inside: PropertyMixer (managed by the mixer) - this._propertyBindings = new Array( nTracks ); + for ( var i = 0; i !== nTracks; ++ i ) { - this._cacheIndex = null; // for the memory manager - this._byClipCacheIndex = null; // for the memory manager + var interpolant = tracks[ i ].createInterpolant( null ); + interpolants[ i ] = interpolant; + interpolant.settings = interpolantSettings; - this._timeScaleInterpolant = null; - this._weightInterpolant = null; + } - this.loop = LoopRepeat; - this._loopCount = -1; + this._interpolantSettings = interpolantSettings; - // global mixer time when the action is to be started - // it's set back to 'null' upon start of the action - this._startTime = null; + this._interpolants = interpolants; // bound by the mixer - // scaled local time of the action - // gets clamped or wrapped to 0..clip.duration according to loop - this.time = 0; + // inside: PropertyMixer (managed by the mixer) + this._propertyBindings = new Array( nTracks ); - this.timeScale = 1; - this._effectiveTimeScale = 1; + this._cacheIndex = null; // for the memory manager + this._byClipCacheIndex = null; // for the memory manager - this.weight = 1; - this._effectiveWeight = 1; + this._timeScaleInterpolant = null; + this._weightInterpolant = null; - this.repetitions = Infinity; // no. of repetitions when looping + this.loop = LoopRepeat; + this._loopCount = -1; - this.paused = false; // false -> zero effective time scale - this.enabled = true; // true -> zero effective weight + // global mixer time when the action is to be started + // it's set back to 'null' upon start of the action + this._startTime = null; - this.clampWhenFinished = false; // keep feeding the last frame? + // scaled local time of the action + // gets clamped or wrapped to 0..clip.duration according to loop + this.time = 0; - this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate - this.zeroSlopeAtEnd = true; // clips for start, loop and end + this.timeScale = 1; + this._effectiveTimeScale = 1; - }; + this.weight = 1; + this._effectiveWeight = 1; - AnimationAction._new.prototype = { + this.repetitions = Infinity; // no. of repetitions when looping - constructor: AnimationAction._new, + this.paused = false; // false -> zero effective time scale + this.enabled = true; // true -> zero effective weight - // State & Scheduling + this.clampWhenFinished = false; // keep feeding the last frame? - play: function() { + this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate + this.zeroSlopeAtEnd = true; // clips for start, loop and end - this._mixer._activateAction( this ); + }; - return this; + AnimationAction._new.prototype = { - }, + constructor: AnimationAction._new, - stop: function() { + // State & Scheduling - this._mixer._deactivateAction( this ); + play: function() { - return this.reset(); + this._mixer._activateAction( this ); - }, + return this; - reset: function() { + }, - this.paused = false; - this.enabled = true; + stop: function() { - this.time = 0; // restart clip - this._loopCount = -1; // forget previous loops - this._startTime = null; // forget scheduling + this._mixer._deactivateAction( this ); - return this.stopFading().stopWarping(); + return this.reset(); - }, + }, - isRunning: function() { + reset: function() { - return this.enabled && ! this.paused && this.timeScale !== 0 && - this._startTime === null && this._mixer._isActiveAction( this ); + this.paused = false; + this.enabled = true; - }, + this.time = 0; // restart clip + this._loopCount = -1; // forget previous loops + this._startTime = null; // forget scheduling - // return true when play has been called - isScheduled: function() { + return this.stopFading().stopWarping(); - return this._mixer._isActiveAction( this ); + }, - }, + isRunning: function() { - startAt: function( time ) { + return this.enabled && ! this.paused && this.timeScale !== 0 && + this._startTime === null && this._mixer._isActiveAction( this ); - this._startTime = time; + }, - return this; + // return true when play has been called + isScheduled: function() { - }, + return this._mixer._isActiveAction( this ); - setLoop: function( mode, repetitions ) { + }, - this.loop = mode; - this.repetitions = repetitions; + startAt: function( time ) { - return this; + this._startTime = time; - }, + return this; - // Weight + }, - // set the weight stopping any scheduled fading - // although .enabled = false yields an effective weight of zero, this - // method does *not* change .enabled, because it would be confusing - setEffectiveWeight: function( weight ) { + setLoop: function( mode, repetitions ) { - this.weight = weight; + this.loop = mode; + this.repetitions = repetitions; - // note: same logic as when updated at runtime - this._effectiveWeight = this.enabled ? weight : 0; + return this; - return this.stopFading(); + }, - }, + // Weight - // return the weight considering fading and .enabled - getEffectiveWeight: function() { + // set the weight stopping any scheduled fading + // although .enabled = false yields an effective weight of zero, this + // method does *not* change .enabled, because it would be confusing + setEffectiveWeight: function( weight ) { - return this._effectiveWeight; + this.weight = weight; - }, + // note: same logic as when updated at runtime + this._effectiveWeight = this.enabled ? weight : 0; - fadeIn: function( duration ) { + return this.stopFading(); - return this._scheduleFading( duration, 0, 1 ); + }, - }, + // return the weight considering fading and .enabled + getEffectiveWeight: function() { - fadeOut: function( duration ) { + return this._effectiveWeight; - return this._scheduleFading( duration, 1, 0 ); + }, - }, + fadeIn: function( duration ) { - crossFadeFrom: function( fadeOutAction, duration, warp ) { + return this._scheduleFading( duration, 0, 1 ); - fadeOutAction.fadeOut( duration ); - this.fadeIn( duration ); + }, - if( warp ) { + fadeOut: function( duration ) { - var fadeInDuration = this._clip.duration, - fadeOutDuration = fadeOutAction._clip.duration, + return this._scheduleFading( duration, 1, 0 ); - startEndRatio = fadeOutDuration / fadeInDuration, - endStartRatio = fadeInDuration / fadeOutDuration; + }, - fadeOutAction.warp( 1.0, startEndRatio, duration ); - this.warp( endStartRatio, 1.0, duration ); + crossFadeFrom: function( fadeOutAction, duration, warp ) { - } + fadeOutAction.fadeOut( duration ); + this.fadeIn( duration ); - return this; + if( warp ) { - }, + var fadeInDuration = this._clip.duration, + fadeOutDuration = fadeOutAction._clip.duration, - crossFadeTo: function( fadeInAction, duration, warp ) { + startEndRatio = fadeOutDuration / fadeInDuration, + endStartRatio = fadeInDuration / fadeOutDuration; - return fadeInAction.crossFadeFrom( this, duration, warp ); + fadeOutAction.warp( 1.0, startEndRatio, duration ); + this.warp( endStartRatio, 1.0, duration ); - }, + } - stopFading: function() { + return this; - var weightInterpolant = this._weightInterpolant; + }, - if ( weightInterpolant !== null ) { + crossFadeTo: function( fadeInAction, duration, warp ) { - this._weightInterpolant = null; - this._mixer._takeBackControlInterpolant( weightInterpolant ); + return fadeInAction.crossFadeFrom( this, duration, warp ); - } + }, - return this; + stopFading: function() { - }, + var weightInterpolant = this._weightInterpolant; - // Time Scale Control + if ( weightInterpolant !== null ) { - // set the weight stopping any scheduled warping - // although .paused = true yields an effective time scale of zero, this - // method does *not* change .paused, because it would be confusing - setEffectiveTimeScale: function( timeScale ) { + this._weightInterpolant = null; + this._mixer._takeBackControlInterpolant( weightInterpolant ); - this.timeScale = timeScale; - this._effectiveTimeScale = this.paused ? 0 :timeScale; + } - return this.stopWarping(); + return this; - }, + }, - // return the time scale considering warping and .paused - getEffectiveTimeScale: function() { + // Time Scale Control - return this._effectiveTimeScale; + // set the weight stopping any scheduled warping + // although .paused = true yields an effective time scale of zero, this + // method does *not* change .paused, because it would be confusing + setEffectiveTimeScale: function( timeScale ) { - }, + this.timeScale = timeScale; + this._effectiveTimeScale = this.paused ? 0 :timeScale; - setDuration: function( duration ) { + return this.stopWarping(); - this.timeScale = this._clip.duration / duration; + }, - return this.stopWarping(); + // return the time scale considering warping and .paused + getEffectiveTimeScale: function() { - }, + return this._effectiveTimeScale; - syncWith: function( action ) { + }, - this.time = action.time; - this.timeScale = action.timeScale; + setDuration: function( duration ) { - return this.stopWarping(); + this.timeScale = this._clip.duration / duration; - }, + return this.stopWarping(); - halt: function( duration ) { + }, - return this.warp( this._effectiveTimeScale, 0, duration ); + syncWith: function( action ) { - }, + this.time = action.time; + this.timeScale = action.timeScale; - warp: function( startTimeScale, endTimeScale, duration ) { + return this.stopWarping(); - var mixer = this._mixer, now = mixer.time, - interpolant = this._timeScaleInterpolant, + }, - timeScale = this.timeScale; + halt: function( duration ) { - if ( interpolant === null ) { + return this.warp( this._effectiveTimeScale, 0, duration ); - interpolant = mixer._lendControlInterpolant(), - this._timeScaleInterpolant = interpolant; + }, - } + warp: function( startTimeScale, endTimeScale, duration ) { - var times = interpolant.parameterPositions, - values = interpolant.sampleValues; + var mixer = this._mixer, now = mixer.time, + interpolant = this._timeScaleInterpolant, - times[ 0 ] = now; - times[ 1 ] = now + duration; + timeScale = this.timeScale; - values[ 0 ] = startTimeScale / timeScale; - values[ 1 ] = endTimeScale / timeScale; + if ( interpolant === null ) { - return this; + interpolant = mixer._lendControlInterpolant(), + this._timeScaleInterpolant = interpolant; - }, + } - stopWarping: function() { + var times = interpolant.parameterPositions, + values = interpolant.sampleValues; - var timeScaleInterpolant = this._timeScaleInterpolant; + times[ 0 ] = now; + times[ 1 ] = now + duration; - if ( timeScaleInterpolant !== null ) { + values[ 0 ] = startTimeScale / timeScale; + values[ 1 ] = endTimeScale / timeScale; - this._timeScaleInterpolant = null; - this._mixer._takeBackControlInterpolant( timeScaleInterpolant ); + return this; - } + }, - return this; + stopWarping: function() { - }, + var timeScaleInterpolant = this._timeScaleInterpolant; - // Object Accessors + if ( timeScaleInterpolant !== null ) { - getMixer: function() { + this._timeScaleInterpolant = null; + this._mixer._takeBackControlInterpolant( timeScaleInterpolant ); - return this._mixer; + } - }, + return this; - getClip: function() { + }, - return this._clip; + // Object Accessors - }, + getMixer: function() { - getRoot: function() { + return this._mixer; - return this._localRoot || this._mixer._root; + }, - }, + getClip: function() { - // Interna + return this._clip; - _update: function( time, deltaTime, timeDirection, accuIndex ) { - // called by the mixer + }, - var startTime = this._startTime; + getRoot: function() { - if ( startTime !== null ) { + return this._localRoot || this._mixer._root; - // check for scheduled start of action + }, - var timeRunning = ( time - startTime ) * timeDirection; - if ( timeRunning < 0 || timeDirection === 0 ) { + // Interna - return; // yet to come / don't decide when delta = 0 + _update: function( time, deltaTime, timeDirection, accuIndex ) { + // called by the mixer - } + var startTime = this._startTime; - // start + if ( startTime !== null ) { - this._startTime = null; // unschedule - deltaTime = timeDirection * timeRunning; + // check for scheduled start of action - } + var timeRunning = ( time - startTime ) * timeDirection; + if ( timeRunning < 0 || timeDirection === 0 ) { - // apply time scale and advance time + return; // yet to come / don't decide when delta = 0 - deltaTime *= this._updateTimeScale( time ); - var clipTime = this._updateTime( deltaTime ); + } - // note: _updateTime may disable the action resulting in - // an effective weight of 0 + // start - var weight = this._updateWeight( time ); + this._startTime = null; // unschedule + deltaTime = timeDirection * timeRunning; - if ( weight > 0 ) { + } - var interpolants = this._interpolants; - var propertyMixers = this._propertyBindings; + // apply time scale and advance time - for ( var j = 0, m = interpolants.length; j !== m; ++ j ) { + deltaTime *= this._updateTimeScale( time ); + var clipTime = this._updateTime( deltaTime ); - interpolants[ j ].evaluate( clipTime ); - propertyMixers[ j ].accumulate( accuIndex, weight ); + // note: _updateTime may disable the action resulting in + // an effective weight of 0 - } + var weight = this._updateWeight( time ); - } + if ( weight > 0 ) { - }, + var interpolants = this._interpolants; + var propertyMixers = this._propertyBindings; - _updateWeight: function( time ) { + for ( var j = 0, m = interpolants.length; j !== m; ++ j ) { - var weight = 0; + interpolants[ j ].evaluate( clipTime ); + propertyMixers[ j ].accumulate( accuIndex, weight ); - if ( this.enabled ) { + } - weight = this.weight; - var interpolant = this._weightInterpolant; + } - if ( interpolant !== null ) { + }, - var interpolantValue = interpolant.evaluate( time )[ 0 ]; + _updateWeight: function( time ) { - weight *= interpolantValue; + var weight = 0; - if ( time > interpolant.parameterPositions[ 1 ] ) { + if ( this.enabled ) { - this.stopFading(); + weight = this.weight; + var interpolant = this._weightInterpolant; - if ( interpolantValue === 0 ) { + if ( interpolant !== null ) { - // faded out, disable - this.enabled = false; + var interpolantValue = interpolant.evaluate( time )[ 0 ]; - } + weight *= interpolantValue; - } + if ( time > interpolant.parameterPositions[ 1 ] ) { - } + this.stopFading(); - } + if ( interpolantValue === 0 ) { - this._effectiveWeight = weight; - return weight; + // faded out, disable + this.enabled = false; - }, + } - _updateTimeScale: function( time ) { + } - var timeScale = 0; + } - if ( ! this.paused ) { + } - timeScale = this.timeScale; + this._effectiveWeight = weight; + return weight; - var interpolant = this._timeScaleInterpolant; + }, - if ( interpolant !== null ) { + _updateTimeScale: function( time ) { - var interpolantValue = interpolant.evaluate( time )[ 0 ]; + var timeScale = 0; - timeScale *= interpolantValue; + if ( ! this.paused ) { - if ( time > interpolant.parameterPositions[ 1 ] ) { + timeScale = this.timeScale; - this.stopWarping(); + var interpolant = this._timeScaleInterpolant; - if ( timeScale === 0 ) { + if ( interpolant !== null ) { - // motion has halted, pause - this.paused = true; + var interpolantValue = interpolant.evaluate( time )[ 0 ]; - } else { + timeScale *= interpolantValue; - // warp done - apply final time scale - this.timeScale = timeScale; + if ( time > interpolant.parameterPositions[ 1 ] ) { - } + this.stopWarping(); - } + if ( timeScale === 0 ) { - } + // motion has halted, pause + this.paused = true; - } + } else { - this._effectiveTimeScale = timeScale; - return timeScale; + // warp done - apply final time scale + this.timeScale = timeScale; - }, + } - _updateTime: function( deltaTime ) { + } - var time = this.time + deltaTime; + } - if ( deltaTime === 0 ) return time; + } - var duration = this._clip.duration, + this._effectiveTimeScale = timeScale; + return timeScale; - loop = this.loop, - loopCount = this._loopCount; + }, - if ( loop === LoopOnce ) { + _updateTime: function( deltaTime ) { - if ( loopCount === -1 ) { - // just started + var time = this.time + deltaTime; - this.loopCount = 0; - this._setEndings( true, true, false ); + if ( deltaTime === 0 ) return time; - } + var duration = this._clip.duration, - handle_stop: { + loop = this.loop, + loopCount = this._loopCount; - if ( time >= duration ) { + if ( loop === LoopOnce ) { - time = duration; + if ( loopCount === -1 ) { + // just started - } else if ( time < 0 ) { + this.loopCount = 0; + this._setEndings( true, true, false ); - time = 0; + } - } else break handle_stop; + handle_stop: { - if ( this.clampWhenFinished ) this.paused = true; - else this.enabled = false; + if ( time >= duration ) { - this._mixer.dispatchEvent( { - type: 'finished', action: this, - direction: deltaTime < 0 ? -1 : 1 - } ); + time = duration; - } + } else if ( time < 0 ) { - } else { // repetitive Repeat or PingPong + time = 0; - var pingPong = ( loop === LoopPingPong ); + } else break handle_stop; - if ( loopCount === -1 ) { - // just started + if ( this.clampWhenFinished ) this.paused = true; + else this.enabled = false; - if ( deltaTime >= 0 ) { + this._mixer.dispatchEvent( { + type: 'finished', action: this, + direction: deltaTime < 0 ? -1 : 1 + } ); - loopCount = 0; + } - this._setEndings( - true, this.repetitions === 0, pingPong ); + } else { // repetitive Repeat or PingPong - } else { + var pingPong = ( loop === LoopPingPong ); - // when looping in reverse direction, the initial - // transition through zero counts as a repetition, - // so leave loopCount at -1 + if ( loopCount === -1 ) { + // just started - this._setEndings( - this.repetitions === 0, true, pingPong ); + if ( deltaTime >= 0 ) { - } + loopCount = 0; - } + this._setEndings( + true, this.repetitions === 0, pingPong ); - if ( time >= duration || time < 0 ) { - // wrap around + } else { - var loopDelta = Math.floor( time / duration ); // signed - time -= duration * loopDelta; + // when looping in reverse direction, the initial + // transition through zero counts as a repetition, + // so leave loopCount at -1 - loopCount += Math.abs( loopDelta ); + this._setEndings( + this.repetitions === 0, true, pingPong ); - var pending = this.repetitions - loopCount; + } - if ( pending < 0 ) { - // have to stop (switch state, clamp time, fire event) + } - if ( this.clampWhenFinished ) this.paused = true; - else this.enabled = false; + if ( time >= duration || time < 0 ) { + // wrap around - time = deltaTime > 0 ? duration : 0; + var loopDelta = Math.floor( time / duration ); // signed + time -= duration * loopDelta; - this._mixer.dispatchEvent( { - type: 'finished', action: this, - direction: deltaTime > 0 ? 1 : -1 - } ); + loopCount += Math.abs( loopDelta ); - } else { - // keep running + var pending = this.repetitions - loopCount; - if ( pending === 0 ) { - // entering the last round + if ( pending < 0 ) { + // have to stop (switch state, clamp time, fire event) - var atStart = deltaTime < 0; - this._setEndings( atStart, ! atStart, pingPong ); + if ( this.clampWhenFinished ) this.paused = true; + else this.enabled = false; - } else { + time = deltaTime > 0 ? duration : 0; - this._setEndings( false, false, pingPong ); + this._mixer.dispatchEvent( { + type: 'finished', action: this, + direction: deltaTime > 0 ? 1 : -1 + } ); - } + } else { + // keep running - this._loopCount = loopCount; + if ( pending === 0 ) { + // entering the last round - this._mixer.dispatchEvent( { - type: 'loop', action: this, loopDelta: loopDelta - } ); + var atStart = deltaTime < 0; + this._setEndings( atStart, ! atStart, pingPong ); - } + } else { - } + this._setEndings( false, false, pingPong ); - if ( pingPong && ( loopCount & 1 ) === 1 ) { - // invert time for the "pong round" + } - this.time = time; - return duration - time; + this._loopCount = loopCount; - } + this._mixer.dispatchEvent( { + type: 'loop', action: this, loopDelta: loopDelta + } ); - } + } - this.time = time; - return time; + } - }, + if ( pingPong && ( loopCount & 1 ) === 1 ) { + // invert time for the "pong round" - _setEndings: function( atStart, atEnd, pingPong ) { + this.time = time; + return duration - time; - var settings = this._interpolantSettings; + } - if ( pingPong ) { + } - settings.endingStart = ZeroSlopeEnding; - settings.endingEnd = ZeroSlopeEnding; + this.time = time; + return time; - } else { + }, - // assuming for LoopOnce atStart == atEnd == true + _setEndings: function( atStart, atEnd, pingPong ) { - if ( atStart ) { + var settings = this._interpolantSettings; - settings.endingStart = this.zeroSlopeAtStart ? - ZeroSlopeEnding : ZeroCurvatureEnding; + if ( pingPong ) { - } else { + settings.endingStart = ZeroSlopeEnding; + settings.endingEnd = ZeroSlopeEnding; - settings.endingStart = WrapAroundEnding; + } else { - } + // assuming for LoopOnce atStart == atEnd == true - if ( atEnd ) { + if ( atStart ) { - settings.endingEnd = this.zeroSlopeAtEnd ? - ZeroSlopeEnding : ZeroCurvatureEnding; + settings.endingStart = this.zeroSlopeAtStart ? + ZeroSlopeEnding : ZeroCurvatureEnding; - } else { + } else { - settings.endingEnd = WrapAroundEnding; + settings.endingStart = WrapAroundEnding; - } + } - } + if ( atEnd ) { - }, + settings.endingEnd = this.zeroSlopeAtEnd ? + ZeroSlopeEnding : ZeroCurvatureEnding; - _scheduleFading: function( duration, weightNow, weightThen ) { + } else { - var mixer = this._mixer, now = mixer.time, - interpolant = this._weightInterpolant; + settings.endingEnd = WrapAroundEnding; - if ( interpolant === null ) { + } - interpolant = mixer._lendControlInterpolant(), - this._weightInterpolant = interpolant; + } - } + }, - var times = interpolant.parameterPositions, - values = interpolant.sampleValues; + _scheduleFading: function( duration, weightNow, weightThen ) { - times[ 0 ] = now; values[ 0 ] = weightNow; - times[ 1 ] = now + duration; values[ 1 ] = weightThen; + var mixer = this._mixer, now = mixer.time, + interpolant = this._weightInterpolant; - return this; + if ( interpolant === null ) { - } + interpolant = mixer._lendControlInterpolant(), + this._weightInterpolant = interpolant; - }; + } - /** - * - * Player for AnimationClips. - * - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + var times = interpolant.parameterPositions, + values = interpolant.sampleValues; - function AnimationMixer( root ) { + times[ 0 ] = now; values[ 0 ] = weightNow; + times[ 1 ] = now + duration; values[ 1 ] = weightThen; - this._root = root; - this._initMemoryManager(); - this._accuIndex = 0; + return this; - this.time = 0; + } - this.timeScale = 1.0; + }; - }; + /** + * + * Player for AnimationClips. + * + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - Object.assign( AnimationMixer.prototype, EventDispatcher.prototype, { + function AnimationMixer( root ) { - // return an action for a clip optionally using a custom root target - // object (this method allocates a lot of dynamic memory in case a - // previously unknown clip/root combination is specified) - clipAction: function( clip, optionalRoot ) { + this._root = root; + this._initMemoryManager(); + this._accuIndex = 0; - var root = optionalRoot || this._root, - rootUuid = root.uuid, + this.time = 0; - clipObject = typeof clip === 'string' ? - AnimationClip.findByName( root, clip ) : clip, + this.timeScale = 1.0; - clipUuid = clipObject !== null ? clipObject.uuid : clip, + } - actionsForClip = this._actionsByClip[ clipUuid ], - prototypeAction = null; + Object.assign( AnimationMixer.prototype, EventDispatcher.prototype, { - if ( actionsForClip !== undefined ) { + // return an action for a clip optionally using a custom root target + // object (this method allocates a lot of dynamic memory in case a + // previously unknown clip/root combination is specified) + clipAction: function( clip, optionalRoot ) { - var existingAction = - actionsForClip.actionByRoot[ rootUuid ]; + var root = optionalRoot || this._root, + rootUuid = root.uuid, - if ( existingAction !== undefined ) { + clipObject = typeof clip === 'string' ? + AnimationClip.findByName( root, clip ) : clip, - return existingAction; + clipUuid = clipObject !== null ? clipObject.uuid : clip, - } + actionsForClip = this._actionsByClip[ clipUuid ], + prototypeAction = null; - // we know the clip, so we don't have to parse all - // the bindings again but can just copy - prototypeAction = actionsForClip.knownActions[ 0 ]; + if ( actionsForClip !== undefined ) { - // also, take the clip from the prototype action - if ( clipObject === null ) - clipObject = prototypeAction._clip; + var existingAction = + actionsForClip.actionByRoot[ rootUuid ]; - } + if ( existingAction !== undefined ) { - // clip must be known when specified via string - if ( clipObject === null ) return null; + return existingAction; - // allocate all resources required to run it - var newAction = new AnimationMixer._Action( this, clipObject, optionalRoot ); + } - this._bindAction( newAction, prototypeAction ); + // we know the clip, so we don't have to parse all + // the bindings again but can just copy + prototypeAction = actionsForClip.knownActions[ 0 ]; - // and make the action known to the memory manager - this._addInactiveAction( newAction, clipUuid, rootUuid ); + // also, take the clip from the prototype action + if ( clipObject === null ) + clipObject = prototypeAction._clip; - return newAction; + } - }, + // clip must be known when specified via string + if ( clipObject === null ) return null; - // get an existing action - existingAction: function( clip, optionalRoot ) { + // allocate all resources required to run it + var newAction = new AnimationMixer._Action( this, clipObject, optionalRoot ); - var root = optionalRoot || this._root, - rootUuid = root.uuid, + this._bindAction( newAction, prototypeAction ); - clipObject = typeof clip === 'string' ? - AnimationClip.findByName( root, clip ) : clip, + // and make the action known to the memory manager + this._addInactiveAction( newAction, clipUuid, rootUuid ); - clipUuid = clipObject ? clipObject.uuid : clip, + return newAction; - actionsForClip = this._actionsByClip[ clipUuid ]; + }, - if ( actionsForClip !== undefined ) { + // get an existing action + existingAction: function( clip, optionalRoot ) { - return actionsForClip.actionByRoot[ rootUuid ] || null; + var root = optionalRoot || this._root, + rootUuid = root.uuid, - } + clipObject = typeof clip === 'string' ? + AnimationClip.findByName( root, clip ) : clip, - return null; + clipUuid = clipObject ? clipObject.uuid : clip, - }, + actionsForClip = this._actionsByClip[ clipUuid ]; - // deactivates all previously scheduled actions - stopAllAction: function() { + if ( actionsForClip !== undefined ) { - var actions = this._actions, - nActions = this._nActiveActions, - bindings = this._bindings, - nBindings = this._nActiveBindings; + return actionsForClip.actionByRoot[ rootUuid ] || null; - this._nActiveActions = 0; - this._nActiveBindings = 0; + } - for ( var i = 0; i !== nActions; ++ i ) { + return null; - actions[ i ].reset(); + }, - } + // deactivates all previously scheduled actions + stopAllAction: function() { - for ( var i = 0; i !== nBindings; ++ i ) { + var actions = this._actions, + nActions = this._nActiveActions, + bindings = this._bindings, + nBindings = this._nActiveBindings; - bindings[ i ].useCount = 0; + this._nActiveActions = 0; + this._nActiveBindings = 0; - } + for ( var i = 0; i !== nActions; ++ i ) { - return this; + actions[ i ].reset(); - }, + } - // advance the time and update apply the animation - update: function( deltaTime ) { + for ( var i = 0; i !== nBindings; ++ i ) { - deltaTime *= this.timeScale; + bindings[ i ].useCount = 0; - var actions = this._actions, - nActions = this._nActiveActions, + } - time = this.time += deltaTime, - timeDirection = Math.sign( deltaTime ), + return this; - accuIndex = this._accuIndex ^= 1; + }, - // run active actions + // advance the time and update apply the animation + update: function( deltaTime ) { - for ( var i = 0; i !== nActions; ++ i ) { + deltaTime *= this.timeScale; - var action = actions[ i ]; + var actions = this._actions, + nActions = this._nActiveActions, - if ( action.enabled ) { + time = this.time += deltaTime, + timeDirection = Math.sign( deltaTime ), - action._update( time, deltaTime, timeDirection, accuIndex ); + accuIndex = this._accuIndex ^= 1; - } + // run active actions - } + for ( var i = 0; i !== nActions; ++ i ) { - // update scene graph + var action = actions[ i ]; - var bindings = this._bindings, - nBindings = this._nActiveBindings; + if ( action.enabled ) { - for ( var i = 0; i !== nBindings; ++ i ) { + action._update( time, deltaTime, timeDirection, accuIndex ); - bindings[ i ].apply( accuIndex ); + } - } + } - return this; + // update scene graph - }, + var bindings = this._bindings, + nBindings = this._nActiveBindings; - // return this mixer's root target object - getRoot: function() { + for ( var i = 0; i !== nBindings; ++ i ) { - return this._root; + bindings[ i ].apply( accuIndex ); - }, + } - // free all resources specific to a particular clip - uncacheClip: function( clip ) { + return this; - var actions = this._actions, - clipUuid = clip.uuid, - actionsByClip = this._actionsByClip, - actionsForClip = actionsByClip[ clipUuid ]; + }, - if ( actionsForClip !== undefined ) { + // return this mixer's root target object + getRoot: function() { - // note: just calling _removeInactiveAction would mess up the - // iteration state and also require updating the state we can - // just throw away + return this._root; - var actionsToRemove = actionsForClip.knownActions; + }, - for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) { + // free all resources specific to a particular clip + uncacheClip: function( clip ) { - var action = actionsToRemove[ i ]; + var actions = this._actions, + clipUuid = clip.uuid, + actionsByClip = this._actionsByClip, + actionsForClip = actionsByClip[ clipUuid ]; - this._deactivateAction( action ); + if ( actionsForClip !== undefined ) { - var cacheIndex = action._cacheIndex, - lastInactiveAction = actions[ actions.length - 1 ]; + // note: just calling _removeInactiveAction would mess up the + // iteration state and also require updating the state we can + // just throw away - action._cacheIndex = null; - action._byClipCacheIndex = null; + var actionsToRemove = actionsForClip.knownActions; - lastInactiveAction._cacheIndex = cacheIndex; - actions[ cacheIndex ] = lastInactiveAction; - actions.pop(); + for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) { - this._removeInactiveBindingsForAction( action ); + var action = actionsToRemove[ i ]; - } + this._deactivateAction( action ); - delete actionsByClip[ clipUuid ]; + var cacheIndex = action._cacheIndex, + lastInactiveAction = actions[ actions.length - 1 ]; - } + action._cacheIndex = null; + action._byClipCacheIndex = null; - }, + lastInactiveAction._cacheIndex = cacheIndex; + actions[ cacheIndex ] = lastInactiveAction; + actions.pop(); - // free all resources specific to a particular root target object - uncacheRoot: function( root ) { + this._removeInactiveBindingsForAction( action ); - var rootUuid = root.uuid, - actionsByClip = this._actionsByClip; + } - for ( var clipUuid in actionsByClip ) { + delete actionsByClip[ clipUuid ]; - var actionByRoot = actionsByClip[ clipUuid ].actionByRoot, - action = actionByRoot[ rootUuid ]; + } - if ( action !== undefined ) { + }, - this._deactivateAction( action ); - this._removeInactiveAction( action ); + // free all resources specific to a particular root target object + uncacheRoot: function( root ) { - } + var rootUuid = root.uuid, + actionsByClip = this._actionsByClip; - } + for ( var clipUuid in actionsByClip ) { - var bindingsByRoot = this._bindingsByRootAndName, - bindingByName = bindingsByRoot[ rootUuid ]; + var actionByRoot = actionsByClip[ clipUuid ].actionByRoot, + action = actionByRoot[ rootUuid ]; - if ( bindingByName !== undefined ) { + if ( action !== undefined ) { - for ( var trackName in bindingByName ) { + this._deactivateAction( action ); + this._removeInactiveAction( action ); - var binding = bindingByName[ trackName ]; - binding.restoreOriginalState(); - this._removeInactiveBinding( binding ); + } - } + } - } + var bindingsByRoot = this._bindingsByRootAndName, + bindingByName = bindingsByRoot[ rootUuid ]; - }, + if ( bindingByName !== undefined ) { - // remove a targeted clip from the cache - uncacheAction: function( clip, optionalRoot ) { + for ( var trackName in bindingByName ) { - var action = this.existingAction( clip, optionalRoot ); + var binding = bindingByName[ trackName ]; + binding.restoreOriginalState(); + this._removeInactiveBinding( binding ); - if ( action !== null ) { + } - this._deactivateAction( action ); - this._removeInactiveAction( action ); + } - } + }, - } + // remove a targeted clip from the cache + uncacheAction: function( clip, optionalRoot ) { - } ); + var action = this.existingAction( clip, optionalRoot ); - AnimationMixer._Action = AnimationAction._new; + if ( action !== null ) { - // Implementation details: + this._deactivateAction( action ); + this._removeInactiveAction( action ); - Object.assign( AnimationMixer.prototype, { + } - _bindAction: function( action, prototypeAction ) { + } - var root = action._localRoot || this._root, - tracks = action._clip.tracks, - nTracks = tracks.length, - bindings = action._propertyBindings, - interpolants = action._interpolants, - rootUuid = root.uuid, - bindingsByRoot = this._bindingsByRootAndName, - bindingsByName = bindingsByRoot[ rootUuid ]; + } ); - if ( bindingsByName === undefined ) { + AnimationMixer._Action = AnimationAction._new; - bindingsByName = {}; - bindingsByRoot[ rootUuid ] = bindingsByName; + // Implementation details: - } + Object.assign( AnimationMixer.prototype, { - for ( var i = 0; i !== nTracks; ++ i ) { + _bindAction: function( action, prototypeAction ) { - var track = tracks[ i ], - trackName = track.name, - binding = bindingsByName[ trackName ]; + var root = action._localRoot || this._root, + tracks = action._clip.tracks, + nTracks = tracks.length, + bindings = action._propertyBindings, + interpolants = action._interpolants, + rootUuid = root.uuid, + bindingsByRoot = this._bindingsByRootAndName, + bindingsByName = bindingsByRoot[ rootUuid ]; - if ( binding !== undefined ) { + if ( bindingsByName === undefined ) { - bindings[ i ] = binding; + bindingsByName = {}; + bindingsByRoot[ rootUuid ] = bindingsByName; - } else { + } - binding = bindings[ i ]; + for ( var i = 0; i !== nTracks; ++ i ) { - if ( binding !== undefined ) { + var track = tracks[ i ], + trackName = track.name, + binding = bindingsByName[ trackName ]; - // existing binding, make sure the cache knows + if ( binding !== undefined ) { - if ( binding._cacheIndex === null ) { + bindings[ i ] = binding; - ++ binding.referenceCount; - this._addInactiveBinding( binding, rootUuid, trackName ); + } else { - } + binding = bindings[ i ]; - continue; + if ( binding !== undefined ) { - } + // existing binding, make sure the cache knows - var path = prototypeAction && prototypeAction. - _propertyBindings[ i ].binding.parsedPath; + if ( binding._cacheIndex === null ) { - binding = new PropertyMixer( - PropertyBinding.create( root, trackName, path ), - track.ValueTypeName, track.getValueSize() ); + ++ binding.referenceCount; + this._addInactiveBinding( binding, rootUuid, trackName ); - ++ binding.referenceCount; - this._addInactiveBinding( binding, rootUuid, trackName ); + } - bindings[ i ] = binding; + continue; - } + } - interpolants[ i ].resultBuffer = binding.buffer; + var path = prototypeAction && prototypeAction. + _propertyBindings[ i ].binding.parsedPath; - } + binding = new PropertyMixer( + PropertyBinding.create( root, trackName, path ), + track.ValueTypeName, track.getValueSize() ); - }, + ++ binding.referenceCount; + this._addInactiveBinding( binding, rootUuid, trackName ); - _activateAction: function( action ) { + bindings[ i ] = binding; - if ( ! this._isActiveAction( action ) ) { + } - if ( action._cacheIndex === null ) { + interpolants[ i ].resultBuffer = binding.buffer; - // this action has been forgotten by the cache, but the user - // appears to be still using it -> rebind + } - var rootUuid = ( action._localRoot || this._root ).uuid, - clipUuid = action._clip.uuid, - actionsForClip = this._actionsByClip[ clipUuid ]; + }, - this._bindAction( action, - actionsForClip && actionsForClip.knownActions[ 0 ] ); + _activateAction: function( action ) { - this._addInactiveAction( action, clipUuid, rootUuid ); + if ( ! this._isActiveAction( action ) ) { - } + if ( action._cacheIndex === null ) { - var bindings = action._propertyBindings; + // this action has been forgotten by the cache, but the user + // appears to be still using it -> rebind - // increment reference counts / sort out state - for ( var i = 0, n = bindings.length; i !== n; ++ i ) { + var rootUuid = ( action._localRoot || this._root ).uuid, + clipUuid = action._clip.uuid, + actionsForClip = this._actionsByClip[ clipUuid ]; - var binding = bindings[ i ]; + this._bindAction( action, + actionsForClip && actionsForClip.knownActions[ 0 ] ); - if ( binding.useCount ++ === 0 ) { + this._addInactiveAction( action, clipUuid, rootUuid ); - this._lendBinding( binding ); - binding.saveOriginalState(); + } - } + var bindings = action._propertyBindings; - } + // increment reference counts / sort out state + for ( var i = 0, n = bindings.length; i !== n; ++ i ) { - this._lendAction( action ); + var binding = bindings[ i ]; - } + if ( binding.useCount ++ === 0 ) { - }, + this._lendBinding( binding ); + binding.saveOriginalState(); - _deactivateAction: function( action ) { + } - if ( this._isActiveAction( action ) ) { + } - var bindings = action._propertyBindings; + this._lendAction( action ); - // decrement reference counts / sort out state - for ( var i = 0, n = bindings.length; i !== n; ++ i ) { + } - var binding = bindings[ i ]; + }, - if ( -- binding.useCount === 0 ) { + _deactivateAction: function( action ) { - binding.restoreOriginalState(); - this._takeBackBinding( binding ); + if ( this._isActiveAction( action ) ) { - } + var bindings = action._propertyBindings; - } + // decrement reference counts / sort out state + for ( var i = 0, n = bindings.length; i !== n; ++ i ) { - this._takeBackAction( action ); + var binding = bindings[ i ]; - } + if ( -- binding.useCount === 0 ) { - }, + binding.restoreOriginalState(); + this._takeBackBinding( binding ); - // Memory manager + } - _initMemoryManager: function() { + } - this._actions = []; // 'nActiveActions' followed by inactive ones - this._nActiveActions = 0; + this._takeBackAction( action ); - this._actionsByClip = {}; - // inside: - // { - // knownActions: Array< _Action > - used as prototypes - // actionByRoot: _Action - lookup - // } + } + }, - this._bindings = []; // 'nActiveBindings' followed by inactive ones - this._nActiveBindings = 0; + // Memory manager - this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer > + _initMemoryManager: function() { + this._actions = []; // 'nActiveActions' followed by inactive ones + this._nActiveActions = 0; - this._controlInterpolants = []; // same game as above - this._nActiveControlInterpolants = 0; + this._actionsByClip = {}; + // inside: + // { + // knownActions: Array< _Action > - used as prototypes + // actionByRoot: _Action - lookup + // } - var scope = this; - this.stats = { + this._bindings = []; // 'nActiveBindings' followed by inactive ones + this._nActiveBindings = 0; - actions: { - get total() { return scope._actions.length; }, - get inUse() { return scope._nActiveActions; } - }, - bindings: { - get total() { return scope._bindings.length; }, - get inUse() { return scope._nActiveBindings; } - }, - controlInterpolants: { - get total() { return scope._controlInterpolants.length; }, - get inUse() { return scope._nActiveControlInterpolants; } - } + this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer > - }; - }, + this._controlInterpolants = []; // same game as above + this._nActiveControlInterpolants = 0; - // Memory management for _Action objects + var scope = this; - _isActiveAction: function( action ) { + this.stats = { - var index = action._cacheIndex; - return index !== null && index < this._nActiveActions; + actions: { + get total() { return scope._actions.length; }, + get inUse() { return scope._nActiveActions; } + }, + bindings: { + get total() { return scope._bindings.length; }, + get inUse() { return scope._nActiveBindings; } + }, + controlInterpolants: { + get total() { return scope._controlInterpolants.length; }, + get inUse() { return scope._nActiveControlInterpolants; } + } - }, + }; - _addInactiveAction: function( action, clipUuid, rootUuid ) { + }, - var actions = this._actions, - actionsByClip = this._actionsByClip, - actionsForClip = actionsByClip[ clipUuid ]; + // Memory management for _Action objects - if ( actionsForClip === undefined ) { + _isActiveAction: function( action ) { - actionsForClip = { + var index = action._cacheIndex; + return index !== null && index < this._nActiveActions; - knownActions: [ action ], - actionByRoot: {} + }, - }; + _addInactiveAction: function( action, clipUuid, rootUuid ) { - action._byClipCacheIndex = 0; + var actions = this._actions, + actionsByClip = this._actionsByClip, + actionsForClip = actionsByClip[ clipUuid ]; - actionsByClip[ clipUuid ] = actionsForClip; + if ( actionsForClip === undefined ) { - } else { + actionsForClip = { - var knownActions = actionsForClip.knownActions; + knownActions: [ action ], + actionByRoot: {} - action._byClipCacheIndex = knownActions.length; - knownActions.push( action ); + }; - } + action._byClipCacheIndex = 0; - action._cacheIndex = actions.length; - actions.push( action ); + actionsByClip[ clipUuid ] = actionsForClip; - actionsForClip.actionByRoot[ rootUuid ] = action; + } else { - }, + var knownActions = actionsForClip.knownActions; - _removeInactiveAction: function( action ) { + action._byClipCacheIndex = knownActions.length; + knownActions.push( action ); - var actions = this._actions, - lastInactiveAction = actions[ actions.length - 1 ], - cacheIndex = action._cacheIndex; + } - lastInactiveAction._cacheIndex = cacheIndex; - actions[ cacheIndex ] = lastInactiveAction; - actions.pop(); + action._cacheIndex = actions.length; + actions.push( action ); - action._cacheIndex = null; + actionsForClip.actionByRoot[ rootUuid ] = action; + }, - var clipUuid = action._clip.uuid, - actionsByClip = this._actionsByClip, - actionsForClip = actionsByClip[ clipUuid ], - knownActionsForClip = actionsForClip.knownActions, + _removeInactiveAction: function( action ) { - lastKnownAction = - knownActionsForClip[ knownActionsForClip.length - 1 ], + var actions = this._actions, + lastInactiveAction = actions[ actions.length - 1 ], + cacheIndex = action._cacheIndex; - byClipCacheIndex = action._byClipCacheIndex; + lastInactiveAction._cacheIndex = cacheIndex; + actions[ cacheIndex ] = lastInactiveAction; + actions.pop(); - lastKnownAction._byClipCacheIndex = byClipCacheIndex; - knownActionsForClip[ byClipCacheIndex ] = lastKnownAction; - knownActionsForClip.pop(); + action._cacheIndex = null; - action._byClipCacheIndex = null; + var clipUuid = action._clip.uuid, + actionsByClip = this._actionsByClip, + actionsForClip = actionsByClip[ clipUuid ], + knownActionsForClip = actionsForClip.knownActions, - var actionByRoot = actionsForClip.actionByRoot, - rootUuid = ( actions._localRoot || this._root ).uuid; + lastKnownAction = + knownActionsForClip[ knownActionsForClip.length - 1 ], - delete actionByRoot[ rootUuid ]; + byClipCacheIndex = action._byClipCacheIndex; - if ( knownActionsForClip.length === 0 ) { + lastKnownAction._byClipCacheIndex = byClipCacheIndex; + knownActionsForClip[ byClipCacheIndex ] = lastKnownAction; + knownActionsForClip.pop(); - delete actionsByClip[ clipUuid ]; + action._byClipCacheIndex = null; - } - this._removeInactiveBindingsForAction( action ); + var actionByRoot = actionsForClip.actionByRoot, + rootUuid = ( actions._localRoot || this._root ).uuid; - }, + delete actionByRoot[ rootUuid ]; - _removeInactiveBindingsForAction: function( action ) { + if ( knownActionsForClip.length === 0 ) { - var bindings = action._propertyBindings; - for ( var i = 0, n = bindings.length; i !== n; ++ i ) { + delete actionsByClip[ clipUuid ]; - var binding = bindings[ i ]; + } - if ( -- binding.referenceCount === 0 ) { + this._removeInactiveBindingsForAction( action ); - this._removeInactiveBinding( binding ); + }, - } + _removeInactiveBindingsForAction: function( action ) { - } + var bindings = action._propertyBindings; + for ( var i = 0, n = bindings.length; i !== n; ++ i ) { - }, + var binding = bindings[ i ]; - _lendAction: function( action ) { + if ( -- binding.referenceCount === 0 ) { - // [ active actions | inactive actions ] - // [ active actions >| inactive actions ] - // s a - // <-swap-> - // a s + this._removeInactiveBinding( binding ); - var actions = this._actions, - prevIndex = action._cacheIndex, + } - lastActiveIndex = this._nActiveActions ++, + } - firstInactiveAction = actions[ lastActiveIndex ]; + }, - action._cacheIndex = lastActiveIndex; - actions[ lastActiveIndex ] = action; + _lendAction: function( action ) { - firstInactiveAction._cacheIndex = prevIndex; - actions[ prevIndex ] = firstInactiveAction; + // [ active actions | inactive actions ] + // [ active actions >| inactive actions ] + // s a + // <-swap-> + // a s - }, + var actions = this._actions, + prevIndex = action._cacheIndex, - _takeBackAction: function( action ) { + lastActiveIndex = this._nActiveActions ++, - // [ active actions | inactive actions ] - // [ active actions |< inactive actions ] - // a s - // <-swap-> - // s a + firstInactiveAction = actions[ lastActiveIndex ]; - var actions = this._actions, - prevIndex = action._cacheIndex, + action._cacheIndex = lastActiveIndex; + actions[ lastActiveIndex ] = action; - firstInactiveIndex = -- this._nActiveActions, + firstInactiveAction._cacheIndex = prevIndex; + actions[ prevIndex ] = firstInactiveAction; - lastActiveAction = actions[ firstInactiveIndex ]; + }, - action._cacheIndex = firstInactiveIndex; - actions[ firstInactiveIndex ] = action; + _takeBackAction: function( action ) { - lastActiveAction._cacheIndex = prevIndex; - actions[ prevIndex ] = lastActiveAction; + // [ active actions | inactive actions ] + // [ active actions |< inactive actions ] + // a s + // <-swap-> + // s a - }, + var actions = this._actions, + prevIndex = action._cacheIndex, - // Memory management for PropertyMixer objects + firstInactiveIndex = -- this._nActiveActions, - _addInactiveBinding: function( binding, rootUuid, trackName ) { + lastActiveAction = actions[ firstInactiveIndex ]; - var bindingsByRoot = this._bindingsByRootAndName, - bindingByName = bindingsByRoot[ rootUuid ], + action._cacheIndex = firstInactiveIndex; + actions[ firstInactiveIndex ] = action; - bindings = this._bindings; + lastActiveAction._cacheIndex = prevIndex; + actions[ prevIndex ] = lastActiveAction; - if ( bindingByName === undefined ) { + }, - bindingByName = {}; - bindingsByRoot[ rootUuid ] = bindingByName; + // Memory management for PropertyMixer objects - } + _addInactiveBinding: function( binding, rootUuid, trackName ) { - bindingByName[ trackName ] = binding; + var bindingsByRoot = this._bindingsByRootAndName, + bindingByName = bindingsByRoot[ rootUuid ], - binding._cacheIndex = bindings.length; - bindings.push( binding ); + bindings = this._bindings; - }, + if ( bindingByName === undefined ) { - _removeInactiveBinding: function( binding ) { + bindingByName = {}; + bindingsByRoot[ rootUuid ] = bindingByName; - var bindings = this._bindings, - propBinding = binding.binding, - rootUuid = propBinding.rootNode.uuid, - trackName = propBinding.path, - bindingsByRoot = this._bindingsByRootAndName, - bindingByName = bindingsByRoot[ rootUuid ], + } - lastInactiveBinding = bindings[ bindings.length - 1 ], - cacheIndex = binding._cacheIndex; + bindingByName[ trackName ] = binding; - lastInactiveBinding._cacheIndex = cacheIndex; - bindings[ cacheIndex ] = lastInactiveBinding; - bindings.pop(); + binding._cacheIndex = bindings.length; + bindings.push( binding ); - delete bindingByName[ trackName ]; + }, - remove_empty_map: { + _removeInactiveBinding: function( binding ) { - for ( var _ in bindingByName ) break remove_empty_map; + var bindings = this._bindings, + propBinding = binding.binding, + rootUuid = propBinding.rootNode.uuid, + trackName = propBinding.path, + bindingsByRoot = this._bindingsByRootAndName, + bindingByName = bindingsByRoot[ rootUuid ], - delete bindingsByRoot[ rootUuid ]; + lastInactiveBinding = bindings[ bindings.length - 1 ], + cacheIndex = binding._cacheIndex; - } + lastInactiveBinding._cacheIndex = cacheIndex; + bindings[ cacheIndex ] = lastInactiveBinding; + bindings.pop(); - }, + delete bindingByName[ trackName ]; - _lendBinding: function( binding ) { + remove_empty_map: { - var bindings = this._bindings, - prevIndex = binding._cacheIndex, + for ( var _ in bindingByName ) break remove_empty_map; - lastActiveIndex = this._nActiveBindings ++, + delete bindingsByRoot[ rootUuid ]; - firstInactiveBinding = bindings[ lastActiveIndex ]; + } - binding._cacheIndex = lastActiveIndex; - bindings[ lastActiveIndex ] = binding; + }, - firstInactiveBinding._cacheIndex = prevIndex; - bindings[ prevIndex ] = firstInactiveBinding; + _lendBinding: function( binding ) { - }, + var bindings = this._bindings, + prevIndex = binding._cacheIndex, - _takeBackBinding: function( binding ) { + lastActiveIndex = this._nActiveBindings ++, - var bindings = this._bindings, - prevIndex = binding._cacheIndex, + firstInactiveBinding = bindings[ lastActiveIndex ]; - firstInactiveIndex = -- this._nActiveBindings, + binding._cacheIndex = lastActiveIndex; + bindings[ lastActiveIndex ] = binding; - lastActiveBinding = bindings[ firstInactiveIndex ]; + firstInactiveBinding._cacheIndex = prevIndex; + bindings[ prevIndex ] = firstInactiveBinding; - binding._cacheIndex = firstInactiveIndex; - bindings[ firstInactiveIndex ] = binding; + }, - lastActiveBinding._cacheIndex = prevIndex; - bindings[ prevIndex ] = lastActiveBinding; + _takeBackBinding: function( binding ) { - }, + var bindings = this._bindings, + prevIndex = binding._cacheIndex, + firstInactiveIndex = -- this._nActiveBindings, - // Memory management of Interpolants for weight and time scale + lastActiveBinding = bindings[ firstInactiveIndex ]; - _lendControlInterpolant: function() { + binding._cacheIndex = firstInactiveIndex; + bindings[ firstInactiveIndex ] = binding; - var interpolants = this._controlInterpolants, - lastActiveIndex = this._nActiveControlInterpolants ++, - interpolant = interpolants[ lastActiveIndex ]; + lastActiveBinding._cacheIndex = prevIndex; + bindings[ prevIndex ] = lastActiveBinding; - if ( interpolant === undefined ) { + }, - interpolant = new LinearInterpolant( - new Float32Array( 2 ), new Float32Array( 2 ), - 1, this._controlInterpolantsResultBuffer ); - interpolant.__cacheIndex = lastActiveIndex; - interpolants[ lastActiveIndex ] = interpolant; + // Memory management of Interpolants for weight and time scale - } + _lendControlInterpolant: function() { - return interpolant; + var interpolants = this._controlInterpolants, + lastActiveIndex = this._nActiveControlInterpolants ++, + interpolant = interpolants[ lastActiveIndex ]; - }, + if ( interpolant === undefined ) { - _takeBackControlInterpolant: function( interpolant ) { + interpolant = new LinearInterpolant( + new Float32Array( 2 ), new Float32Array( 2 ), + 1, this._controlInterpolantsResultBuffer ); - var interpolants = this._controlInterpolants, - prevIndex = interpolant.__cacheIndex, + interpolant.__cacheIndex = lastActiveIndex; + interpolants[ lastActiveIndex ] = interpolant; - firstInactiveIndex = -- this._nActiveControlInterpolants, + } - lastActiveInterpolant = interpolants[ firstInactiveIndex ]; + return interpolant; - interpolant.__cacheIndex = firstInactiveIndex; - interpolants[ firstInactiveIndex ] = interpolant; + }, - lastActiveInterpolant.__cacheIndex = prevIndex; - interpolants[ prevIndex ] = lastActiveInterpolant; + _takeBackControlInterpolant: function( interpolant ) { - }, + var interpolants = this._controlInterpolants, + prevIndex = interpolant.__cacheIndex, - _controlInterpolantsResultBuffer: new Float32Array( 1 ) + firstInactiveIndex = -- this._nActiveControlInterpolants, - } ); + lastActiveInterpolant = interpolants[ firstInactiveIndex ]; - /** - * @author mrdoob / http://mrdoob.com/ - */ + interpolant.__cacheIndex = firstInactiveIndex; + interpolants[ firstInactiveIndex ] = interpolant; - function Uniform( value ) { + lastActiveInterpolant.__cacheIndex = prevIndex; + interpolants[ prevIndex ] = lastActiveInterpolant; - if ( typeof value === 'string' ) { + }, - console.warn( 'THREE.Uniform: Type parameter is no longer needed.' ); - value = arguments[ 1 ]; + _controlInterpolantsResultBuffer: new Float32Array( 1 ) - } + } ); - this.value = value; + /** + * @author mrdoob / http://mrdoob.com/ + */ - this.dynamic = false; + function Uniform( value ) { - }; + if ( typeof value === 'string' ) { - Uniform.prototype = { + console.warn( 'THREE.Uniform: Type parameter is no longer needed.' ); + value = arguments[ 1 ]; - constructor: Uniform, + } - onUpdate: function ( callback ) { + this.value = value; - this.dynamic = true; - this.onUpdateCallback = callback; + this.dynamic = false; - return this; + } - } + Uniform.prototype = { - }; + constructor: Uniform, - /** - * @author benaadams / https://twitter.com/ben_a_adams - */ + onUpdate: function ( callback ) { - function InstancedBufferGeometry() { + this.dynamic = true; + this.onUpdateCallback = callback; - BufferGeometry.call( this ); + return this; - this.type = 'InstancedBufferGeometry'; - this.maxInstancedCount = undefined; + } - }; + }; - InstancedBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); - InstancedBufferGeometry.prototype.constructor = InstancedBufferGeometry; + /** + * @author benaadams / https://twitter.com/ben_a_adams + */ - InstancedBufferGeometry.prototype.isBufferGeometry = true; + function InstancedBufferGeometry() { - InstancedBufferGeometry.prototype.addGroup = function ( start, count, instances ) { + BufferGeometry.call( this ); - this.groups.push( { + this.type = 'InstancedBufferGeometry'; + this.maxInstancedCount = undefined; - start: start, - count: count, - instances: instances + } - } ); + InstancedBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + InstancedBufferGeometry.prototype.constructor = InstancedBufferGeometry; - }; + InstancedBufferGeometry.prototype.isInstancedBufferGeometry = true; - InstancedBufferGeometry.prototype.copy = function ( source ) { + InstancedBufferGeometry.prototype.addGroup = function ( start, count, instances ) { - var index = source.index; + this.groups.push( { - if ( index !== null ) { + start: start, + count: count, + instances: instances - this.setIndex( index.clone() ); + } ); - } + }; - var attributes = source.attributes; + InstancedBufferGeometry.prototype.copy = function ( source ) { - for ( var name in attributes ) { + var index = source.index; - var attribute = attributes[ name ]; - this.addAttribute( name, attribute.clone() ); + if ( index !== null ) { - } + this.setIndex( index.clone() ); - var groups = source.groups; + } - for ( var i = 0, l = groups.length; i < l; i ++ ) { + var attributes = source.attributes; - var group = groups[ i ]; - this.addGroup( group.start, group.count, group.instances ); + for ( var name in attributes ) { - } + var attribute = attributes[ name ]; + this.addAttribute( name, attribute.clone() ); - return this; + } - }; + var groups = source.groups; - /** - * @author benaadams / https://twitter.com/ben_a_adams - */ + for ( var i = 0, l = groups.length; i < l; i ++ ) { - function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) { + var group = groups[ i ]; + this.addGroup( group.start, group.count, group.instances ); - this.uuid = exports.Math.generateUUID(); + } - this.data = interleavedBuffer; - this.itemSize = itemSize; - this.offset = offset; + return this; - this.normalized = normalized === true; + }; - }; + /** + * @author benaadams / https://twitter.com/ben_a_adams + */ + function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) { - InterleavedBufferAttribute.prototype = { + this.uuid = exports.Math.generateUUID(); - constructor: InterleavedBufferAttribute, + this.data = interleavedBuffer; + this.itemSize = itemSize; + this.offset = offset; - isInterleavedBufferAttribute: true, + this.normalized = normalized === true; - get length() { + } - console.warn( 'THREE.BufferAttribute: .length has been deprecated. Please use .count.' ); - return this.array.length; - }, + InterleavedBufferAttribute.prototype = { - get count() { + constructor: InterleavedBufferAttribute, - return this.data.count; + isInterleavedBufferAttribute: true, - }, + get length() { - get array() { + console.warn( 'THREE.BufferAttribute: .length has been deprecated. Please use .count.' ); + return this.array.length; - return this.data.array; + }, - }, + get count() { - setX: function ( index, x ) { + return this.data.count; - this.data.array[ index * this.data.stride + this.offset ] = x; + }, - return this; + get array() { - }, + return this.data.array; - setY: function ( index, y ) { + }, - this.data.array[ index * this.data.stride + this.offset + 1 ] = y; + setX: function ( index, x ) { - return this; + this.data.array[ index * this.data.stride + this.offset ] = x; - }, + return this; - setZ: function ( index, z ) { + }, - this.data.array[ index * this.data.stride + this.offset + 2 ] = z; + setY: function ( index, y ) { - return this; + this.data.array[ index * this.data.stride + this.offset + 1 ] = y; - }, + return this; - setW: function ( index, w ) { + }, - this.data.array[ index * this.data.stride + this.offset + 3 ] = w; + setZ: function ( index, z ) { - return this; + this.data.array[ index * this.data.stride + this.offset + 2 ] = z; - }, + return this; - getX: function ( index ) { + }, - return this.data.array[ index * this.data.stride + this.offset ]; + setW: function ( index, w ) { - }, + this.data.array[ index * this.data.stride + this.offset + 3 ] = w; - getY: function ( index ) { + return this; - return this.data.array[ index * this.data.stride + this.offset + 1 ]; + }, - }, + getX: function ( index ) { - getZ: function ( index ) { + return this.data.array[ index * this.data.stride + this.offset ]; - return this.data.array[ index * this.data.stride + this.offset + 2 ]; + }, - }, + getY: function ( index ) { - getW: function ( index ) { + return this.data.array[ index * this.data.stride + this.offset + 1 ]; - return this.data.array[ index * this.data.stride + this.offset + 3 ]; + }, - }, + getZ: function ( index ) { - setXY: function ( index, x, y ) { + return this.data.array[ index * this.data.stride + this.offset + 2 ]; - index = index * this.data.stride + this.offset; + }, - this.data.array[ index + 0 ] = x; - this.data.array[ index + 1 ] = y; + getW: function ( index ) { - return this; + return this.data.array[ index * this.data.stride + this.offset + 3 ]; - }, + }, - setXYZ: function ( index, x, y, z ) { + setXY: function ( index, x, y ) { - index = index * this.data.stride + this.offset; + index = index * this.data.stride + this.offset; - this.data.array[ index + 0 ] = x; - this.data.array[ index + 1 ] = y; - this.data.array[ index + 2 ] = z; + this.data.array[ index + 0 ] = x; + this.data.array[ index + 1 ] = y; - return this; + return this; - }, + }, - setXYZW: function ( index, x, y, z, w ) { + setXYZ: function ( index, x, y, z ) { - index = index * this.data.stride + this.offset; + index = index * this.data.stride + this.offset; - this.data.array[ index + 0 ] = x; - this.data.array[ index + 1 ] = y; - this.data.array[ index + 2 ] = z; - this.data.array[ index + 3 ] = w; + this.data.array[ index + 0 ] = x; + this.data.array[ index + 1 ] = y; + this.data.array[ index + 2 ] = z; - return this; + return this; - } + }, - }; + setXYZW: function ( index, x, y, z, w ) { - /** - * @author benaadams / https://twitter.com/ben_a_adams - */ + index = index * this.data.stride + this.offset; - function InterleavedBuffer( array, stride ) { + this.data.array[ index + 0 ] = x; + this.data.array[ index + 1 ] = y; + this.data.array[ index + 2 ] = z; + this.data.array[ index + 3 ] = w; - this.uuid = exports.Math.generateUUID(); + return this; - this.array = array; - this.stride = stride; + } - this.dynamic = false; - this.updateRange = { offset: 0, count: - 1 }; + }; - this.version = 0; + /** + * @author benaadams / https://twitter.com/ben_a_adams + */ - }; + function InterleavedBuffer( array, stride ) { - InterleavedBuffer.prototype = { + this.uuid = exports.Math.generateUUID(); - constructor: InterleavedBuffer, + this.array = array; + this.stride = stride; - isInterleavedBuffer: true, + this.dynamic = false; + this.updateRange = { offset: 0, count: - 1 }; - get length () { + this.version = 0; - return this.array.length; + } - }, + InterleavedBuffer.prototype = { - get count () { + constructor: InterleavedBuffer, - return this.array.length / this.stride; + isInterleavedBuffer: true, - }, + get length () { - set needsUpdate( value ) { + return this.array.length; - if ( value === true ) this.version ++; + }, - }, + get count () { - setDynamic: function ( value ) { + return this.array.length / this.stride; - this.dynamic = value; + }, - return this; + set needsUpdate( value ) { - }, + if ( value === true ) this.version ++; - copy: function ( source ) { + }, - this.array = new source.array.constructor( source.array ); - this.stride = source.stride; - this.dynamic = source.dynamic; + setDynamic: function ( value ) { - return this; + this.dynamic = value; - }, + return this; - copyAt: function ( index1, attribute, index2 ) { + }, - index1 *= this.stride; - index2 *= attribute.stride; + copy: function ( source ) { - for ( var i = 0, l = this.stride; i < l; i ++ ) { + this.array = new source.array.constructor( source.array ); + this.stride = source.stride; + this.dynamic = source.dynamic; - this.array[ index1 + i ] = attribute.array[ index2 + i ]; + return this; - } + }, - return this; + copyAt: function ( index1, attribute, index2 ) { - }, + index1 *= this.stride; + index2 *= attribute.stride; - set: function ( value, offset ) { + for ( var i = 0, l = this.stride; i < l; i ++ ) { - if ( offset === undefined ) offset = 0; + this.array[ index1 + i ] = attribute.array[ index2 + i ]; - this.array.set( value, offset ); + } - return this; + return this; - }, + }, - clone: function () { + set: function ( value, offset ) { - return new this.constructor().copy( this ); + if ( offset === undefined ) offset = 0; - } + this.array.set( value, offset ); - }; + return this; - /** - * @author benaadams / https://twitter.com/ben_a_adams - */ + }, - function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) { + clone: function () { - InterleavedBuffer.call( this, array, stride ); + return new this.constructor().copy( this ); - this.meshPerAttribute = meshPerAttribute || 1; + } - }; + }; - InstancedInterleavedBuffer.prototype = Object.create( InterleavedBuffer.prototype ); - InstancedInterleavedBuffer.prototype.constructor = InstancedInterleavedBuffer; + /** + * @author benaadams / https://twitter.com/ben_a_adams + */ - InstancedInterleavedBuffer.prototype.isInstancedInterleavedBuffer = true; + function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) { - InstancedInterleavedBuffer.prototype.copy = function ( source ) { + InterleavedBuffer.call( this, array, stride ); - InterleavedBuffer.prototype.copy.call( this, source ); + this.meshPerAttribute = meshPerAttribute || 1; - this.meshPerAttribute = source.meshPerAttribute; + } - return this; + InstancedInterleavedBuffer.prototype = Object.create( InterleavedBuffer.prototype ); + InstancedInterleavedBuffer.prototype.constructor = InstancedInterleavedBuffer; - }; + InstancedInterleavedBuffer.prototype.isInstancedInterleavedBuffer = true; - /** - * @author benaadams / https://twitter.com/ben_a_adams - */ + InstancedInterleavedBuffer.prototype.copy = function ( source ) { - function InstancedBufferAttribute( array, itemSize, meshPerAttribute ) { + InterleavedBuffer.prototype.copy.call( this, source ); - BufferAttribute.call( this, array, itemSize ); + this.meshPerAttribute = source.meshPerAttribute; - this.meshPerAttribute = meshPerAttribute || 1; + return this; - }; + }; - InstancedBufferAttribute.prototype = Object.create( BufferAttribute.prototype ); - InstancedBufferAttribute.prototype.constructor = InstancedBufferAttribute; + /** + * @author benaadams / https://twitter.com/ben_a_adams + */ - InstancedBufferAttribute.prototype.isInstancedBufferAttribute = true; + function InstancedBufferAttribute( array, itemSize, meshPerAttribute ) { - InstancedBufferAttribute.prototype.copy = function ( source ) { + BufferAttribute.call( this, array, itemSize ); - BufferAttribute.prototype.copy.call( this, source ); + this.meshPerAttribute = meshPerAttribute || 1; - this.meshPerAttribute = source.meshPerAttribute; + } - return this; + InstancedBufferAttribute.prototype = Object.create( BufferAttribute.prototype ); + InstancedBufferAttribute.prototype.constructor = InstancedBufferAttribute; - }; + InstancedBufferAttribute.prototype.isInstancedBufferAttribute = true; - /** - * @author mrdoob / http://mrdoob.com/ - * @author bhouston / http://clara.io/ - * @author stephomi / http://stephaneginier.com/ - */ + InstancedBufferAttribute.prototype.copy = function ( source ) { - function Raycaster( origin, direction, near, far ) { + BufferAttribute.prototype.copy.call( this, source ); - this.ray = new Ray( origin, direction ); - // direction is assumed to be normalized (for accurate distance calculations) + this.meshPerAttribute = source.meshPerAttribute; - this.near = near || 0; - this.far = far || Infinity; + return this; - this.params = { - Mesh: {}, - Line: {}, - LOD: {}, - Points: { threshold: 1 }, - Sprite: {} - }; + }; - Object.defineProperties( this.params, { - PointCloud: { - get: function () { - console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' ); - return this.Points; - } - } - } ); + /** + * @author mrdoob / http://mrdoob.com/ + * @author bhouston / http://clara.io/ + * @author stephomi / http://stephaneginier.com/ + */ + + function Raycaster( origin, direction, near, far ) { + + this.ray = new Ray( origin, direction ); + // direction is assumed to be normalized (for accurate distance calculations) + + this.near = near || 0; + this.far = far || Infinity; + + this.params = { + Mesh: {}, + Line: {}, + LOD: {}, + Points: { threshold: 1 }, + Sprite: {} + }; + + Object.defineProperties( this.params, { + PointCloud: { + get: function () { + console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' ); + return this.Points; + } + } + } ); - }; + } - function ascSort( a, b ) { + function ascSort( a, b ) { - return a.distance - b.distance; + return a.distance - b.distance; - } + } - function intersectObject( object, raycaster, intersects, recursive ) { + function intersectObject( object, raycaster, intersects, recursive ) { - if ( object.visible === false ) return; + if ( object.visible === false ) return; - object.raycast( raycaster, intersects ); + object.raycast( raycaster, intersects ); - if ( recursive === true ) { + if ( recursive === true ) { - var children = object.children; + var children = object.children; - for ( var i = 0, l = children.length; i < l; i ++ ) { + for ( var i = 0, l = children.length; i < l; i ++ ) { - intersectObject( children[ i ], raycaster, intersects, true ); + intersectObject( children[ i ], raycaster, intersects, true ); - } + } - } + } - } + } - // + // - Raycaster.prototype = { + Raycaster.prototype = { - constructor: Raycaster, + constructor: Raycaster, - linePrecision: 1, + linePrecision: 1, - set: function ( origin, direction ) { + set: function ( origin, direction ) { - // direction is assumed to be normalized (for accurate distance calculations) + // direction is assumed to be normalized (for accurate distance calculations) - this.ray.set( origin, direction ); + this.ray.set( origin, direction ); - }, + }, - setFromCamera: function ( coords, camera ) { + setFromCamera: function ( coords, camera ) { - if ( (camera && camera.isPerspectiveCamera) ) { + if ( (camera && camera.isPerspectiveCamera) ) { - this.ray.origin.setFromMatrixPosition( camera.matrixWorld ); - this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize(); + this.ray.origin.setFromMatrixPosition( camera.matrixWorld ); + this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize(); - } else if ( (camera && camera.isOrthographicCamera) ) { + } else if ( (camera && camera.isOrthographicCamera) ) { - this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera - this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld ); + this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera + this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld ); - } else { + } else { - console.error( 'THREE.Raycaster: Unsupported camera type.' ); + console.error( 'THREE.Raycaster: Unsupported camera type.' ); - } + } - }, + }, - intersectObject: function ( object, recursive ) { + intersectObject: function ( object, recursive ) { - var intersects = []; + var intersects = []; - intersectObject( object, this, intersects, recursive ); + intersectObject( object, this, intersects, recursive ); - intersects.sort( ascSort ); + intersects.sort( ascSort ); - return intersects; + return intersects; - }, + }, - intersectObjects: function ( objects, recursive ) { + intersectObjects: function ( objects, recursive ) { - var intersects = []; + var intersects = []; - if ( Array.isArray( objects ) === false ) { + if ( Array.isArray( objects ) === false ) { - console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' ); - return intersects; + console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' ); + return intersects; - } + } - for ( var i = 0, l = objects.length; i < l; i ++ ) { + for ( var i = 0, l = objects.length; i < l; i ++ ) { - intersectObject( objects[ i ], this, intersects, recursive ); + intersectObject( objects[ i ], this, intersects, recursive ); - } + } - intersects.sort( ascSort ); + intersects.sort( ascSort ); - return intersects; + return intersects; - } + } - }; + }; - /** - * @author alteredq / http://alteredqualia.com/ - */ + /** + * @author alteredq / http://alteredqualia.com/ + */ - function Clock( autoStart ) { + function Clock( autoStart ) { - this.autoStart = ( autoStart !== undefined ) ? autoStart : true; + this.autoStart = ( autoStart !== undefined ) ? autoStart : true; - this.startTime = 0; - this.oldTime = 0; - this.elapsedTime = 0; + this.startTime = 0; + this.oldTime = 0; + this.elapsedTime = 0; - this.running = false; + this.running = false; - }; + } - Clock.prototype = { + Clock.prototype = { - constructor: Clock, + constructor: Clock, - start: function () { + start: function () { - this.startTime = ( performance || Date ).now(); + this.startTime = ( performance || Date ).now(); - this.oldTime = this.startTime; - this.running = true; + this.oldTime = this.startTime; + this.running = true; - }, + }, - stop: function () { + stop: function () { - this.getElapsedTime(); - this.running = false; + this.getElapsedTime(); + this.running = false; - }, + }, - getElapsedTime: function () { + getElapsedTime: function () { - this.getDelta(); - return this.elapsedTime; + this.getDelta(); + return this.elapsedTime; - }, + }, - getDelta: function () { + getDelta: function () { - var diff = 0; + var diff = 0; - if ( this.autoStart && ! this.running ) { + if ( this.autoStart && ! this.running ) { - this.start(); + this.start(); - } + } - if ( this.running ) { + if ( this.running ) { - var newTime = ( performance || Date ).now(); + var newTime = ( performance || Date ).now(); - diff = ( newTime - this.oldTime ) / 1000; - this.oldTime = newTime; + diff = ( newTime - this.oldTime ) / 1000; + this.oldTime = newTime; - this.elapsedTime += diff; + this.elapsedTime += diff; - } + } - return diff; + return diff; - } + } - }; + }; - /** - * Spline from Tween.js, slightly optimized (and trashed) - * http://sole.github.com/tween.js/examples/05_spline.html - * - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + /** + * Spline from Tween.js, slightly optimized (and trashed) + * http://sole.github.com/tween.js/examples/05_spline.html + * + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - function Spline( points ) { + function Spline( points ) { - this.points = points; + this.points = points; - var c = [], v3 = { x: 0, y: 0, z: 0 }, - point, intPoint, weight, w2, w3, - pa, pb, pc, pd; + var c = [], v3 = { x: 0, y: 0, z: 0 }, + point, intPoint, weight, w2, w3, + pa, pb, pc, pd; - this.initFromArray = function ( a ) { + this.initFromArray = function ( a ) { - this.points = []; + this.points = []; - for ( var i = 0; i < a.length; i ++ ) { + for ( var i = 0; i < a.length; i ++ ) { - this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] }; + this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] }; - } + } - }; + }; - this.getPoint = function ( k ) { + this.getPoint = function ( k ) { - point = ( this.points.length - 1 ) * k; - intPoint = Math.floor( point ); - weight = point - intPoint; + point = ( this.points.length - 1 ) * k; + intPoint = Math.floor( point ); + weight = point - intPoint; - c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1; - c[ 1 ] = intPoint; - c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1; - c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2; + c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1; + c[ 1 ] = intPoint; + c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1; + c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2; - pa = this.points[ c[ 0 ] ]; - pb = this.points[ c[ 1 ] ]; - pc = this.points[ c[ 2 ] ]; - pd = this.points[ c[ 3 ] ]; + pa = this.points[ c[ 0 ] ]; + pb = this.points[ c[ 1 ] ]; + pc = this.points[ c[ 2 ] ]; + pd = this.points[ c[ 3 ] ]; - w2 = weight * weight; - w3 = weight * w2; + w2 = weight * weight; + w3 = weight * w2; - v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 ); - v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 ); - v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 ); + v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 ); + v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 ); + v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 ); - return v3; + return v3; - }; + }; - this.getControlPointsArray = function () { + this.getControlPointsArray = function () { - var i, p, l = this.points.length, - coords = []; + var i, p, l = this.points.length, + coords = []; - for ( i = 0; i < l; i ++ ) { + for ( i = 0; i < l; i ++ ) { - p = this.points[ i ]; - coords[ i ] = [ p.x, p.y, p.z ]; + p = this.points[ i ]; + coords[ i ] = [ p.x, p.y, p.z ]; - } + } - return coords; + return coords; - }; + }; - // approximate length by summing linear segments + // approximate length by summing linear segments - this.getLength = function ( nSubDivisions ) { + this.getLength = function ( nSubDivisions ) { - var i, index, nSamples, position, - point = 0, intPoint = 0, oldIntPoint = 0, - oldPosition = new Vector3(), - tmpVec = new Vector3(), - chunkLengths = [], - totalLength = 0; + var i, index, nSamples, position, + point = 0, intPoint = 0, oldIntPoint = 0, + oldPosition = new Vector3(), + tmpVec = new Vector3(), + chunkLengths = [], + totalLength = 0; - // first point has 0 length + // first point has 0 length - chunkLengths[ 0 ] = 0; + chunkLengths[ 0 ] = 0; - if ( ! nSubDivisions ) nSubDivisions = 100; + if ( ! nSubDivisions ) nSubDivisions = 100; - nSamples = this.points.length * nSubDivisions; + nSamples = this.points.length * nSubDivisions; - oldPosition.copy( this.points[ 0 ] ); + oldPosition.copy( this.points[ 0 ] ); - for ( i = 1; i < nSamples; i ++ ) { + for ( i = 1; i < nSamples; i ++ ) { - index = i / nSamples; + index = i / nSamples; - position = this.getPoint( index ); - tmpVec.copy( position ); + position = this.getPoint( index ); + tmpVec.copy( position ); - totalLength += tmpVec.distanceTo( oldPosition ); + totalLength += tmpVec.distanceTo( oldPosition ); - oldPosition.copy( position ); + oldPosition.copy( position ); - point = ( this.points.length - 1 ) * index; - intPoint = Math.floor( point ); + point = ( this.points.length - 1 ) * index; + intPoint = Math.floor( point ); - if ( intPoint !== oldIntPoint ) { + if ( intPoint !== oldIntPoint ) { - chunkLengths[ intPoint ] = totalLength; - oldIntPoint = intPoint; + chunkLengths[ intPoint ] = totalLength; + oldIntPoint = intPoint; - } + } - } + } - // last point ends with total length + // last point ends with total length - chunkLengths[ chunkLengths.length ] = totalLength; + chunkLengths[ chunkLengths.length ] = totalLength; - return { chunks: chunkLengths, total: totalLength }; + return { chunks: chunkLengths, total: totalLength }; - }; + }; - this.reparametrizeByArcLength = function ( samplingCoef ) { + this.reparametrizeByArcLength = function ( samplingCoef ) { - var i, j, - index, indexCurrent, indexNext, - realDistance, - sampling, position, - newpoints = [], - tmpVec = new Vector3(), - sl = this.getLength(); + var i, j, + index, indexCurrent, indexNext, + realDistance, + sampling, position, + newpoints = [], + tmpVec = new Vector3(), + sl = this.getLength(); - newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() ); + newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() ); - for ( i = 1; i < this.points.length; i ++ ) { + for ( i = 1; i < this.points.length; i ++ ) { - //tmpVec.copy( this.points[ i - 1 ] ); - //linearDistance = tmpVec.distanceTo( this.points[ i ] ); + //tmpVec.copy( this.points[ i - 1 ] ); + //linearDistance = tmpVec.distanceTo( this.points[ i ] ); - realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ]; + realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ]; - sampling = Math.ceil( samplingCoef * realDistance / sl.total ); + sampling = Math.ceil( samplingCoef * realDistance / sl.total ); - indexCurrent = ( i - 1 ) / ( this.points.length - 1 ); - indexNext = i / ( this.points.length - 1 ); + indexCurrent = ( i - 1 ) / ( this.points.length - 1 ); + indexNext = i / ( this.points.length - 1 ); - for ( j = 1; j < sampling - 1; j ++ ) { + for ( j = 1; j < sampling - 1; j ++ ) { - index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent ); + index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent ); - position = this.getPoint( index ); - newpoints.push( tmpVec.copy( position ).clone() ); + position = this.getPoint( index ); + newpoints.push( tmpVec.copy( position ).clone() ); - } + } - newpoints.push( tmpVec.copy( this.points[ i ] ).clone() ); + newpoints.push( tmpVec.copy( this.points[ i ] ).clone() ); - } + } - this.points = newpoints; + this.points = newpoints; - }; + }; - // Catmull-Rom + // Catmull-Rom - function interpolate( p0, p1, p2, p3, t, t2, t3 ) { + function interpolate( p0, p1, p2, p3, t, t2, t3 ) { - var v0 = ( p2 - p0 ) * 0.5, - v1 = ( p3 - p1 ) * 0.5; + var v0 = ( p2 - p0 ) * 0.5, + v1 = ( p3 - p1 ) * 0.5; - return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1; + return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1; - } + } - }; + } - /** - * @author bhouston / http://clara.io - * @author WestLangley / http://github.com/WestLangley - * - * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system - * - * The poles (phi) are at the positive and negative y axis. - * The equator starts at positive z. - */ + /** + * @author bhouston / http://clara.io + * @author WestLangley / http://github.com/WestLangley + * + * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system + * + * The poles (phi) are at the positive and negative y axis. + * The equator starts at positive z. + */ - function Spherical( radius, phi, theta ) { + function Spherical( radius, phi, theta ) { - this.radius = ( radius !== undefined ) ? radius : 1.0; - this.phi = ( phi !== undefined ) ? phi : 0; // up / down towards top and bottom pole - this.theta = ( theta !== undefined ) ? theta : 0; // around the equator of the sphere + this.radius = ( radius !== undefined ) ? radius : 1.0; + this.phi = ( phi !== undefined ) ? phi : 0; // up / down towards top and bottom pole + this.theta = ( theta !== undefined ) ? theta : 0; // around the equator of the sphere - return this; + return this; - }; + } - Spherical.prototype = { + Spherical.prototype = { - constructor: Spherical, + constructor: Spherical, - set: function ( radius, phi, theta ) { + set: function ( radius, phi, theta ) { - this.radius = radius; - this.phi = phi; - this.theta = theta; + this.radius = radius; + this.phi = phi; + this.theta = theta; - return this; + return this; - }, + }, - clone: function () { + clone: function () { - return new this.constructor().copy( this ); + return new this.constructor().copy( this ); - }, + }, - copy: function ( other ) { + copy: function ( other ) { - this.radius.copy( other.radius ); - this.phi.copy( other.phi ); - this.theta.copy( other.theta ); + this.radius.copy( other.radius ); + this.phi.copy( other.phi ); + this.theta.copy( other.theta ); - return this; + return this; - }, + }, - // restrict phi to be betwee EPS and PI-EPS - makeSafe: function() { + // restrict phi to be betwee EPS and PI-EPS + makeSafe: function() { - var EPS = 0.000001; - this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) ); + var EPS = 0.000001; + this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) ); - return this; + return this; - }, + }, - setFromVector3: function( vec3 ) { + setFromVector3: function( vec3 ) { - this.radius = vec3.length(); + this.radius = vec3.length(); - if ( this.radius === 0 ) { + if ( this.radius === 0 ) { - this.theta = 0; - this.phi = 0; + this.theta = 0; + this.phi = 0; - } else { + } else { - this.theta = Math.atan2( vec3.x, vec3.z ); // equator angle around y-up axis - this.phi = Math.acos( exports.Math.clamp( vec3.y / this.radius, - 1, 1 ) ); // polar angle + this.theta = Math.atan2( vec3.x, vec3.z ); // equator angle around y-up axis + this.phi = Math.acos( exports.Math.clamp( vec3.y / this.radius, - 1, 1 ) ); // polar angle - } + } - return this; + return this; - }, + }, - }; + }; - /** - * @author alteredq / http://alteredqualia.com/ - */ + /** + * @author alteredq / http://alteredqualia.com/ + */ - function MorphBlendMesh( geometry, material ) { + function MorphBlendMesh( geometry, material ) { - Mesh.call( this, geometry, material ); + Mesh.call( this, geometry, material ); - this.animationsMap = {}; - this.animationsList = []; + this.animationsMap = {}; + this.animationsList = []; - // prepare default animation - // (all frames played together in 1 second) + // prepare default animation + // (all frames played together in 1 second) - var numFrames = this.geometry.morphTargets.length; + var numFrames = this.geometry.morphTargets.length; - var name = "__default"; + var name = "__default"; - var startFrame = 0; - var endFrame = numFrames - 1; + var startFrame = 0; + var endFrame = numFrames - 1; - var fps = numFrames / 1; + var fps = numFrames / 1; - this.createAnimation( name, startFrame, endFrame, fps ); - this.setAnimationWeight( name, 1 ); + this.createAnimation( name, startFrame, endFrame, fps ); + this.setAnimationWeight( name, 1 ); - }; + } - MorphBlendMesh.prototype = Object.create( Mesh.prototype ); - MorphBlendMesh.prototype.constructor = MorphBlendMesh; + MorphBlendMesh.prototype = Object.create( Mesh.prototype ); + MorphBlendMesh.prototype.constructor = MorphBlendMesh; - MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) { + MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) { - var animation = { + var animation = { - start: start, - end: end, + start: start, + end: end, - length: end - start + 1, + length: end - start + 1, - fps: fps, - duration: ( end - start ) / fps, + fps: fps, + duration: ( end - start ) / fps, - lastFrame: 0, - currentFrame: 0, + lastFrame: 0, + currentFrame: 0, - active: false, + active: false, - time: 0, - direction: 1, - weight: 1, + time: 0, + direction: 1, + weight: 1, - directionBackwards: false, - mirroredLoop: false + directionBackwards: false, + mirroredLoop: false - }; + }; - this.animationsMap[ name ] = animation; - this.animationsList.push( animation ); + this.animationsMap[ name ] = animation; + this.animationsList.push( animation ); - }; + }; - MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) { + MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) { - var pattern = /([a-z]+)_?(\d+)/i; + var pattern = /([a-z]+)_?(\d+)/i; - var firstAnimation, frameRanges = {}; + var firstAnimation, frameRanges = {}; - var geometry = this.geometry; + var geometry = this.geometry; - for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) { + for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) { - var morph = geometry.morphTargets[ i ]; - var chunks = morph.name.match( pattern ); + var morph = geometry.morphTargets[ i ]; + var chunks = morph.name.match( pattern ); - if ( chunks && chunks.length > 1 ) { + if ( chunks && chunks.length > 1 ) { - var name = chunks[ 1 ]; + var name = chunks[ 1 ]; - if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: - Infinity }; + if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: - Infinity }; - var range = frameRanges[ name ]; + var range = frameRanges[ name ]; - if ( i < range.start ) range.start = i; - if ( i > range.end ) range.end = i; + if ( i < range.start ) range.start = i; + if ( i > range.end ) range.end = i; - if ( ! firstAnimation ) firstAnimation = name; + if ( ! firstAnimation ) firstAnimation = name; - } + } - } + } - for ( var name in frameRanges ) { + for ( var name in frameRanges ) { - var range = frameRanges[ name ]; - this.createAnimation( name, range.start, range.end, fps ); + var range = frameRanges[ name ]; + this.createAnimation( name, range.start, range.end, fps ); - } + } - this.firstAnimation = firstAnimation; + this.firstAnimation = firstAnimation; - }; + }; - MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) { + MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) { - var animation = this.animationsMap[ name ]; + var animation = this.animationsMap[ name ]; - if ( animation ) { + if ( animation ) { - animation.direction = 1; - animation.directionBackwards = false; + animation.direction = 1; + animation.directionBackwards = false; - } + } - }; + }; - MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) { + MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) { - var animation = this.animationsMap[ name ]; + var animation = this.animationsMap[ name ]; - if ( animation ) { + if ( animation ) { - animation.direction = - 1; - animation.directionBackwards = true; + animation.direction = - 1; + animation.directionBackwards = true; - } + } - }; + }; - MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) { + MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) { - var animation = this.animationsMap[ name ]; + var animation = this.animationsMap[ name ]; - if ( animation ) { + if ( animation ) { - animation.fps = fps; - animation.duration = ( animation.end - animation.start ) / animation.fps; + animation.fps = fps; + animation.duration = ( animation.end - animation.start ) / animation.fps; - } + } - }; + }; - MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) { + MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) { - var animation = this.animationsMap[ name ]; + var animation = this.animationsMap[ name ]; - if ( animation ) { + if ( animation ) { - animation.duration = duration; - animation.fps = ( animation.end - animation.start ) / animation.duration; + animation.duration = duration; + animation.fps = ( animation.end - animation.start ) / animation.duration; - } + } - }; + }; - MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) { + MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) { - var animation = this.animationsMap[ name ]; + var animation = this.animationsMap[ name ]; - if ( animation ) { + if ( animation ) { - animation.weight = weight; + animation.weight = weight; - } + } - }; + }; - MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) { + MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) { - var animation = this.animationsMap[ name ]; + var animation = this.animationsMap[ name ]; - if ( animation ) { + if ( animation ) { - animation.time = time; + animation.time = time; - } + } - }; + }; - MorphBlendMesh.prototype.getAnimationTime = function ( name ) { + MorphBlendMesh.prototype.getAnimationTime = function ( name ) { - var time = 0; + var time = 0; - var animation = this.animationsMap[ name ]; + var animation = this.animationsMap[ name ]; - if ( animation ) { + if ( animation ) { - time = animation.time; + time = animation.time; - } + } - return time; + return time; - }; + }; - MorphBlendMesh.prototype.getAnimationDuration = function ( name ) { + MorphBlendMesh.prototype.getAnimationDuration = function ( name ) { - var duration = - 1; + var duration = - 1; - var animation = this.animationsMap[ name ]; + var animation = this.animationsMap[ name ]; - if ( animation ) { + if ( animation ) { - duration = animation.duration; + duration = animation.duration; - } + } - return duration; + return duration; - }; + }; - MorphBlendMesh.prototype.playAnimation = function ( name ) { + MorphBlendMesh.prototype.playAnimation = function ( name ) { - var animation = this.animationsMap[ name ]; + var animation = this.animationsMap[ name ]; - if ( animation ) { + if ( animation ) { - animation.time = 0; - animation.active = true; + animation.time = 0; + animation.active = true; - } else { + } else { - console.warn( "THREE.MorphBlendMesh: animation[" + name + "] undefined in .playAnimation()" ); + console.warn( "THREE.MorphBlendMesh: animation[" + name + "] undefined in .playAnimation()" ); - } + } - }; + }; - MorphBlendMesh.prototype.stopAnimation = function ( name ) { + MorphBlendMesh.prototype.stopAnimation = function ( name ) { - var animation = this.animationsMap[ name ]; + var animation = this.animationsMap[ name ]; - if ( animation ) { + if ( animation ) { - animation.active = false; + animation.active = false; - } + } - }; + }; - MorphBlendMesh.prototype.update = function ( delta ) { + MorphBlendMesh.prototype.update = function ( delta ) { - for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) { + for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) { - var animation = this.animationsList[ i ]; + var animation = this.animationsList[ i ]; - if ( ! animation.active ) continue; + if ( ! animation.active ) continue; - var frameTime = animation.duration / animation.length; + var frameTime = animation.duration / animation.length; - animation.time += animation.direction * delta; + animation.time += animation.direction * delta; - if ( animation.mirroredLoop ) { + if ( animation.mirroredLoop ) { - if ( animation.time > animation.duration || animation.time < 0 ) { + if ( animation.time > animation.duration || animation.time < 0 ) { - animation.direction *= - 1; + animation.direction *= - 1; - if ( animation.time > animation.duration ) { + if ( animation.time > animation.duration ) { - animation.time = animation.duration; - animation.directionBackwards = true; + animation.time = animation.duration; + animation.directionBackwards = true; - } + } - if ( animation.time < 0 ) { + if ( animation.time < 0 ) { - animation.time = 0; - animation.directionBackwards = false; + animation.time = 0; + animation.directionBackwards = false; - } + } - } + } - } else { + } else { - animation.time = animation.time % animation.duration; + animation.time = animation.time % animation.duration; - if ( animation.time < 0 ) animation.time += animation.duration; + if ( animation.time < 0 ) animation.time += animation.duration; - } + } - var keyframe = animation.start + exports.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 ); - var weight = animation.weight; + var keyframe = animation.start + exports.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 ); + var weight = animation.weight; - if ( keyframe !== animation.currentFrame ) { + if ( keyframe !== animation.currentFrame ) { - this.morphTargetInfluences[ animation.lastFrame ] = 0; - this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight; + this.morphTargetInfluences[ animation.lastFrame ] = 0; + this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight; - this.morphTargetInfluences[ keyframe ] = 0; + this.morphTargetInfluences[ keyframe ] = 0; - animation.lastFrame = animation.currentFrame; - animation.currentFrame = keyframe; + animation.lastFrame = animation.currentFrame; + animation.currentFrame = keyframe; - } + } - var mix = ( animation.time % frameTime ) / frameTime; + var mix = ( animation.time % frameTime ) / frameTime; - if ( animation.directionBackwards ) mix = 1 - mix; + if ( animation.directionBackwards ) mix = 1 - mix; - if ( animation.currentFrame !== animation.lastFrame ) { + if ( animation.currentFrame !== animation.lastFrame ) { - this.morphTargetInfluences[ animation.currentFrame ] = mix * weight; - this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight; + this.morphTargetInfluences[ animation.currentFrame ] = mix * weight; + this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight; - } else { + } else { - this.morphTargetInfluences[ animation.currentFrame ] = weight; + this.morphTargetInfluences[ animation.currentFrame ] = weight; - } + } - } + } - }; + }; + + /** + * @author alteredq / http://alteredqualia.com/ + */ + + function ImmediateRenderObject( material ) { + + Object3D.call( this ); - /** - * @author alteredq / http://alteredqualia.com/ - */ + this.material = material; + this.render = function ( renderCallback ) {}; - function ImmediateRenderObject( material ) { + } + + ImmediateRenderObject.prototype = Object.create( Object3D.prototype ); + ImmediateRenderObject.prototype.constructor = ImmediateRenderObject; - Object3D.call( this ); + ImmediateRenderObject.prototype.isImmediateRenderObject = true; - this.material = material; - this.render = function ( renderCallback ) {}; + /** + * @author mrdoob / http://mrdoob.com/ + */ - }; + function WireframeGeometry( geometry ) { - ImmediateRenderObject.prototype = Object.create( Object3D.prototype ); - ImmediateRenderObject.prototype.constructor = ImmediateRenderObject; + BufferGeometry.call( this ); - ImmediateRenderObject.prototype.isImmediateRenderObject = true; + var edge = [ 0, 0 ], hash = {}; - /** - * @author mrdoob / http://mrdoob.com/ - */ + function sortFunction( a, b ) { - function WireframeGeometry( geometry ) { + return a - b; + + } - BufferGeometry.call( this ); + var keys = [ 'a', 'b', 'c' ]; - var edge = [ 0, 0 ], hash = {}; + if ( (geometry && geometry.isGeometry) ) { - function sortFunction( a, b ) { + var vertices = geometry.vertices; + var faces = geometry.faces; + var numEdges = 0; - return a - b; + // allocate maximal size + var edges = new Uint32Array( 6 * faces.length ); - } + for ( var i = 0, l = faces.length; i < l; i ++ ) { - var keys = [ 'a', 'b', 'c' ]; + var face = faces[ i ]; - if ( (geometry && geometry.isGeometry) ) { + for ( var j = 0; j < 3; j ++ ) { - var vertices = geometry.vertices; - var faces = geometry.faces; - var numEdges = 0; + edge[ 0 ] = face[ keys[ j ] ]; + edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ]; + edge.sort( sortFunction ); - // allocate maximal size - var edges = new Uint32Array( 6 * faces.length ); + var key = edge.toString(); - for ( var i = 0, l = faces.length; i < l; i ++ ) { + if ( hash[ key ] === undefined ) { - var face = faces[ i ]; + edges[ 2 * numEdges ] = edge[ 0 ]; + edges[ 2 * numEdges + 1 ] = edge[ 1 ]; + hash[ key ] = true; + numEdges ++; - for ( var j = 0; j < 3; j ++ ) { + } - edge[ 0 ] = face[ keys[ j ] ]; - edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ]; - edge.sort( sortFunction ); + } - var key = edge.toString(); + } - if ( hash[ key ] === undefined ) { + var coords = new Float32Array( numEdges * 2 * 3 ); - edges[ 2 * numEdges ] = edge[ 0 ]; - edges[ 2 * numEdges + 1 ] = edge[ 1 ]; - hash[ key ] = true; - numEdges ++; + for ( var i = 0, l = numEdges; i < l; i ++ ) { - } + for ( var j = 0; j < 2; j ++ ) { - } + var vertex = vertices[ edges [ 2 * i + j ] ]; - } + var index = 6 * i + 3 * j; + coords[ index + 0 ] = vertex.x; + coords[ index + 1 ] = vertex.y; + coords[ index + 2 ] = vertex.z; - var coords = new Float32Array( numEdges * 2 * 3 ); + } - for ( var i = 0, l = numEdges; i < l; i ++ ) { + } - for ( var j = 0; j < 2; j ++ ) { + this.addAttribute( 'position', new BufferAttribute( coords, 3 ) ); - var vertex = vertices[ edges [ 2 * i + j ] ]; + } else if ( (geometry && geometry.isBufferGeometry) ) { - var index = 6 * i + 3 * j; - coords[ index + 0 ] = vertex.x; - coords[ index + 1 ] = vertex.y; - coords[ index + 2 ] = vertex.z; + if ( geometry.index !== null ) { - } + // Indexed BufferGeometry - } + var indices = geometry.index.array; + var vertices = geometry.attributes.position; + var groups = geometry.groups; + var numEdges = 0; - this.addAttribute( 'position', new BufferAttribute( coords, 3 ) ); + if ( groups.length === 0 ) { - } else if ( (geometry && geometry.isBufferGeometry) ) { + geometry.addGroup( 0, indices.length ); - if ( geometry.index !== null ) { + } - // Indexed BufferGeometry + // allocate maximal size + var edges = new Uint32Array( 2 * indices.length ); - var indices = geometry.index.array; - var vertices = geometry.attributes.position; - var groups = geometry.groups; - var numEdges = 0; + for ( var o = 0, ol = groups.length; o < ol; ++ o ) { - if ( groups.length === 0 ) { + var group = groups[ o ]; - geometry.addGroup( 0, indices.length ); + var start = group.start; + var count = group.count; - } + for ( var i = start, il = start + count; i < il; i += 3 ) { - // allocate maximal size - var edges = new Uint32Array( 2 * indices.length ); + for ( var j = 0; j < 3; j ++ ) { - for ( var o = 0, ol = groups.length; o < ol; ++ o ) { + edge[ 0 ] = indices[ i + j ]; + edge[ 1 ] = indices[ i + ( j + 1 ) % 3 ]; + edge.sort( sortFunction ); - var group = groups[ o ]; + var key = edge.toString(); - var start = group.start; - var count = group.count; + if ( hash[ key ] === undefined ) { - for ( var i = start, il = start + count; i < il; i += 3 ) { + edges[ 2 * numEdges ] = edge[ 0 ]; + edges[ 2 * numEdges + 1 ] = edge[ 1 ]; + hash[ key ] = true; + numEdges ++; - for ( var j = 0; j < 3; j ++ ) { + } - edge[ 0 ] = indices[ i + j ]; - edge[ 1 ] = indices[ i + ( j + 1 ) % 3 ]; - edge.sort( sortFunction ); + } - var key = edge.toString(); + } - if ( hash[ key ] === undefined ) { + } - edges[ 2 * numEdges ] = edge[ 0 ]; - edges[ 2 * numEdges + 1 ] = edge[ 1 ]; - hash[ key ] = true; - numEdges ++; + var coords = new Float32Array( numEdges * 2 * 3 ); - } + for ( var i = 0, l = numEdges; i < l; i ++ ) { - } + for ( var j = 0; j < 2; j ++ ) { - } + var index = 6 * i + 3 * j; + var index2 = edges[ 2 * i + j ]; - } + coords[ index + 0 ] = vertices.getX( index2 ); + coords[ index + 1 ] = vertices.getY( index2 ); + coords[ index + 2 ] = vertices.getZ( index2 ); - var coords = new Float32Array( numEdges * 2 * 3 ); + } - for ( var i = 0, l = numEdges; i < l; i ++ ) { + } - for ( var j = 0; j < 2; j ++ ) { + this.addAttribute( 'position', new BufferAttribute( coords, 3 ) ); - var index = 6 * i + 3 * j; - var index2 = edges[ 2 * i + j ]; + } else { - coords[ index + 0 ] = vertices.getX( index2 ); - coords[ index + 1 ] = vertices.getY( index2 ); - coords[ index + 2 ] = vertices.getZ( index2 ); + // non-indexed BufferGeometry - } + var vertices = geometry.attributes.position.array; + var numEdges = vertices.length / 3; + var numTris = numEdges / 3; - } + var coords = new Float32Array( numEdges * 2 * 3 ); - this.addAttribute( 'position', new BufferAttribute( coords, 3 ) ); + for ( var i = 0, l = numTris; i < l; i ++ ) { - } else { + for ( var j = 0; j < 3; j ++ ) { - // non-indexed BufferGeometry + var index = 18 * i + 6 * j; - var vertices = geometry.attributes.position.array; - var numEdges = vertices.length / 3; - var numTris = numEdges / 3; + var index1 = 9 * i + 3 * j; + coords[ index + 0 ] = vertices[ index1 ]; + coords[ index + 1 ] = vertices[ index1 + 1 ]; + coords[ index + 2 ] = vertices[ index1 + 2 ]; - var coords = new Float32Array( numEdges * 2 * 3 ); + var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 ); + coords[ index + 3 ] = vertices[ index2 ]; + coords[ index + 4 ] = vertices[ index2 + 1 ]; + coords[ index + 5 ] = vertices[ index2 + 2 ]; - for ( var i = 0, l = numTris; i < l; i ++ ) { + } - for ( var j = 0; j < 3; j ++ ) { + } - var index = 18 * i + 6 * j; + this.addAttribute( 'position', new BufferAttribute( coords, 3 ) ); - var index1 = 9 * i + 3 * j; - coords[ index + 0 ] = vertices[ index1 ]; - coords[ index + 1 ] = vertices[ index1 + 1 ]; - coords[ index + 2 ] = vertices[ index1 + 2 ]; + } - var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 ); - coords[ index + 3 ] = vertices[ index2 ]; - coords[ index + 4 ] = vertices[ index2 + 1 ]; - coords[ index + 5 ] = vertices[ index2 + 2 ]; + } - } + } - } + WireframeGeometry.prototype = Object.create( BufferGeometry.prototype ); + WireframeGeometry.prototype.constructor = WireframeGeometry; - this.addAttribute( 'position', new BufferAttribute( coords, 3 ) ); + /** + * @author mrdoob / http://mrdoob.com/ + */ - } + function WireframeHelper( object, hex ) { - } + var color = ( hex !== undefined ) ? hex : 0xffffff; - }; + LineSegments.call( this, new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: color } ) ); - WireframeGeometry.prototype = Object.create( BufferGeometry.prototype ); - WireframeGeometry.prototype.constructor = WireframeGeometry; + this.matrix = object.matrixWorld; + this.matrixAutoUpdate = false; - /** - * @author mrdoob / http://mrdoob.com/ - */ + } - function WireframeHelper( object, hex ) { + WireframeHelper.prototype = Object.create( LineSegments.prototype ); + WireframeHelper.prototype.constructor = WireframeHelper; - var color = ( hex !== undefined ) ? hex : 0xffffff; + /** + * @author mrdoob / http://mrdoob.com/ + * @author WestLangley / http://github.com/WestLangley + */ - LineSegments.call( this, new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: color } ) ); + function VertexNormalsHelper( object, size, hex, linewidth ) { - this.matrix = object.matrixWorld; - this.matrixAutoUpdate = false; + this.object = object; - }; + this.size = ( size !== undefined ) ? size : 1; - WireframeHelper.prototype = Object.create( LineSegments.prototype ); - WireframeHelper.prototype.constructor = WireframeHelper; + var color = ( hex !== undefined ) ? hex : 0xff0000; - /** - * @author mrdoob / http://mrdoob.com/ - * @author WestLangley / http://github.com/WestLangley - */ + var width = ( linewidth !== undefined ) ? linewidth : 1; - function VertexNormalsHelper( object, size, hex, linewidth ) { + // - this.object = object; + var nNormals = 0; - this.size = ( size !== undefined ) ? size : 1; + var objGeometry = this.object.geometry; - var color = ( hex !== undefined ) ? hex : 0xff0000; + if ( (objGeometry && objGeometry.isGeometry) ) { - var width = ( linewidth !== undefined ) ? linewidth : 1; + nNormals = objGeometry.faces.length * 3; - // + } else if ( (objGeometry && objGeometry.isBufferGeometry) ) { - var nNormals = 0; + nNormals = objGeometry.attributes.normal.count; - var objGeometry = this.object.geometry; + } - if ( (objGeometry && objGeometry.isGeometry) ) { + // - nNormals = objGeometry.faces.length * 3; + var geometry = new BufferGeometry(); - } else if ( (objGeometry && objGeometry.isBufferGeometry) ) { + var positions = new Float32Attribute( nNormals * 2 * 3, 3 ); - nNormals = objGeometry.attributes.normal.count; + geometry.addAttribute( 'position', positions ); - } + LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) ); - // + // - var geometry = new BufferGeometry(); + this.matrixAutoUpdate = false; - var positions = new Float32Attribute( nNormals * 2 * 3, 3 ); + this.update(); - geometry.addAttribute( 'position', positions ); + } - LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) ); + VertexNormalsHelper.prototype = Object.create( LineSegments.prototype ); + VertexNormalsHelper.prototype.constructor = VertexNormalsHelper; - // + VertexNormalsHelper.prototype.update = ( function () { - this.matrixAutoUpdate = false; + var v1 = new Vector3(); + var v2 = new Vector3(); + var normalMatrix = new Matrix3(); - this.update(); + return function update() { - }; + var keys = [ 'a', 'b', 'c' ]; - VertexNormalsHelper.prototype = Object.create( LineSegments.prototype ); - VertexNormalsHelper.prototype.constructor = VertexNormalsHelper; + this.object.updateMatrixWorld( true ); - VertexNormalsHelper.prototype.update = ( function () { + normalMatrix.getNormalMatrix( this.object.matrixWorld ); - var v1 = new Vector3(); - var v2 = new Vector3(); - var normalMatrix = new Matrix3(); + var matrixWorld = this.object.matrixWorld; - return function update() { + var position = this.geometry.attributes.position; - var keys = [ 'a', 'b', 'c' ]; + // - this.object.updateMatrixWorld( true ); + var objGeometry = this.object.geometry; - normalMatrix.getNormalMatrix( this.object.matrixWorld ); + if ( (objGeometry && objGeometry.isGeometry) ) { - var matrixWorld = this.object.matrixWorld; + var vertices = objGeometry.vertices; - var position = this.geometry.attributes.position; + var faces = objGeometry.faces; - // + var idx = 0; - var objGeometry = this.object.geometry; + for ( var i = 0, l = faces.length; i < l; i ++ ) { - if ( (objGeometry && objGeometry.isGeometry) ) { + var face = faces[ i ]; - var vertices = objGeometry.vertices; + for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) { - var faces = objGeometry.faces; + var vertex = vertices[ face[ keys[ j ] ] ]; - var idx = 0; + var normal = face.vertexNormals[ j ]; - for ( var i = 0, l = faces.length; i < l; i ++ ) { + v1.copy( vertex ).applyMatrix4( matrixWorld ); - var face = faces[ i ]; + v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 ); - for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) { + position.setXYZ( idx, v1.x, v1.y, v1.z ); - var vertex = vertices[ face[ keys[ j ] ] ]; + idx = idx + 1; - var normal = face.vertexNormals[ j ]; + position.setXYZ( idx, v2.x, v2.y, v2.z ); - v1.copy( vertex ).applyMatrix4( matrixWorld ); + idx = idx + 1; - v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 ); + } - position.setXYZ( idx, v1.x, v1.y, v1.z ); + } - idx = idx + 1; + } else if ( (objGeometry && objGeometry.isBufferGeometry) ) { - position.setXYZ( idx, v2.x, v2.y, v2.z ); + var objPos = objGeometry.attributes.position; - idx = idx + 1; + var objNorm = objGeometry.attributes.normal; - } + var idx = 0; - } + // for simplicity, ignore index and drawcalls, and render every normal - } else if ( (objGeometry && objGeometry.isBufferGeometry) ) { + for ( var j = 0, jl = objPos.count; j < jl; j ++ ) { - var objPos = objGeometry.attributes.position; + v1.set( objPos.getX( j ), objPos.getY( j ), objPos.getZ( j ) ).applyMatrix4( matrixWorld ); - var objNorm = objGeometry.attributes.normal; + v2.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) ); - var idx = 0; + v2.applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 ); - // for simplicity, ignore index and drawcalls, and render every normal + position.setXYZ( idx, v1.x, v1.y, v1.z ); - for ( var j = 0, jl = objPos.count; j < jl; j ++ ) { + idx = idx + 1; - v1.set( objPos.getX( j ), objPos.getY( j ), objPos.getZ( j ) ).applyMatrix4( matrixWorld ); + position.setXYZ( idx, v2.x, v2.y, v2.z ); - v2.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) ); + idx = idx + 1; - v2.applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 ); + } - position.setXYZ( idx, v1.x, v1.y, v1.z ); + } - idx = idx + 1; + position.needsUpdate = true; - position.setXYZ( idx, v2.x, v2.y, v2.z ); + return this; - idx = idx + 1; + }; - } + }() ); - } + /** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + * @author WestLangley / http://github.com/WestLangley + */ - position.needsUpdate = true; + function SpotLightHelper( light ) { - return this; + Object3D.call( this ); - }; + this.light = light; + this.light.updateMatrixWorld(); - }() ); + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; - /** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - * @author WestLangley / http://github.com/WestLangley - */ + var geometry = new BufferGeometry(); - function SpotLightHelper( light ) { + var positions = [ + 0, 0, 0, 0, 0, 1, + 0, 0, 0, 1, 0, 1, + 0, 0, 0, - 1, 0, 1, + 0, 0, 0, 0, 1, 1, + 0, 0, 0, 0, - 1, 1 + ]; - Object3D.call( this ); + for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) { - this.light = light; - this.light.updateMatrixWorld(); + var p1 = ( i / l ) * Math.PI * 2; + var p2 = ( j / l ) * Math.PI * 2; - this.matrix = light.matrixWorld; - this.matrixAutoUpdate = false; + positions.push( + Math.cos( p1 ), Math.sin( p1 ), 1, + Math.cos( p2 ), Math.sin( p2 ), 1 + ); - var geometry = new BufferGeometry(); + } - var positions = [ - 0, 0, 0, 0, 0, 1, - 0, 0, 0, 1, 0, 1, - 0, 0, 0, - 1, 0, 1, - 0, 0, 0, 0, 1, 1, - 0, 0, 0, 0, - 1, 1 - ]; + geometry.addAttribute( 'position', new Float32Attribute( positions, 3 ) ); - for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) { + var material = new LineBasicMaterial( { fog: false } ); - var p1 = ( i / l ) * Math.PI * 2; - var p2 = ( j / l ) * Math.PI * 2; + this.cone = new LineSegments( geometry, material ); + this.add( this.cone ); - positions.push( - Math.cos( p1 ), Math.sin( p1 ), 1, - Math.cos( p2 ), Math.sin( p2 ), 1 - ); + this.update(); - } + } - geometry.addAttribute( 'position', new Float32Attribute( positions, 3 ) ); + SpotLightHelper.prototype = Object.create( Object3D.prototype ); + SpotLightHelper.prototype.constructor = SpotLightHelper; - var material = new LineBasicMaterial( { fog: false } ); + SpotLightHelper.prototype.dispose = function () { - this.cone = new LineSegments( geometry, material ); - this.add( this.cone ); + this.cone.geometry.dispose(); + this.cone.material.dispose(); - this.update(); + }; - }; + SpotLightHelper.prototype.update = function () { - SpotLightHelper.prototype = Object.create( Object3D.prototype ); - SpotLightHelper.prototype.constructor = SpotLightHelper; + var vector = new Vector3(); + var vector2 = new Vector3(); - SpotLightHelper.prototype.dispose = function () { + return function update() { - this.cone.geometry.dispose(); - this.cone.material.dispose(); + var coneLength = this.light.distance ? this.light.distance : 1000; + var coneWidth = coneLength * Math.tan( this.light.angle ); - }; + this.cone.scale.set( coneWidth, coneWidth, coneLength ); - SpotLightHelper.prototype.update = function () { + vector.setFromMatrixPosition( this.light.matrixWorld ); + vector2.setFromMatrixPosition( this.light.target.matrixWorld ); - var vector = new Vector3(); - var vector2 = new Vector3(); + this.cone.lookAt( vector2.sub( vector ) ); - return function update() { + this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); - var coneLength = this.light.distance ? this.light.distance : 1000; - var coneWidth = coneLength * Math.tan( this.light.angle ); + }; - this.cone.scale.set( coneWidth, coneWidth, coneLength ); + }(); - vector.setFromMatrixPosition( this.light.matrixWorld ); - vector2.setFromMatrixPosition( this.light.target.matrixWorld ); + /** + * @author Sean Griffin / http://twitter.com/sgrif + * @author Michael Guerrero / http://realitymeltdown.com + * @author mrdoob / http://mrdoob.com/ + * @author ikerr / http://verold.com + */ - this.cone.lookAt( vector2.sub( vector ) ); + function SkeletonHelper( object ) { - this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); + this.bones = this.getBoneList( object ); - }; + var geometry = new Geometry(); - }(); + for ( var i = 0; i < this.bones.length; i ++ ) { - /** - * @author Sean Griffin / http://twitter.com/sgrif - * @author Michael Guerrero / http://realitymeltdown.com - * @author mrdoob / http://mrdoob.com/ - * @author ikerr / http://verold.com - */ + var bone = this.bones[ i ]; - function SkeletonHelper( object ) { + if ( (bone.parent && bone.parent.isBone) ) { - this.bones = this.getBoneList( object ); + geometry.vertices.push( new Vector3() ); + geometry.vertices.push( new Vector3() ); + geometry.colors.push( new Color( 0, 0, 1 ) ); + geometry.colors.push( new Color( 0, 1, 0 ) ); - var geometry = new Geometry(); + } - for ( var i = 0; i < this.bones.length; i ++ ) { + } - var bone = this.bones[ i ]; + geometry.dynamic = true; - if ( (bone.parent && bone.parent.isBone) ) { + var material = new LineBasicMaterial( { vertexColors: VertexColors, depthTest: false, depthWrite: false, transparent: true } ); - geometry.vertices.push( new Vector3() ); - geometry.vertices.push( new Vector3() ); - geometry.colors.push( new Color( 0, 0, 1 ) ); - geometry.colors.push( new Color( 0, 1, 0 ) ); + LineSegments.call( this, geometry, material ); - } + this.root = object; - } + this.matrix = object.matrixWorld; + this.matrixAutoUpdate = false; - geometry.dynamic = true; + this.update(); - var material = new LineBasicMaterial( { vertexColors: VertexColors, depthTest: false, depthWrite: false, transparent: true } ); + } - LineSegments.call( this, geometry, material ); - this.root = object; + SkeletonHelper.prototype = Object.create( LineSegments.prototype ); + SkeletonHelper.prototype.constructor = SkeletonHelper; - this.matrix = object.matrixWorld; - this.matrixAutoUpdate = false; + SkeletonHelper.prototype.getBoneList = function( object ) { - this.update(); + var boneList = []; - }; + if ( (object && object.isBone) ) { + boneList.push( object ); - SkeletonHelper.prototype = Object.create( LineSegments.prototype ); - SkeletonHelper.prototype.constructor = SkeletonHelper; + } - SkeletonHelper.prototype.getBoneList = function( object ) { + for ( var i = 0; i < object.children.length; i ++ ) { - var boneList = []; + boneList.push.apply( boneList, this.getBoneList( object.children[ i ] ) ); - if ( (object && object.isBone) ) { + } - boneList.push( object ); + return boneList; - } + }; - for ( var i = 0; i < object.children.length; i ++ ) { + SkeletonHelper.prototype.update = function () { - boneList.push.apply( boneList, this.getBoneList( object.children[ i ] ) ); + var geometry = this.geometry; - } + var matrixWorldInv = new Matrix4().getInverse( this.root.matrixWorld ); - return boneList; + var boneMatrix = new Matrix4(); - }; + var j = 0; - SkeletonHelper.prototype.update = function () { + for ( var i = 0; i < this.bones.length; i ++ ) { - var geometry = this.geometry; + var bone = this.bones[ i ]; - var matrixWorldInv = new Matrix4().getInverse( this.root.matrixWorld ); + if ( (bone.parent && bone.parent.isBone) ) { - var boneMatrix = new Matrix4(); + boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld ); + geometry.vertices[ j ].setFromMatrixPosition( boneMatrix ); - var j = 0; + boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld ); + geometry.vertices[ j + 1 ].setFromMatrixPosition( boneMatrix ); - for ( var i = 0; i < this.bones.length; i ++ ) { + j += 2; - var bone = this.bones[ i ]; + } - if ( (bone.parent && bone.parent.isBone) ) { + } - boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld ); - geometry.vertices[ j ].setFromMatrixPosition( boneMatrix ); + geometry.verticesNeedUpdate = true; - boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld ); - geometry.vertices[ j + 1 ].setFromMatrixPosition( boneMatrix ); + geometry.computeBoundingSphere(); - j += 2; + }; - } + /** + * @author benaadams / https://twitter.com/ben_a_adams + * based on THREE.SphereGeometry + */ - } + function SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) { - geometry.verticesNeedUpdate = true; + BufferGeometry.call( this ); - geometry.computeBoundingSphere(); + this.type = 'SphereBufferGeometry'; - }; + this.parameters = { + radius: radius, + widthSegments: widthSegments, + heightSegments: heightSegments, + phiStart: phiStart, + phiLength: phiLength, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - /** - * @author benaadams / https://twitter.com/ben_a_adams - * based on THREE.SphereGeometry - */ + radius = radius || 50; - function SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) { + widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 ); + heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 ); - BufferGeometry.call( this ); + phiStart = phiStart !== undefined ? phiStart : 0; + phiLength = phiLength !== undefined ? phiLength : Math.PI * 2; - this.type = 'SphereBufferGeometry'; + thetaStart = thetaStart !== undefined ? thetaStart : 0; + thetaLength = thetaLength !== undefined ? thetaLength : Math.PI; - this.parameters = { - radius: radius, - widthSegments: widthSegments, - heightSegments: heightSegments, - phiStart: phiStart, - phiLength: phiLength, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + var thetaEnd = thetaStart + thetaLength; - radius = radius || 50; + var vertexCount = ( ( widthSegments + 1 ) * ( heightSegments + 1 ) ); - widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 ); - heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 ); + var positions = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); + var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); + var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); - phiStart = phiStart !== undefined ? phiStart : 0; - phiLength = phiLength !== undefined ? phiLength : Math.PI * 2; + var index = 0, vertices = [], normal = new Vector3(); - thetaStart = thetaStart !== undefined ? thetaStart : 0; - thetaLength = thetaLength !== undefined ? thetaLength : Math.PI; + for ( var y = 0; y <= heightSegments; y ++ ) { - var thetaEnd = thetaStart + thetaLength; + var verticesRow = []; - var vertexCount = ( ( widthSegments + 1 ) * ( heightSegments + 1 ) ); + var v = y / heightSegments; - var positions = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); - var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); - var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); + for ( var x = 0; x <= widthSegments; x ++ ) { - var index = 0, vertices = [], normal = new Vector3(); + var u = x / widthSegments; - for ( var y = 0; y <= heightSegments; y ++ ) { + var px = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength ); + var py = radius * Math.cos( thetaStart + v * thetaLength ); + var pz = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength ); - var verticesRow = []; + normal.set( px, py, pz ).normalize(); - var v = y / heightSegments; + positions.setXYZ( index, px, py, pz ); + normals.setXYZ( index, normal.x, normal.y, normal.z ); + uvs.setXY( index, u, 1 - v ); - for ( var x = 0; x <= widthSegments; x ++ ) { + verticesRow.push( index ); - var u = x / widthSegments; + index ++; - var px = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength ); - var py = radius * Math.cos( thetaStart + v * thetaLength ); - var pz = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength ); + } - normal.set( px, py, pz ).normalize(); + vertices.push( verticesRow ); - positions.setXYZ( index, px, py, pz ); - normals.setXYZ( index, normal.x, normal.y, normal.z ); - uvs.setXY( index, u, 1 - v ); + } - verticesRow.push( index ); + var indices = []; - index ++; + for ( var y = 0; y < heightSegments; y ++ ) { - } + for ( var x = 0; x < widthSegments; x ++ ) { - vertices.push( verticesRow ); + var v1 = vertices[ y ][ x + 1 ]; + var v2 = vertices[ y ][ x ]; + var v3 = vertices[ y + 1 ][ x ]; + var v4 = vertices[ y + 1 ][ x + 1 ]; - } + if ( y !== 0 || thetaStart > 0 ) indices.push( v1, v2, v4 ); + if ( y !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( v2, v3, v4 ); - var indices = []; + } - for ( var y = 0; y < heightSegments; y ++ ) { + } - for ( var x = 0; x < widthSegments; x ++ ) { + this.setIndex( new ( positions.count > 65535 ? Uint32Attribute : Uint16Attribute )( indices, 1 ) ); + this.addAttribute( 'position', positions ); + this.addAttribute( 'normal', normals ); + this.addAttribute( 'uv', uvs ); - var v1 = vertices[ y ][ x + 1 ]; - var v2 = vertices[ y ][ x ]; - var v3 = vertices[ y + 1 ][ x ]; - var v4 = vertices[ y + 1 ][ x + 1 ]; + this.boundingSphere = new Sphere( new Vector3(), radius ); - if ( y !== 0 || thetaStart > 0 ) indices.push( v1, v2, v4 ); - if ( y !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( v2, v3, v4 ); + } - } + SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + SphereBufferGeometry.prototype.constructor = SphereBufferGeometry; - } + /** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + */ - this.setIndex( new ( positions.count > 65535 ? Uint32Attribute : Uint16Attribute )( indices, 1 ) ); - this.addAttribute( 'position', positions ); - this.addAttribute( 'normal', normals ); - this.addAttribute( 'uv', uvs ); + function PointLightHelper( light, sphereSize ) { - this.boundingSphere = new Sphere( new Vector3(), radius ); + this.light = light; + this.light.updateMatrixWorld(); - }; + var geometry = new SphereBufferGeometry( sphereSize, 4, 2 ); + var material = new MeshBasicMaterial( { wireframe: true, fog: false } ); + material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); - SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); - SphereBufferGeometry.prototype.constructor = SphereBufferGeometry; + Mesh.call( this, geometry, material ); - /** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - */ + this.matrix = this.light.matrixWorld; + this.matrixAutoUpdate = false; - function PointLightHelper( light, sphereSize ) { + /* + var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 ); + var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } ); - this.light = light; - this.light.updateMatrixWorld(); + this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial ); + this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial ); - var geometry = new SphereBufferGeometry( sphereSize, 4, 2 ); - var material = new MeshBasicMaterial( { wireframe: true, fog: false } ); - material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); + var d = light.distance; - Mesh.call( this, geometry, material ); + if ( d === 0.0 ) { - this.matrix = this.light.matrixWorld; - this.matrixAutoUpdate = false; + this.lightDistance.visible = false; - /* - var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 ); - var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } ); + } else { - this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial ); - this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial ); + this.lightDistance.scale.set( d, d, d ); - var d = light.distance; + } - if ( d === 0.0 ) { + this.add( this.lightDistance ); + */ - this.lightDistance.visible = false; + } - } else { + PointLightHelper.prototype = Object.create( Mesh.prototype ); + PointLightHelper.prototype.constructor = PointLightHelper; - this.lightDistance.scale.set( d, d, d ); + PointLightHelper.prototype.dispose = function () { - } + this.geometry.dispose(); + this.material.dispose(); - this.add( this.lightDistance ); - */ + }; - }; + PointLightHelper.prototype.update = function () { - PointLightHelper.prototype = Object.create( Mesh.prototype ); - PointLightHelper.prototype.constructor = PointLightHelper; + this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); - PointLightHelper.prototype.dispose = function () { + /* + var d = this.light.distance; - this.geometry.dispose(); - this.material.dispose(); + if ( d === 0.0 ) { - }; + this.lightDistance.visible = false; - PointLightHelper.prototype.update = function () { + } else { - this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); + this.lightDistance.visible = true; + this.lightDistance.scale.set( d, d, d ); - /* - var d = this.light.distance; + } + */ - if ( d === 0.0 ) { + }; - this.lightDistance.visible = false; + /** + * @author mrdoob / http://mrdoob.com/ + */ - } else { + function SphereGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) { - this.lightDistance.visible = true; - this.lightDistance.scale.set( d, d, d ); + Geometry.call( this ); - } - */ + this.type = 'SphereGeometry'; - }; + this.parameters = { + radius: radius, + widthSegments: widthSegments, + heightSegments: heightSegments, + phiStart: phiStart, + phiLength: phiLength, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - /** - * @author mrdoob / http://mrdoob.com/ - */ + this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) ); - function SphereGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) { + } - Geometry.call( this ); + SphereGeometry.prototype = Object.create( Geometry.prototype ); + SphereGeometry.prototype.constructor = SphereGeometry; - this.type = 'SphereGeometry'; + /** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + */ - this.parameters = { - radius: radius, - widthSegments: widthSegments, - heightSegments: heightSegments, - phiStart: phiStart, - phiLength: phiLength, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + function HemisphereLightHelper( light, sphereSize ) { - this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) ); + Object3D.call( this ); - }; + this.light = light; + this.light.updateMatrixWorld(); - SphereGeometry.prototype = Object.create( Geometry.prototype ); - SphereGeometry.prototype.constructor = SphereGeometry; + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; - /** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - */ + this.colors = [ new Color(), new Color() ]; - function HemisphereLightHelper( light, sphereSize ) { + var geometry = new SphereGeometry( sphereSize, 4, 2 ); + geometry.rotateX( - Math.PI / 2 ); - Object3D.call( this ); + for ( var i = 0, il = 8; i < il; i ++ ) { - this.light = light; - this.light.updateMatrixWorld(); + geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ]; - this.matrix = light.matrixWorld; - this.matrixAutoUpdate = false; + } - this.colors = [ new Color(), new Color() ]; + var material = new MeshBasicMaterial( { vertexColors: FaceColors, wireframe: true } ); - var geometry = new SphereGeometry( sphereSize, 4, 2 ); - geometry.rotateX( - Math.PI / 2 ); + this.lightSphere = new Mesh( geometry, material ); + this.add( this.lightSphere ); - for ( var i = 0, il = 8; i < il; i ++ ) { + this.update(); - geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ]; + } - } + HemisphereLightHelper.prototype = Object.create( Object3D.prototype ); + HemisphereLightHelper.prototype.constructor = HemisphereLightHelper; - var material = new MeshBasicMaterial( { vertexColors: FaceColors, wireframe: true } ); + HemisphereLightHelper.prototype.dispose = function () { - this.lightSphere = new Mesh( geometry, material ); - this.add( this.lightSphere ); + this.lightSphere.geometry.dispose(); + this.lightSphere.material.dispose(); - this.update(); + }; - }; + HemisphereLightHelper.prototype.update = function () { - HemisphereLightHelper.prototype = Object.create( Object3D.prototype ); - HemisphereLightHelper.prototype.constructor = HemisphereLightHelper; + var vector = new Vector3(); - HemisphereLightHelper.prototype.dispose = function () { + return function update() { - this.lightSphere.geometry.dispose(); - this.lightSphere.material.dispose(); + this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity ); + this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity ); - }; + this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() ); + this.lightSphere.geometry.colorsNeedUpdate = true; - HemisphereLightHelper.prototype.update = function () { + }; - var vector = new Vector3(); + }(); - return function update() { + /** + * @author mrdoob / http://mrdoob.com/ + */ - this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity ); - this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity ); + function GridHelper( size, divisions, color1, color2 ) { - this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() ); - this.lightSphere.geometry.colorsNeedUpdate = true; + divisions = divisions || 1; + color1 = new Color( color1 !== undefined ? color1 : 0x444444 ); + color2 = new Color( color2 !== undefined ? color2 : 0x888888 ); - }; + var center = divisions / 2; + var step = ( size * 2 ) / divisions; + var vertices = [], colors = []; - }(); + for ( var i = 0, j = 0, k = - size; i <= divisions; i ++, k += step ) { - /** - * @author mrdoob / http://mrdoob.com/ - */ + vertices.push( - size, 0, k, size, 0, k ); + vertices.push( k, 0, - size, k, 0, size ); - function GridHelper( size, divisions, color1, color2 ) { + var color = i === center ? color1 : color2; - divisions = divisions || 1; - color1 = new Color( color1 !== undefined ? color1 : 0x444444 ); - color2 = new Color( color2 !== undefined ? color2 : 0x888888 ); + color.toArray( colors, j ); j += 3; + color.toArray( colors, j ); j += 3; + color.toArray( colors, j ); j += 3; + color.toArray( colors, j ); j += 3; - var center = divisions / 2; - var step = ( size * 2 ) / divisions; - var vertices = [], colors = []; + } - for ( var i = 0, j = 0, k = - size; i <= divisions; i ++, k += step ) { + var geometry = new BufferGeometry(); + geometry.addAttribute( 'position', new Float32Attribute( vertices, 3 ) ); + geometry.addAttribute( 'color', new Float32Attribute( colors, 3 ) ); - vertices.push( - size, 0, k, size, 0, k ); - vertices.push( k, 0, - size, k, 0, size ); + var material = new LineBasicMaterial( { vertexColors: VertexColors } ); - var color = i === center ? color1 : color2; + LineSegments.call( this, geometry, material ); - color.toArray( colors, j ); j += 3; - color.toArray( colors, j ); j += 3; - color.toArray( colors, j ); j += 3; - color.toArray( colors, j ); j += 3; + } - } + GridHelper.prototype = Object.create( LineSegments.prototype ); + GridHelper.prototype.constructor = GridHelper; - var geometry = new BufferGeometry(); - geometry.addAttribute( 'position', new Float32Attribute( vertices, 3 ) ); - geometry.addAttribute( 'color', new Float32Attribute( colors, 3 ) ); + GridHelper.prototype.setColors = function () { - var material = new LineBasicMaterial( { vertexColors: VertexColors } ); + console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' ); - LineSegments.call( this, geometry, material ); + }; - }; + /** + * @author mrdoob / http://mrdoob.com/ + * @author WestLangley / http://github.com/WestLangley + */ - GridHelper.prototype = Object.create( LineSegments.prototype ); - GridHelper.prototype.constructor = GridHelper; + function FaceNormalsHelper( object, size, hex, linewidth ) { - GridHelper.prototype.setColors = function () { + // FaceNormalsHelper only supports THREE.Geometry - console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' ); + this.object = object; - }; + this.size = ( size !== undefined ) ? size : 1; - /** - * @author mrdoob / http://mrdoob.com/ - * @author WestLangley / http://github.com/WestLangley - */ + var color = ( hex !== undefined ) ? hex : 0xffff00; - function FaceNormalsHelper( object, size, hex, linewidth ) { + var width = ( linewidth !== undefined ) ? linewidth : 1; - // FaceNormalsHelper only supports THREE.Geometry + // - this.object = object; + var nNormals = 0; - this.size = ( size !== undefined ) ? size : 1; + var objGeometry = this.object.geometry; - var color = ( hex !== undefined ) ? hex : 0xffff00; + if ( (objGeometry && objGeometry.isGeometry) ) { - var width = ( linewidth !== undefined ) ? linewidth : 1; + nNormals = objGeometry.faces.length; - // + } else { - var nNormals = 0; + console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' ); - var objGeometry = this.object.geometry; + } - if ( (objGeometry && objGeometry.isGeometry) ) { + // - nNormals = objGeometry.faces.length; + var geometry = new BufferGeometry(); - } else { + var positions = new Float32Attribute( nNormals * 2 * 3, 3 ); - console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' ); + geometry.addAttribute( 'position', positions ); - } + LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) ); - // + // - var geometry = new BufferGeometry(); + this.matrixAutoUpdate = false; + this.update(); - var positions = new Float32Attribute( nNormals * 2 * 3, 3 ); + } - geometry.addAttribute( 'position', positions ); + FaceNormalsHelper.prototype = Object.create( LineSegments.prototype ); + FaceNormalsHelper.prototype.constructor = FaceNormalsHelper; - LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) ); + FaceNormalsHelper.prototype.update = ( function () { - // + var v1 = new Vector3(); + var v2 = new Vector3(); + var normalMatrix = new Matrix3(); - this.matrixAutoUpdate = false; - this.update(); + return function update() { - }; + this.object.updateMatrixWorld( true ); - FaceNormalsHelper.prototype = Object.create( LineSegments.prototype ); - FaceNormalsHelper.prototype.constructor = FaceNormalsHelper; + normalMatrix.getNormalMatrix( this.object.matrixWorld ); - FaceNormalsHelper.prototype.update = ( function () { + var matrixWorld = this.object.matrixWorld; - var v1 = new Vector3(); - var v2 = new Vector3(); - var normalMatrix = new Matrix3(); + var position = this.geometry.attributes.position; - return function update() { + // - this.object.updateMatrixWorld( true ); + var objGeometry = this.object.geometry; - normalMatrix.getNormalMatrix( this.object.matrixWorld ); + var vertices = objGeometry.vertices; - var matrixWorld = this.object.matrixWorld; + var faces = objGeometry.faces; - var position = this.geometry.attributes.position; + var idx = 0; - // + for ( var i = 0, l = faces.length; i < l; i ++ ) { - var objGeometry = this.object.geometry; + var face = faces[ i ]; - var vertices = objGeometry.vertices; + var normal = face.normal; - var faces = objGeometry.faces; + v1.copy( vertices[ face.a ] ) + .add( vertices[ face.b ] ) + .add( vertices[ face.c ] ) + .divideScalar( 3 ) + .applyMatrix4( matrixWorld ); - var idx = 0; + v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 ); - for ( var i = 0, l = faces.length; i < l; i ++ ) { + position.setXYZ( idx, v1.x, v1.y, v1.z ); - var face = faces[ i ]; + idx = idx + 1; - var normal = face.normal; + position.setXYZ( idx, v2.x, v2.y, v2.z ); - v1.copy( vertices[ face.a ] ) - .add( vertices[ face.b ] ) - .add( vertices[ face.c ] ) - .divideScalar( 3 ) - .applyMatrix4( matrixWorld ); + idx = idx + 1; - v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 ); + } - position.setXYZ( idx, v1.x, v1.y, v1.z ); + position.needsUpdate = true; - idx = idx + 1; + return this; - position.setXYZ( idx, v2.x, v2.y, v2.z ); + }; - idx = idx + 1; + }() ); - } + /** + * @author WestLangley / http://github.com/WestLangley + */ - position.needsUpdate = true; + function EdgesGeometry( geometry, thresholdAngle ) { - return this; + BufferGeometry.call( this ); - }; + thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1; - }() ); + var thresholdDot = Math.cos( exports.Math.DEG2RAD * thresholdAngle ); - /** - * @author WestLangley / http://github.com/WestLangley - */ + var edge = [ 0, 0 ], hash = {}; - function EdgesGeometry( geometry, thresholdAngle ) { + function sortFunction( a, b ) { - BufferGeometry.call( this ); + return a - b; - thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1; + } - var thresholdDot = Math.cos( exports.Math.DEG2RAD * thresholdAngle ); + var keys = [ 'a', 'b', 'c' ]; - var edge = [ 0, 0 ], hash = {}; + var geometry2; - function sortFunction( a, b ) { + if ( (geometry && geometry.isBufferGeometry) ) { - return a - b; + geometry2 = new Geometry(); + geometry2.fromBufferGeometry( geometry ); - } + } else { - var keys = [ 'a', 'b', 'c' ]; + geometry2 = geometry.clone(); - var geometry2; + } - if ( (geometry && geometry.isBufferGeometry) ) { + geometry2.mergeVertices(); + geometry2.computeFaceNormals(); - geometry2 = new Geometry(); - geometry2.fromBufferGeometry( geometry ); + var vertices = geometry2.vertices; + var faces = geometry2.faces; - } else { + for ( var i = 0, l = faces.length; i < l; i ++ ) { - geometry2 = geometry.clone(); + var face = faces[ i ]; - } + for ( var j = 0; j < 3; j ++ ) { - geometry2.mergeVertices(); - geometry2.computeFaceNormals(); + edge[ 0 ] = face[ keys[ j ] ]; + edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ]; + edge.sort( sortFunction ); - var vertices = geometry2.vertices; - var faces = geometry2.faces; + var key = edge.toString(); - for ( var i = 0, l = faces.length; i < l; i ++ ) { + if ( hash[ key ] === undefined ) { - var face = faces[ i ]; + hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined }; - for ( var j = 0; j < 3; j ++ ) { + } else { - edge[ 0 ] = face[ keys[ j ] ]; - edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ]; - edge.sort( sortFunction ); + hash[ key ].face2 = i; - var key = edge.toString(); + } - if ( hash[ key ] === undefined ) { + } - hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined }; + } - } else { + var coords = []; - hash[ key ].face2 = i; + for ( var key in hash ) { - } + var h = hash[ key ]; - } + if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) <= thresholdDot ) { - } + var vertex = vertices[ h.vert1 ]; + coords.push( vertex.x ); + coords.push( vertex.y ); + coords.push( vertex.z ); - var coords = []; + vertex = vertices[ h.vert2 ]; + coords.push( vertex.x ); + coords.push( vertex.y ); + coords.push( vertex.z ); - for ( var key in hash ) { + } - var h = hash[ key ]; + } - if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) <= thresholdDot ) { + this.addAttribute( 'position', new BufferAttribute( new Float32Array( coords ), 3 ) ); - var vertex = vertices[ h.vert1 ]; - coords.push( vertex.x ); - coords.push( vertex.y ); - coords.push( vertex.z ); + } - vertex = vertices[ h.vert2 ]; - coords.push( vertex.x ); - coords.push( vertex.y ); - coords.push( vertex.z ); + EdgesGeometry.prototype = Object.create( BufferGeometry.prototype ); + EdgesGeometry.prototype.constructor = EdgesGeometry; - } + /** + * @author WestLangley / http://github.com/WestLangley + * @param object THREE.Mesh whose geometry will be used + * @param hex line color + * @param thresholdAngle the minimum angle (in degrees), + * between the face normals of adjacent faces, + * that is required to render an edge. A value of 10 means + * an edge is only rendered if the angle is at least 10 degrees. + */ - } + function EdgesHelper( object, hex, thresholdAngle ) { - this.addAttribute( 'position', new BufferAttribute( new Float32Array( coords ), 3 ) ); + var color = ( hex !== undefined ) ? hex : 0xffffff; - }; + LineSegments.call( this, new EdgesGeometry( object.geometry, thresholdAngle ), new LineBasicMaterial( { color: color } ) ); - EdgesGeometry.prototype = Object.create( BufferGeometry.prototype ); - EdgesGeometry.prototype.constructor = EdgesGeometry; + this.matrix = object.matrixWorld; + this.matrixAutoUpdate = false; - /** - * @author WestLangley / http://github.com/WestLangley - * @param object THREE.Mesh whose geometry will be used - * @param hex line color - * @param thresholdAngle the minimum angle (in degrees), - * between the face normals of adjacent faces, - * that is required to render an edge. A value of 10 means - * an edge is only rendered if the angle is at least 10 degrees. - */ + } - function EdgesHelper( object, hex, thresholdAngle ) { + EdgesHelper.prototype = Object.create( LineSegments.prototype ); + EdgesHelper.prototype.constructor = EdgesHelper; - var color = ( hex !== undefined ) ? hex : 0xffffff; + /** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + * @author WestLangley / http://github.com/WestLangley + */ - LineSegments.call( this, new EdgesGeometry( object.geometry, thresholdAngle ), new LineBasicMaterial( { color: color } ) ); + function DirectionalLightHelper( light, size ) { - this.matrix = object.matrixWorld; - this.matrixAutoUpdate = false; + Object3D.call( this ); - }; + this.light = light; + this.light.updateMatrixWorld(); - EdgesHelper.prototype = Object.create( LineSegments.prototype ); - EdgesHelper.prototype.constructor = EdgesHelper; + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; - /** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - * @author WestLangley / http://github.com/WestLangley - */ + if ( size === undefined ) size = 1; - function DirectionalLightHelper( light, size ) { + var geometry = new BufferGeometry(); + geometry.addAttribute( 'position', new Float32Attribute( [ + - size, size, 0, + size, size, 0, + size, - size, 0, + - size, - size, 0, + - size, size, 0 + ], 3 ) ); - Object3D.call( this ); + var material = new LineBasicMaterial( { fog: false } ); - this.light = light; - this.light.updateMatrixWorld(); + this.add( new Line( geometry, material ) ); - this.matrix = light.matrixWorld; - this.matrixAutoUpdate = false; + geometry = new BufferGeometry(); + geometry.addAttribute( 'position', new Float32Attribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) ); - if ( size === undefined ) size = 1; + this.add( new Line( geometry, material )); - var geometry = new BufferGeometry(); - geometry.addAttribute( 'position', new Float32Attribute( [ - - size, size, 0, - size, size, 0, - size, - size, 0, - - size, - size, 0, - - size, size, 0 - ], 3 ) ); + this.update(); - var material = new LineBasicMaterial( { fog: false } ); + } - this.add( new Line( geometry, material ) ); + DirectionalLightHelper.prototype = Object.create( Object3D.prototype ); + DirectionalLightHelper.prototype.constructor = DirectionalLightHelper; - geometry = new BufferGeometry(); - geometry.addAttribute( 'position', new Float32Attribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) ); + DirectionalLightHelper.prototype.dispose = function () { - this.add( new Line( geometry, material )); + var lightPlane = this.children[ 0 ]; + var targetLine = this.children[ 1 ]; - this.update(); + lightPlane.geometry.dispose(); + lightPlane.material.dispose(); + targetLine.geometry.dispose(); + targetLine.material.dispose(); - }; + }; - DirectionalLightHelper.prototype = Object.create( Object3D.prototype ); - DirectionalLightHelper.prototype.constructor = DirectionalLightHelper; + DirectionalLightHelper.prototype.update = function () { - DirectionalLightHelper.prototype.dispose = function () { + var v1 = new Vector3(); + var v2 = new Vector3(); + var v3 = new Vector3(); - var lightPlane = this.children[ 0 ]; - var targetLine = this.children[ 1 ]; + return function update() { - lightPlane.geometry.dispose(); - lightPlane.material.dispose(); - targetLine.geometry.dispose(); - targetLine.material.dispose(); + v1.setFromMatrixPosition( this.light.matrixWorld ); + v2.setFromMatrixPosition( this.light.target.matrixWorld ); + v3.subVectors( v2, v1 ); - }; + var lightPlane = this.children[ 0 ]; + var targetLine = this.children[ 1 ]; - DirectionalLightHelper.prototype.update = function () { + lightPlane.lookAt( v3 ); + lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); - var v1 = new Vector3(); - var v2 = new Vector3(); - var v3 = new Vector3(); + targetLine.lookAt( v3 ); + targetLine.scale.z = v3.length(); - return function update() { + }; - v1.setFromMatrixPosition( this.light.matrixWorld ); - v2.setFromMatrixPosition( this.light.target.matrixWorld ); - v3.subVectors( v2, v1 ); + }(); - var lightPlane = this.children[ 0 ]; - var targetLine = this.children[ 1 ]; + /** + * @author alteredq / http://alteredqualia.com/ + * + * - shows frustum, line of sight and up of the camera + * - suitable for fast updates + * - based on frustum visualization in lightgl.js shadowmap example + * http://evanw.github.com/lightgl.js/tests/shadowmap.html + */ - lightPlane.lookAt( v3 ); - lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); + function CameraHelper( camera ) { - targetLine.lookAt( v3 ); - targetLine.scale.z = v3.length(); + var geometry = new Geometry(); + var material = new LineBasicMaterial( { color: 0xffffff, vertexColors: FaceColors } ); - }; + var pointMap = {}; - }(); + // colors - /** - * @author alteredq / http://alteredqualia.com/ - * - * - shows frustum, line of sight and up of the camera - * - suitable for fast updates - * - based on frustum visualization in lightgl.js shadowmap example - * http://evanw.github.com/lightgl.js/tests/shadowmap.html - */ + var hexFrustum = 0xffaa00; + var hexCone = 0xff0000; + var hexUp = 0x00aaff; + var hexTarget = 0xffffff; + var hexCross = 0x333333; - function CameraHelper( camera ) { + // near - var geometry = new Geometry(); - var material = new LineBasicMaterial( { color: 0xffffff, vertexColors: FaceColors } ); + addLine( "n1", "n2", hexFrustum ); + addLine( "n2", "n4", hexFrustum ); + addLine( "n4", "n3", hexFrustum ); + addLine( "n3", "n1", hexFrustum ); - var pointMap = {}; + // far - // colors + addLine( "f1", "f2", hexFrustum ); + addLine( "f2", "f4", hexFrustum ); + addLine( "f4", "f3", hexFrustum ); + addLine( "f3", "f1", hexFrustum ); - var hexFrustum = 0xffaa00; - var hexCone = 0xff0000; - var hexUp = 0x00aaff; - var hexTarget = 0xffffff; - var hexCross = 0x333333; + // sides - // near + addLine( "n1", "f1", hexFrustum ); + addLine( "n2", "f2", hexFrustum ); + addLine( "n3", "f3", hexFrustum ); + addLine( "n4", "f4", hexFrustum ); - addLine( "n1", "n2", hexFrustum ); - addLine( "n2", "n4", hexFrustum ); - addLine( "n4", "n3", hexFrustum ); - addLine( "n3", "n1", hexFrustum ); + // cone - // far + addLine( "p", "n1", hexCone ); + addLine( "p", "n2", hexCone ); + addLine( "p", "n3", hexCone ); + addLine( "p", "n4", hexCone ); - addLine( "f1", "f2", hexFrustum ); - addLine( "f2", "f4", hexFrustum ); - addLine( "f4", "f3", hexFrustum ); - addLine( "f3", "f1", hexFrustum ); + // up - // sides + addLine( "u1", "u2", hexUp ); + addLine( "u2", "u3", hexUp ); + addLine( "u3", "u1", hexUp ); - addLine( "n1", "f1", hexFrustum ); - addLine( "n2", "f2", hexFrustum ); - addLine( "n3", "f3", hexFrustum ); - addLine( "n4", "f4", hexFrustum ); + // target - // cone + addLine( "c", "t", hexTarget ); + addLine( "p", "c", hexCross ); - addLine( "p", "n1", hexCone ); - addLine( "p", "n2", hexCone ); - addLine( "p", "n3", hexCone ); - addLine( "p", "n4", hexCone ); + // cross - // up + addLine( "cn1", "cn2", hexCross ); + addLine( "cn3", "cn4", hexCross ); - addLine( "u1", "u2", hexUp ); - addLine( "u2", "u3", hexUp ); - addLine( "u3", "u1", hexUp ); + addLine( "cf1", "cf2", hexCross ); + addLine( "cf3", "cf4", hexCross ); - // target + function addLine( a, b, hex ) { - addLine( "c", "t", hexTarget ); - addLine( "p", "c", hexCross ); + addPoint( a, hex ); + addPoint( b, hex ); - // cross + } - addLine( "cn1", "cn2", hexCross ); - addLine( "cn3", "cn4", hexCross ); + function addPoint( id, hex ) { - addLine( "cf1", "cf2", hexCross ); - addLine( "cf3", "cf4", hexCross ); + geometry.vertices.push( new Vector3() ); + geometry.colors.push( new Color( hex ) ); - function addLine( a, b, hex ) { + if ( pointMap[ id ] === undefined ) { - addPoint( a, hex ); - addPoint( b, hex ); + pointMap[ id ] = []; - } + } - function addPoint( id, hex ) { + pointMap[ id ].push( geometry.vertices.length - 1 ); - geometry.vertices.push( new Vector3() ); - geometry.colors.push( new Color( hex ) ); + } - if ( pointMap[ id ] === undefined ) { + LineSegments.call( this, geometry, material ); - pointMap[ id ] = []; + this.camera = camera; + if( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix(); - } + this.matrix = camera.matrixWorld; + this.matrixAutoUpdate = false; - pointMap[ id ].push( geometry.vertices.length - 1 ); + this.pointMap = pointMap; - } + this.update(); - LineSegments.call( this, geometry, material ); + } - this.camera = camera; - if( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix(); + CameraHelper.prototype = Object.create( LineSegments.prototype ); + CameraHelper.prototype.constructor = CameraHelper; - this.matrix = camera.matrixWorld; - this.matrixAutoUpdate = false; + CameraHelper.prototype.update = function () { - this.pointMap = pointMap; + var geometry, pointMap; - this.update(); + var vector = new Vector3(); + var camera = new Camera(); - }; + function setPoint( point, x, y, z ) { - CameraHelper.prototype = Object.create( LineSegments.prototype ); - CameraHelper.prototype.constructor = CameraHelper; + vector.set( x, y, z ).unproject( camera ); - CameraHelper.prototype.update = function () { + var points = pointMap[ point ]; - var geometry, pointMap; + if ( points !== undefined ) { - var vector = new Vector3(); - var camera = new Camera(); + for ( var i = 0, il = points.length; i < il; i ++ ) { - function setPoint( point, x, y, z ) { + geometry.vertices[ points[ i ] ].copy( vector ); - vector.set( x, y, z ).unproject( camera ); + } - var points = pointMap[ point ]; + } - if ( points !== undefined ) { + } - for ( var i = 0, il = points.length; i < il; i ++ ) { + return function update() { - geometry.vertices[ points[ i ] ].copy( vector ); + geometry = this.geometry; + pointMap = this.pointMap; - } + var w = 1, h = 1; - } + // we need just camera projection matrix + // world matrix must be identity - } + camera.projectionMatrix.copy( this.camera.projectionMatrix ); - return function update() { + // center / target - geometry = this.geometry; - pointMap = this.pointMap; + setPoint( "c", 0, 0, - 1 ); + setPoint( "t", 0, 0, 1 ); - var w = 1, h = 1; + // near - // we need just camera projection matrix - // world matrix must be identity + setPoint( "n1", - w, - h, - 1 ); + setPoint( "n2", w, - h, - 1 ); + setPoint( "n3", - w, h, - 1 ); + setPoint( "n4", w, h, - 1 ); - camera.projectionMatrix.copy( this.camera.projectionMatrix ); + // far - // center / target + setPoint( "f1", - w, - h, 1 ); + setPoint( "f2", w, - h, 1 ); + setPoint( "f3", - w, h, 1 ); + setPoint( "f4", w, h, 1 ); - setPoint( "c", 0, 0, - 1 ); - setPoint( "t", 0, 0, 1 ); + // up - // near + setPoint( "u1", w * 0.7, h * 1.1, - 1 ); + setPoint( "u2", - w * 0.7, h * 1.1, - 1 ); + setPoint( "u3", 0, h * 2, - 1 ); - setPoint( "n1", - w, - h, - 1 ); - setPoint( "n2", w, - h, - 1 ); - setPoint( "n3", - w, h, - 1 ); - setPoint( "n4", w, h, - 1 ); + // cross - // far + setPoint( "cf1", - w, 0, 1 ); + setPoint( "cf2", w, 0, 1 ); + setPoint( "cf3", 0, - h, 1 ); + setPoint( "cf4", 0, h, 1 ); - setPoint( "f1", - w, - h, 1 ); - setPoint( "f2", w, - h, 1 ); - setPoint( "f3", - w, h, 1 ); - setPoint( "f4", w, h, 1 ); + setPoint( "cn1", - w, 0, - 1 ); + setPoint( "cn2", w, 0, - 1 ); + setPoint( "cn3", 0, - h, - 1 ); + setPoint( "cn4", 0, h, - 1 ); - // up + geometry.verticesNeedUpdate = true; - setPoint( "u1", w * 0.7, h * 1.1, - 1 ); - setPoint( "u2", - w * 0.7, h * 1.1, - 1 ); - setPoint( "u3", 0, h * 2, - 1 ); + }; - // cross + }(); - setPoint( "cf1", - w, 0, 1 ); - setPoint( "cf2", w, 0, 1 ); - setPoint( "cf3", 0, - h, 1 ); - setPoint( "cf4", 0, h, 1 ); + /** + * @author mrdoob / http://mrdoob.com/ + * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as + */ - setPoint( "cn1", - w, 0, - 1 ); - setPoint( "cn2", w, 0, - 1 ); - setPoint( "cn3", 0, - h, - 1 ); - setPoint( "cn4", 0, h, - 1 ); + function BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) { - geometry.verticesNeedUpdate = true; + Geometry.call( this ); - }; + this.type = 'BoxGeometry'; - }(); + this.parameters = { + width: width, + height: height, + depth: depth, + widthSegments: widthSegments, + heightSegments: heightSegments, + depthSegments: depthSegments + }; - /** - * @author mrdoob / http://mrdoob.com/ - * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as - */ + this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) ); + this.mergeVertices(); - function BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) { + } - Geometry.call( this ); + BoxGeometry.prototype = Object.create( Geometry.prototype ); + BoxGeometry.prototype.constructor = BoxGeometry; - this.type = 'BoxGeometry'; + /** + * @author WestLangley / http://github.com/WestLangley + */ - this.parameters = { - width: width, - height: height, - depth: depth, - widthSegments: widthSegments, - heightSegments: heightSegments, - depthSegments: depthSegments - }; + // a helper to show the world-axis-aligned bounding box for an object - this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) ); - this.mergeVertices(); + function BoundingBoxHelper( object, hex ) { - }; + var color = ( hex !== undefined ) ? hex : 0x888888; - BoxGeometry.prototype = Object.create( Geometry.prototype ); - BoxGeometry.prototype.constructor = BoxGeometry; + this.object = object; - exports.CubeGeometry = BoxGeometry; + this.box = new Box3(); - /** - * @author WestLangley / http://github.com/WestLangley - */ + Mesh.call( this, new BoxGeometry( 1, 1, 1 ), new MeshBasicMaterial( { color: color, wireframe: true } ) ); - // a helper to show the world-axis-aligned bounding box for an object + } - function BoundingBoxHelper( object, hex ) { + BoundingBoxHelper.prototype = Object.create( Mesh.prototype ); + BoundingBoxHelper.prototype.constructor = BoundingBoxHelper; - var color = ( hex !== undefined ) ? hex : 0x888888; + BoundingBoxHelper.prototype.update = function () { - this.object = object; + this.box.setFromObject( this.object ); - this.box = new Box3(); + this.box.size( this.scale ); - Mesh.call( this, new BoxGeometry( 1, 1, 1 ), new MeshBasicMaterial( { color: color, wireframe: true } ) ); + this.box.center( this.position ); - }; + }; - BoundingBoxHelper.prototype = Object.create( Mesh.prototype ); - BoundingBoxHelper.prototype.constructor = BoundingBoxHelper; + /** + * @author mrdoob / http://mrdoob.com/ + */ - BoundingBoxHelper.prototype.update = function () { + function BoxHelper( object, color ) { - this.box.setFromObject( this.object ); + if ( color === undefined ) color = 0xffff00; - this.box.size( this.scale ); + var indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] ); + var positions = new Float32Array( 8 * 3 ); - this.box.center( this.position ); + var geometry = new BufferGeometry(); + geometry.setIndex( new BufferAttribute( indices, 1 ) ); + geometry.addAttribute( 'position', new BufferAttribute( positions, 3 ) ); - }; + LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) ); - /** - * @author mrdoob / http://mrdoob.com/ - */ + if ( object !== undefined ) { - function BoxHelper( object, color ) { + this.update( object ); - if ( color === undefined ) color = 0xffff00; + } - var indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] ); - var positions = new Float32Array( 8 * 3 ); + } - var geometry = new BufferGeometry(); - geometry.setIndex( new BufferAttribute( indices, 1 ) ); - geometry.addAttribute( 'position', new BufferAttribute( positions, 3 ) ); + BoxHelper.prototype = Object.create( LineSegments.prototype ); + BoxHelper.prototype.constructor = BoxHelper; - LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) ); + BoxHelper.prototype.update = ( function () { - if ( object !== undefined ) { + var box = new Box3(); - this.update( object ); + return function update( object ) { - } + if ( (object && object.isBox3) ) { - }; + box.copy( object ); - BoxHelper.prototype = Object.create( LineSegments.prototype ); - BoxHelper.prototype.constructor = BoxHelper; + } else { - BoxHelper.prototype.update = ( function () { + box.setFromObject( object ); - var box = new Box3(); + } - return function update( object ) { + if ( box.isEmpty() ) return; - if ( (object && object.isBox3) ) { + var min = box.min; + var max = box.max; - box.copy( object ); + /* + 5____4 + 1/___0/| + | 6__|_7 + 2/___3/ - } else { + 0: max.x, max.y, max.z + 1: min.x, max.y, max.z + 2: min.x, min.y, max.z + 3: max.x, min.y, max.z + 4: max.x, max.y, min.z + 5: min.x, max.y, min.z + 6: min.x, min.y, min.z + 7: max.x, min.y, min.z + */ - box.setFromObject( object ); + var position = this.geometry.attributes.position; + var array = position.array; - } + array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z; + array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z; + array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z; + array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z; + array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z; + array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z; + array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z; + array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z; - if ( box.isEmpty() ) return; + position.needsUpdate = true; - var min = box.min; - var max = box.max; + this.geometry.computeBoundingSphere(); - /* - 5____4 - 1/___0/| - | 6__|_7 - 2/___3/ + }; - 0: max.x, max.y, max.z - 1: min.x, max.y, max.z - 2: min.x, min.y, max.z - 3: max.x, min.y, max.z - 4: max.x, max.y, min.z - 5: min.x, max.y, min.z - 6: min.x, min.y, min.z - 7: max.x, min.y, min.z - */ + } )(); - var position = this.geometry.attributes.position; - var array = position.array; + /** + * @author Mugen87 / https://github.com/Mugen87 + */ - array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z; - array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z; - array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z; - array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z; - array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z; - array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z; - array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z; - array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z; + function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { - position.needsUpdate = true; + BufferGeometry.call( this ); - this.geometry.computeBoundingSphere(); + this.type = 'CylinderBufferGeometry'; - }; + this.parameters = { + radiusTop: radiusTop, + radiusBottom: radiusBottom, + height: height, + radialSegments: radialSegments, + heightSegments: heightSegments, + openEnded: openEnded, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - } )(); + var scope = this; - /** - * @author Mugen87 / https://github.com/Mugen87 - */ + radiusTop = radiusTop !== undefined ? radiusTop : 20; + radiusBottom = radiusBottom !== undefined ? radiusBottom : 20; + height = height !== undefined ? height : 100; - function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { + radialSegments = Math.floor( radialSegments ) || 8; + heightSegments = Math.floor( heightSegments ) || 1; - BufferGeometry.call( this ); + openEnded = openEnded !== undefined ? openEnded : false; + thetaStart = thetaStart !== undefined ? thetaStart : 0.0; + thetaLength = thetaLength !== undefined ? thetaLength : 2.0 * Math.PI; - this.type = 'CylinderBufferGeometry'; + // used to calculate buffer length - this.parameters = { - radiusTop: radiusTop, - radiusBottom: radiusBottom, - height: height, - radialSegments: radialSegments, - heightSegments: heightSegments, - openEnded: openEnded, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + var nbCap = 0; - var scope = this; + if ( openEnded === false ) { - radiusTop = radiusTop !== undefined ? radiusTop : 20; - radiusBottom = radiusBottom !== undefined ? radiusBottom : 20; - height = height !== undefined ? height : 100; + if ( radiusTop > 0 ) nbCap ++; + if ( radiusBottom > 0 ) nbCap ++; - radialSegments = Math.floor( radialSegments ) || 8; - heightSegments = Math.floor( heightSegments ) || 1; + } - openEnded = openEnded !== undefined ? openEnded : false; - thetaStart = thetaStart !== undefined ? thetaStart : 0.0; - thetaLength = thetaLength !== undefined ? thetaLength : 2.0 * Math.PI; + var vertexCount = calculateVertexCount(); + var indexCount = calculateIndexCount(); - // used to calculate buffer length + // buffers - var nbCap = 0; + var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ), 1 ); + var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); + var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); + var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); - if ( openEnded === false ) { + // helper variables - if ( radiusTop > 0 ) nbCap ++; - if ( radiusBottom > 0 ) nbCap ++; + var index = 0, + indexOffset = 0, + indexArray = [], + halfHeight = height / 2; - } + // group variables + var groupStart = 0; - var vertexCount = calculateVertexCount(); - var indexCount = calculateIndexCount(); + // generate geometry - // buffers + generateTorso(); - var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ), 1 ); - var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); - var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); - var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); + if ( openEnded === false ) { - // helper variables + if ( radiusTop > 0 ) generateCap( true ); + if ( radiusBottom > 0 ) generateCap( false ); - var index = 0, - indexOffset = 0, - indexArray = [], - halfHeight = height / 2; + } - // group variables - var groupStart = 0; + // build geometry - // generate geometry + this.setIndex( indices ); + this.addAttribute( 'position', vertices ); + this.addAttribute( 'normal', normals ); + this.addAttribute( 'uv', uvs ); - generateTorso(); + // helper functions - if ( openEnded === false ) { + function calculateVertexCount() { - if ( radiusTop > 0 ) generateCap( true ); - if ( radiusBottom > 0 ) generateCap( false ); + var count = ( radialSegments + 1 ) * ( heightSegments + 1 ); - } + if ( openEnded === false ) { - // build geometry + count += ( ( radialSegments + 1 ) * nbCap ) + ( radialSegments * nbCap ); - this.setIndex( indices ); - this.addAttribute( 'position', vertices ); - this.addAttribute( 'normal', normals ); - this.addAttribute( 'uv', uvs ); + } - // helper functions + return count; - function calculateVertexCount() { + } - var count = ( radialSegments + 1 ) * ( heightSegments + 1 ); + function calculateIndexCount() { - if ( openEnded === false ) { + var count = radialSegments * heightSegments * 2 * 3; - count += ( ( radialSegments + 1 ) * nbCap ) + ( radialSegments * nbCap ); + if ( openEnded === false ) { - } + count += radialSegments * nbCap * 3; - return count; + } - } + return count; - function calculateIndexCount() { + } - var count = radialSegments * heightSegments * 2 * 3; + function generateTorso() { - if ( openEnded === false ) { + var x, y; + var normal = new Vector3(); + var vertex = new Vector3(); - count += radialSegments * nbCap * 3; + var groupCount = 0; - } + // this will be used to calculate the normal + var tanTheta = ( radiusBottom - radiusTop ) / height; - return count; + // generate vertices, normals and uvs - } + for ( y = 0; y <= heightSegments; y ++ ) { - function generateTorso() { + var indexRow = []; - var x, y; - var normal = new Vector3(); - var vertex = new Vector3(); + var v = y / heightSegments; - var groupCount = 0; + // calculate the radius of the current row + var radius = v * ( radiusBottom - radiusTop ) + radiusTop; - // this will be used to calculate the normal - var tanTheta = ( radiusBottom - radiusTop ) / height; + for ( x = 0; x <= radialSegments; x ++ ) { - // generate vertices, normals and uvs + var u = x / radialSegments; - for ( y = 0; y <= heightSegments; y ++ ) { + // vertex + vertex.x = radius * Math.sin( u * thetaLength + thetaStart ); + vertex.y = - v * height + halfHeight; + vertex.z = radius * Math.cos( u * thetaLength + thetaStart ); + vertices.setXYZ( index, vertex.x, vertex.y, vertex.z ); - var indexRow = []; + // normal + normal.copy( vertex ); - var v = y / heightSegments; + // handle special case if radiusTop/radiusBottom is zero - // calculate the radius of the current row - var radius = v * ( radiusBottom - radiusTop ) + radiusTop; + if ( ( radiusTop === 0 && y === 0 ) || ( radiusBottom === 0 && y === heightSegments ) ) { - for ( x = 0; x <= radialSegments; x ++ ) { + normal.x = Math.sin( u * thetaLength + thetaStart ); + normal.z = Math.cos( u * thetaLength + thetaStart ); - var u = x / radialSegments; + } - // vertex - vertex.x = radius * Math.sin( u * thetaLength + thetaStart ); - vertex.y = - v * height + halfHeight; - vertex.z = radius * Math.cos( u * thetaLength + thetaStart ); - vertices.setXYZ( index, vertex.x, vertex.y, vertex.z ); + normal.setY( Math.sqrt( normal.x * normal.x + normal.z * normal.z ) * tanTheta ).normalize(); + normals.setXYZ( index, normal.x, normal.y, normal.z ); - // normal - normal.copy( vertex ); + // uv + uvs.setXY( index, u, 1 - v ); - // handle special case if radiusTop/radiusBottom is zero + // save index of vertex in respective row + indexRow.push( index ); - if ( ( radiusTop === 0 && y === 0 ) || ( radiusBottom === 0 && y === heightSegments ) ) { + // increase index + index ++; - normal.x = Math.sin( u * thetaLength + thetaStart ); - normal.z = Math.cos( u * thetaLength + thetaStart ); + } - } + // now save vertices of the row in our index array + indexArray.push( indexRow ); - normal.setY( Math.sqrt( normal.x * normal.x + normal.z * normal.z ) * tanTheta ).normalize(); - normals.setXYZ( index, normal.x, normal.y, normal.z ); + } - // uv - uvs.setXY( index, u, 1 - v ); + // generate indices - // save index of vertex in respective row - indexRow.push( index ); + for ( x = 0; x < radialSegments; x ++ ) { - // increase index - index ++; + for ( y = 0; y < heightSegments; y ++ ) { - } + // we use the index array to access the correct indices + var i1 = indexArray[ y ][ x ]; + var i2 = indexArray[ y + 1 ][ x ]; + var i3 = indexArray[ y + 1 ][ x + 1 ]; + var i4 = indexArray[ y ][ x + 1 ]; - // now save vertices of the row in our index array - indexArray.push( indexRow ); + // face one + indices.setX( indexOffset, i1 ); indexOffset ++; + indices.setX( indexOffset, i2 ); indexOffset ++; + indices.setX( indexOffset, i4 ); indexOffset ++; - } + // face two + indices.setX( indexOffset, i2 ); indexOffset ++; + indices.setX( indexOffset, i3 ); indexOffset ++; + indices.setX( indexOffset, i4 ); indexOffset ++; - // generate indices + // update counters + groupCount += 6; - for ( x = 0; x < radialSegments; x ++ ) { + } - for ( y = 0; y < heightSegments; y ++ ) { + } - // we use the index array to access the correct indices - var i1 = indexArray[ y ][ x ]; - var i2 = indexArray[ y + 1 ][ x ]; - var i3 = indexArray[ y + 1 ][ x + 1 ]; - var i4 = indexArray[ y ][ x + 1 ]; + // add a group to the geometry. this will ensure multi material support + scope.addGroup( groupStart, groupCount, 0 ); - // face one - indices.setX( indexOffset, i1 ); indexOffset ++; - indices.setX( indexOffset, i2 ); indexOffset ++; - indices.setX( indexOffset, i4 ); indexOffset ++; + // calculate new start value for groups + groupStart += groupCount; - // face two - indices.setX( indexOffset, i2 ); indexOffset ++; - indices.setX( indexOffset, i3 ); indexOffset ++; - indices.setX( indexOffset, i4 ); indexOffset ++; + } - // update counters - groupCount += 6; + function generateCap( top ) { - } + var x, centerIndexStart, centerIndexEnd; - } + var uv = new Vector2(); + var vertex = new Vector3(); - // add a group to the geometry. this will ensure multi material support - scope.addGroup( groupStart, groupCount, 0 ); + var groupCount = 0; - // calculate new start value for groups - groupStart += groupCount; + var radius = ( top === true ) ? radiusTop : radiusBottom; + var sign = ( top === true ) ? 1 : - 1; - } + // save the index of the first center vertex + centerIndexStart = index; - function generateCap( top ) { + // first we generate the center vertex data of the cap. + // because the geometry needs one set of uvs per face, + // we must generate a center vertex per face/segment - var x, centerIndexStart, centerIndexEnd; + for ( x = 1; x <= radialSegments; x ++ ) { - var uv = new Vector2(); - var vertex = new Vector3(); + // vertex + vertices.setXYZ( index, 0, halfHeight * sign, 0 ); - var groupCount = 0; + // normal + normals.setXYZ( index, 0, sign, 0 ); - var radius = ( top === true ) ? radiusTop : radiusBottom; - var sign = ( top === true ) ? 1 : - 1; + // uv + uv.x = 0.5; + uv.y = 0.5; - // save the index of the first center vertex - centerIndexStart = index; + uvs.setXY( index, uv.x, uv.y ); - // first we generate the center vertex data of the cap. - // because the geometry needs one set of uvs per face, - // we must generate a center vertex per face/segment + // increase index + index ++; - for ( x = 1; x <= radialSegments; x ++ ) { + } - // vertex - vertices.setXYZ( index, 0, halfHeight * sign, 0 ); + // save the index of the last center vertex + centerIndexEnd = index; - // normal - normals.setXYZ( index, 0, sign, 0 ); + // now we generate the surrounding vertices, normals and uvs - // uv - uv.x = 0.5; - uv.y = 0.5; + for ( x = 0; x <= radialSegments; x ++ ) { - uvs.setXY( index, uv.x, uv.y ); + var u = x / radialSegments; + var theta = u * thetaLength + thetaStart; - // increase index - index ++; + var cosTheta = Math.cos( theta ); + var sinTheta = Math.sin( theta ); - } + // vertex + vertex.x = radius * sinTheta; + vertex.y = halfHeight * sign; + vertex.z = radius * cosTheta; + vertices.setXYZ( index, vertex.x, vertex.y, vertex.z ); - // save the index of the last center vertex - centerIndexEnd = index; + // normal + normals.setXYZ( index, 0, sign, 0 ); - // now we generate the surrounding vertices, normals and uvs + // uv + uv.x = ( cosTheta * 0.5 ) + 0.5; + uv.y = ( sinTheta * 0.5 * sign ) + 0.5; + uvs.setXY( index, uv.x, uv.y ); - for ( x = 0; x <= radialSegments; x ++ ) { + // increase index + index ++; - var u = x / radialSegments; - var theta = u * thetaLength + thetaStart; + } - var cosTheta = Math.cos( theta ); - var sinTheta = Math.sin( theta ); + // generate indices - // vertex - vertex.x = radius * sinTheta; - vertex.y = halfHeight * sign; - vertex.z = radius * cosTheta; - vertices.setXYZ( index, vertex.x, vertex.y, vertex.z ); + for ( x = 0; x < radialSegments; x ++ ) { - // normal - normals.setXYZ( index, 0, sign, 0 ); + var c = centerIndexStart + x; + var i = centerIndexEnd + x; - // uv - uv.x = ( cosTheta * 0.5 ) + 0.5; - uv.y = ( sinTheta * 0.5 * sign ) + 0.5; - uvs.setXY( index, uv.x, uv.y ); + if ( top === true ) { - // increase index - index ++; + // face top + indices.setX( indexOffset, i ); indexOffset ++; + indices.setX( indexOffset, i + 1 ); indexOffset ++; + indices.setX( indexOffset, c ); indexOffset ++; - } + } else { - // generate indices + // face bottom + indices.setX( indexOffset, i + 1 ); indexOffset ++; + indices.setX( indexOffset, i ); indexOffset ++; + indices.setX( indexOffset, c ); indexOffset ++; - for ( x = 0; x < radialSegments; x ++ ) { + } - var c = centerIndexStart + x; - var i = centerIndexEnd + x; + // update counters + groupCount += 3; - if ( top === true ) { + } - // face top - indices.setX( indexOffset, i ); indexOffset ++; - indices.setX( indexOffset, i + 1 ); indexOffset ++; - indices.setX( indexOffset, c ); indexOffset ++; + // add a group to the geometry. this will ensure multi material support + scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 ); - } else { + // calculate new start value for groups + groupStart += groupCount; - // face bottom - indices.setX( indexOffset, i + 1 ); indexOffset ++; - indices.setX( indexOffset, i ); indexOffset ++; - indices.setX( indexOffset, c ); indexOffset ++; + } - } + } - // update counters - groupCount += 3; + CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry; - } + /** + * @author WestLangley / http://github.com/WestLangley + * @author zz85 / http://github.com/zz85 + * @author bhouston / http://clara.io + * + * Creates an arrow for visualizing directions + * + * Parameters: + * dir - Vector3 + * origin - Vector3 + * length - Number + * color - color in hex value + * headLength - Number + * headWidth - Number + */ - // add a group to the geometry. this will ensure multi material support - scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 ); + exports.ArrowHelper = ( function () { - // calculate new start value for groups - groupStart += groupCount; + var lineGeometry = new BufferGeometry(); + lineGeometry.addAttribute( 'position', new Float32Attribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) ); - } + var coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 ); + coneGeometry.translate( 0, - 0.5, 0 ); - }; + return function ArrowHelper( dir, origin, length, color, headLength, headWidth ) { - CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); - CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry; + // dir is assumed to be normalized - /** - * @author WestLangley / http://github.com/WestLangley - * @author zz85 / http://github.com/zz85 - * @author bhouston / http://clara.io - * - * Creates an arrow for visualizing directions - * - * Parameters: - * dir - Vector3 - * origin - Vector3 - * length - Number - * color - color in hex value - * headLength - Number - * headWidth - Number - */ + Object3D.call( this ); - exports.ArrowHelper = ( function () { + if ( color === undefined ) color = 0xffff00; + if ( length === undefined ) length = 1; + if ( headLength === undefined ) headLength = 0.2 * length; + if ( headWidth === undefined ) headWidth = 0.2 * headLength; - var lineGeometry = new BufferGeometry(); - lineGeometry.addAttribute( 'position', new Float32Attribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) ); + this.position.copy( origin ); - var coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 ); - coneGeometry.translate( 0, - 0.5, 0 ); + this.line = new Line( lineGeometry, new LineBasicMaterial( { color: color } ) ); + this.line.matrixAutoUpdate = false; + this.add( this.line ); - return function ArrowHelper( dir, origin, length, color, headLength, headWidth ) { + this.cone = new Mesh( coneGeometry, new MeshBasicMaterial( { color: color } ) ); + this.cone.matrixAutoUpdate = false; + this.add( this.cone ); - // dir is assumed to be normalized + this.setDirection( dir ); + this.setLength( length, headLength, headWidth ); - Object3D.call( this ); + }; - if ( color === undefined ) color = 0xffff00; - if ( length === undefined ) length = 1; - if ( headLength === undefined ) headLength = 0.2 * length; - if ( headWidth === undefined ) headWidth = 0.2 * headLength; + }() ); - this.position.copy( origin ); + exports.ArrowHelper.prototype = Object.create( Object3D.prototype ); + exports.ArrowHelper.prototype.constructor = exports.ArrowHelper; - this.line = new Line( lineGeometry, new LineBasicMaterial( { color: color } ) ); - this.line.matrixAutoUpdate = false; - this.add( this.line ); + exports.ArrowHelper.prototype.setDirection = ( function () { - this.cone = new Mesh( coneGeometry, new MeshBasicMaterial( { color: color } ) ); - this.cone.matrixAutoUpdate = false; - this.add( this.cone ); + var axis = new Vector3(); + var radians; - this.setDirection( dir ); - this.setLength( length, headLength, headWidth ); + return function setDirection( dir ) { - }; + // dir is assumed to be normalized - }() ); + if ( dir.y > 0.99999 ) { - exports.ArrowHelper.prototype = Object.create( Object3D.prototype ); - exports.ArrowHelper.prototype.constructor = exports.ArrowHelper; + this.quaternion.set( 0, 0, 0, 1 ); - exports.ArrowHelper.prototype.setDirection = ( function () { + } else if ( dir.y < - 0.99999 ) { - var axis = new Vector3(); - var radians; + this.quaternion.set( 1, 0, 0, 0 ); - return function setDirection( dir ) { + } else { - // dir is assumed to be normalized + axis.set( dir.z, 0, - dir.x ).normalize(); - if ( dir.y > 0.99999 ) { + radians = Math.acos( dir.y ); - this.quaternion.set( 0, 0, 0, 1 ); + this.quaternion.setFromAxisAngle( axis, radians ); - } else if ( dir.y < - 0.99999 ) { + } - this.quaternion.set( 1, 0, 0, 0 ); + }; - } else { + }() ); - axis.set( dir.z, 0, - dir.x ).normalize(); + exports.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) { - radians = Math.acos( dir.y ); + if ( headLength === undefined ) headLength = 0.2 * length; + if ( headWidth === undefined ) headWidth = 0.2 * headLength; - this.quaternion.setFromAxisAngle( axis, radians ); + this.line.scale.set( 1, Math.max( 0, length - headLength ), 1 ); + this.line.updateMatrix(); - } + this.cone.scale.set( headWidth, headLength, headWidth ); + this.cone.position.y = length; + this.cone.updateMatrix(); - }; + }; - }() ); + exports.ArrowHelper.prototype.setColor = function ( color ) { - exports.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) { + this.line.material.color.copy( color ); + this.cone.material.color.copy( color ); - if ( headLength === undefined ) headLength = 0.2 * length; - if ( headWidth === undefined ) headWidth = 0.2 * headLength; + }; - this.line.scale.set( 1, Math.max( 0, length - headLength ), 1 ); - this.line.updateMatrix(); + /** + * @author sroucheray / http://sroucheray.org/ + * @author mrdoob / http://mrdoob.com/ + */ - this.cone.scale.set( headWidth, headLength, headWidth ); - this.cone.position.y = length; - this.cone.updateMatrix(); + function AxisHelper( size ) { - }; + size = size || 1; - exports.ArrowHelper.prototype.setColor = function ( color ) { + var vertices = new Float32Array( [ + 0, 0, 0, size, 0, 0, + 0, 0, 0, 0, size, 0, + 0, 0, 0, 0, 0, size + ] ); - this.line.material.color.copy( color ); - this.cone.material.color.copy( color ); + var colors = new Float32Array( [ + 1, 0, 0, 1, 0.6, 0, + 0, 1, 0, 0.6, 1, 0, + 0, 0, 1, 0, 0.6, 1 + ] ); - }; + var geometry = new BufferGeometry(); + geometry.addAttribute( 'position', new BufferAttribute( vertices, 3 ) ); + geometry.addAttribute( 'color', new BufferAttribute( colors, 3 ) ); - /** - * @author sroucheray / http://sroucheray.org/ - * @author mrdoob / http://mrdoob.com/ - */ + var material = new LineBasicMaterial( { vertexColors: VertexColors } ); - function AxisHelper( size ) { + LineSegments.call( this, geometry, material ); - size = size || 1; + } - var vertices = new Float32Array( [ - 0, 0, 0, size, 0, 0, - 0, 0, 0, 0, size, 0, - 0, 0, 0, 0, 0, size - ] ); + AxisHelper.prototype = Object.create( LineSegments.prototype ); + AxisHelper.prototype.constructor = AxisHelper; - var colors = new Float32Array( [ - 1, 0, 0, 1, 0.6, 0, - 0, 1, 0, 0.6, 1, 0, - 0, 0, 1, 0, 0.6, 1 - ] ); + /** + * @author zz85 / https://github.com/zz85 + * Parametric Surfaces Geometry + * based on the brilliant article by @prideout http://prideout.net/blog/?p=44 + * + * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements ); + * + */ - var geometry = new BufferGeometry(); - geometry.addAttribute( 'position', new BufferAttribute( vertices, 3 ) ); - geometry.addAttribute( 'color', new BufferAttribute( colors, 3 ) ); + function ParametricGeometry( func, slices, stacks ) { - var material = new LineBasicMaterial( { vertexColors: VertexColors } ); + Geometry.call( this ); - LineSegments.call( this, geometry, material ); + this.type = 'ParametricGeometry'; - }; + this.parameters = { + func: func, + slices: slices, + stacks: stacks + }; - AxisHelper.prototype = Object.create( LineSegments.prototype ); - AxisHelper.prototype.constructor = AxisHelper; + var verts = this.vertices; + var faces = this.faces; + var uvs = this.faceVertexUvs[ 0 ]; - /** - * @author zz85 / https://github.com/zz85 - * Parametric Surfaces Geometry - * based on the brilliant article by @prideout http://prideout.net/blog/?p=44 - * - * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements ); - * - */ + var i, j, p; + var u, v; - function ParametricGeometry( func, slices, stacks ) { + var sliceCount = slices + 1; - Geometry.call( this ); + for ( i = 0; i <= stacks; i ++ ) { - this.type = 'ParametricGeometry'; + v = i / stacks; - this.parameters = { - func: func, - slices: slices, - stacks: stacks - }; + for ( j = 0; j <= slices; j ++ ) { - var verts = this.vertices; - var faces = this.faces; - var uvs = this.faceVertexUvs[ 0 ]; + u = j / slices; - var i, j, p; - var u, v; + p = func( u, v ); + verts.push( p ); - var sliceCount = slices + 1; + } - for ( i = 0; i <= stacks; i ++ ) { + } - v = i / stacks; + var a, b, c, d; + var uva, uvb, uvc, uvd; - for ( j = 0; j <= slices; j ++ ) { + for ( i = 0; i < stacks; i ++ ) { - u = j / slices; + for ( j = 0; j < slices; j ++ ) { - p = func( u, v ); - verts.push( p ); + a = i * sliceCount + j; + b = i * sliceCount + j + 1; + c = ( i + 1 ) * sliceCount + j + 1; + d = ( i + 1 ) * sliceCount + j; - } + uva = new Vector2( j / slices, i / stacks ); + uvb = new Vector2( ( j + 1 ) / slices, i / stacks ); + uvc = new Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks ); + uvd = new Vector2( j / slices, ( i + 1 ) / stacks ); - } + faces.push( new Face3( a, b, d ) ); + uvs.push( [ uva, uvb, uvd ] ); - var a, b, c, d; - var uva, uvb, uvc, uvd; + faces.push( new Face3( b, c, d ) ); + uvs.push( [ uvb.clone(), uvc, uvd.clone() ] ); - for ( i = 0; i < stacks; i ++ ) { + } - for ( j = 0; j < slices; j ++ ) { + } - a = i * sliceCount + j; - b = i * sliceCount + j + 1; - c = ( i + 1 ) * sliceCount + j + 1; - d = ( i + 1 ) * sliceCount + j; + // console.log(this); - uva = new Vector2( j / slices, i / stacks ); - uvb = new Vector2( ( j + 1 ) / slices, i / stacks ); - uvc = new Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks ); - uvd = new Vector2( j / slices, ( i + 1 ) / stacks ); + // magic bullet + // var diff = this.mergeVertices(); + // console.log('removed ', diff, ' vertices by merging'); - faces.push( new Face3( a, b, d ) ); - uvs.push( [ uva, uvb, uvd ] ); + this.computeFaceNormals(); + this.computeVertexNormals(); - faces.push( new Face3( b, c, d ) ); - uvs.push( [ uvb.clone(), uvc, uvd.clone() ] ); + } - } + ParametricGeometry.prototype = Object.create( Geometry.prototype ); + ParametricGeometry.prototype.constructor = ParametricGeometry; - } + /** + * @author clockworkgeek / https://github.com/clockworkgeek + * @author timothypratley / https://github.com/timothypratley + * @author WestLangley / http://github.com/WestLangley + */ - // console.log(this); + function PolyhedronGeometry( vertices, indices, radius, detail ) { - // magic bullet - // var diff = this.mergeVertices(); - // console.log('removed ', diff, ' vertices by merging'); + Geometry.call( this ); - this.computeFaceNormals(); - this.computeVertexNormals(); + this.type = 'PolyhedronGeometry'; - }; + this.parameters = { + vertices: vertices, + indices: indices, + radius: radius, + detail: detail + }; - ParametricGeometry.prototype = Object.create( Geometry.prototype ); - ParametricGeometry.prototype.constructor = ParametricGeometry; + radius = radius || 1; + detail = detail || 0; - /** - * @author clockworkgeek / https://github.com/clockworkgeek - * @author timothypratley / https://github.com/timothypratley - * @author WestLangley / http://github.com/WestLangley - */ + var that = this; - function PolyhedronGeometry( vertices, indices, radius, detail ) { + for ( var i = 0, l = vertices.length; i < l; i += 3 ) { - Geometry.call( this ); + prepare( new Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) ); - this.type = 'PolyhedronGeometry'; + } - this.parameters = { - vertices: vertices, - indices: indices, - radius: radius, - detail: detail - }; + var p = this.vertices; - radius = radius || 1; - detail = detail || 0; + var faces = []; - var that = this; + for ( var i = 0, j = 0, l = indices.length; i < l; i += 3, j ++ ) { - for ( var i = 0, l = vertices.length; i < l; i += 3 ) { + var v1 = p[ indices[ i ] ]; + var v2 = p[ indices[ i + 1 ] ]; + var v3 = p[ indices[ i + 2 ] ]; - prepare( new Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) ); + faces[ j ] = new Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] ); - } + } - var p = this.vertices; + var centroid = new Vector3(); - var faces = []; + for ( var i = 0, l = faces.length; i < l; i ++ ) { - for ( var i = 0, j = 0, l = indices.length; i < l; i += 3, j ++ ) { + subdivide( faces[ i ], detail ); - var v1 = p[ indices[ i ] ]; - var v2 = p[ indices[ i + 1 ] ]; - var v3 = p[ indices[ i + 2 ] ]; + } - faces[ j ] = new Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] ); - } + // Handle case when face straddles the seam - var centroid = new Vector3(); + for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) { - for ( var i = 0, l = faces.length; i < l; i ++ ) { + var uvs = this.faceVertexUvs[ 0 ][ i ]; - subdivide( faces[ i ], detail ); + var x0 = uvs[ 0 ].x; + var x1 = uvs[ 1 ].x; + var x2 = uvs[ 2 ].x; - } + var max = Math.max( x0, x1, x2 ); + var min = Math.min( x0, x1, x2 ); + if ( max > 0.9 && min < 0.1 ) { - // Handle case when face straddles the seam + // 0.9 is somewhat arbitrary - for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) { + if ( x0 < 0.2 ) uvs[ 0 ].x += 1; + if ( x1 < 0.2 ) uvs[ 1 ].x += 1; + if ( x2 < 0.2 ) uvs[ 2 ].x += 1; - var uvs = this.faceVertexUvs[ 0 ][ i ]; + } - var x0 = uvs[ 0 ].x; - var x1 = uvs[ 1 ].x; - var x2 = uvs[ 2 ].x; + } - var max = Math.max( x0, x1, x2 ); - var min = Math.min( x0, x1, x2 ); - if ( max > 0.9 && min < 0.1 ) { + // Apply radius - // 0.9 is somewhat arbitrary + for ( var i = 0, l = this.vertices.length; i < l; i ++ ) { - if ( x0 < 0.2 ) uvs[ 0 ].x += 1; - if ( x1 < 0.2 ) uvs[ 1 ].x += 1; - if ( x2 < 0.2 ) uvs[ 2 ].x += 1; + this.vertices[ i ].multiplyScalar( radius ); - } + } - } + // Merge vertices - // Apply radius + this.mergeVertices(); - for ( var i = 0, l = this.vertices.length; i < l; i ++ ) { + this.computeFaceNormals(); - this.vertices[ i ].multiplyScalar( radius ); + this.boundingSphere = new Sphere( new Vector3(), radius ); - } + // Project vector onto sphere's surface - // Merge vertices + function prepare( vector ) { - this.mergeVertices(); + var vertex = vector.normalize().clone(); + vertex.index = that.vertices.push( vertex ) - 1; - this.computeFaceNormals(); + // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle. - this.boundingSphere = new Sphere( new Vector3(), radius ); + var u = azimuth( vector ) / 2 / Math.PI + 0.5; + var v = inclination( vector ) / Math.PI + 0.5; + vertex.uv = new Vector2( u, 1 - v ); + return vertex; - // Project vector onto sphere's surface + } - function prepare( vector ) { - var vertex = vector.normalize().clone(); - vertex.index = that.vertices.push( vertex ) - 1; + // Approximate a curved face with recursively sub-divided triangles. - // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle. + function make( v1, v2, v3 ) { - var u = azimuth( vector ) / 2 / Math.PI + 0.5; - var v = inclination( vector ) / Math.PI + 0.5; - vertex.uv = new Vector2( u, 1 - v ); + var face = new Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] ); + that.faces.push( face ); - return vertex; + centroid.copy( v1 ).add( v2 ).add( v3 ).divideScalar( 3 ); - } + var azi = azimuth( centroid ); + that.faceVertexUvs[ 0 ].push( [ + correctUV( v1.uv, v1, azi ), + correctUV( v2.uv, v2, azi ), + correctUV( v3.uv, v3, azi ) + ] ); - // Approximate a curved face with recursively sub-divided triangles. + } - function make( v1, v2, v3 ) { - var face = new Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] ); - that.faces.push( face ); + // Analytically subdivide a face to the required detail level. - centroid.copy( v1 ).add( v2 ).add( v3 ).divideScalar( 3 ); + function subdivide( face, detail ) { - var azi = azimuth( centroid ); + var cols = Math.pow( 2, detail ); + var a = prepare( that.vertices[ face.a ] ); + var b = prepare( that.vertices[ face.b ] ); + var c = prepare( that.vertices[ face.c ] ); + var v = []; - that.faceVertexUvs[ 0 ].push( [ - correctUV( v1.uv, v1, azi ), - correctUV( v2.uv, v2, azi ), - correctUV( v3.uv, v3, azi ) - ] ); + // Construct all of the vertices for this subdivision. - } + for ( var i = 0 ; i <= cols; i ++ ) { + v[ i ] = []; - // Analytically subdivide a face to the required detail level. + var aj = prepare( a.clone().lerp( c, i / cols ) ); + var bj = prepare( b.clone().lerp( c, i / cols ) ); + var rows = cols - i; - function subdivide( face, detail ) { + for ( var j = 0; j <= rows; j ++ ) { - var cols = Math.pow( 2, detail ); - var a = prepare( that.vertices[ face.a ] ); - var b = prepare( that.vertices[ face.b ] ); - var c = prepare( that.vertices[ face.c ] ); - var v = []; + if ( j === 0 && i === cols ) { - // Construct all of the vertices for this subdivision. + v[ i ][ j ] = aj; - for ( var i = 0 ; i <= cols; i ++ ) { + } else { - v[ i ] = []; + v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) ); - var aj = prepare( a.clone().lerp( c, i / cols ) ); - var bj = prepare( b.clone().lerp( c, i / cols ) ); - var rows = cols - i; + } - for ( var j = 0; j <= rows; j ++ ) { + } - if ( j === 0 && i === cols ) { + } - v[ i ][ j ] = aj; + // Construct all of the faces. - } else { + for ( var i = 0; i < cols ; i ++ ) { - v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) ); + for ( var j = 0; j < 2 * ( cols - i ) - 1; j ++ ) { - } + var k = Math.floor( j / 2 ); - } + if ( j % 2 === 0 ) { - } + make( + v[ i ][ k + 1 ], + v[ i + 1 ][ k ], + v[ i ][ k ] + ); - // Construct all of the faces. + } else { - for ( var i = 0; i < cols ; i ++ ) { + make( + v[ i ][ k + 1 ], + v[ i + 1 ][ k + 1 ], + v[ i + 1 ][ k ] + ); - for ( var j = 0; j < 2 * ( cols - i ) - 1; j ++ ) { + } - var k = Math.floor( j / 2 ); + } - if ( j % 2 === 0 ) { + } - make( - v[ i ][ k + 1 ], - v[ i + 1 ][ k ], - v[ i ][ k ] - ); + } - } else { - make( - v[ i ][ k + 1 ], - v[ i + 1 ][ k + 1 ], - v[ i + 1 ][ k ] - ); + // Angle around the Y axis, counter-clockwise when looking from above. - } + function azimuth( vector ) { - } + return Math.atan2( vector.z, - vector.x ); - } + } - } + // Angle above the XZ plane. - // Angle around the Y axis, counter-clockwise when looking from above. + function inclination( vector ) { - function azimuth( vector ) { + return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) ); - return Math.atan2( vector.z, - vector.x ); + } - } + // Texture fixing helper. Spheres have some odd behaviours. - // Angle above the XZ plane. + function correctUV( uv, vector, azimuth ) { - function inclination( vector ) { + if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new Vector2( uv.x - 1, uv.y ); + if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new Vector2( azimuth / 2 / Math.PI + 0.5, uv.y ); + return uv.clone(); - return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) ); + } - } + } + PolyhedronGeometry.prototype = Object.create( Geometry.prototype ); + PolyhedronGeometry.prototype.constructor = PolyhedronGeometry; - // Texture fixing helper. Spheres have some odd behaviours. + /** + * @author timothypratley / https://github.com/timothypratley + */ - function correctUV( uv, vector, azimuth ) { + function TetrahedronGeometry( radius, detail ) { - if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new Vector2( uv.x - 1, uv.y ); - if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new Vector2( azimuth / 2 / Math.PI + 0.5, uv.y ); - return uv.clone(); + var vertices = [ + 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1 + ]; - } + var indices = [ + 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1 + ]; + PolyhedronGeometry.call( this, vertices, indices, radius, detail ); - }; + this.type = 'TetrahedronGeometry'; - PolyhedronGeometry.prototype = Object.create( Geometry.prototype ); - PolyhedronGeometry.prototype.constructor = PolyhedronGeometry; + this.parameters = { + radius: radius, + detail: detail + }; - /** - * @author timothypratley / https://github.com/timothypratley - */ + } - function TetrahedronGeometry( radius, detail ) { + TetrahedronGeometry.prototype = Object.create( PolyhedronGeometry.prototype ); + TetrahedronGeometry.prototype.constructor = TetrahedronGeometry; - var vertices = [ - 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1 - ]; + /** + * @author timothypratley / https://github.com/timothypratley + */ - var indices = [ - 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1 - ]; + function OctahedronGeometry( radius, detail ) { - PolyhedronGeometry.call( this, vertices, indices, radius, detail ); + var vertices = [ + 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1 + ]; - this.type = 'TetrahedronGeometry'; + var indices = [ + 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2 + ]; - this.parameters = { - radius: radius, - detail: detail - }; + PolyhedronGeometry.call( this, vertices, indices, radius, detail ); - }; + this.type = 'OctahedronGeometry'; - TetrahedronGeometry.prototype = Object.create( PolyhedronGeometry.prototype ); - TetrahedronGeometry.prototype.constructor = TetrahedronGeometry; + this.parameters = { + radius: radius, + detail: detail + }; - /** - * @author timothypratley / https://github.com/timothypratley - */ + } - function OctahedronGeometry( radius, detail ) { + OctahedronGeometry.prototype = Object.create( PolyhedronGeometry.prototype ); + OctahedronGeometry.prototype.constructor = OctahedronGeometry; - var vertices = [ - 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1 - ]; + /** + * @author timothypratley / https://github.com/timothypratley + */ - var indices = [ - 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2 - ]; + function IcosahedronGeometry( radius, detail ) { - PolyhedronGeometry.call( this, vertices, indices, radius, detail ); + var t = ( 1 + Math.sqrt( 5 ) ) / 2; - this.type = 'OctahedronGeometry'; + var vertices = [ + - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0, + 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, + t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1 + ]; - this.parameters = { - radius: radius, - detail: detail - }; + var indices = [ + 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11, + 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8, + 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9, + 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1 + ]; - }; + PolyhedronGeometry.call( this, vertices, indices, radius, detail ); - OctahedronGeometry.prototype = Object.create( PolyhedronGeometry.prototype ); - OctahedronGeometry.prototype.constructor = OctahedronGeometry; + this.type = 'IcosahedronGeometry'; - /** - * @author timothypratley / https://github.com/timothypratley - */ + this.parameters = { + radius: radius, + detail: detail + }; - function IcosahedronGeometry( radius, detail ) { + } - var t = ( 1 + Math.sqrt( 5 ) ) / 2; + IcosahedronGeometry.prototype = Object.create( PolyhedronGeometry.prototype ); + IcosahedronGeometry.prototype.constructor = IcosahedronGeometry; - var vertices = [ - - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0, - 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, - t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1 - ]; + /** + * @author Abe Pazos / https://hamoid.com + */ - var indices = [ - 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11, - 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8, - 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9, - 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1 - ]; + function DodecahedronGeometry( radius, detail ) { - PolyhedronGeometry.call( this, vertices, indices, radius, detail ); + var t = ( 1 + Math.sqrt( 5 ) ) / 2; + var r = 1 / t; - this.type = 'IcosahedronGeometry'; + var vertices = [ - this.parameters = { - radius: radius, - detail: detail - }; + // (±1, ±1, ±1) + - 1, - 1, - 1, - 1, - 1, 1, + - 1, 1, - 1, - 1, 1, 1, + 1, - 1, - 1, 1, - 1, 1, + 1, 1, - 1, 1, 1, 1, - }; + // (0, ±1/φ, ±φ) + 0, - r, - t, 0, - r, t, + 0, r, - t, 0, r, t, - IcosahedronGeometry.prototype = Object.create( PolyhedronGeometry.prototype ); - IcosahedronGeometry.prototype.constructor = IcosahedronGeometry; + // (±1/φ, ±φ, 0) + - r, - t, 0, - r, t, 0, + r, - t, 0, r, t, 0, - /** - * @author Abe Pazos / https://hamoid.com - */ + // (±φ, 0, ±1/φ) + - t, 0, - r, t, 0, - r, + - t, 0, r, t, 0, r + ]; - function DodecahedronGeometry( radius, detail ) { + var indices = [ + 3, 11, 7, 3, 7, 15, 3, 15, 13, + 7, 19, 17, 7, 17, 6, 7, 6, 15, + 17, 4, 8, 17, 8, 10, 17, 10, 6, + 8, 0, 16, 8, 16, 2, 8, 2, 10, + 0, 12, 1, 0, 1, 18, 0, 18, 16, + 6, 10, 2, 6, 2, 13, 6, 13, 15, + 2, 16, 18, 2, 18, 3, 2, 3, 13, + 18, 1, 9, 18, 9, 11, 18, 11, 3, + 4, 14, 12, 4, 12, 0, 4, 0, 8, + 11, 9, 5, 11, 5, 19, 11, 19, 7, + 19, 5, 14, 19, 14, 4, 19, 4, 17, + 1, 12, 14, 1, 14, 5, 1, 5, 9 + ]; - var t = ( 1 + Math.sqrt( 5 ) ) / 2; - var r = 1 / t; + PolyhedronGeometry.call( this, vertices, indices, radius, detail ); - var vertices = [ + this.type = 'DodecahedronGeometry'; - // (±1, ±1, ±1) - - 1, - 1, - 1, - 1, - 1, 1, - - 1, 1, - 1, - 1, 1, 1, - 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, 1, 1, 1, + this.parameters = { + radius: radius, + detail: detail + }; - // (0, ±1/φ, ±φ) - 0, - r, - t, 0, - r, t, - 0, r, - t, 0, r, t, + } - // (±1/φ, ±φ, 0) - - r, - t, 0, - r, t, 0, - r, - t, 0, r, t, 0, + DodecahedronGeometry.prototype = Object.create( PolyhedronGeometry.prototype ); + DodecahedronGeometry.prototype.constructor = DodecahedronGeometry; - // (±φ, 0, ±1/φ) - - t, 0, - r, t, 0, - r, - - t, 0, r, t, 0, r - ]; + /** + * @author Mugen87 / https://github.com/Mugen87 + * + * see: http://www.blackpawn.com/texts/pqtorus/ + */ + function TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) { - var indices = [ - 3, 11, 7, 3, 7, 15, 3, 15, 13, - 7, 19, 17, 7, 17, 6, 7, 6, 15, - 17, 4, 8, 17, 8, 10, 17, 10, 6, - 8, 0, 16, 8, 16, 2, 8, 2, 10, - 0, 12, 1, 0, 1, 18, 0, 18, 16, - 6, 10, 2, 6, 2, 13, 6, 13, 15, - 2, 16, 18, 2, 18, 3, 2, 3, 13, - 18, 1, 9, 18, 9, 11, 18, 11, 3, - 4, 14, 12, 4, 12, 0, 4, 0, 8, - 11, 9, 5, 11, 5, 19, 11, 19, 7, - 19, 5, 14, 19, 14, 4, 19, 4, 17, - 1, 12, 14, 1, 14, 5, 1, 5, 9 - ]; + BufferGeometry.call( this ); - PolyhedronGeometry.call( this, vertices, indices, radius, detail ); + this.type = 'TorusKnotBufferGeometry'; - this.type = 'DodecahedronGeometry'; + this.parameters = { + radius: radius, + tube: tube, + tubularSegments: tubularSegments, + radialSegments: radialSegments, + p: p, + q: q + }; - this.parameters = { - radius: radius, - detail: detail - }; + radius = radius || 100; + tube = tube || 40; + tubularSegments = Math.floor( tubularSegments ) || 64; + radialSegments = Math.floor( radialSegments ) || 8; + p = p || 2; + q = q || 3; - }; + // used to calculate buffer length + var vertexCount = ( ( radialSegments + 1 ) * ( tubularSegments + 1 ) ); + var indexCount = radialSegments * tubularSegments * 2 * 3; - DodecahedronGeometry.prototype = Object.create( PolyhedronGeometry.prototype ); - DodecahedronGeometry.prototype.constructor = DodecahedronGeometry; + // buffers + var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 ); + var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); + var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); + var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); - /** - * @author Mugen87 / https://github.com/Mugen87 - * - * see: http://www.blackpawn.com/texts/pqtorus/ - */ - function TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) { + // helper variables + var i, j, index = 0, indexOffset = 0; - BufferGeometry.call( this ); + var vertex = new Vector3(); + var normal = new Vector3(); + var uv = new Vector2(); - this.type = 'TorusKnotBufferGeometry'; + var P1 = new Vector3(); + var P2 = new Vector3(); - this.parameters = { - radius: radius, - tube: tube, - tubularSegments: tubularSegments, - radialSegments: radialSegments, - p: p, - q: q - }; + var B = new Vector3(); + var T = new Vector3(); + var N = new Vector3(); - radius = radius || 100; - tube = tube || 40; - tubularSegments = Math.floor( tubularSegments ) || 64; - radialSegments = Math.floor( radialSegments ) || 8; - p = p || 2; - q = q || 3; + // generate vertices, normals and uvs - // used to calculate buffer length - var vertexCount = ( ( radialSegments + 1 ) * ( tubularSegments + 1 ) ); - var indexCount = radialSegments * tubularSegments * 2 * 3; + for ( i = 0; i <= tubularSegments; ++ i ) { - // buffers - var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 ); - var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); - var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); - var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); + // the radian "u" is used to calculate the position on the torus curve of the current tubular segement - // helper variables - var i, j, index = 0, indexOffset = 0; + var u = i / tubularSegments * p * Math.PI * 2; - var vertex = new Vector3(); - var normal = new Vector3(); - var uv = new Vector2(); + // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead. + // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions - var P1 = new Vector3(); - var P2 = new Vector3(); + calculatePositionOnCurve( u, p, q, radius, P1 ); + calculatePositionOnCurve( u + 0.01, p, q, radius, P2 ); - var B = new Vector3(); - var T = new Vector3(); - var N = new Vector3(); + // calculate orthonormal basis - // generate vertices, normals and uvs + T.subVectors( P2, P1 ); + N.addVectors( P2, P1 ); + B.crossVectors( T, N ); + N.crossVectors( B, T ); - for ( i = 0; i <= tubularSegments; ++ i ) { + // normalize B, N. T can be ignored, we don't use it - // the radian "u" is used to calculate the position on the torus curve of the current tubular segement + B.normalize(); + N.normalize(); - var u = i / tubularSegments * p * Math.PI * 2; + for ( j = 0; j <= radialSegments; ++ j ) { - // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead. - // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions + // now calculate the vertices. they are nothing more than an extrusion of the torus curve. + // because we extrude a shape in the xy-plane, there is no need to calculate a z-value. - calculatePositionOnCurve( u, p, q, radius, P1 ); - calculatePositionOnCurve( u + 0.01, p, q, radius, P2 ); + var v = j / radialSegments * Math.PI * 2; + var cx = - tube * Math.cos( v ); + var cy = tube * Math.sin( v ); - // calculate orthonormal basis + // now calculate the final vertex position. + // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve - T.subVectors( P2, P1 ); - N.addVectors( P2, P1 ); - B.crossVectors( T, N ); - N.crossVectors( B, T ); + vertex.x = P1.x + ( cx * N.x + cy * B.x ); + vertex.y = P1.y + ( cx * N.y + cy * B.y ); + vertex.z = P1.z + ( cx * N.z + cy * B.z ); - // normalize B, N. T can be ignored, we don't use it + // vertex + vertices.setXYZ( index, vertex.x, vertex.y, vertex.z ); - B.normalize(); - N.normalize(); + // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal) + normal.subVectors( vertex, P1 ).normalize(); + normals.setXYZ( index, normal.x, normal.y, normal.z ); - for ( j = 0; j <= radialSegments; ++ j ) { + // uv + uv.x = i / tubularSegments; + uv.y = j / radialSegments; + uvs.setXY( index, uv.x, uv.y ); - // now calculate the vertices. they are nothing more than an extrusion of the torus curve. - // because we extrude a shape in the xy-plane, there is no need to calculate a z-value. + // increase index + index ++; - var v = j / radialSegments * Math.PI * 2; - var cx = - tube * Math.cos( v ); - var cy = tube * Math.sin( v ); + } - // now calculate the final vertex position. - // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve + } - vertex.x = P1.x + ( cx * N.x + cy * B.x ); - vertex.y = P1.y + ( cx * N.y + cy * B.y ); - vertex.z = P1.z + ( cx * N.z + cy * B.z ); + // generate indices - // vertex - vertices.setXYZ( index, vertex.x, vertex.y, vertex.z ); + for ( j = 1; j <= tubularSegments; j ++ ) { - // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal) - normal.subVectors( vertex, P1 ).normalize(); - normals.setXYZ( index, normal.x, normal.y, normal.z ); + for ( i = 1; i <= radialSegments; i ++ ) { - // uv - uv.x = i / tubularSegments; - uv.y = j / radialSegments; - uvs.setXY( index, uv.x, uv.y ); + // indices + var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 ); + var b = ( radialSegments + 1 ) * j + ( i - 1 ); + var c = ( radialSegments + 1 ) * j + i; + var d = ( radialSegments + 1 ) * ( j - 1 ) + i; - // increase index - index ++; + // face one + indices.setX( indexOffset, a ); indexOffset++; + indices.setX( indexOffset, b ); indexOffset++; + indices.setX( indexOffset, d ); indexOffset++; - } + // face two + indices.setX( indexOffset, b ); indexOffset++; + indices.setX( indexOffset, c ); indexOffset++; + indices.setX( indexOffset, d ); indexOffset++; - } + } - // generate indices + } - for ( j = 1; j <= tubularSegments; j ++ ) { + // build geometry - for ( i = 1; i <= radialSegments; i ++ ) { + this.setIndex( indices ); + this.addAttribute( 'position', vertices ); + this.addAttribute( 'normal', normals ); + this.addAttribute( 'uv', uvs ); - // indices - var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 ); - var b = ( radialSegments + 1 ) * j + ( i - 1 ); - var c = ( radialSegments + 1 ) * j + i; - var d = ( radialSegments + 1 ) * ( j - 1 ) + i; + // this function calculates the current position on the torus curve - // face one - indices.setX( indexOffset, a ); indexOffset++; - indices.setX( indexOffset, b ); indexOffset++; - indices.setX( indexOffset, d ); indexOffset++; + function calculatePositionOnCurve( u, p, q, radius, position ) { - // face two - indices.setX( indexOffset, b ); indexOffset++; - indices.setX( indexOffset, c ); indexOffset++; - indices.setX( indexOffset, d ); indexOffset++; + var cu = Math.cos( u ); + var su = Math.sin( u ); + var quOverP = q / p * u; + var cs = Math.cos( quOverP ); - } + position.x = radius * ( 2 + cs ) * 0.5 * cu; + position.y = radius * ( 2 + cs ) * su * 0.5; + position.z = radius * Math.sin( quOverP ) * 0.5; - } + } - // build geometry + } - this.setIndex( indices ); - this.addAttribute( 'position', vertices ); - this.addAttribute( 'normal', normals ); - this.addAttribute( 'uv', uvs ); + TorusKnotBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry; - // this function calculates the current position on the torus curve + /** + * @author oosmoxiecode + */ - function calculatePositionOnCurve( u, p, q, radius, position ) { + function TorusKnotGeometry( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) { - var cu = Math.cos( u ); - var su = Math.sin( u ); - var quOverP = q / p * u; - var cs = Math.cos( quOverP ); + Geometry.call( this ); - position.x = radius * ( 2 + cs ) * 0.5 * cu; - position.y = radius * ( 2 + cs ) * su * 0.5; - position.z = radius * Math.sin( quOverP ) * 0.5; + this.type = 'TorusKnotGeometry'; - } + this.parameters = { + radius: radius, + tube: tube, + tubularSegments: tubularSegments, + radialSegments: radialSegments, + p: p, + q: q + }; - }; + if( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' ); - TorusKnotBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); - TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry; + this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) ); + this.mergeVertices(); - /** - * @author oosmoxiecode - */ + } - function TorusKnotGeometry( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) { + TorusKnotGeometry.prototype = Object.create( Geometry.prototype ); + TorusKnotGeometry.prototype.constructor = TorusKnotGeometry; - Geometry.call( this ); + /** + * @author Mugen87 / https://github.com/Mugen87 + */ - this.type = 'TorusKnotGeometry'; + function TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) { - this.parameters = { - radius: radius, - tube: tube, - tubularSegments: tubularSegments, - radialSegments: radialSegments, - p: p, - q: q - }; + BufferGeometry.call( this ); - if( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' ); + this.type = 'TorusBufferGeometry'; - this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) ); - this.mergeVertices(); + this.parameters = { + radius: radius, + tube: tube, + radialSegments: radialSegments, + tubularSegments: tubularSegments, + arc: arc + }; - }; + radius = radius || 100; + tube = tube || 40; + radialSegments = Math.floor( radialSegments ) || 8; + tubularSegments = Math.floor( tubularSegments ) || 6; + arc = arc || Math.PI * 2; - TorusKnotGeometry.prototype = Object.create( Geometry.prototype ); - TorusKnotGeometry.prototype.constructor = TorusKnotGeometry; + // used to calculate buffer length + var vertexCount = ( ( radialSegments + 1 ) * ( tubularSegments + 1 ) ); + var indexCount = radialSegments * tubularSegments * 2 * 3; - /** - * @author Mugen87 / https://github.com/Mugen87 - */ + // buffers + var indices = new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ); + var vertices = new Float32Array( vertexCount * 3 ); + var normals = new Float32Array( vertexCount * 3 ); + var uvs = new Float32Array( vertexCount * 2 ); - function TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) { + // offset variables + var vertexBufferOffset = 0; + var uvBufferOffset = 0; + var indexBufferOffset = 0; - BufferGeometry.call( this ); + // helper variables + var center = new Vector3(); + var vertex = new Vector3(); + var normal = new Vector3(); - this.type = 'TorusBufferGeometry'; + var j, i; - this.parameters = { - radius: radius, - tube: tube, - radialSegments: radialSegments, - tubularSegments: tubularSegments, - arc: arc - }; + // generate vertices, normals and uvs - radius = radius || 100; - tube = tube || 40; - radialSegments = Math.floor( radialSegments ) || 8; - tubularSegments = Math.floor( tubularSegments ) || 6; - arc = arc || Math.PI * 2; + for ( j = 0; j <= radialSegments; j ++ ) { - // used to calculate buffer length - var vertexCount = ( ( radialSegments + 1 ) * ( tubularSegments + 1 ) ); - var indexCount = radialSegments * tubularSegments * 2 * 3; + for ( i = 0; i <= tubularSegments; i ++ ) { - // buffers - var indices = new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ); - var vertices = new Float32Array( vertexCount * 3 ); - var normals = new Float32Array( vertexCount * 3 ); - var uvs = new Float32Array( vertexCount * 2 ); + var u = i / tubularSegments * arc; + var v = j / radialSegments * Math.PI * 2; - // offset variables - var vertexBufferOffset = 0; - var uvBufferOffset = 0; - var indexBufferOffset = 0; + // vertex + vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u ); + vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u ); + vertex.z = tube * Math.sin( v ); - // helper variables - var center = new Vector3(); - var vertex = new Vector3(); - var normal = new Vector3(); + vertices[ vertexBufferOffset ] = vertex.x; + vertices[ vertexBufferOffset + 1 ] = vertex.y; + vertices[ vertexBufferOffset + 2 ] = vertex.z; - var j, i; + // this vector is used to calculate the normal + center.x = radius * Math.cos( u ); + center.y = radius * Math.sin( u ); - // generate vertices, normals and uvs + // normal + normal.subVectors( vertex, center ).normalize(); - for ( j = 0; j <= radialSegments; j ++ ) { + normals[ vertexBufferOffset ] = normal.x; + normals[ vertexBufferOffset + 1 ] = normal.y; + normals[ vertexBufferOffset + 2 ] = normal.z; - for ( i = 0; i <= tubularSegments; i ++ ) { + // uv + uvs[ uvBufferOffset ] = i / tubularSegments; + uvs[ uvBufferOffset + 1 ] = j / radialSegments; - var u = i / tubularSegments * arc; - var v = j / radialSegments * Math.PI * 2; + // update offsets + vertexBufferOffset += 3; + uvBufferOffset += 2; - // vertex - vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u ); - vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u ); - vertex.z = tube * Math.sin( v ); + } - vertices[ vertexBufferOffset ] = vertex.x; - vertices[ vertexBufferOffset + 1 ] = vertex.y; - vertices[ vertexBufferOffset + 2 ] = vertex.z; + } - // this vector is used to calculate the normal - center.x = radius * Math.cos( u ); - center.y = radius * Math.sin( u ); + // generate indices - // normal - normal.subVectors( vertex, center ).normalize(); + for ( j = 1; j <= radialSegments; j ++ ) { - normals[ vertexBufferOffset ] = normal.x; - normals[ vertexBufferOffset + 1 ] = normal.y; - normals[ vertexBufferOffset + 2 ] = normal.z; + for ( i = 1; i <= tubularSegments; i ++ ) { - // uv - uvs[ uvBufferOffset ] = i / tubularSegments; - uvs[ uvBufferOffset + 1 ] = j / radialSegments; + // indices + var a = ( tubularSegments + 1 ) * j + i - 1; + var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1; + var c = ( tubularSegments + 1 ) * ( j - 1 ) + i; + var d = ( tubularSegments + 1 ) * j + i; - // update offsets - vertexBufferOffset += 3; - uvBufferOffset += 2; + // face one + indices[ indexBufferOffset ] = a; + indices[ indexBufferOffset + 1 ] = b; + indices[ indexBufferOffset + 2 ] = d; - } + // face two + indices[ indexBufferOffset + 3 ] = b; + indices[ indexBufferOffset + 4 ] = c; + indices[ indexBufferOffset + 5 ] = d; - } + // update offset + indexBufferOffset += 6; - // generate indices + } - for ( j = 1; j <= radialSegments; j ++ ) { + } - for ( i = 1; i <= tubularSegments; i ++ ) { + // build geometry + this.setIndex( new BufferAttribute( indices, 1 ) ); + this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) ); + this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) ); + this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) ); - // indices - var a = ( tubularSegments + 1 ) * j + i - 1; - var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1; - var c = ( tubularSegments + 1 ) * ( j - 1 ) + i; - var d = ( tubularSegments + 1 ) * j + i; + } - // face one - indices[ indexBufferOffset ] = a; - indices[ indexBufferOffset + 1 ] = b; - indices[ indexBufferOffset + 2 ] = d; + TorusBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + TorusBufferGeometry.prototype.constructor = TorusBufferGeometry; - // face two - indices[ indexBufferOffset + 3 ] = b; - indices[ indexBufferOffset + 4 ] = c; - indices[ indexBufferOffset + 5 ] = d; + /** + * @author oosmoxiecode + * @author mrdoob / http://mrdoob.com/ + * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888 + */ - // update offset - indexBufferOffset += 6; + function TorusGeometry( radius, tube, radialSegments, tubularSegments, arc ) { - } + Geometry.call( this ); - } + this.type = 'TorusGeometry'; - // build geometry - this.setIndex( new BufferAttribute( indices, 1 ) ); - this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) ); - this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) ); - this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) ); + this.parameters = { + radius: radius, + tube: tube, + radialSegments: radialSegments, + tubularSegments: tubularSegments, + arc: arc + }; - }; + this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) ); - TorusBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); - TorusBufferGeometry.prototype.constructor = TorusBufferGeometry; + } - /** - * @author oosmoxiecode - * @author mrdoob / http://mrdoob.com/ - * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888 - */ + TorusGeometry.prototype = Object.create( Geometry.prototype ); + TorusGeometry.prototype.constructor = TorusGeometry; - function TorusGeometry( radius, tube, radialSegments, tubularSegments, arc ) { + /** + * @author zz85 / http://www.lab4games.net/zz85/blog + * @author alteredq / http://alteredqualia.com/ + * + * Text = 3D Text + * + * parameters = { + * font: , // font + * + * size: , // size of the text + * height: , // thickness to extrude text + * curveSegments: , // number of points on the curves + * + * bevelEnabled: , // turn on bevel + * bevelThickness: , // how deep into text bevel goes + * bevelSize: // how far from text outline is bevel + * } + */ - Geometry.call( this ); + function TextGeometry( text, parameters ) { - this.type = 'TorusGeometry'; + parameters = parameters || {}; - this.parameters = { - radius: radius, - tube: tube, - radialSegments: radialSegments, - tubularSegments: tubularSegments, - arc: arc - }; + var font = parameters.font; - this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) ); + if ( (font && font.isFont) === false ) { - }; + console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' ); + return new Geometry(); - TorusGeometry.prototype = Object.create( Geometry.prototype ); - TorusGeometry.prototype.constructor = TorusGeometry; + } - /** - * @author zz85 / http://www.lab4games.net/zz85/blog - * @author alteredq / http://alteredqualia.com/ - * - * Text = 3D Text - * - * parameters = { - * font: , // font - * - * size: , // size of the text - * height: , // thickness to extrude text - * curveSegments: , // number of points on the curves - * - * bevelEnabled: , // turn on bevel - * bevelThickness: , // how deep into text bevel goes - * bevelSize: // how far from text outline is bevel - * } - */ + var shapes = font.generateShapes( text, parameters.size, parameters.curveSegments ); - function TextGeometry( text, parameters ) { + // translate parameters to ExtrudeGeometry API - parameters = parameters || {}; + parameters.amount = parameters.height !== undefined ? parameters.height : 50; - var font = parameters.font; + // defaults - if ( (font && font.isFont) === false ) { + if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10; + if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8; + if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false; - console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' ); - return new Geometry(); + ExtrudeGeometry.call( this, shapes, parameters ); - } + this.type = 'TextGeometry'; - var shapes = font.generateShapes( text, parameters.size, parameters.curveSegments ); + } - // translate parameters to ExtrudeGeometry API + TextGeometry.prototype = Object.create( ExtrudeGeometry.prototype ); + TextGeometry.prototype.constructor = TextGeometry; - parameters.amount = parameters.height !== undefined ? parameters.height : 50; + /** + * @author Mugen87 / https://github.com/Mugen87 + */ - // defaults + function RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) { - if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10; - if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8; - if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false; + BufferGeometry.call( this ); - ExtrudeGeometry.call( this, shapes, parameters ); + this.type = 'RingBufferGeometry'; - this.type = 'TextGeometry'; + this.parameters = { + innerRadius: innerRadius, + outerRadius: outerRadius, + thetaSegments: thetaSegments, + phiSegments: phiSegments, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - }; + innerRadius = innerRadius || 20; + outerRadius = outerRadius || 50; - TextGeometry.prototype = Object.create( ExtrudeGeometry.prototype ); - TextGeometry.prototype.constructor = TextGeometry; + thetaStart = thetaStart !== undefined ? thetaStart : 0; + thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; - /** - * @author Mugen87 / https://github.com/Mugen87 - */ + thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8; + phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1; - function RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) { + // these are used to calculate buffer length + var vertexCount = ( thetaSegments + 1 ) * ( phiSegments + 1 ); + var indexCount = thetaSegments * phiSegments * 2 * 3; - BufferGeometry.call( this ); + // buffers + var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 ); + var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); + var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); + var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); - this.type = 'RingBufferGeometry'; + // some helper variables + var index = 0, indexOffset = 0, segment; + var radius = innerRadius; + var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments ); + var vertex = new Vector3(); + var uv = new Vector2(); + var j, i; - this.parameters = { - innerRadius: innerRadius, - outerRadius: outerRadius, - thetaSegments: thetaSegments, - phiSegments: phiSegments, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + // generate vertices, normals and uvs - innerRadius = innerRadius || 20; - outerRadius = outerRadius || 50; + // values are generate from the inside of the ring to the outside - thetaStart = thetaStart !== undefined ? thetaStart : 0; - thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; + for ( j = 0; j <= phiSegments; j ++ ) { - thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8; - phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1; + for ( i = 0; i <= thetaSegments; i ++ ) { - // these are used to calculate buffer length - var vertexCount = ( thetaSegments + 1 ) * ( phiSegments + 1 ); - var indexCount = thetaSegments * phiSegments * 2 * 3; + segment = thetaStart + i / thetaSegments * thetaLength; - // buffers - var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 ); - var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); - var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); - var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); + // vertex + vertex.x = radius * Math.cos( segment ); + vertex.y = radius * Math.sin( segment ); + vertices.setXYZ( index, vertex.x, vertex.y, vertex.z ); - // some helper variables - var index = 0, indexOffset = 0, segment; - var radius = innerRadius; - var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments ); - var vertex = new Vector3(); - var uv = new Vector2(); - var j, i; + // normal + normals.setXYZ( index, 0, 0, 1 ); - // generate vertices, normals and uvs + // uv + uv.x = ( vertex.x / outerRadius + 1 ) / 2; + uv.y = ( vertex.y / outerRadius + 1 ) / 2; + uvs.setXY( index, uv.x, uv.y ); - // values are generate from the inside of the ring to the outside + // increase index + index++; - for ( j = 0; j <= phiSegments; j ++ ) { + } - for ( i = 0; i <= thetaSegments; i ++ ) { + // increase the radius for next row of vertices + radius += radiusStep; - segment = thetaStart + i / thetaSegments * thetaLength; + } - // vertex - vertex.x = radius * Math.cos( segment ); - vertex.y = radius * Math.sin( segment ); - vertices.setXYZ( index, vertex.x, vertex.y, vertex.z ); + // generate indices - // normal - normals.setXYZ( index, 0, 0, 1 ); + for ( j = 0; j < phiSegments; j ++ ) { - // uv - uv.x = ( vertex.x / outerRadius + 1 ) / 2; - uv.y = ( vertex.y / outerRadius + 1 ) / 2; - uvs.setXY( index, uv.x, uv.y ); + var thetaSegmentLevel = j * ( thetaSegments + 1 ); - // increase index - index++; + for ( i = 0; i < thetaSegments; i ++ ) { - } + segment = i + thetaSegmentLevel; - // increase the radius for next row of vertices - radius += radiusStep; + // indices + var a = segment; + var b = segment + thetaSegments + 1; + var c = segment + thetaSegments + 2; + var d = segment + 1; - } + // face one + indices.setX( indexOffset, a ); indexOffset++; + indices.setX( indexOffset, b ); indexOffset++; + indices.setX( indexOffset, c ); indexOffset++; - // generate indices + // face two + indices.setX( indexOffset, a ); indexOffset++; + indices.setX( indexOffset, c ); indexOffset++; + indices.setX( indexOffset, d ); indexOffset++; - for ( j = 0; j < phiSegments; j ++ ) { + } - var thetaSegmentLevel = j * ( thetaSegments + 1 ); + } - for ( i = 0; i < thetaSegments; i ++ ) { + // build geometry - segment = i + thetaSegmentLevel; + this.setIndex( indices ); + this.addAttribute( 'position', vertices ); + this.addAttribute( 'normal', normals ); + this.addAttribute( 'uv', uvs ); - // indices - var a = segment; - var b = segment + thetaSegments + 1; - var c = segment + thetaSegments + 2; - var d = segment + 1; + } - // face one - indices.setX( indexOffset, a ); indexOffset++; - indices.setX( indexOffset, b ); indexOffset++; - indices.setX( indexOffset, c ); indexOffset++; + RingBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + RingBufferGeometry.prototype.constructor = RingBufferGeometry; - // face two - indices.setX( indexOffset, a ); indexOffset++; - indices.setX( indexOffset, c ); indexOffset++; - indices.setX( indexOffset, d ); indexOffset++; + /** + * @author Kaleb Murphy + */ - } + function RingGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) { - } + Geometry.call( this ); - // build geometry + this.type = 'RingGeometry'; - this.setIndex( indices ); - this.addAttribute( 'position', vertices ); - this.addAttribute( 'normal', normals ); - this.addAttribute( 'uv', uvs ); + this.parameters = { + innerRadius: innerRadius, + outerRadius: outerRadius, + thetaSegments: thetaSegments, + phiSegments: phiSegments, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - }; + this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) ); - RingBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); - RingBufferGeometry.prototype.constructor = RingBufferGeometry; + } - /** - * @author Kaleb Murphy - */ + RingGeometry.prototype = Object.create( Geometry.prototype ); + RingGeometry.prototype.constructor = RingGeometry; - function RingGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) { + /** + * @author mrdoob / http://mrdoob.com/ + * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as + */ - Geometry.call( this ); + function PlaneGeometry( width, height, widthSegments, heightSegments ) { - this.type = 'RingGeometry'; + Geometry.call( this ); - this.parameters = { - innerRadius: innerRadius, - outerRadius: outerRadius, - thetaSegments: thetaSegments, - phiSegments: phiSegments, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + this.type = 'PlaneGeometry'; - this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) ); + this.parameters = { + width: width, + height: height, + widthSegments: widthSegments, + heightSegments: heightSegments + }; - }; + this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) ); - RingGeometry.prototype = Object.create( Geometry.prototype ); - RingGeometry.prototype.constructor = RingGeometry; + } - /** - * @author mrdoob / http://mrdoob.com/ - * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as - */ + PlaneGeometry.prototype = Object.create( Geometry.prototype ); + PlaneGeometry.prototype.constructor = PlaneGeometry; - function PlaneGeometry( width, height, widthSegments, heightSegments ) { + /** + * @author Mugen87 / https://github.com/Mugen87 + */ - Geometry.call( this ); + // points - to create a closed torus, one must use a set of points + // like so: [ a, b, c, d, a ], see first is the same as last. + // segments - the number of circumference segments to create + // phiStart - the starting radian + // phiLength - the radian (0 to 2PI) range of the lathed section + // 2PI is a closed lathe, less than 2PI is a portion. - this.type = 'PlaneGeometry'; + function LatheBufferGeometry( points, segments, phiStart, phiLength ) { - this.parameters = { - width: width, - height: height, - widthSegments: widthSegments, - heightSegments: heightSegments - }; + BufferGeometry.call( this ); - this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) ); + this.type = 'LatheBufferGeometry'; - }; + this.parameters = { + points: points, + segments: segments, + phiStart: phiStart, + phiLength: phiLength + }; - PlaneGeometry.prototype = Object.create( Geometry.prototype ); - PlaneGeometry.prototype.constructor = PlaneGeometry; + segments = Math.floor( segments ) || 12; + phiStart = phiStart || 0; + phiLength = phiLength || Math.PI * 2; - /** - * @author Mugen87 / https://github.com/Mugen87 - */ + // clamp phiLength so it's in range of [ 0, 2PI ] + phiLength = exports.Math.clamp( phiLength, 0, Math.PI * 2 ); - // points - to create a closed torus, one must use a set of points - // like so: [ a, b, c, d, a ], see first is the same as last. - // segments - the number of circumference segments to create - // phiStart - the starting radian - // phiLength - the radian (0 to 2PI) range of the lathed section - // 2PI is a closed lathe, less than 2PI is a portion. + // these are used to calculate buffer length + var vertexCount = ( segments + 1 ) * points.length; + var indexCount = segments * points.length * 2 * 3; - function LatheBufferGeometry( points, segments, phiStart, phiLength ) { + // buffers + var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 ); + var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); + var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); - BufferGeometry.call( this ); + // helper variables + var index = 0, indexOffset = 0, base; + var inverseSegments = 1.0 / segments; + var vertex = new Vector3(); + var uv = new Vector2(); + var i, j; - this.type = 'LatheBufferGeometry'; + // generate vertices and uvs - this.parameters = { - points: points, - segments: segments, - phiStart: phiStart, - phiLength: phiLength - }; + for ( i = 0; i <= segments; i ++ ) { - segments = Math.floor( segments ) || 12; - phiStart = phiStart || 0; - phiLength = phiLength || Math.PI * 2; + var phi = phiStart + i * inverseSegments * phiLength; - // clamp phiLength so it's in range of [ 0, 2PI ] - phiLength = exports.Math.clamp( phiLength, 0, Math.PI * 2 ); + var sin = Math.sin( phi ); + var cos = Math.cos( phi ); - // these are used to calculate buffer length - var vertexCount = ( segments + 1 ) * points.length; - var indexCount = segments * points.length * 2 * 3; + for ( j = 0; j <= ( points.length - 1 ); j ++ ) { - // buffers - var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 ); - var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 ); - var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 ); + // vertex + vertex.x = points[ j ].x * sin; + vertex.y = points[ j ].y; + vertex.z = points[ j ].x * cos; + vertices.setXYZ( index, vertex.x, vertex.y, vertex.z ); - // helper variables - var index = 0, indexOffset = 0, base; - var inverseSegments = 1.0 / segments; - var vertex = new Vector3(); - var uv = new Vector2(); - var i, j; + // uv + uv.x = i / segments; + uv.y = j / ( points.length - 1 ); + uvs.setXY( index, uv.x, uv.y ); - // generate vertices and uvs + // increase index + index ++; - for ( i = 0; i <= segments; i ++ ) { + } - var phi = phiStart + i * inverseSegments * phiLength; + } - var sin = Math.sin( phi ); - var cos = Math.cos( phi ); + // generate indices - for ( j = 0; j <= ( points.length - 1 ); j ++ ) { + for ( i = 0; i < segments; i ++ ) { - // vertex - vertex.x = points[ j ].x * sin; - vertex.y = points[ j ].y; - vertex.z = points[ j ].x * cos; - vertices.setXYZ( index, vertex.x, vertex.y, vertex.z ); + for ( j = 0; j < ( points.length - 1 ); j ++ ) { - // uv - uv.x = i / segments; - uv.y = j / ( points.length - 1 ); - uvs.setXY( index, uv.x, uv.y ); + base = j + i * points.length; - // increase index - index ++; + // indices + var a = base; + var b = base + points.length; + var c = base + points.length + 1; + var d = base + 1; - } + // face one + indices.setX( indexOffset, a ); indexOffset++; + indices.setX( indexOffset, b ); indexOffset++; + indices.setX( indexOffset, d ); indexOffset++; - } + // face two + indices.setX( indexOffset, b ); indexOffset++; + indices.setX( indexOffset, c ); indexOffset++; + indices.setX( indexOffset, d ); indexOffset++; - // generate indices + } - for ( i = 0; i < segments; i ++ ) { + } - for ( j = 0; j < ( points.length - 1 ); j ++ ) { + // build geometry - base = j + i * points.length; + this.setIndex( indices ); + this.addAttribute( 'position', vertices ); + this.addAttribute( 'uv', uvs ); - // indices - var a = base; - var b = base + points.length; - var c = base + points.length + 1; - var d = base + 1; + // generate normals - // face one - indices.setX( indexOffset, a ); indexOffset++; - indices.setX( indexOffset, b ); indexOffset++; - indices.setX( indexOffset, d ); indexOffset++; + this.computeVertexNormals(); - // face two - indices.setX( indexOffset, b ); indexOffset++; - indices.setX( indexOffset, c ); indexOffset++; - indices.setX( indexOffset, d ); indexOffset++; + // if the geometry is closed, we need to average the normals along the seam. + // because the corresponding vertices are identical (but still have different UVs). - } + if( phiLength === Math.PI * 2 ) { - } + var normals = this.attributes.normal.array; + var n1 = new Vector3(); + var n2 = new Vector3(); + var n = new Vector3(); - // build geometry + // this is the buffer offset for the last line of vertices + base = segments * points.length * 3; - this.setIndex( indices ); - this.addAttribute( 'position', vertices ); - this.addAttribute( 'uv', uvs ); + for( i = 0, j = 0; i < points.length; i ++, j += 3 ) { - // generate normals + // select the normal of the vertex in the first line + n1.x = normals[ j + 0 ]; + n1.y = normals[ j + 1 ]; + n1.z = normals[ j + 2 ]; - this.computeVertexNormals(); + // select the normal of the vertex in the last line + n2.x = normals[ base + j + 0 ]; + n2.y = normals[ base + j + 1 ]; + n2.z = normals[ base + j + 2 ]; - // if the geometry is closed, we need to average the normals along the seam. - // because the corresponding vertices are identical (but still have different UVs). + // average normals + n.addVectors( n1, n2 ).normalize(); - if( phiLength === Math.PI * 2 ) { + // assign the new values to both normals + normals[ j + 0 ] = normals[ base + j + 0 ] = n.x; + normals[ j + 1 ] = normals[ base + j + 1 ] = n.y; + normals[ j + 2 ] = normals[ base + j + 2 ] = n.z; - var normals = this.attributes.normal.array; - var n1 = new Vector3(); - var n2 = new Vector3(); - var n = new Vector3(); + } // next row - // this is the buffer offset for the last line of vertices - base = segments * points.length * 3; + } - for( i = 0, j = 0; i < points.length; i ++, j += 3 ) { + } - // select the normal of the vertex in the first line - n1.x = normals[ j + 0 ]; - n1.y = normals[ j + 1 ]; - n1.z = normals[ j + 2 ]; + LatheBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + LatheBufferGeometry.prototype.constructor = LatheBufferGeometry; - // select the normal of the vertex in the last line - n2.x = normals[ base + j + 0 ]; - n2.y = normals[ base + j + 1 ]; - n2.z = normals[ base + j + 2 ]; + /** + * @author astrodud / http://astrodud.isgreat.org/ + * @author zz85 / https://github.com/zz85 + * @author bhouston / http://clara.io + */ - // average normals - n.addVectors( n1, n2 ).normalize(); + // points - to create a closed torus, one must use a set of points + // like so: [ a, b, c, d, a ], see first is the same as last. + // segments - the number of circumference segments to create + // phiStart - the starting radian + // phiLength - the radian (0 to 2PI) range of the lathed section + // 2PI is a closed lathe, less than 2PI is a portion. - // assign the new values to both normals - normals[ j + 0 ] = normals[ base + j + 0 ] = n.x; - normals[ j + 1 ] = normals[ base + j + 1 ] = n.y; - normals[ j + 2 ] = normals[ base + j + 2 ] = n.z; + function LatheGeometry( points, segments, phiStart, phiLength ) { - } // next row + Geometry.call( this ); - } + this.type = 'LatheGeometry'; - }; + this.parameters = { + points: points, + segments: segments, + phiStart: phiStart, + phiLength: phiLength + }; - LatheBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); - LatheBufferGeometry.prototype.constructor = LatheBufferGeometry; + this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) ); + this.mergeVertices(); - /** - * @author astrodud / http://astrodud.isgreat.org/ - * @author zz85 / https://github.com/zz85 - * @author bhouston / http://clara.io - */ + } - // points - to create a closed torus, one must use a set of points - // like so: [ a, b, c, d, a ], see first is the same as last. - // segments - the number of circumference segments to create - // phiStart - the starting radian - // phiLength - the radian (0 to 2PI) range of the lathed section - // 2PI is a closed lathe, less than 2PI is a portion. + LatheGeometry.prototype = Object.create( Geometry.prototype ); + LatheGeometry.prototype.constructor = LatheGeometry; - function LatheGeometry( points, segments, phiStart, phiLength ) { + /** + * @author mrdoob / http://mrdoob.com/ + */ - Geometry.call( this ); + function CylinderGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { - this.type = 'LatheGeometry'; + Geometry.call( this ); - this.parameters = { - points: points, - segments: segments, - phiStart: phiStart, - phiLength: phiLength - }; + this.type = 'CylinderGeometry'; - this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) ); - this.mergeVertices(); + this.parameters = { + radiusTop: radiusTop, + radiusBottom: radiusBottom, + height: height, + radialSegments: radialSegments, + heightSegments: heightSegments, + openEnded: openEnded, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - }; + this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) ); + this.mergeVertices(); - LatheGeometry.prototype = Object.create( Geometry.prototype ); - LatheGeometry.prototype.constructor = LatheGeometry; + } - /** - * @author mrdoob / http://mrdoob.com/ - */ + CylinderGeometry.prototype = Object.create( Geometry.prototype ); + CylinderGeometry.prototype.constructor = CylinderGeometry; - function CylinderGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { + /** + * @author abelnation / http://github.com/abelnation + */ - Geometry.call( this ); + function ConeGeometry( + radius, height, + radialSegments, heightSegments, + openEnded, thetaStart, thetaLength ) { - this.type = 'CylinderGeometry'; + CylinderGeometry.call( this, + 0, radius, height, + radialSegments, heightSegments, + openEnded, thetaStart, thetaLength ); - this.parameters = { - radiusTop: radiusTop, - radiusBottom: radiusBottom, - height: height, - radialSegments: radialSegments, - heightSegments: heightSegments, - openEnded: openEnded, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + this.type = 'ConeGeometry'; - this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) ); - this.mergeVertices(); + this.parameters = { + radius: radius, + height: height, + radialSegments: radialSegments, + heightSegments: heightSegments, + openEnded: openEnded, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - }; + } - CylinderGeometry.prototype = Object.create( Geometry.prototype ); - CylinderGeometry.prototype.constructor = CylinderGeometry; + ConeGeometry.prototype = Object.create( CylinderGeometry.prototype ); + ConeGeometry.prototype.constructor = ConeGeometry; - /** - * @author abelnation / http://github.com/abelnation - */ + /* + * @author: abelnation / http://github.com/abelnation + */ - function ConeGeometry( - radius, height, - radialSegments, heightSegments, - openEnded, thetaStart, thetaLength ) { + function ConeBufferGeometry( + radius, height, + radialSegments, heightSegments, + openEnded, thetaStart, thetaLength ) { - CylinderGeometry.call( this, - 0, radius, height, - radialSegments, heightSegments, - openEnded, thetaStart, thetaLength ); + CylinderBufferGeometry.call( this, + 0, radius, height, + radialSegments, heightSegments, + openEnded, thetaStart, thetaLength ); - this.type = 'ConeGeometry'; + this.type = 'ConeBufferGeometry'; - this.parameters = { - radius: radius, - height: height, - radialSegments: radialSegments, - heightSegments: heightSegments, - openEnded: openEnded, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + this.parameters = { + radius: radius, + height: height, + radialSegments: radialSegments, + heightSegments: heightSegments, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - }; + } - ConeGeometry.prototype = Object.create( CylinderGeometry.prototype ); - ConeGeometry.prototype.constructor = ConeGeometry; + ConeBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + ConeBufferGeometry.prototype.constructor = ConeBufferGeometry; - /* - * @author: abelnation / http://github.com/abelnation - */ + /** + * @author benaadams / https://twitter.com/ben_a_adams + */ - function ConeBufferGeometry( - radius, height, - radialSegments, heightSegments, - openEnded, thetaStart, thetaLength ) { + function CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) { - CylinderBufferGeometry.call( this, - 0, radius, height, - radialSegments, heightSegments, - openEnded, thetaStart, thetaLength ); + BufferGeometry.call( this ); - this.type = 'ConeBufferGeometry'; + this.type = 'CircleBufferGeometry'; - this.parameters = { - radius: radius, - height: height, - radialSegments: radialSegments, - heightSegments: heightSegments, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + this.parameters = { + radius: radius, + segments: segments, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - }; + radius = radius || 50; + segments = segments !== undefined ? Math.max( 3, segments ) : 8; - ConeBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); - ConeBufferGeometry.prototype.constructor = ConeBufferGeometry; + thetaStart = thetaStart !== undefined ? thetaStart : 0; + thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; - /** - * @author benaadams / https://twitter.com/ben_a_adams - */ + var vertices = segments + 2; - function CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) { + var positions = new Float32Array( vertices * 3 ); + var normals = new Float32Array( vertices * 3 ); + var uvs = new Float32Array( vertices * 2 ); - BufferGeometry.call( this ); + // center data is already zero, but need to set a few extras + normals[ 2 ] = 1.0; + uvs[ 0 ] = 0.5; + uvs[ 1 ] = 0.5; - this.type = 'CircleBufferGeometry'; + for ( var s = 0, i = 3, ii = 2 ; s <= segments; s ++, i += 3, ii += 2 ) { - this.parameters = { - radius: radius, - segments: segments, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + var segment = thetaStart + s / segments * thetaLength; - radius = radius || 50; - segments = segments !== undefined ? Math.max( 3, segments ) : 8; + positions[ i ] = radius * Math.cos( segment ); + positions[ i + 1 ] = radius * Math.sin( segment ); - thetaStart = thetaStart !== undefined ? thetaStart : 0; - thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; + normals[ i + 2 ] = 1; // normal z - var vertices = segments + 2; + uvs[ ii ] = ( positions[ i ] / radius + 1 ) / 2; + uvs[ ii + 1 ] = ( positions[ i + 1 ] / radius + 1 ) / 2; - var positions = new Float32Array( vertices * 3 ); - var normals = new Float32Array( vertices * 3 ); - var uvs = new Float32Array( vertices * 2 ); + } - // center data is already zero, but need to set a few extras - normals[ 2 ] = 1.0; - uvs[ 0 ] = 0.5; - uvs[ 1 ] = 0.5; + var indices = []; - for ( var s = 0, i = 3, ii = 2 ; s <= segments; s ++, i += 3, ii += 2 ) { + for ( var i = 1; i <= segments; i ++ ) { - var segment = thetaStart + s / segments * thetaLength; + indices.push( i, i + 1, 0 ); - positions[ i ] = radius * Math.cos( segment ); - positions[ i + 1 ] = radius * Math.sin( segment ); + } - normals[ i + 2 ] = 1; // normal z + this.setIndex( new BufferAttribute( new Uint16Array( indices ), 1 ) ); + this.addAttribute( 'position', new BufferAttribute( positions, 3 ) ); + this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) ); + this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) ); - uvs[ ii ] = ( positions[ i ] / radius + 1 ) / 2; - uvs[ ii + 1 ] = ( positions[ i + 1 ] / radius + 1 ) / 2; + this.boundingSphere = new Sphere( new Vector3(), radius ); - } + } - var indices = []; + CircleBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + CircleBufferGeometry.prototype.constructor = CircleBufferGeometry; - for ( var i = 1; i <= segments; i ++ ) { + /** + * @author hughes + */ - indices.push( i, i + 1, 0 ); + function CircleGeometry( radius, segments, thetaStart, thetaLength ) { - } + Geometry.call( this ); - this.setIndex( new BufferAttribute( new Uint16Array( indices ), 1 ) ); - this.addAttribute( 'position', new BufferAttribute( positions, 3 ) ); - this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) ); - this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) ); + this.type = 'CircleGeometry'; - this.boundingSphere = new Sphere( new Vector3(), radius ); + this.parameters = { + radius: radius, + segments: segments, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - }; + this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) ); - CircleBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); - CircleBufferGeometry.prototype.constructor = CircleBufferGeometry; + } - /** - * @author hughes - */ + CircleGeometry.prototype = Object.create( Geometry.prototype ); + CircleGeometry.prototype.constructor = CircleGeometry; - function CircleGeometry( radius, segments, thetaStart, thetaLength ) { + /** + * @author zz85 https://github.com/zz85 + * + * Centripetal CatmullRom Curve - which is useful for avoiding + * cusps and self-intersections in non-uniform catmull rom curves. + * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf + * + * curve.type accepts centripetal(default), chordal and catmullrom + * curve.tension is used for catmullrom which defaults to 0.5 + */ - Geometry.call( this ); + exports.CatmullRomCurve3 = ( function() { - this.type = 'CircleGeometry'; + var + tmp = new Vector3(), + px = new CubicPoly(), + py = new CubicPoly(), + pz = new CubicPoly(); - this.parameters = { - radius: radius, - segments: segments, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + /* + Based on an optimized c++ solution in + - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/ + - http://ideone.com/NoEbVM - this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) ); + This CubicPoly class could be used for reusing some variables and calculations, + but for three.js curve use, it could be possible inlined and flatten into a single function call + which can be placed in CurveUtils. + */ - }; + function CubicPoly() { - CircleGeometry.prototype = Object.create( Geometry.prototype ); - CircleGeometry.prototype.constructor = CircleGeometry; + } - /** - * @author zz85 https://github.com/zz85 - * - * Centripetal CatmullRom Curve - which is useful for avoiding - * cusps and self-intersections in non-uniform catmull rom curves. - * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf - * - * curve.type accepts centripetal(default), chordal and catmullrom - * curve.tension is used for catmullrom which defaults to 0.5 - */ + /* + * Compute coefficients for a cubic polynomial + * p(s) = c0 + c1*s + c2*s^2 + c3*s^3 + * such that + * p(0) = x0, p(1) = x1 + * and + * p'(0) = t0, p'(1) = t1. + */ + CubicPoly.prototype.init = function( x0, x1, t0, t1 ) { - exports.CatmullRomCurve3 = ( function() { + this.c0 = x0; + this.c1 = t0; + this.c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1; + this.c3 = 2 * x0 - 2 * x1 + t0 + t1; - var - tmp = new Vector3(), - px = new CubicPoly(), - py = new CubicPoly(), - pz = new CubicPoly(); + }; - /* - Based on an optimized c++ solution in - - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/ - - http://ideone.com/NoEbVM + CubicPoly.prototype.initNonuniformCatmullRom = function( x0, x1, x2, x3, dt0, dt1, dt2 ) { - This CubicPoly class could be used for reusing some variables and calculations, - but for three.js curve use, it could be possible inlined and flatten into a single function call - which can be placed in CurveUtils. - */ + // compute tangents when parameterized in [t1,t2] + var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1; + var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2; - function CubicPoly() { + // rescale tangents for parametrization in [0,1] + t1 *= dt1; + t2 *= dt1; - } + // initCubicPoly + this.init( x1, x2, t1, t2 ); - /* - * Compute coefficients for a cubic polynomial - * p(s) = c0 + c1*s + c2*s^2 + c3*s^3 - * such that - * p(0) = x0, p(1) = x1 - * and - * p'(0) = t0, p'(1) = t1. - */ - CubicPoly.prototype.init = function( x0, x1, t0, t1 ) { + }; - this.c0 = x0; - this.c1 = t0; - this.c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1; - this.c3 = 2 * x0 - 2 * x1 + t0 + t1; + // standard Catmull-Rom spline: interpolate between x1 and x2 with previous/following points x1/x4 + CubicPoly.prototype.initCatmullRom = function( x0, x1, x2, x3, tension ) { - }; + this.init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) ); - CubicPoly.prototype.initNonuniformCatmullRom = function( x0, x1, x2, x3, dt0, dt1, dt2 ) { + }; - // compute tangents when parameterized in [t1,t2] - var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1; - var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2; + CubicPoly.prototype.calc = function( t ) { - // rescale tangents for parametrization in [0,1] - t1 *= dt1; - t2 *= dt1; + var t2 = t * t; + var t3 = t2 * t; + return this.c0 + this.c1 * t + this.c2 * t2 + this.c3 * t3; - // initCubicPoly - this.init( x1, x2, t1, t2 ); + }; - }; + // Subclass Three.js curve + return Curve.create( - // standard Catmull-Rom spline: interpolate between x1 and x2 with previous/following points x1/x4 - CubicPoly.prototype.initCatmullRom = function( x0, x1, x2, x3, tension ) { + function ( p /* array of Vector3 */ ) { - this.init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) ); + this.points = p || []; + this.closed = false; - }; + }, - CubicPoly.prototype.calc = function( t ) { + function ( t ) { - var t2 = t * t; - var t3 = t2 * t; - return this.c0 + this.c1 * t + this.c2 * t2 + this.c3 * t3; + var points = this.points, + point, intPoint, weight, l; - }; + l = points.length; - // Subclass Three.js curve - return Curve.create( + if ( l < 2 ) console.log( 'duh, you need at least 2 points' ); - function ( p /* array of Vector3 */ ) { + point = ( l - ( this.closed ? 0 : 1 ) ) * t; + intPoint = Math.floor( point ); + weight = point - intPoint; - this.points = p || []; - this.closed = false; + if ( this.closed ) { - }, + intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length; - function ( t ) { + } else if ( weight === 0 && intPoint === l - 1 ) { - var points = this.points, - point, intPoint, weight, l; + intPoint = l - 2; + weight = 1; - l = points.length; + } - if ( l < 2 ) console.log( 'duh, you need at least 2 points' ); + var p0, p1, p2, p3; // 4 points - point = ( l - ( this.closed ? 0 : 1 ) ) * t; - intPoint = Math.floor( point ); - weight = point - intPoint; + if ( this.closed || intPoint > 0 ) { - if ( this.closed ) { + p0 = points[ ( intPoint - 1 ) % l ]; - intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length; + } else { - } else if ( weight === 0 && intPoint === l - 1 ) { + // extrapolate first point + tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] ); + p0 = tmp; - intPoint = l - 2; - weight = 1; + } - } + p1 = points[ intPoint % l ]; + p2 = points[ ( intPoint + 1 ) % l ]; - var p0, p1, p2, p3; // 4 points + if ( this.closed || intPoint + 2 < l ) { - if ( this.closed || intPoint > 0 ) { + p3 = points[ ( intPoint + 2 ) % l ]; - p0 = points[ ( intPoint - 1 ) % l ]; + } else { - } else { + // extrapolate last point + tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] ); + p3 = tmp; - // extrapolate first point - tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] ); - p0 = tmp; + } - } + if ( this.type === undefined || this.type === 'centripetal' || this.type === 'chordal' ) { - p1 = points[ intPoint % l ]; - p2 = points[ ( intPoint + 1 ) % l ]; + // init Centripetal / Chordal Catmull-Rom + var pow = this.type === 'chordal' ? 0.5 : 0.25; + var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow ); + var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow ); + var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow ); - if ( this.closed || intPoint + 2 < l ) { + // safety check for repeated points + if ( dt1 < 1e-4 ) dt1 = 1.0; + if ( dt0 < 1e-4 ) dt0 = dt1; + if ( dt2 < 1e-4 ) dt2 = dt1; - p3 = points[ ( intPoint + 2 ) % l ]; + px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 ); + py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 ); + pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 ); - } else { + } else if ( this.type === 'catmullrom' ) { - // extrapolate last point - tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] ); - p3 = tmp; + var tension = this.tension !== undefined ? this.tension : 0.5; + px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, tension ); + py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, tension ); + pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, tension ); - } + } - if ( this.type === undefined || this.type === 'centripetal' || this.type === 'chordal' ) { + var v = new Vector3( + px.calc( weight ), + py.calc( weight ), + pz.calc( weight ) + ); - // init Centripetal / Chordal Catmull-Rom - var pow = this.type === 'chordal' ? 0.5 : 0.25; - var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow ); - var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow ); - var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow ); + return v; - // safety check for repeated points - if ( dt1 < 1e-4 ) dt1 = 1.0; - if ( dt0 < 1e-4 ) dt0 = dt1; - if ( dt2 < 1e-4 ) dt2 = dt1; + } - px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 ); - py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 ); - pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 ); + ); - } else if ( this.type === 'catmullrom' ) { + } )(); - var tension = this.tension !== undefined ? this.tension : 0.5; - px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, tension ); - py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, tension ); - pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, tension ); + /************************************************************** + * Closed Spline 3D curve + **************************************************************/ - } - var v = new Vector3( - px.calc( weight ), - py.calc( weight ), - pz.calc( weight ) - ); + function ClosedSplineCurve3( points ) { - return v; + console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Please use THREE.CatmullRomCurve3.' ); - } + exports.CatmullRomCurve3.call( this, points ); + this.type = 'catmullrom'; + this.closed = true; - ); + } - } )(); + ClosedSplineCurve3.prototype = Object.create( exports.CatmullRomCurve3.prototype ); - /************************************************************** - * Closed Spline 3D curve - **************************************************************/ + /************************************************************** + * Spline 3D curve + **************************************************************/ - function ClosedSplineCurve3( points ) { + var SplineCurve3 = Curve.create( - console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Please use THREE.CatmullRomCurve3.' ); + function ( points /* array of Vector3 */ ) { - exports.CatmullRomCurve3.call( this, points ); - this.type = 'catmullrom'; - this.closed = true; + console.warn( 'THREE.SplineCurve3 will be deprecated. Please use THREE.CatmullRomCurve3' ); + this.points = ( points === undefined ) ? [] : points; - }; + }, - ClosedSplineCurve3.prototype = Object.create( exports.CatmullRomCurve3.prototype ); + function ( t ) { - /************************************************************** - * Spline 3D curve - **************************************************************/ + var points = this.points; + var point = ( points.length - 1 ) * t; + var intPoint = Math.floor( point ); + var weight = point - intPoint; - var SplineCurve3 = Curve.create( + var point0 = points[ intPoint == 0 ? intPoint : intPoint - 1 ]; + var point1 = points[ intPoint ]; + var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ]; + var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ]; - function ( points /* array of Vector3 */ ) { + var interpolate = exports.CurveUtils.interpolate; - console.warn( 'THREE.SplineCurve3 will be deprecated. Please use THREE.CatmullRomCurve3' ); - this.points = ( points == undefined ) ? [] : points; + return new Vector3( + interpolate( point0.x, point1.x, point2.x, point3.x, weight ), + interpolate( point0.y, point1.y, point2.y, point3.y, weight ), + interpolate( point0.z, point1.z, point2.z, point3.z, weight ) + ); - }, + } - function ( t ) { + ); - var points = this.points; - var point = ( points.length - 1 ) * t; + /************************************************************** + * Cubic Bezier 3D curve + **************************************************************/ - var intPoint = Math.floor( point ); - var weight = point - intPoint; + exports.CubicBezierCurve3 = Curve.create( - var point0 = points[ intPoint == 0 ? intPoint : intPoint - 1 ]; - var point1 = points[ intPoint ]; - var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ]; - var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ]; + function ( v0, v1, v2, v3 ) { - var interpolate = exports.CurveUtils.interpolate; + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + this.v3 = v3; - return new Vector3( - interpolate( point0.x, point1.x, point2.x, point3.x, weight ), - interpolate( point0.y, point1.y, point2.y, point3.y, weight ), - interpolate( point0.z, point1.z, point2.z, point3.z, weight ) - ); + }, - } + function ( t ) { - ); + var b3 = exports.ShapeUtils.b3; - /************************************************************** - * Cubic Bezier 3D curve - **************************************************************/ + return new Vector3( + b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ), + b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ), + b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z ) + ); - exports.CubicBezierCurve3 = Curve.create( + } - function ( v0, v1, v2, v3 ) { + ); - this.v0 = v0; - this.v1 = v1; - this.v2 = v2; - this.v3 = v3; + /************************************************************** + * Quadratic Bezier 3D curve + **************************************************************/ - }, + exports.QuadraticBezierCurve3 = Curve.create( - function ( t ) { + function ( v0, v1, v2 ) { - var b3 = exports.ShapeUtils.b3; + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; - return new Vector3( - b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ), - b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ), - b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z ) - ); + }, - } + function ( t ) { - ); + var b2 = exports.ShapeUtils.b2; - /************************************************************** - * Quadratic Bezier 3D curve - **************************************************************/ + return new Vector3( + b2( t, this.v0.x, this.v1.x, this.v2.x ), + b2( t, this.v0.y, this.v1.y, this.v2.y ), + b2( t, this.v0.z, this.v1.z, this.v2.z ) + ); - exports.QuadraticBezierCurve3 = Curve.create( + } - function ( v0, v1, v2 ) { + ); - this.v0 = v0; - this.v1 = v1; - this.v2 = v2; + /************************************************************** + * Line3D + **************************************************************/ - }, + exports.LineCurve3 = Curve.create( - function ( t ) { + function ( v1, v2 ) { - var b2 = exports.ShapeUtils.b2; + this.v1 = v1; + this.v2 = v2; - return new Vector3( - b2( t, this.v0.x, this.v1.x, this.v2.x ), - b2( t, this.v0.y, this.v1.y, this.v2.y ), - b2( t, this.v0.z, this.v1.z, this.v2.z ) - ); + }, - } + function ( t ) { - ); + if ( t === 1 ) { - /************************************************************** - * Line3D - **************************************************************/ + return this.v2.clone(); - exports.LineCurve3 = Curve.create( + } - function ( v1, v2 ) { + var vector = new Vector3(); - this.v1 = v1; - this.v2 = v2; + vector.subVectors( this.v2, this.v1 ); // diff + vector.multiplyScalar( t ); + vector.add( this.v1 ); - }, + return vector; - function ( t ) { + } - if ( t === 1 ) { + ); - return this.v2.clone(); + /************************************************************** + * Arc curve + **************************************************************/ - } + function ArcCurve( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { - var vector = new Vector3(); + EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); - vector.subVectors( this.v2, this.v1 ); // diff - vector.multiplyScalar( t ); - vector.add( this.v1 ); + } - return vector; + ArcCurve.prototype = Object.create( EllipseCurve.prototype ); + ArcCurve.prototype.constructor = ArcCurve; - } + /** + * @author alteredq / http://alteredqualia.com/ + */ - ); + exports.SceneUtils = { - /************************************************************** - * Arc curve - **************************************************************/ + createMultiMaterialObject: function ( geometry, materials ) { - function ArcCurve( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { + var group = new Group(); - EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); + for ( var i = 0, l = materials.length; i < l; i ++ ) { - }; + group.add( new Mesh( geometry, materials[ i ] ) ); - ArcCurve.prototype = Object.create( EllipseCurve.prototype ); - ArcCurve.prototype.constructor = ArcCurve; + } - /** - * @author alteredq / http://alteredqualia.com/ - */ + return group; - exports.SceneUtils = { + }, - createMultiMaterialObject: function ( geometry, materials ) { + detach: function ( child, parent, scene ) { - var group = new Group(); + child.applyMatrix( parent.matrixWorld ); + parent.remove( child ); + scene.add( child ); - for ( var i = 0, l = materials.length; i < l; i ++ ) { + }, - group.add( new Mesh( geometry, materials[ i ] ) ); + attach: function ( child, scene, parent ) { - } + var matrixWorldInverse = new Matrix4(); + matrixWorldInverse.getInverse( parent.matrixWorld ); + child.applyMatrix( matrixWorldInverse ); - return group; + scene.remove( child ); + parent.add( child ); - }, + } - detach: function ( child, parent, scene ) { + }; - child.applyMatrix( parent.matrixWorld ); - parent.remove( child ); - scene.add( child ); - - }, - - attach: function ( child, scene, parent ) { - - var matrixWorldInverse = new Matrix4(); - matrixWorldInverse.getInverse( parent.matrixWorld ); - child.applyMatrix( matrixWorldInverse ); - - scene.remove( child ); - parent.add( child ); - - } - - }; - - Object.defineProperty( exports, 'AudioContext', { - get: function () { - return exports.getAudioContext(); - } - }); - - exports.SpritePlugin = SpritePlugin; - exports.LensFlarePlugin = LensFlarePlugin; - exports.WebGLTextures = WebGLTextures; - exports.WebGLStencilBuffer = WebGLStencilBuffer; - exports.WebGLDepthBuffer = WebGLDepthBuffer; - exports.WebGLColorBuffer = WebGLColorBuffer; - exports.WebGLState = WebGLState; - exports.WebGLShadowMap = WebGLShadowMap; - exports.WebGLProperties = WebGLProperties; - exports.WebGLPrograms = WebGLPrograms; - exports.WebGLObjects = WebGLObjects; - exports.WebGLLights = WebGLLights; - exports.WebGLGeometries = WebGLGeometries; - exports.WebGLCapabilities = WebGLCapabilities; - exports.WebGLExtensions = WebGLExtensions; - exports.WebGLIndexedBufferRenderer = WebGLIndexedBufferRenderer; - exports.WebGLClipping = WebGLClipping; - exports.WebGLBufferRenderer = WebGLBufferRenderer; - exports.WebGLRenderTargetCube = WebGLRenderTargetCube; - exports.WebGLRenderTarget = WebGLRenderTarget; - exports.WebGLRenderer = WebGLRenderer; - exports.ShaderChunk = ShaderChunk; - exports.FogExp2 = FogExp2; - exports.Fog = Fog; - exports.Scene = Scene; - exports.LensFlare = LensFlare; - exports.Sprite = Sprite; - exports.LOD = LOD; - exports.SkinnedMesh = SkinnedMesh; - exports.Skeleton = Skeleton; - exports.Bone = Bone; - exports.Mesh = Mesh; - exports.LineSegments = LineSegments; - exports.Line = Line; - exports.Points = Points; - exports.Group = Group; - exports.VideoTexture = VideoTexture; - exports.DataTexture = DataTexture; - exports.CompressedTexture = CompressedTexture; - exports.CubeTexture = CubeTexture; - exports.CanvasTexture = CanvasTexture; - exports.DepthTexture = DepthTexture; - exports.TextureIdCount = TextureIdCount; - exports.Texture = Texture; - exports.ShadowMaterial = ShadowMaterial; - exports.SpriteMaterial = SpriteMaterial; - exports.RawShaderMaterial = RawShaderMaterial; - exports.ShaderMaterial = ShaderMaterial; - exports.PointsMaterial = PointsMaterial; - exports.MultiMaterial = MultiMaterial; - exports.MeshPhysicalMaterial = MeshPhysicalMaterial; - exports.MeshStandardMaterial = MeshStandardMaterial; - exports.MeshPhongMaterial = MeshPhongMaterial; - exports.MeshNormalMaterial = MeshNormalMaterial; - exports.MeshLambertMaterial = MeshLambertMaterial; - exports.MeshDepthMaterial = MeshDepthMaterial; - exports.MeshBasicMaterial = MeshBasicMaterial; - exports.LineDashedMaterial = LineDashedMaterial; - exports.LineBasicMaterial = LineBasicMaterial; - exports.MaterialIdCount = MaterialIdCount; - exports.Material = Material; - exports.CompressedTextureLoader = CompressedTextureLoader; - exports.BinaryTextureLoader = BinaryTextureLoader; - exports.DataTextureLoader = DataTextureLoader; - exports.CubeTextureLoader = CubeTextureLoader; - exports.TextureLoader = TextureLoader; - exports.ObjectLoader = ObjectLoader; - exports.MaterialLoader = MaterialLoader; - exports.BufferGeometryLoader = BufferGeometryLoader; - exports.LoadingManager = LoadingManager; - exports.JSONLoader = JSONLoader; - exports.ImageLoader = ImageLoader; - exports.FontLoader = FontLoader; - exports.XHRLoader = XHRLoader; - exports.Loader = Loader; - exports.AudioLoader = AudioLoader; - exports.SpotLightShadow = SpotLightShadow; - exports.SpotLight = SpotLight; - exports.PointLight = PointLight; - exports.HemisphereLight = HemisphereLight; - exports.DirectionalLightShadow = DirectionalLightShadow; - exports.DirectionalLight = DirectionalLight; - exports.AmbientLight = AmbientLight; - exports.LightShadow = LightShadow; - exports.Light = Light; - exports.StereoCamera = StereoCamera; - exports.PerspectiveCamera = PerspectiveCamera; - exports.OrthographicCamera = OrthographicCamera; - exports.CubeCamera = CubeCamera; - exports.Camera = Camera; - exports.AudioListener = AudioListener; - exports.PositionalAudio = PositionalAudio; - exports.getAudioContext = getAudioContext; - exports.AudioAnalyser = AudioAnalyser; - exports.Audio = Audio; - exports.VectorKeyframeTrack = VectorKeyframeTrack; - exports.StringKeyframeTrack = StringKeyframeTrack; - exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack; - exports.NumberKeyframeTrack = NumberKeyframeTrack; - exports.ColorKeyframeTrack = ColorKeyframeTrack; - exports.BooleanKeyframeTrack = BooleanKeyframeTrack; - exports.PropertyMixer = PropertyMixer; - exports.PropertyBinding = PropertyBinding; - exports.KeyframeTrack = KeyframeTrack; - exports.AnimationObjectGroup = AnimationObjectGroup; - exports.AnimationMixer = AnimationMixer; - exports.AnimationClip = AnimationClip; - exports.AnimationAction = AnimationAction; - exports.Uniform = Uniform; - exports.InstancedBufferGeometry = InstancedBufferGeometry; - exports.BufferGeometry = BufferGeometry; - exports.DirectGeometry = DirectGeometry; - exports.GeometryIdCount = GeometryIdCount; - exports.Geometry = Geometry; - exports.InterleavedBufferAttribute = InterleavedBufferAttribute; - exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer; - exports.InterleavedBuffer = InterleavedBuffer; - exports.InstancedBufferAttribute = InstancedBufferAttribute; - exports.DynamicBufferAttribute = DynamicBufferAttribute; - exports.Float64Attribute = Float64Attribute; - exports.Float32Attribute = Float32Attribute; - exports.Uint32Attribute = Uint32Attribute; - exports.Int32Attribute = Int32Attribute; - exports.Uint16Attribute = Uint16Attribute; - exports.Int16Attribute = Int16Attribute; - exports.Uint8ClampedAttribute = Uint8ClampedAttribute; - exports.Uint8Attribute = Uint8Attribute; - exports.Int8Attribute = Int8Attribute; - exports.BufferAttribute = BufferAttribute; - exports.Face3 = Face3; - exports.Object3DIdCount = Object3DIdCount; - exports.Object3D = Object3D; - exports.Raycaster = Raycaster; - exports.Layers = Layers; - exports.EventDispatcher = EventDispatcher; - exports.Clock = Clock; - exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant; - exports.LinearInterpolant = LinearInterpolant; - exports.DiscreteInterpolant = DiscreteInterpolant; - exports.CubicInterpolant = CubicInterpolant; - exports.Interpolant = Interpolant; - exports.Triangle = Triangle; - exports.Spline = Spline; - exports.Spherical = Spherical; - exports.Plane = Plane; - exports.Frustum = Frustum; - exports.Sphere = Sphere; - exports.Ray = Ray; - exports.Matrix4 = Matrix4; - exports.Matrix3 = Matrix3; - exports.Box3 = Box3; - exports.Box2 = Box2; - exports.Line3 = Line3; - exports.Euler = Euler; - exports.Vector4 = Vector4; - exports.Vector3 = Vector3; - exports.Vector2 = Vector2; - exports.Quaternion = Quaternion; - exports.Color = Color; - exports.MorphBlendMesh = MorphBlendMesh; - exports.ImmediateRenderObject = ImmediateRenderObject; - exports.WireframeHelper = WireframeHelper; - exports.VertexNormalsHelper = VertexNormalsHelper; - exports.SpotLightHelper = SpotLightHelper; - exports.SkeletonHelper = SkeletonHelper; - exports.PointLightHelper = PointLightHelper; - exports.HemisphereLightHelper = HemisphereLightHelper; - exports.GridHelper = GridHelper; - exports.FaceNormalsHelper = FaceNormalsHelper; - exports.EdgesHelper = EdgesHelper; - exports.DirectionalLightHelper = DirectionalLightHelper; - exports.CameraHelper = CameraHelper; - exports.BoundingBoxHelper = BoundingBoxHelper; - exports.BoxHelper = BoxHelper; - exports.AxisHelper = AxisHelper; - exports.WireframeGeometry = WireframeGeometry; - exports.ParametricGeometry = ParametricGeometry; - exports.TetrahedronGeometry = TetrahedronGeometry; - exports.OctahedronGeometry = OctahedronGeometry; - exports.IcosahedronGeometry = IcosahedronGeometry; - exports.DodecahedronGeometry = DodecahedronGeometry; - exports.PolyhedronGeometry = PolyhedronGeometry; - exports.TubeGeometry = TubeGeometry; - exports.TorusKnotGeometry = TorusKnotGeometry; - exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry; - exports.TorusGeometry = TorusGeometry; - exports.TorusBufferGeometry = TorusBufferGeometry; - exports.TextGeometry = TextGeometry; - exports.SphereBufferGeometry = SphereBufferGeometry; - exports.SphereGeometry = SphereGeometry; - exports.RingGeometry = RingGeometry; - exports.RingBufferGeometry = RingBufferGeometry; - exports.PlaneBufferGeometry = PlaneBufferGeometry; - exports.PlaneGeometry = PlaneGeometry; - exports.LatheGeometry = LatheGeometry; - exports.LatheBufferGeometry = LatheBufferGeometry; - exports.ShapeGeometry = ShapeGeometry; - exports.ExtrudeGeometry = ExtrudeGeometry; - exports.EdgesGeometry = EdgesGeometry; - exports.ConeGeometry = ConeGeometry; - exports.ConeBufferGeometry = ConeBufferGeometry; - exports.CylinderGeometry = CylinderGeometry; - exports.CylinderBufferGeometry = CylinderBufferGeometry; - exports.CircleBufferGeometry = CircleBufferGeometry; - exports.CircleGeometry = CircleGeometry; - exports.BoxBufferGeometry = BoxBufferGeometry; - exports.BoxGeometry = BoxGeometry; - exports.ClosedSplineCurve3 = ClosedSplineCurve3; - exports.SplineCurve3 = SplineCurve3; - exports.ArcCurve = ArcCurve; - exports.EllipseCurve = EllipseCurve; - exports.SplineCurve = SplineCurve; - exports.CubicBezierCurve = CubicBezierCurve; - exports.QuadraticBezierCurve = QuadraticBezierCurve; - exports.LineCurve = LineCurve; - exports.Shape = Shape; - exports.ShapePath = ShapePath; - exports.Path = Path; - exports.Font = Font; - exports.CurvePath = CurvePath; - exports.Curve = Curve; - exports.REVISION = REVISION; - exports.MOUSE = MOUSE; - exports.CullFaceNone = CullFaceNone; - exports.CullFaceBack = CullFaceBack; - exports.CullFaceFront = CullFaceFront; - exports.CullFaceFrontBack = CullFaceFrontBack; - exports.FrontFaceDirectionCW = FrontFaceDirectionCW; - exports.FrontFaceDirectionCCW = FrontFaceDirectionCCW; - exports.BasicShadowMap = BasicShadowMap; - exports.PCFShadowMap = PCFShadowMap; - exports.PCFSoftShadowMap = PCFSoftShadowMap; - exports.FrontSide = FrontSide; - exports.BackSide = BackSide; - exports.DoubleSide = DoubleSide; - exports.FlatShading = FlatShading; - exports.SmoothShading = SmoothShading; - exports.NoColors = NoColors; - exports.FaceColors = FaceColors; - exports.VertexColors = VertexColors; - exports.NoBlending = NoBlending; - exports.NormalBlending = NormalBlending; - exports.AdditiveBlending = AdditiveBlending; - exports.SubtractiveBlending = SubtractiveBlending; - exports.MultiplyBlending = MultiplyBlending; - exports.CustomBlending = CustomBlending; - exports.AddEquation = AddEquation; - exports.SubtractEquation = SubtractEquation; - exports.ReverseSubtractEquation = ReverseSubtractEquation; - exports.MinEquation = MinEquation; - exports.MaxEquation = MaxEquation; - exports.ZeroFactor = ZeroFactor; - exports.OneFactor = OneFactor; - exports.SrcColorFactor = SrcColorFactor; - exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor; - exports.SrcAlphaFactor = SrcAlphaFactor; - exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor; - exports.DstAlphaFactor = DstAlphaFactor; - exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor; - exports.DstColorFactor = DstColorFactor; - exports.OneMinusDstColorFactor = OneMinusDstColorFactor; - exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor; - exports.NeverDepth = NeverDepth; - exports.AlwaysDepth = AlwaysDepth; - exports.LessDepth = LessDepth; - exports.LessEqualDepth = LessEqualDepth; - exports.EqualDepth = EqualDepth; - exports.GreaterEqualDepth = GreaterEqualDepth; - exports.GreaterDepth = GreaterDepth; - exports.NotEqualDepth = NotEqualDepth; - exports.MultiplyOperation = MultiplyOperation; - exports.MixOperation = MixOperation; - exports.AddOperation = AddOperation; - exports.NoToneMapping = NoToneMapping; - exports.LinearToneMapping = LinearToneMapping; - exports.ReinhardToneMapping = ReinhardToneMapping; - exports.Uncharted2ToneMapping = Uncharted2ToneMapping; - exports.CineonToneMapping = CineonToneMapping; - exports.UVMapping = UVMapping; - exports.CubeReflectionMapping = CubeReflectionMapping; - exports.CubeRefractionMapping = CubeRefractionMapping; - exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping; - exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping; - exports.SphericalReflectionMapping = SphericalReflectionMapping; - exports.CubeUVReflectionMapping = CubeUVReflectionMapping; - exports.CubeUVRefractionMapping = CubeUVRefractionMapping; - exports.RepeatWrapping = RepeatWrapping; - exports.ClampToEdgeWrapping = ClampToEdgeWrapping; - exports.MirroredRepeatWrapping = MirroredRepeatWrapping; - exports.NearestFilter = NearestFilter; - exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter; - exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter; - exports.LinearFilter = LinearFilter; - exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter; - exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter; - exports.UnsignedByteType = UnsignedByteType; - exports.ByteType = ByteType; - exports.ShortType = ShortType; - exports.UnsignedShortType = UnsignedShortType; - exports.IntType = IntType; - exports.UnsignedIntType = UnsignedIntType; - exports.FloatType = FloatType; - exports.HalfFloatType = HalfFloatType; - exports.UnsignedShort4444Type = UnsignedShort4444Type; - exports.UnsignedShort5551Type = UnsignedShort5551Type; - exports.UnsignedShort565Type = UnsignedShort565Type; - exports.UnsignedInt248Type = UnsignedInt248Type; - exports.AlphaFormat = AlphaFormat; - exports.RGBFormat = RGBFormat; - exports.RGBAFormat = RGBAFormat; - exports.LuminanceFormat = LuminanceFormat; - exports.LuminanceAlphaFormat = LuminanceAlphaFormat; - exports.RGBEFormat = RGBEFormat; - exports.DepthFormat = DepthFormat; - exports.DepthStencilFormat = DepthStencilFormat; - exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format; - exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format; - exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format; - exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format; - exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format; - exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format; - exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format; - exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format; - exports.RGB_ETC1_Format = RGB_ETC1_Format; - exports.LoopOnce = LoopOnce; - exports.LoopRepeat = LoopRepeat; - exports.LoopPingPong = LoopPingPong; - exports.InterpolateDiscrete = InterpolateDiscrete; - exports.InterpolateLinear = InterpolateLinear; - exports.InterpolateSmooth = InterpolateSmooth; - exports.ZeroCurvatureEnding = ZeroCurvatureEnding; - exports.ZeroSlopeEnding = ZeroSlopeEnding; - exports.WrapAroundEnding = WrapAroundEnding; - exports.TrianglesDrawMode = TrianglesDrawMode; - exports.TriangleStripDrawMode = TriangleStripDrawMode; - exports.TriangleFanDrawMode = TriangleFanDrawMode; - exports.LinearEncoding = LinearEncoding; - exports.sRGBEncoding = sRGBEncoding; - exports.GammaEncoding = GammaEncoding; - exports.RGBEEncoding = RGBEEncoding; - exports.LogLuvEncoding = LogLuvEncoding; - exports.RGBM7Encoding = RGBM7Encoding; - exports.RGBM16Encoding = RGBM16Encoding; - exports.RGBDEncoding = RGBDEncoding; - exports.BasicDepthPacking = BasicDepthPacking; - exports.RGBADepthPacking = RGBADepthPacking; - - Object.defineProperty(exports, '__esModule', { value: true }); - -})); + Object.defineProperty( exports, 'AudioContext', { + get: function () { + return exports.getAudioContext(); + } + }); + + exports.SpritePlugin = SpritePlugin; + exports.LensFlarePlugin = LensFlarePlugin; + exports.WebGLTextures = WebGLTextures; + exports.WebGLStencilBuffer = WebGLStencilBuffer; + exports.WebGLDepthBuffer = WebGLDepthBuffer; + exports.WebGLColorBuffer = WebGLColorBuffer; + exports.WebGLState = WebGLState; + exports.WebGLShadowMap = WebGLShadowMap; + exports.WebGLProperties = WebGLProperties; + exports.WebGLPrograms = WebGLPrograms; + exports.WebGLObjects = WebGLObjects; + exports.WebGLLights = WebGLLights; + exports.WebGLGeometries = WebGLGeometries; + exports.WebGLCapabilities = WebGLCapabilities; + exports.WebGLExtensions = WebGLExtensions; + exports.WebGLIndexedBufferRenderer = WebGLIndexedBufferRenderer; + exports.WebGLClipping = WebGLClipping; + exports.WebGLBufferRenderer = WebGLBufferRenderer; + exports.WebGLRenderTargetCube = WebGLRenderTargetCube; + exports.WebGLRenderTarget = WebGLRenderTarget; + exports.WebGLRenderer = WebGLRenderer; + exports.ShaderChunk = ShaderChunk; + exports.FogExp2 = FogExp2; + exports.Fog = Fog; + exports.Scene = Scene; + exports.LensFlare = LensFlare; + exports.Sprite = Sprite; + exports.LOD = LOD; + exports.SkinnedMesh = SkinnedMesh; + exports.Skeleton = Skeleton; + exports.Bone = Bone; + exports.Mesh = Mesh; + exports.LineSegments = LineSegments; + exports.Line = Line; + exports.Points = Points; + exports.Group = Group; + exports.VideoTexture = VideoTexture; + exports.DataTexture = DataTexture; + exports.CompressedTexture = CompressedTexture; + exports.CubeTexture = CubeTexture; + exports.CanvasTexture = CanvasTexture; + exports.DepthTexture = DepthTexture; + exports.TextureIdCount = TextureIdCount; + exports.Texture = Texture; + exports.ShadowMaterial = ShadowMaterial; + exports.SpriteMaterial = SpriteMaterial; + exports.RawShaderMaterial = RawShaderMaterial; + exports.ShaderMaterial = ShaderMaterial; + exports.PointsMaterial = PointsMaterial; + exports.MultiMaterial = MultiMaterial; + exports.MeshPhysicalMaterial = MeshPhysicalMaterial; + exports.MeshStandardMaterial = MeshStandardMaterial; + exports.MeshPhongMaterial = MeshPhongMaterial; + exports.MeshNormalMaterial = MeshNormalMaterial; + exports.MeshLambertMaterial = MeshLambertMaterial; + exports.MeshDepthMaterial = MeshDepthMaterial; + exports.MeshBasicMaterial = MeshBasicMaterial; + exports.LineDashedMaterial = LineDashedMaterial; + exports.LineBasicMaterial = LineBasicMaterial; + exports.MaterialIdCount = MaterialIdCount; + exports.Material = Material; + exports.CompressedTextureLoader = CompressedTextureLoader; + exports.BinaryTextureLoader = BinaryTextureLoader; + exports.DataTextureLoader = DataTextureLoader; + exports.CubeTextureLoader = CubeTextureLoader; + exports.TextureLoader = TextureLoader; + exports.ObjectLoader = ObjectLoader; + exports.MaterialLoader = MaterialLoader; + exports.BufferGeometryLoader = BufferGeometryLoader; + exports.LoadingManager = LoadingManager; + exports.JSONLoader = JSONLoader; + exports.ImageLoader = ImageLoader; + exports.FontLoader = FontLoader; + exports.XHRLoader = XHRLoader; + exports.Loader = Loader; + exports.AudioLoader = AudioLoader; + exports.SpotLightShadow = SpotLightShadow; + exports.SpotLight = SpotLight; + exports.PointLight = PointLight; + exports.HemisphereLight = HemisphereLight; + exports.DirectionalLightShadow = DirectionalLightShadow; + exports.DirectionalLight = DirectionalLight; + exports.AmbientLight = AmbientLight; + exports.LightShadow = LightShadow; + exports.Light = Light; + exports.StereoCamera = StereoCamera; + exports.PerspectiveCamera = PerspectiveCamera; + exports.OrthographicCamera = OrthographicCamera; + exports.CubeCamera = CubeCamera; + exports.Camera = Camera; + exports.AudioListener = AudioListener; + exports.PositionalAudio = PositionalAudio; + exports.getAudioContext = getAudioContext; + exports.AudioAnalyser = AudioAnalyser; + exports.Audio = Audio; + exports.VectorKeyframeTrack = VectorKeyframeTrack; + exports.StringKeyframeTrack = StringKeyframeTrack; + exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack; + exports.NumberKeyframeTrack = NumberKeyframeTrack; + exports.ColorKeyframeTrack = ColorKeyframeTrack; + exports.BooleanKeyframeTrack = BooleanKeyframeTrack; + exports.PropertyMixer = PropertyMixer; + exports.PropertyBinding = PropertyBinding; + exports.KeyframeTrack = KeyframeTrack; + exports.AnimationObjectGroup = AnimationObjectGroup; + exports.AnimationMixer = AnimationMixer; + exports.AnimationClip = AnimationClip; + exports.AnimationAction = AnimationAction; + exports.Uniform = Uniform; + exports.InstancedBufferGeometry = InstancedBufferGeometry; + exports.BufferGeometry = BufferGeometry; + exports.DirectGeometry = DirectGeometry; + exports.GeometryIdCount = GeometryIdCount; + exports.Geometry = Geometry; + exports.InterleavedBufferAttribute = InterleavedBufferAttribute; + exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer; + exports.InterleavedBuffer = InterleavedBuffer; + exports.InstancedBufferAttribute = InstancedBufferAttribute; + exports.DynamicBufferAttribute = DynamicBufferAttribute; + exports.Float64Attribute = Float64Attribute; + exports.Float32Attribute = Float32Attribute; + exports.Uint32Attribute = Uint32Attribute; + exports.Int32Attribute = Int32Attribute; + exports.Uint16Attribute = Uint16Attribute; + exports.Int16Attribute = Int16Attribute; + exports.Uint8ClampedAttribute = Uint8ClampedAttribute; + exports.Uint8Attribute = Uint8Attribute; + exports.Int8Attribute = Int8Attribute; + exports.BufferAttribute = BufferAttribute; + exports.Face3 = Face3; + exports.Object3DIdCount = Object3DIdCount; + exports.Object3D = Object3D; + exports.Raycaster = Raycaster; + exports.Layers = Layers; + exports.EventDispatcher = EventDispatcher; + exports.Clock = Clock; + exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant; + exports.LinearInterpolant = LinearInterpolant; + exports.DiscreteInterpolant = DiscreteInterpolant; + exports.CubicInterpolant = CubicInterpolant; + exports.Interpolant = Interpolant; + exports.Triangle = Triangle; + exports.Spline = Spline; + exports.Spherical = Spherical; + exports.Plane = Plane; + exports.Frustum = Frustum; + exports.Sphere = Sphere; + exports.Ray = Ray; + exports.Matrix4 = Matrix4; + exports.Matrix3 = Matrix3; + exports.Box3 = Box3; + exports.Box2 = Box2; + exports.Line3 = Line3; + exports.Euler = Euler; + exports.Vector4 = Vector4; + exports.Vector3 = Vector3; + exports.Vector2 = Vector2; + exports.Quaternion = Quaternion; + exports.Color = Color; + exports.MorphBlendMesh = MorphBlendMesh; + exports.ImmediateRenderObject = ImmediateRenderObject; + exports.WireframeHelper = WireframeHelper; + exports.VertexNormalsHelper = VertexNormalsHelper; + exports.SpotLightHelper = SpotLightHelper; + exports.SkeletonHelper = SkeletonHelper; + exports.PointLightHelper = PointLightHelper; + exports.HemisphereLightHelper = HemisphereLightHelper; + exports.GridHelper = GridHelper; + exports.FaceNormalsHelper = FaceNormalsHelper; + exports.EdgesHelper = EdgesHelper; + exports.DirectionalLightHelper = DirectionalLightHelper; + exports.CameraHelper = CameraHelper; + exports.BoundingBoxHelper = BoundingBoxHelper; + exports.BoxHelper = BoxHelper; + exports.AxisHelper = AxisHelper; + exports.WireframeGeometry = WireframeGeometry; + exports.ParametricGeometry = ParametricGeometry; + exports.TetrahedronGeometry = TetrahedronGeometry; + exports.OctahedronGeometry = OctahedronGeometry; + exports.IcosahedronGeometry = IcosahedronGeometry; + exports.DodecahedronGeometry = DodecahedronGeometry; + exports.PolyhedronGeometry = PolyhedronGeometry; + exports.TubeGeometry = TubeGeometry; + exports.TorusKnotGeometry = TorusKnotGeometry; + exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry; + exports.TorusGeometry = TorusGeometry; + exports.TorusBufferGeometry = TorusBufferGeometry; + exports.TextGeometry = TextGeometry; + exports.SphereBufferGeometry = SphereBufferGeometry; + exports.SphereGeometry = SphereGeometry; + exports.RingGeometry = RingGeometry; + exports.RingBufferGeometry = RingBufferGeometry; + exports.PlaneBufferGeometry = PlaneBufferGeometry; + exports.PlaneGeometry = PlaneGeometry; + exports.LatheGeometry = LatheGeometry; + exports.LatheBufferGeometry = LatheBufferGeometry; + exports.ShapeGeometry = ShapeGeometry; + exports.ExtrudeGeometry = ExtrudeGeometry; + exports.EdgesGeometry = EdgesGeometry; + exports.ConeGeometry = ConeGeometry; + exports.ConeBufferGeometry = ConeBufferGeometry; + exports.CylinderGeometry = CylinderGeometry; + exports.CylinderBufferGeometry = CylinderBufferGeometry; + exports.CircleBufferGeometry = CircleBufferGeometry; + exports.CircleGeometry = CircleGeometry; + exports.BoxBufferGeometry = BoxBufferGeometry; + exports.BoxGeometry = BoxGeometry; + exports.ClosedSplineCurve3 = ClosedSplineCurve3; + exports.SplineCurve3 = SplineCurve3; + exports.ArcCurve = ArcCurve; + exports.EllipseCurve = EllipseCurve; + exports.SplineCurve = SplineCurve; + exports.CubicBezierCurve = CubicBezierCurve; + exports.QuadraticBezierCurve = QuadraticBezierCurve; + exports.LineCurve = LineCurve; + exports.Shape = Shape; + exports.ShapePath = ShapePath; + exports.Path = Path; + exports.Font = Font; + exports.CurvePath = CurvePath; + exports.Curve = Curve; + exports.REVISION = REVISION; + exports.MOUSE = MOUSE; + exports.CullFaceNone = CullFaceNone; + exports.CullFaceBack = CullFaceBack; + exports.CullFaceFront = CullFaceFront; + exports.CullFaceFrontBack = CullFaceFrontBack; + exports.FrontFaceDirectionCW = FrontFaceDirectionCW; + exports.FrontFaceDirectionCCW = FrontFaceDirectionCCW; + exports.BasicShadowMap = BasicShadowMap; + exports.PCFShadowMap = PCFShadowMap; + exports.PCFSoftShadowMap = PCFSoftShadowMap; + exports.FrontSide = FrontSide; + exports.BackSide = BackSide; + exports.DoubleSide = DoubleSide; + exports.FlatShading = FlatShading; + exports.SmoothShading = SmoothShading; + exports.NoColors = NoColors; + exports.FaceColors = FaceColors; + exports.VertexColors = VertexColors; + exports.NoBlending = NoBlending; + exports.NormalBlending = NormalBlending; + exports.AdditiveBlending = AdditiveBlending; + exports.SubtractiveBlending = SubtractiveBlending; + exports.MultiplyBlending = MultiplyBlending; + exports.CustomBlending = CustomBlending; + exports.AddEquation = AddEquation; + exports.SubtractEquation = SubtractEquation; + exports.ReverseSubtractEquation = ReverseSubtractEquation; + exports.MinEquation = MinEquation; + exports.MaxEquation = MaxEquation; + exports.ZeroFactor = ZeroFactor; + exports.OneFactor = OneFactor; + exports.SrcColorFactor = SrcColorFactor; + exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor; + exports.SrcAlphaFactor = SrcAlphaFactor; + exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor; + exports.DstAlphaFactor = DstAlphaFactor; + exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor; + exports.DstColorFactor = DstColorFactor; + exports.OneMinusDstColorFactor = OneMinusDstColorFactor; + exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor; + exports.NeverDepth = NeverDepth; + exports.AlwaysDepth = AlwaysDepth; + exports.LessDepth = LessDepth; + exports.LessEqualDepth = LessEqualDepth; + exports.EqualDepth = EqualDepth; + exports.GreaterEqualDepth = GreaterEqualDepth; + exports.GreaterDepth = GreaterDepth; + exports.NotEqualDepth = NotEqualDepth; + exports.MultiplyOperation = MultiplyOperation; + exports.MixOperation = MixOperation; + exports.AddOperation = AddOperation; + exports.NoToneMapping = NoToneMapping; + exports.LinearToneMapping = LinearToneMapping; + exports.ReinhardToneMapping = ReinhardToneMapping; + exports.Uncharted2ToneMapping = Uncharted2ToneMapping; + exports.CineonToneMapping = CineonToneMapping; + exports.UVMapping = UVMapping; + exports.CubeReflectionMapping = CubeReflectionMapping; + exports.CubeRefractionMapping = CubeRefractionMapping; + exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping; + exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping; + exports.SphericalReflectionMapping = SphericalReflectionMapping; + exports.CubeUVReflectionMapping = CubeUVReflectionMapping; + exports.CubeUVRefractionMapping = CubeUVRefractionMapping; + exports.RepeatWrapping = RepeatWrapping; + exports.ClampToEdgeWrapping = ClampToEdgeWrapping; + exports.MirroredRepeatWrapping = MirroredRepeatWrapping; + exports.NearestFilter = NearestFilter; + exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter; + exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter; + exports.LinearFilter = LinearFilter; + exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter; + exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter; + exports.UnsignedByteType = UnsignedByteType; + exports.ByteType = ByteType; + exports.ShortType = ShortType; + exports.UnsignedShortType = UnsignedShortType; + exports.IntType = IntType; + exports.UnsignedIntType = UnsignedIntType; + exports.FloatType = FloatType; + exports.HalfFloatType = HalfFloatType; + exports.UnsignedShort4444Type = UnsignedShort4444Type; + exports.UnsignedShort5551Type = UnsignedShort5551Type; + exports.UnsignedShort565Type = UnsignedShort565Type; + exports.UnsignedInt248Type = UnsignedInt248Type; + exports.AlphaFormat = AlphaFormat; + exports.RGBFormat = RGBFormat; + exports.RGBAFormat = RGBAFormat; + exports.LuminanceFormat = LuminanceFormat; + exports.LuminanceAlphaFormat = LuminanceAlphaFormat; + exports.RGBEFormat = RGBEFormat; + exports.DepthFormat = DepthFormat; + exports.DepthStencilFormat = DepthStencilFormat; + exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format; + exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format; + exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format; + exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format; + exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format; + exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format; + exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format; + exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format; + exports.RGB_ETC1_Format = RGB_ETC1_Format; + exports.LoopOnce = LoopOnce; + exports.LoopRepeat = LoopRepeat; + exports.LoopPingPong = LoopPingPong; + exports.InterpolateDiscrete = InterpolateDiscrete; + exports.InterpolateLinear = InterpolateLinear; + exports.InterpolateSmooth = InterpolateSmooth; + exports.ZeroCurvatureEnding = ZeroCurvatureEnding; + exports.ZeroSlopeEnding = ZeroSlopeEnding; + exports.WrapAroundEnding = WrapAroundEnding; + exports.TrianglesDrawMode = TrianglesDrawMode; + exports.TriangleStripDrawMode = TriangleStripDrawMode; + exports.TriangleFanDrawMode = TriangleFanDrawMode; + exports.LinearEncoding = LinearEncoding; + exports.sRGBEncoding = sRGBEncoding; + exports.GammaEncoding = GammaEncoding; + exports.RGBEEncoding = RGBEEncoding; + exports.LogLuvEncoding = LogLuvEncoding; + exports.RGBM7Encoding = RGBM7Encoding; + exports.RGBM16Encoding = RGBM16Encoding; + exports.RGBDEncoding = RGBDEncoding; + exports.BasicDepthPacking = BasicDepthPacking; + exports.RGBADepthPacking = RGBADepthPacking; + + Object.defineProperty(exports, '__esModule', { value: true }); + +}))); /** * @author mrdoob / http://mrdoob.com/ */ Object.assign( THREE, { + CubeGeometry: THREE.BoxGeometry, Face4: function ( a, b, c, d, normal, color, materialIndex ) { console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' ); return new THREE.Face3( a, b, c, normal, color, materialIndex ); diff --git a/build/three.min.js b/build/three.min.js index ced4ec8c54a012..122ef0932eecf9 100644 --- a/build/three.min.js +++ b/build/three.min.js @@ -1,14 +1,14 @@ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e(t.THREE=t.THREE||{})}(this,function(t){"use strict";function e(){}function i(t,e){this.x=t||0,this.y=e||0}function n(e,a,o,s,c,h,l,u,p,d){Object.defineProperty(this,"id",{value:r()}),this.uuid=t.Math.generateUUID(),this.name="",this.sourceFile="",this.image=void 0!==e?e:n.DEFAULT_IMAGE,this.mipmaps=[],this.mapping=void 0!==a?a:n.DEFAULT_MAPPING,this.wrapS=void 0!==o?o:xr,this.wrapT=void 0!==s?s:xr,this.magFilter=void 0!==c?c:Er,this.minFilter=void 0!==h?h:Sr,this.anisotropy=void 0!==p?p:1,this.format=void 0!==l?l:Hr,this.type=void 0!==u?u:Ar,this.offset=new i(0,0),this.repeat=new i(1,1),this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.encoding=void 0!==d?d:fa,this.version=0,this.onUpdate=null}function r(){return Ea++}function a(){this.elements=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),arguments.length>0&&console.error("THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.")}function o(t,e,i,n){this._x=t||0,this._y=e||0,this._z=i||0,this._w=void 0!==n?n:1}function s(t,e,i){this.x=t||0,this.y=e||0,this.z=i||0}function c(t,e){function i(){var t=new Float32Array([-.5,-.5,0,0,.5,-.5,1,0,.5,.5,1,1,-.5,.5,0,1]),e=new Uint16Array([0,1,2,0,2,3]);c=f.createBuffer(),h=f.createBuffer(),f.bindBuffer(f.ARRAY_BUFFER,c),f.bufferData(f.ARRAY_BUFFER,t,f.STATIC_DRAW),f.bindBuffer(f.ELEMENT_ARRAY_BUFFER,h),f.bufferData(f.ELEMENT_ARRAY_BUFFER,e,f.STATIC_DRAW),l=r(),u={position:f.getAttribLocation(l,"position"),uv:f.getAttribLocation(l,"uv")},p={uvOffset:f.getUniformLocation(l,"uvOffset"),uvScale:f.getUniformLocation(l,"uvScale"),rotation:f.getUniformLocation(l,"rotation"),scale:f.getUniformLocation(l,"scale"),color:f.getUniformLocation(l,"color"),map:f.getUniformLocation(l,"map"),opacity:f.getUniformLocation(l,"opacity"),modelViewMatrix:f.getUniformLocation(l,"modelViewMatrix"),projectionMatrix:f.getUniformLocation(l,"projectionMatrix"),fogType:f.getUniformLocation(l,"fogType"),fogDensity:f.getUniformLocation(l,"fogDensity"),fogNear:f.getUniformLocation(l,"fogNear"),fogFar:f.getUniformLocation(l,"fogFar"),fogColor:f.getUniformLocation(l,"fogColor"),alphaTest:f.getUniformLocation(l,"alphaTest")};var i=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");i.width=8,i.height=8;var a=i.getContext("2d");a.fillStyle="white",a.fillRect(0,0,8,8),d=new n(i),d.needsUpdate=!0}function r(){var e=f.createProgram(),i=f.createShader(f.VERTEX_SHADER),n=f.createShader(f.FRAGMENT_SHADER);return f.shaderSource(i,["precision "+t.getPrecision()+" float;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform float rotation;","uniform vec2 scale;","uniform vec2 uvOffset;","uniform vec2 uvScale;","attribute vec2 position;","attribute vec2 uv;","varying vec2 vUV;","void main() {","vUV = uvOffset + uv * uvScale;","vec2 alignedPosition = position * scale;","vec2 rotatedPosition;","rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;","rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;","vec4 finalPosition;","finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );","finalPosition.xy += rotatedPosition;","finalPosition = projectionMatrix * finalPosition;","gl_Position = finalPosition;","}"].join("\n")),f.shaderSource(n,["precision "+t.getPrecision()+" float;","uniform vec3 color;","uniform sampler2D map;","uniform float opacity;","uniform int fogType;","uniform vec3 fogColor;","uniform float fogDensity;","uniform float fogNear;","uniform float fogFar;","uniform float alphaTest;","varying vec2 vUV;","void main() {","vec4 texture = texture2D( map, vUV );","if ( texture.a < alphaTest ) discard;","gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );","if ( fogType > 0 ) {","float depth = gl_FragCoord.z / gl_FragCoord.w;","float fogFactor = 0.0;","if ( fogType == 1 ) {","fogFactor = smoothstep( fogNear, fogFar, depth );","} else {","const float LOG2 = 1.442695;","fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );","fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );","}","gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );","}","}"].join("\n")),f.compileShader(i),f.compileShader(n),f.attachShader(e,i),f.attachShader(e,n),f.linkProgram(e),e}function a(t,e){return t.renderOrder!==e.renderOrder?t.renderOrder-e.renderOrder:t.z!==e.z?e.z-t.z:e.id-t.id}var c,h,l,u,p,d,f=t.context,m=t.state,v=new s,g=new o,y=new s;this.render=function(n,r){if(0!==e.length){void 0===l&&i(),f.useProgram(l),m.initAttributes(),m.enableAttribute(u.position),m.enableAttribute(u.uv),m.disableUnusedAttributes(),m.disable(f.CULL_FACE),m.enable(f.BLEND),f.bindBuffer(f.ARRAY_BUFFER,c),f.vertexAttribPointer(u.position,2,f.FLOAT,!1,16,0),f.vertexAttribPointer(u.uv,2,f.FLOAT,!1,16,8),f.bindBuffer(f.ELEMENT_ARRAY_BUFFER,h),f.uniformMatrix4fv(p.projectionMatrix,!1,r.projectionMatrix.elements),m.activeTexture(f.TEXTURE0),f.uniform1i(p.map,0);var o=0,s=0,x=n.fog;x?(f.uniform3f(p.fogColor,x.color.r,x.color.g,x.color.b),x&&x.isFog?(f.uniform1f(p.fogNear,x.near),f.uniform1f(p.fogFar,x.far),f.uniform1i(p.fogType,1),o=1,s=1):x&&x.isFogExp2&&(f.uniform1f(p.fogDensity,x.density),f.uniform1i(p.fogType,2),o=2,s=2)):(f.uniform1i(p.fogType,0),o=0,s=0);for(var _=0,b=e.length;_.001&&U.scale>.001&&(E.x=U.x,E.y=U.y,E.z=U.z,w=U.size*U.scale/g.w,M.x=w*x,M.y=w,m.uniform3f(p.screenPosition,E.x,E.y,E.z),m.uniform2f(p.scale,M.x,M.y),m.uniform1f(p.rotation,U.rotation),m.uniform1f(p.opacity,U.opacity),m.uniform3f(p.color,U.color.r,U.color.g,U.color.b),v.setBlending(U.blending,U.blendEquation,U.blendSrc,U.blendDst),t.setTexture2D(U.texture,1),m.drawElements(m.TRIANGLES,6,m.UNSIGNED_SHORT,0))}}}v.enable(m.CULL_FACE),v.enable(m.DEPTH_TEST),v.setDepthWrite(!0),t.resetGLState()}}}function u(t,e,i,r,a,o,s,c,h,l){t=void 0!==t?t:[],e=void 0!==e?e:ur,n.call(this,t,e,i,r,a,o,s,c,h,l),this.flipY=!1}function p(e,i,n,r,a,o,s){function c(t,e){if(t.width>e||t.height>e){var i=e/Math.max(t.width,t.height),n=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");n.width=Math.floor(t.width*i),n.height=Math.floor(t.height*i);var r=n.getContext("2d");return r.drawImage(t,0,0,t.width,t.height,0,0,n.width,n.height),console.warn("THREE.WebGLRenderer: image is too big ("+t.width+"x"+t.height+"). Resized to "+n.width+"x"+n.height,t),n}return t}function h(e){return t.Math.isPowerOfTwo(e.width)&&t.Math.isPowerOfTwo(e.height)}function l(e){if(e instanceof HTMLImageElement||e instanceof HTMLCanvasElement){var i=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");i.width=t.Math.nearestPowerOfTwo(e.width),i.height=t.Math.nearestPowerOfTwo(e.height);var n=i.getContext("2d");return n.drawImage(e,0,0,i.width,i.height),console.warn("THREE.WebGLRenderer: image is not power of two ("+e.width+"x"+e.height+"). Resized to "+i.width+"x"+i.height,e),i}return e}function u(t){return t.wrapS!==xr||t.wrapT!==xr||t.minFilter!==br&&t.minFilter!==Er}function p(t){return t===br||t===wr||t===Mr?e.NEAREST:e.LINEAR}function d(t){var e=t.target;e.removeEventListener("dispose",d),m(e),L.textures--}function f(t){var e=t.target;e.removeEventListener("dispose",f),v(e),L.textures--}function m(t){var i=r.get(t);if(t.image&&i.__image__webglTextureCube)e.deleteTexture(i.__image__webglTextureCube);else{if(void 0===i.__webglInit)return;e.deleteTexture(i.__webglTexture)}r.delete(t)}function v(t){var i=r.get(t),n=r.get(t.texture);if(t){if(void 0!==n.__webglTexture&&e.deleteTexture(n.__webglTexture),t.depthTexture&&t.depthTexture.dispose(),t&&t.isWebGLRenderTargetCube)for(var a=0;a<6;a++)e.deleteFramebuffer(i.__webglFramebuffer[a]),i.__webglDepthbuffer&&e.deleteRenderbuffer(i.__webglDepthbuffer[a]);else e.deleteFramebuffer(i.__webglFramebuffer),i.__webglDepthbuffer&&e.deleteRenderbuffer(i.__webglDepthbuffer);r.delete(t.texture),r.delete(t)}}function g(t,i){var a=r.get(t);if(t.version>0&&a.__version!==t.version){var o=t.image;if(void 0===o)console.warn("THREE.WebGLRenderer: Texture marked for update but image is undefined",t);else{if(o.complete!==!1)return void b(a,t,i);console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete",t)}}n.activeTexture(e.TEXTURE0+i),n.bindTexture(e.TEXTURE_2D,a.__webglTexture)}function y(t,i){var s=r.get(t);if(6===t.image.length)if(t.version>0&&s.__version!==t.version){s.__image__webglTextureCube||(t.addEventListener("dispose",d),s.__image__webglTextureCube=e.createTexture(),L.textures++),n.activeTexture(e.TEXTURE0+i),n.bindTexture(e.TEXTURE_CUBE_MAP,s.__image__webglTextureCube),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,t.flipY);for(var l=t&&t.isCompressedTexture,u=t.image[0]&&t.image[0].isDataTexture,p=[],f=0;f<6;f++)l||u?p[f]=u?t.image[f].image:t.image[f]:p[f]=c(t.image[f],a.maxCubemapSize);var m=p[0],v=h(m),g=o(t.format),y=o(t.type);_(e.TEXTURE_CUBE_MAP,t,v);for(var f=0;f<6;f++)if(l)for(var x,b=p[f].mipmaps,w=0,M=b.length;w-1?n.compressedTexImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+f,w,g,x.width,x.height,0,x.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+f,w,g,x.width,x.height,0,g,y,x.data);else u?n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+f,0,g,p[f].width,p[f].height,0,g,y,p[f].data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+f,0,g,g,y,p[f]);t.generateMipmaps&&v&&e.generateMipmap(e.TEXTURE_CUBE_MAP),s.__version=t.version,t.onUpdate&&t.onUpdate(t)}else n.activeTexture(e.TEXTURE0+i),n.bindTexture(e.TEXTURE_CUBE_MAP,s.__image__webglTextureCube)}function x(t,i){n.activeTexture(e.TEXTURE0+i),n.bindTexture(e.TEXTURE_CUBE_MAP,r.get(t).__webglTexture)}function _(t,n,s){var c;if(s?(e.texParameteri(t,e.TEXTURE_WRAP_S,o(n.wrapS)),e.texParameteri(t,e.TEXTURE_WRAP_T,o(n.wrapT)),e.texParameteri(t,e.TEXTURE_MAG_FILTER,o(n.magFilter)),e.texParameteri(t,e.TEXTURE_MIN_FILTER,o(n.minFilter))):(e.texParameteri(t,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(t,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),n.wrapS===xr&&n.wrapT===xr||console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.",n),e.texParameteri(t,e.TEXTURE_MAG_FILTER,p(n.magFilter)),e.texParameteri(t,e.TEXTURE_MIN_FILTER,p(n.minFilter)),n.minFilter!==br&&n.minFilter!==Er&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.",n)),c=i.get("EXT_texture_filter_anisotropic")){if(n.type===Ir&&null===i.get("OES_texture_float_linear"))return;if(n.type===Dr&&null===i.get("OES_texture_half_float_linear"))return;(n.anisotropy>1||r.get(n).__currentAnisotropy)&&(e.texParameterf(t,c.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(n.anisotropy,a.getMaxAnisotropy())),r.get(n).__currentAnisotropy=n.anisotropy)}}function b(t,i,r){void 0===t.__webglInit&&(t.__webglInit=!0,i.addEventListener("dispose",d),t.__webglTexture=e.createTexture(),L.textures++),n.activeTexture(e.TEXTURE0+r),n.bindTexture(e.TEXTURE_2D,t.__webglTexture),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,i.flipY),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,i.premultiplyAlpha),e.pixelStorei(e.UNPACK_ALIGNMENT,i.unpackAlignment);var s=c(i.image,a.maxTextureSize);u(i)&&h(s)===!1&&(s=l(s));var p=h(s),f=o(i.format),m=o(i.type);_(e.TEXTURE_2D,i,p);var v,g=i.mipmaps;if(i&&i.isDepthTexture){var y=e.DEPTH_COMPONENT;if(i.type===Ir){if(!R)throw new Error("Float Depth Texture only supported in WebGL2.0");y=e.DEPTH_COMPONENT32F}else R&&(y=e.DEPTH_COMPONENT16);i.format===Xr&&(y=e.DEPTH_STENCIL),n.texImage2D(e.TEXTURE_2D,0,y,s.width,s.height,0,f,m,null)}else if(i&&i.isDataTexture)if(g.length>0&&p){for(var x=0,b=g.length;x-1?n.compressedTexImage2D(e.TEXTURE_2D,x,f,v.width,v.height,0,v.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):n.texImage2D(e.TEXTURE_2D,x,f,v.width,v.height,0,f,m,v.data);else if(g.length>0&&p){for(var x=0,b=g.length;x0&&console.error("THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.")}function A(t,e){this.normal=void 0!==t?t:new s(1,0,0),this.constant=void 0!==e?e:0}function L(t,e,i,n,r,a){this.planes=[void 0!==t?t:new A,void 0!==e?e:new A,void 0!==i?i:new A,void 0!==n?n:new A,void 0!==r?r:new A,void 0!==a?a:new A]}function R(e,n,r,o){function c(t,i,n,r){var a=t.geometry,o=null,s=A,c=t.customDepthMaterial;if(n&&(s=R,c=t.customDistanceMaterial),c)o=c;else{var h=!1;i.morphTargets&&(a&&a.isBufferGeometry?h=a.morphAttributes&&a.morphAttributes.position&&a.morphAttributes.position.length>0:a&&a.isGeometry&&(h=a.morphTargets&&a.morphTargets.length>0));var l=t&&t.isSkinnedMesh&&i.skinning,u=0;h&&(u|=E),l&&(u|=T),o=s[u]}if(e.localClippingEnabled&&i.clipShadows===!0&&0!==i.clippingPlanes.length){var p=o.uuid,d=i.uuid,f=P[p];void 0===f&&(f={},P[p]=f);var m=f[d];void 0===m&&(m=o.clone(),f[d]=m),o=m}o.visible=i.visible,o.wireframe=i.wireframe;var v=i.side;return V.renderSingleSided&&v==_n&&(v=yn),V.renderReverseSided&&(v===yn?v=xn:v===xn&&(v=yn)),o.side=v,o.clipShadows=i.clipShadows,o.clippingPlanes=i.clippingPlanes,o.wireframeLinewidth=i.wireframeLinewidth,o.linewidth=i.linewidth,n&&void 0!==o.uniforms.lightPos&&o.uniforms.lightPos.value.copy(r),o}function h(t,e,i){if(t.visible!==!1){if(t.layers.test(e.layers)&&(t&&t.isMesh||t&&t.isLine||t&&t.isPoints)&&t.castShadow&&(t.frustumCulled===!1||p.intersectsObject(t)===!0)){var n=t.material;n.visible===!0&&(t.modelViewMatrix.multiplyMatrices(i.matrixWorldInverse,t.matrixWorld),w.push(t))}for(var r=t.children,a=0,o=r.length;a0,shadowMapType:e.shadowMap.type,toneMapping:e.toneMapping,physicallyCorrectLights:e.physicallyCorrectLights,premultipliedAlpha:t.premultipliedAlpha,alphaTest:t.alphaTest,doubleSided:t.side===_n,flipSided:t.side===xn,depthPacking:void 0!==t.depthPacking&&t.depthPacking};return f},this.getProgramCode=function(t,e){var i=[];if(e.shaderID?i.push(e.shaderID):(i.push(t.fragmentShader),i.push(t.vertexShader)),void 0!==t.defines)for(var n in t.defines)i.push(n),i.push(t.defines[n]);for(var r=0;r65535?Uint32Array:Uint16Array,y=new U(new g(a),1);return r(y,t.ELEMENT_ARRAY_BUFFER),n.wireframe=y,y}function h(t,e,i){if(e>i){var n=e;e=i,i=n}var r=t[e];return void 0===r?(t[e]=[i],!0):r.indexOf(i)===-1&&(r.push(i),!0)}var l=new K(t,e,i);this.getAttributeBuffer=s,this.getWireframeAttribute=c,this.update=n}function tt(){var t={};this.get=function(e){if(void 0!==t[e.id])return t[e.id];var n;switch(e.type){case"DirectionalLight":n={direction:new s,color:new w,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new i};break;case"SpotLight":n={position:new s,direction:new s,color:new w,distance:0,coneCos:0,penumbraCos:0,decay:0,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new i};break;case"PointLight":n={position:new s,color:new w,distance:0,decay:0,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new i};break;case"HemisphereLight":n={direction:new s,skyColor:new w,groundColor:new w}}return t[e.id]=n,n}}function et(t,e,i){function n(){if(void 0!==a)return a;var i=e.get("EXT_texture_filter_anisotropic");return a=null!==i?t.getParameter(i.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0}function r(e){if("highp"===e){if(t.getShaderPrecisionFormat(t.VERTEX_SHADER,t.HIGH_FLOAT).precision>0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.HIGH_FLOAT).precision>0)return"highp";e="mediump"}return"mediump"===e&&t.getShaderPrecisionFormat(t.VERTEX_SHADER,t.MEDIUM_FLOAT).precision>0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}var a;this.getMaxAnisotropy=n,this.getMaxPrecision=r,this.precision=void 0!==i.precision?i.precision:"highp",this.logarithmicDepthBuffer=void 0!==i.logarithmicDepthBuffer&&i.logarithmicDepthBuffer,this.maxTextures=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS),this.maxVertexTextures=t.getParameter(t.MAX_VERTEX_TEXTURE_IMAGE_UNITS),this.maxTextureSize=t.getParameter(t.MAX_TEXTURE_SIZE),this.maxCubemapSize=t.getParameter(t.MAX_CUBE_MAP_TEXTURE_SIZE),this.maxAttributes=t.getParameter(t.MAX_VERTEX_ATTRIBS),this.maxVertexUniforms=t.getParameter(t.MAX_VERTEX_UNIFORM_VECTORS),this.maxVaryings=t.getParameter(t.MAX_VARYING_VECTORS),this.maxFragmentUniforms=t.getParameter(t.MAX_FRAGMENT_UNIFORM_VECTORS),this.vertexTextures=this.maxVertexTextures>0,this.floatFragmentTextures=!!e.get("OES_texture_float"),this.floatVertexTextures=this.vertexTextures&&this.floatFragmentTextures;var o=r(this.precision);o!==this.precision&&(console.warn("THREE.WebGLRenderer:",this.precision,"not supported, using",o,"instead."),this.precision=o),this.logarithmicDepthBuffer&&(this.logarithmicDepthBuffer=!!e.get("EXT_frag_depth"))}function it(t){var e={};this.get=function(i){if(void 0!==e[i])return e[i];var n;switch(i){case"WEBGL_depth_texture":n=t.getExtension("WEBGL_depth_texture")||t.getExtension("MOZ_WEBGL_depth_texture")||t.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":n=t.getExtension("EXT_texture_filter_anisotropic")||t.getExtension("MOZ_EXT_texture_filter_anisotropic")||t.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":n=t.getExtension("WEBGL_compressed_texture_s3tc")||t.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||t.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":n=t.getExtension("WEBGL_compressed_texture_pvrtc")||t.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;case"WEBGL_compressed_texture_etc1":n=t.getExtension("WEBGL_compressed_texture_etc1");break;default:n=t.getExtension(i)}return null===n&&console.warn("THREE.WebGLRenderer: "+i+" extension not supported."),e[i]=n,n}}function nt(t,e,i){function n(t){s=t}function r(i){i.array instanceof Uint32Array&&e.get("OES_element_index_uint")?(c=t.UNSIGNED_INT,h=4):(c=t.UNSIGNED_SHORT,h=2)}function a(e,n){t.drawElements(s,n,c,e*h),i.calls++,i.vertices+=n,s===t.TRIANGLES&&(i.faces+=n/3)}function o(n,r,a){var o=e.get("ANGLE_instanced_arrays");return null===o?void console.error("THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays."):(o.drawElementsInstancedANGLE(s,a,c,r*h,n.maxInstancedCount),i.calls++,i.vertices+=a*n.maxInstancedCount,void(s===t.TRIANGLES&&(i.faces+=n.maxInstancedCount*a/3)))}var s,c,h;this.setMode=n,this.setIndex=r,this.render=a,this.renderInstances=o}function rt(){function t(){h.value!==n&&(h.value=n,h.needsUpdate=r>0),i.numPlanes=r}function e(t,e,n,r){var a=null!==t?t.length:0,o=null;if(0!==a){if(o=h.value,r!==!0||null===o){var l=n+4*a,u=e.matrixWorldInverse;c.getNormalMatrix(u),(null===o||o.length0?1:-1,m[g]=C.x,m[g+1]=C.y,m[g+2]=C.z,v[y]=D/h,v[y+1]=1-U/u,g+=3,y+=2,R+=1}for(U=0;U65535?Uint32Array:Uint16Array)(p),f=new Float32Array(3*u),m=new Float32Array(3*u),v=new Float32Array(2*u),g=0,y=0,x=0,_=0,b=0;h("z","y","x",-1,-1,i,e,t,a,r,0),h("z","y","x",1,-1,i,e,-t,a,r,1),h("x","z","y",1,1,t,i,e,n,a,2),h("x","z","y",1,-1,t,i,-e,n,a,3),h("x","y","z",1,-1,t,e,i,n,r,4),h("x","y","z",-1,-1,t,e,-i,n,r,5),this.setIndex(new U(d,1)),this.addAttribute("position",new U(f,3)),this.addAttribute("normal",new U(m,3)),this.addAttribute("uv",new U(v,2))}function ct(t,e){this.origin=void 0!==t?t:new s,this.direction=void 0!==e?e:new s}function ht(t,e){this.start=void 0!==t?t:new s,this.end=void 0!==e?e:new s}function lt(t,e,i){this.a=void 0!==t?t:new s,this.b=void 0!==e?e:new s,this.c=void 0!==i?i:new s}function ut(t){x.call(this),this.type="MeshBasicMaterial",this.color=new w(16777215),this.map=null,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=ir,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.skinning=!1,this.morphTargets=!1,this.lights=!1,this.setValues(t)}function pt(t,e){X.call(this),this.type="Mesh",this.geometry=void 0!==t?t:new Q,this.material=void 0!==e?e:new ut({color:16777215*Math.random()}),this.drawMode=ua,this.updateMorphTargets()}function dt(t,e,i,n){Q.call(this),this.type="PlaneBufferGeometry",this.parameters={width:t,height:e,widthSegments:i,heightSegments:n};for(var r=t/2,a=e/2,o=Math.floor(i)||1,s=Math.floor(n)||1,c=o+1,h=s+1,l=t/o,u=e/s,p=new Float32Array(c*h*3),d=new Float32Array(c*h*3),f=new Float32Array(c*h*2),m=0,v=0,g=0;g65535?Uint32Array:Uint16Array)(o*s*6),g=0;g=0){var l=a[c];if(void 0!==l){var u=ee.FLOAT,p=l.array,d=l.normalized;p instanceof Float32Array?u=ee.FLOAT:p instanceof Float64Array?console.warn("Unsupported data buffer format: Float64Array"):p instanceof Uint16Array?u=ee.UNSIGNED_SHORT:p instanceof Int16Array?u=ee.SHORT:p instanceof Uint32Array?u=ee.UNSIGNED_INT:p instanceof Int32Array?u=ee.INT:p instanceof Int8Array?u=ee.BYTE:p instanceof Uint8Array&&(u=ee.UNSIGNED_BYTE);var f=l.itemSize,m=ce.getAttributeBuffer(l);if(l&&l.isInterleavedBufferAttribute){var v=l.data,g=v.stride,y=l.offset;v&&v.isInstancedInterleavedBuffer?(ae.enableAttributeAndDivisor(h,v.meshPerAttribute,r),void 0===i.maxInstancedCount&&(i.maxInstancedCount=v.meshPerAttribute*v.count)):ae.enableAttribute(h),ee.bindBuffer(ee.ARRAY_BUFFER,m),ee.vertexAttribPointer(h,f,u,d,g*v.array.BYTES_PER_ELEMENT,(n*g+y)*v.array.BYTES_PER_ELEMENT)}else l&&l.isInstancedBufferAttribute?(ae.enableAttributeAndDivisor(h,l.meshPerAttribute,r),void 0===i.maxInstancedCount&&(i.maxInstancedCount=l.meshPerAttribute*l.count)):ae.enableAttribute(h),ee.bindBuffer(ee.ARRAY_BUFFER,m),ee.vertexAttribPointer(h,f,u,d,0,n*f*l.array.BYTES_PER_ELEMENT)}else if(void 0!==s){var x=s[c];if(void 0!==x)switch(x.length){case 2:ee.vertexAttrib2fv(h,x);break;case 3:ee.vertexAttrib3fv(h,x);break;case 4:ee.vertexAttrib4fv(h,x);break;default:ee.vertexAttrib1fv(h,x)}}}}ae.disableUnusedAttributes()}function y(t,e){return Math.abs(e[0])-Math.abs(t[0])}function x(t,e){return t.object.renderOrder!==e.object.renderOrder?t.object.renderOrder-e.object.renderOrder:t.material.program&&e.material.program&&t.material.program!==e.material.program?t.material.program.id-e.material.program.id:t.material.id!==e.material.id?t.material.id-e.material.id:t.z!==e.z?t.z-e.z:t.id-e.id}function _(t,e){return t.object.renderOrder!==e.object.renderOrder?t.object.renderOrder-e.object.renderOrder:t.z!==e.z?e.z-t.z:t.id-e.id}function M(t,e,i,n,r){var a,o;i.transparent?(a=wt,o=++Mt):(a=_t,o=++bt);var s=a[o];void 0!==s?(s.id=t.id,s.object=t,s.geometry=e,s.material=i,s.z=Kt.z,s.group=r):(s={id:t.id,object:t,geometry:e,material:i,z:Kt.z,group:r},a.push(s))}function E(t){var e=t.geometry;return null===e.boundingSphere&&e.computeBoundingSphere(),Jt.copy(e.boundingSphere).applyMatrix4(t.matrixWorld),A(Jt)}function S(t){return Jt.center.set(0,0,0),Jt.radius=.7071067811865476,Jt.applyMatrix4(t.matrixWorld),A(Jt)}function A(t){if(!Xt.intersectsSphere(t))return!1;var e=Yt.numPlanes;if(0===e)return!0;var i=At.clippingPlanes,n=t.center,r=-t.radius,a=0;do if(i[a].distanceToPoint(n)=0&&e.numSupportedMorphTargets++}if(e.morphNormals){e.numSupportedMorphNormals=0;for(var p=0;p=0&&e.numSupportedMorphNormals++}var d=r.__webglShader.uniforms;(e&&e.isShaderMaterial||e&&e.isRawShaderMaterial)&&e.clipping!==!0||(r.numClippingPlanes=Yt.numPlanes,d.clippingPlanes=Yt.uniform),e.lights&&(r.lightsHash=$t.hash,d.ambientLightColor.value=$t.ambient,d.directionalLights.value=$t.directional,d.spotLights.value=$t.spot,d.pointLights.value=$t.point,d.hemisphereLights.value=$t.hemi,d.directionalShadowMap.value=$t.directionalShadowMap,d.directionalShadowMatrix.value=$t.directionalShadowMatrix,d.spotShadowMap.value=$t.spotShadowMap,d.spotShadowMatrix.value=$t.spotShadowMatrix,d.pointShadowMap.value=$t.pointShadowMap,d.pointShadowMatrix.value=$t.pointShadowMatrix);var f=r.program.getUniforms(),m=t.WebGLUniforms.seqWithValue(f.seq,d);r.uniformsList=m,r.dynamicUniforms=t.WebGLUniforms.splitDynamic(m,d)}function N(t){t.side!==_n?ae.enable(ee.CULL_FACE):ae.disable(ee.CULL_FACE),ae.setFlipSided(t.side===xn),t.transparent===!0?ae.setBlending(t.blending,t.blendEquation,t.blendSrc,t.blendDst,t.blendEquationAlpha,t.blendSrcAlpha,t.blendDstAlpha,t.premultipliedAlpha):ae.setBlending(Sn),ae.setDepthFunc(t.depthFunc),ae.setDepthTest(t.depthTest),ae.setDepthWrite(t.depthWrite),ae.setColorWrite(t.colorWrite),ae.setPolygonOffset(t.polygonOffset,t.polygonOffsetFactor,t.polygonOffsetUnits)}function O(e,i,n,r){Ft=0;var a=oe.get(n);if(qt){if(Zt||e!==It){var o=e===It&&n.id===Ct;Yt.setState(n.clippingPlanes,n.clipShadows,e,a,o)}void 0!==a.numClippingPlanes&&a.numClippingPlanes!==Yt.numPlanes&&(n.needsUpdate=!0)}void 0===a.program&&(n.needsUpdate=!0),void 0!==a.lightsHash&&a.lightsHash!==$t.hash&&(n.needsUpdate=!0),n.needsUpdate&&(D(n,i,r),n.needsUpdate=!1);var s=!1,c=!1,h=!1,l=a.program,u=l.getUniforms(),p=a.__webglShader.uniforms;if(l.id!==Lt&&(ee.useProgram(l.program),Lt=l.id,s=!0,c=!0,h=!0),n.id!==Ct&&(Ct=n.id,c=!0),s||e!==It){if(u.set(ee,e,"projectionMatrix"),re.logarithmicDepthBuffer&&u.setValue(ee,"logDepthBufFC",2/(Math.log(e.far+1)/Math.LN2)), -e!==It&&(It=e,c=!0,h=!0),n&&n.isShaderMaterial||n&&n.isMeshPhongMaterial||n&&n.isMeshStandardMaterial||n.envMap){var d=u.map.cameraPosition;void 0!==d&&d.setValue(ee,Kt.setFromMatrixPosition(e.matrixWorld))}(n&&n.isMeshPhongMaterial||n&&n.isMeshLambertMaterial||n&&n.isMeshBasicMaterial||n&&n.isMeshStandardMaterial||n&&n.isShaderMaterial||n.skinning)&&u.setValue(ee,"viewMatrix",e.matrixWorldInverse),u.set(ee,At,"toneMappingExposure"),u.set(ee,At,"toneMappingWhitePoint")}if(n.skinning){u.setOptional(ee,r,"bindMatrix"),u.setOptional(ee,r,"bindMatrixInverse");var f=r.skeleton;f&&(re.floatVertexTextures&&f.useVertexTexture?(u.set(ee,f,"boneTexture"),u.set(ee,f,"boneTextureWidth"),u.set(ee,f,"boneTextureHeight")):u.setOptional(ee,f,"boneMatrices"))}c&&(n.lights&&X(p,h),i&&n.fog&&H(p,i),(n&&n.isMeshBasicMaterial||n&&n.isMeshLambertMaterial||n&&n.isMeshPhongMaterial||n&&n.isMeshStandardMaterial||n&&n.isMeshDepthMaterial)&&F(p,n),n&&n.isLineBasicMaterial?B(p,n):n&&n.isLineDashedMaterial?(B(p,n),z(p,n)):n&&n.isPointsMaterial?G(p,n):n&&n.isMeshLambertMaterial?V(p,n):n&&n.isMeshPhongMaterial?k(p,n):n&&n.isMeshPhysicalMaterial?W(p,n):n&&n.isMeshStandardMaterial?j(p,n):n&&n.isMeshDepthMaterial?n.displacementMap&&(p.displacementMap.value=n.displacementMap,p.displacementScale.value=n.displacementScale,p.displacementBias.value=n.displacementBias):n&&n.isMeshNormalMaterial&&(p.opacity.value=n.opacity),t.WebGLUniforms.upload(ee,a.uniformsList,p,At)),u.set(ee,r,"modelViewMatrix"),u.set(ee,r,"normalMatrix"),u.setValue(ee,"modelMatrix",r.matrixWorld);var m=a.dynamicUniforms;return null!==m&&(t.WebGLUniforms.evalDynamic(m,p,r,e),t.WebGLUniforms.upload(ee,m,p,At)),l}function F(t,e){t.opacity.value=e.opacity,t.diffuse.value=e.color,e.emissive&&t.emissive.value.copy(e.emissive).multiplyScalar(e.emissiveIntensity),t.map.value=e.map,t.specularMap.value=e.specularMap,t.alphaMap.value=e.alphaMap,e.aoMap&&(t.aoMap.value=e.aoMap,t.aoMapIntensity.value=e.aoMapIntensity);var i;if(e.map?i=e.map:e.specularMap?i=e.specularMap:e.displacementMap?i=e.displacementMap:e.normalMap?i=e.normalMap:e.bumpMap?i=e.bumpMap:e.roughnessMap?i=e.roughnessMap:e.metalnessMap?i=e.metalnessMap:e.alphaMap?i=e.alphaMap:e.emissiveMap&&(i=e.emissiveMap),void 0!==i){i&&i.isWebGLRenderTarget&&(i=i.texture);var n=i.offset,r=i.repeat;t.offsetRepeat.value.set(n.x,n.y,r.x,r.y)}t.envMap.value=e.envMap,t.flipEnvMap.value=e.envMap&&e.envMap.isCubeTexture?-1:1,t.reflectivity.value=e.reflectivity,t.refractionRatio.value=e.refractionRatio}function B(t,e){t.diffuse.value=e.color,t.opacity.value=e.opacity}function z(t,e){t.dashSize.value=e.dashSize,t.totalSize.value=e.dashSize+e.gapSize,t.scale.value=e.scale}function G(t,e){if(t.diffuse.value=e.color,t.opacity.value=e.opacity,t.size.value=e.size*Vt,t.scale.value=.5*K.clientHeight,t.map.value=e.map,null!==e.map){var i=e.map.offset,n=e.map.repeat;t.offsetRepeat.value.set(i.x,i.y,n.x,n.y)}}function H(t,e){t.fogColor.value=e.color,e&&e.isFog?(t.fogNear.value=e.near,t.fogFar.value=e.far):e&&e.isFogExp2&&(t.fogDensity.value=e.density)}function V(t,e){e.lightMap&&(t.lightMap.value=e.lightMap,t.lightMapIntensity.value=e.lightMapIntensity),e.emissiveMap&&(t.emissiveMap.value=e.emissiveMap)}function k(t,e){t.specular.value=e.specular,t.shininess.value=Math.max(e.shininess,1e-4),e.lightMap&&(t.lightMap.value=e.lightMap,t.lightMapIntensity.value=e.lightMapIntensity),e.emissiveMap&&(t.emissiveMap.value=e.emissiveMap),e.bumpMap&&(t.bumpMap.value=e.bumpMap,t.bumpScale.value=e.bumpScale),e.normalMap&&(t.normalMap.value=e.normalMap,t.normalScale.value.copy(e.normalScale)),e.displacementMap&&(t.displacementMap.value=e.displacementMap,t.displacementScale.value=e.displacementScale,t.displacementBias.value=e.displacementBias)}function j(t,e){t.roughness.value=e.roughness,t.metalness.value=e.metalness,e.roughnessMap&&(t.roughnessMap.value=e.roughnessMap),e.metalnessMap&&(t.metalnessMap.value=e.metalnessMap),e.lightMap&&(t.lightMap.value=e.lightMap,t.lightMapIntensity.value=e.lightMapIntensity),e.emissiveMap&&(t.emissiveMap.value=e.emissiveMap),e.bumpMap&&(t.bumpMap.value=e.bumpMap,t.bumpScale.value=e.bumpScale),e.normalMap&&(t.normalMap.value=e.normalMap,t.normalScale.value.copy(e.normalScale)),e.displacementMap&&(t.displacementMap.value=e.displacementMap,t.displacementScale.value=e.displacementScale,t.displacementBias.value=e.displacementBias),e.envMap&&(t.envMapIntensity.value=e.envMapIntensity)}function W(t,e){t.clearCoat.value=e.clearCoat,t.clearCoatRoughness.value=e.clearCoatRoughness,j(t,e)}function X(t,e){t.ambientLightColor.needsUpdate=e,t.directionalLights.needsUpdate=e,t.pointLights.needsUpdate=e,t.spotLights.needsUpdate=e,t.hemisphereLights.needsUpdate=e}function Y(t){for(var e=0,i=0,n=t.length;i=re.maxTextures&&console.warn("WebGLRenderer: trying to use "+t+" texture units while this GPU supports only "+re.maxTextures),Ft+=1,t}function J(t){var e;if(t===yr)return ee.REPEAT;if(t===xr)return ee.CLAMP_TO_EDGE;if(t===_r)return ee.MIRRORED_REPEAT;if(t===br)return ee.NEAREST;if(t===wr)return ee.NEAREST_MIPMAP_NEAREST;if(t===Mr)return ee.NEAREST_MIPMAP_LINEAR;if(t===Er)return ee.LINEAR;if(t===Tr)return ee.LINEAR_MIPMAP_NEAREST;if(t===Sr)return ee.LINEAR_MIPMAP_LINEAR;if(t===Ar)return ee.UNSIGNED_BYTE;if(t===Nr)return ee.UNSIGNED_SHORT_4_4_4_4;if(t===Or)return ee.UNSIGNED_SHORT_5_5_5_1;if(t===Fr)return ee.UNSIGNED_SHORT_5_6_5;if(t===Lr)return ee.BYTE;if(t===Rr)return ee.SHORT;if(t===Pr)return ee.UNSIGNED_SHORT;if(t===Cr)return ee.INT;if(t===Ur)return ee.UNSIGNED_INT;if(t===Ir)return ee.FLOAT;if(e=ne.get("OES_texture_half_float"),null!==e&&t===Dr)return e.HALF_FLOAT_OES;if(t===zr)return ee.ALPHA;if(t===Gr)return ee.RGB;if(t===Hr)return ee.RGBA;if(t===Vr)return ee.LUMINANCE;if(t===kr)return ee.LUMINANCE_ALPHA;if(t===Wr)return ee.DEPTH_COMPONENT;if(t===Xr)return ee.DEPTH_STENCIL;if(t===Un)return ee.FUNC_ADD;if(t===In)return ee.FUNC_SUBTRACT;if(t===Dn)return ee.FUNC_REVERSE_SUBTRACT;if(t===Fn)return ee.ZERO;if(t===Bn)return ee.ONE;if(t===zn)return ee.SRC_COLOR;if(t===Gn)return ee.ONE_MINUS_SRC_COLOR;if(t===Hn)return ee.SRC_ALPHA;if(t===Vn)return ee.ONE_MINUS_SRC_ALPHA;if(t===kn)return ee.DST_ALPHA;if(t===jn)return ee.ONE_MINUS_DST_ALPHA;if(t===Wn)return ee.DST_COLOR;if(t===Xn)return ee.ONE_MINUS_DST_COLOR;if(t===Yn)return ee.SRC_ALPHA_SATURATE;if(e=ne.get("WEBGL_compressed_texture_s3tc"),null!==e){if(t===Yr)return e.COMPRESSED_RGB_S3TC_DXT1_EXT;if(t===qr)return e.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(t===Zr)return e.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(t===Jr)return e.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(e=ne.get("WEBGL_compressed_texture_pvrtc"),null!==e){if(t===Qr)return e.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(t===Kr)return e.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(t===$r)return e.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(t===ta)return e.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(e=ne.get("WEBGL_compressed_texture_etc1"),null!==e&&t===ea)return e.COMPRESSED_RGB_ETC1_WEBGL;if(e=ne.get("EXT_blend_minmax"),null!==e){if(t===Nn)return e.MIN_EXT;if(t===On)return e.MAX_EXT}return e=ne.get("WEBGL_depth_texture"),null!==e&&t===THREE.UnsignedInt248Type?e.UNSIGNED_INT_24_8_WEBGL:0}console.log("THREE.WebGLRenderer","80dev"),e=e||{};var K=void 0!==e.canvas?e.canvas:document.createElementNS("http://www.w3.org/1999/xhtml","canvas"),ot=void 0!==e.context?e.context:null,ct=void 0!==e.alpha&&e.alpha,ht=void 0===e.depth||e.depth,lt=void 0===e.stencil||e.stencil,ft=void 0!==e.antialias&&e.antialias,gt=void 0===e.premultipliedAlpha||e.premultipliedAlpha,yt=void 0!==e.preserveDrawingBuffer&&e.preserveDrawingBuffer,xt=[],_t=[],bt=-1,wt=[],Mt=-1,Et=new Float32Array(8),Tt=[],St=[];this.domElement=K,this.context=null,this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.gammaFactor=2,this.gammaInput=!1,this.gammaOutput=!1,this.physicallyCorrectLights=!1,this.toneMapping=or,this.toneMappingExposure=1,this.toneMappingWhitePoint=1,this.maxMorphTargets=8,this.maxMorphNormals=4;var At=this,Lt=null,Rt=null,Pt=null,Ct=-1,Ut="",It=null,Dt=new d,Nt=null,Ot=new d,Ft=0,Bt=new w(0),zt=0,Gt=K.width,Ht=K.height,Vt=1,kt=new d(0,0,Gt,Ht),jt=!1,Wt=new d(0,0,Gt,Ht),Xt=new L,Yt=new rt,qt=!1,Zt=!1,Jt=new T,Qt=new a,Kt=new s,$t={hash:"",ambient:[0,0,0],directional:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotShadowMap:[],spotShadowMatrix:[],point:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],shadows:[]},te={calls:0,vertices:0,faces:0,points:0};this.info={render:te,memory:{geometries:0,textures:0},programs:null};var ee;try{var ie={alpha:ct,depth:ht,stencil:lt,antialias:ft,premultipliedAlpha:gt,preserveDrawingBuffer:yt};if(ee=ot||K.getContext("webgl",ie)||K.getContext("experimental-webgl",ie),null===ee)throw null!==K.getContext("webgl")?"Error creating WebGL context with your selected attributes.":"Error creating WebGL context.";void 0===ee.getShaderPrecisionFormat&&(ee.getShaderPrecisionFormat=function(){return{rangeMin:1,rangeMax:1,precision:1}}),K.addEventListener("webglcontextlost",h,!1)}catch(t){console.error("THREE.WebGLRenderer: "+t)}var ne=new it(ee);ne.get("WEBGL_depth_texture"),ne.get("OES_texture_float"),ne.get("OES_texture_float_linear"),ne.get("OES_texture_half_float"),ne.get("OES_texture_half_float_linear"),ne.get("OES_standard_derivatives"),ne.get("ANGLE_instanced_arrays"),ne.get("OES_element_index_uint")&&(Q.MaxIndex=4294967296);var re=new et(ee,ne,e),ae=new f(ee,ne,J),oe=new P,se=new p(ee,ne,ae,oe,re,J,this.info),ce=new $(ee,oe,this.info),he=new C(this,re),le=new tt;this.info.programs=he.programs;var ue=new at(ee,ne,te),pe=new nt(ee,ne,te),de=new vt((-1),1,1,(-1),0,1),fe=new mt,me=new pt(new dt(2,2),new ut({depthTest:!1,depthWrite:!1,fog:!1})),ve=t.ShaderLib.cube,ge=new pt(new st(5,5,5),new b({uniforms:ve.uniforms,vertexShader:ve.vertexShader,fragmentShader:ve.fragmentShader,side:xn,depthTest:!1,depthWrite:!1,fog:!1}));r(),this.context=ee,this.capabilities=re,this.extensions=ne,this.properties=oe,this.state=ae;var ye=new R(this,$t,ce,re);this.shadowMap=ye;var xe=new c(this,Tt),_e=new l(this,St);this.getContext=function(){return ee},this.getContextAttributes=function(){return ee.getContextAttributes()},this.forceContextLoss=function(){ne.get("WEBGL_lose_context").loseContext()},this.getMaxAnisotropy=function(){return re.getMaxAnisotropy()},this.getPrecision=function(){return re.precision},this.getPixelRatio=function(){return Vt},this.setPixelRatio=function(t){void 0!==t&&(Vt=t,this.setSize(Wt.z,Wt.w,!1))},this.getSize=function(){return{width:Gt,height:Ht}},this.setSize=function(t,e,i){Gt=t,Ht=e,K.width=t*Vt,K.height=e*Vt,i!==!1&&(K.style.width=t+"px",K.style.height=e+"px"),this.setViewport(0,0,t,e)},this.setViewport=function(t,e,i,n){ae.viewport(Wt.set(t,e,i,n))},this.setScissor=function(t,e,i,n){ae.scissor(kt.set(t,e,i,n))},this.setScissorTest=function(t){ae.setScissorTest(jt=t)},this.getClearColor=function(){return Bt},this.setClearColor=function(t,e){Bt.set(t),zt=void 0!==e?e:1,n(Bt.r,Bt.g,Bt.b,zt)},this.getClearAlpha=function(){return zt},this.setClearAlpha=function(t){zt=t,n(Bt.r,Bt.g,Bt.b,zt)},this.clear=function(t,e,i){var n=0;(void 0===t||t)&&(n|=ee.COLOR_BUFFER_BIT),(void 0===e||e)&&(n|=ee.DEPTH_BUFFER_BIT),(void 0===i||i)&&(n|=ee.STENCIL_BUFFER_BIT),ee.clear(n)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.clearTarget=function(t,e,i,n){this.setRenderTarget(t),this.clear(e,i,n)},this.resetGLState=o,this.dispose=function(){wt=[],Mt=-1,_t=[],bt=-1,K.removeEventListener("webglcontextlost",h,!1)},this.renderBufferImmediate=function(t,e,i){ae.initAttributes();var n=oe.get(t);t.hasPositions&&!n.position&&(n.position=ee.createBuffer()),t.hasNormals&&!n.normal&&(n.normal=ee.createBuffer()),t.hasUvs&&!n.uv&&(n.uv=ee.createBuffer()),t.hasColors&&!n.color&&(n.color=ee.createBuffer());var r=e.getAttributes();if(t.hasPositions&&(ee.bindBuffer(ee.ARRAY_BUFFER,n.position),ee.bufferData(ee.ARRAY_BUFFER,t.positionArray,ee.DYNAMIC_DRAW),ae.enableAttribute(r.position),ee.vertexAttribPointer(r.position,3,ee.FLOAT,!1,0,0)),t.hasNormals){if(ee.bindBuffer(ee.ARRAY_BUFFER,n.normal),"MeshPhongMaterial"!==i.type&&"MeshStandardMaterial"!==i.type&&"MeshPhysicalMaterial"!==i.type&&i.shading===bn)for(var a=0,o=3*t.count;a8&&(u.length=8);for(var m=n.morphAttributes,p=0,d=u.length;p0&&_.renderInstances(n,A,R):_.render(A,R)},this.render=function(t,e,i,r){if((e&&e.isCamera)===!1)return void console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");var a=t.fog;Ut="",Ct=-1,It=null,t.autoUpdate===!0&&t.updateMatrixWorld(),null===e.parent&&e.updateMatrixWorld(),e.matrixWorldInverse.getInverse(e.matrixWorld),Qt.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),Xt.setFromMatrix(Qt),xt.length=0,bt=-1,Mt=-1,Tt.length=0,St.length=0,Zt=this.localClippingEnabled,qt=Yt.init(this.clippingPlanes,Zt,e),U(t,e),_t.length=bt+1,wt.length=Mt+1,At.sortObjects===!0&&(_t.sort(x),wt.sort(_)),qt&&Yt.beginShadows(),Y(xt),ye.render(t,e),q(xt,e),qt&&Yt.endShadows(),te.calls=0,te.vertices=0,te.faces=0,te.points=0,void 0===i&&(i=null),this.setRenderTarget(i);var o=t.background;if(null===o?n(Bt.r,Bt.g,Bt.b,zt):o&&o.isColor&&n(o.r,o.g,o.b,1),(this.autoClear||r)&&this.clear(this.autoClearColor,this.autoClearDepth,this.autoClearStencil),o&&o.isCubeTexture?(fe.projectionMatrix.copy(e.projectionMatrix),fe.matrixWorld.extractRotation(e.matrixWorld),fe.matrixWorldInverse.getInverse(fe.matrixWorld),ge.material.uniforms.tCube.value=o,ge.modelViewMatrix.multiplyMatrices(fe.matrixWorldInverse,ge.matrixWorld),ce.update(ge),At.renderBufferDirect(fe,null,ge.geometry,ge.material,ge,null)):o&&o.isTexture&&(me.material.map=o,ce.update(me),At.renderBufferDirect(de,null,me.geometry,me.material,me,null)),t.overrideMaterial){var s=t.overrideMaterial;I(_t,e,a,s),I(wt,e,a,s)}else ae.setBlending(Sn),I(_t,e,a),I(wt,e,a);xe.render(t,e),_e.render(t,e,Ot),i&&se.updateRenderTargetMipmap(i),ae.setDepthTest(!0),ae.setDepthWrite(!0),ae.setColorWrite(!0)},this.setFaceCulling=function(t,e){ae.setCullFace(t),ae.setFlipSided(e===dn)},this.allocTextureUnit=Z,this.setTexture2D=function(){var t=!1;return function(e,i){e&&e.isWebGLRenderTarget&&(t||(console.warn("THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead."),t=!0),e=e.texture),se.setTexture2D(e,i)}}(),this.setTexture=function(){var t=!1;return function(e,i){t||(console.warn("THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead."),t=!0),se.setTexture2D(e,i)}}(),this.setTextureCube=function(){var t=!1;return function(e,i){e&&e.isWebGLRenderTargetCube&&(t||(console.warn("THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead."),t=!0),e=e.texture),e&&e.isCubeTexture||Array.isArray(e.image)&&6===e.image.length?se.setTextureCube(e,i):se.setTextureCubeDynamic(e,i)}}(),this.getCurrentRenderTarget=function(){return Rt},this.setRenderTarget=function(t){Rt=t,t&&void 0===oe.get(t).__webglFramebuffer&&se.setupRenderTarget(t);var e,i=t&&t.isWebGLRenderTargetCube;if(t){var n=oe.get(t);e=i?n.__webglFramebuffer[t.activeCubeFace]:n.__webglFramebuffer,Dt.copy(t.scissor),Nt=t.scissorTest,Ot.copy(t.viewport)}else e=null,Dt.copy(kt).multiplyScalar(Vt),Nt=jt,Ot.copy(Wt).multiplyScalar(Vt);if(Pt!==e&&(ee.bindFramebuffer(ee.FRAMEBUFFER,e),Pt=e),ae.scissor(Dt),ae.setScissorTest(Nt),ae.viewport(Ot),i){var r=oe.get(t.texture);ee.framebufferTexture2D(ee.FRAMEBUFFER,ee.COLOR_ATTACHMENT0,ee.TEXTURE_CUBE_MAP_POSITIVE_X+t.activeCubeFace,r.__webglTexture,t.activeMipMapLevel)}},this.readRenderTargetPixels=function(t,e,i,n,r,a){if((t&&t.isWebGLRenderTarget)===!1)return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");var o=oe.get(t).__webglFramebuffer;if(o){var s=!1;o!==Pt&&(ee.bindFramebuffer(ee.FRAMEBUFFER,o),s=!0);try{var c=t.texture;if(c.format!==Hr&&J(c.format)!==ee.getParameter(ee.IMPLEMENTATION_COLOR_READ_FORMAT))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");if(!(c.type===Ar||J(c.type)===ee.getParameter(ee.IMPLEMENTATION_COLOR_READ_TYPE)||c.type===Ir&&ne.get("WEBGL_color_buffer_float")||c.type===Dr&&ne.get("EXT_color_buffer_half_float")))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");ee.checkFramebufferStatus(ee.FRAMEBUFFER)===ee.FRAMEBUFFER_COMPLETE?e>=0&&e<=t.width-n&&i>=0&&i<=t.height-r&&ee.readPixels(e,i,n,r,J(c.format),J(c.type),a):console.error("THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.")}finally{s&&ee.bindFramebuffer(ee.FRAMEBUFFER,Pt)}}}}function yt(t,e){this.name="",this.color=new w(t),this.density=void 0!==e?e:25e-5}function xt(t,e,i){this.name="",this.color=new w(t),this.near=void 0!==e?e:1,this.far=void 0!==i?i:1e3}function _t(){X.call(this),this.type="Scene",this.background=null,this.fog=null,this.overrideMaterial=null,this.autoUpdate=!0}function bt(t,e,i,n,r){X.call(this),this.lensFlares=[],this.positionScreen=new s,this.customUpdateCallback=void 0,void 0!==t&&this.add(t,e,i,n,r)}function wt(t){x.call(this),this.type="SpriteMaterial",this.color=new w(16777215),this.map=null,this.rotation=0,this.fog=!1,this.lights=!1,this.setValues(t)}function Mt(t){X.call(this),this.type="Sprite",this.material=void 0!==t?t:new wt}function Et(){X.call(this),this.type="LOD",Object.defineProperties(this,{levels:{enumerable:!0,value:[]}})}function Tt(t,e,i,r,a,o,s,c,h,l,u,p){n.call(this,null,o,s,c,h,l,r,a,u,p),this.image={data:t,width:e,height:i},this.magFilter=void 0!==h?h:br,this.minFilter=void 0!==l?l:br,this.flipY=!1,this.generateMipmaps=!1}function St(e,i,n){if(this.useVertexTexture=void 0===n||n,this.identityMatrix=new a,e=e||[],this.bones=e.slice(0),this.useVertexTexture){var r=Math.sqrt(4*this.bones.length);r=t.Math.nextPowerOfTwo(Math.ceil(r)),r=Math.max(r,4),this.boneTextureWidth=r,this.boneTextureHeight=r,this.boneMatrices=new Float32Array(this.boneTextureWidth*this.boneTextureHeight*4),this.boneTexture=new Tt(this.boneMatrices,this.boneTextureWidth,this.boneTextureHeight,Hr,Ir)}else this.boneMatrices=new Float32Array(16*this.bones.length);if(void 0===i)this.calculateInverses();else if(this.bones.length===i.length)this.boneInverses=i.slice(0);else{console.warn("THREE.Skeleton bonInverses is the wrong length."),this.boneInverses=[];for(var o=0,s=this.bones.length;o=t.HAVE_CURRENT_DATA&&(u.needsUpdate=!0)}n.call(this,t,e,i,r,a,o,s,c,h),this.generateMipmaps=!1;var u=this;l()}function Ot(t,e,i,r,a,o,s,c,h,l,u,p){n.call(this,null,o,s,c,h,l,r,a,u,p),this.image={width:e,height:i},this.mipmaps=t,this.flipY=!1,this.generateMipmaps=!1}function Ft(t,e,i,r,a,o,s,c,h){n.call(this,t,e,i,r,a,o,s,c,h),this.needsUpdate=!0}function Bt(t,e,i,r,a,o,s,c,h,l){if(l=void 0!==l?l:Wr,l!==Wr&&l!==Xr)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");n.call(this,null,r,a,o,s,c,l,i,h),this.image={width:t,height:e},this.type=void 0!==i?i:Pr,this.magFilter=void 0!==s?s:br,this.minFilter=void 0!==c?c:br,this.flipY=!1,this.generateMipmaps=!1}function zt(){b.call(this,{uniforms:t.UniformsUtils.merge([t.UniformsLib.lights,{opacity:{value:1}}]),vertexShader:Es.shadow_vert,fragmentShader:Es.shadow_frag}),this.lights=!0,this.transparent=!0,Object.defineProperties(this,{opacity:{enumerable:!0,get:function(){return this.uniforms.opacity.value},set:function(t){this.uniforms.opacity.value=t}}})}function Gt(t){b.call(this,t),this.type="RawShaderMaterial"}function Ht(e){this.uuid=t.Math.generateUUID(),this.type="MultiMaterial",this.materials=e instanceof Array?e:[],this.visible=!0}function Vt(t){x.call(this),this.defines={STANDARD:""},this.type="MeshStandardMaterial",this.color=new w(16777215),this.roughness=.5,this.metalness=.5,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new w(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalScale=new i(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapIntensity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.skinning=!1,this.morphTargets=!1,this.morphNormals=!1,this.setValues(t)}function kt(t){Vt.call(this),this.defines={PHYSICAL:""},this.type="MeshPhysicalMaterial",this.reflectivity=.5,this.clearCoat=0,this.clearCoatRoughness=0,this.setValues(t)}function jt(t){x.call(this),this.type="MeshPhongMaterial",this.color=new w(16777215),this.specular=new w(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new w(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalScale=new i(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=ir,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.skinning=!1,this.morphTargets=!1,this.morphNormals=!1,this.setValues(t)}function Wt(t){x.call(this,t),this.type="MeshNormalMaterial",this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.morphTargets=!1,this.setValues(t)}function Xt(t){x.call(this),this.type="MeshLambertMaterial",this.color=new w(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new w(0),this.emissiveIntensity=1,this.emissiveMap=null,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=ir,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.skinning=!1,this.morphTargets=!1,this.morphNormals=!1,this.setValues(t)}function Yt(t){x.call(this),this.type="LineDashedMaterial",this.color=new w(16777215),this.linewidth=1,this.scale=1,this.dashSize=3,this.gapSize=1,this.lights=!1,this.setValues(t)}function qt(t,e,i){var n=this,r=!1,a=0,o=0;this.onStart=void 0,this.onLoad=t,this.onProgress=e,this.onError=i,this.itemStart=function(t){o++,r===!1&&void 0!==n.onStart&&n.onStart(t,a,o),r=!0},this.itemEnd=function(t){a++,void 0!==n.onProgress&&n.onProgress(t,a,o),a===o&&(r=!1,void 0!==n.onLoad&&n.onLoad())},this.itemError=function(t){void 0!==n.onError&&n.onError(t)}}function Zt(e){this.manager=void 0!==e?e:t.DefaultLoadingManager}function Jt(e){this.manager=void 0!==e?e:t.DefaultLoadingManager,this._parser=null}function Qt(e){this.manager=void 0!==e?e:t.DefaultLoadingManager,this._parser=null}function Kt(e){this.manager=void 0!==e?e:t.DefaultLoadingManager}function $t(e){this.manager=void 0!==e?e:t.DefaultLoadingManager}function te(e){this.manager=void 0!==e?e:t.DefaultLoadingManager}function ee(t,e){X.call(this),this.type="Light",this.color=new w(t),this.intensity=void 0!==e?e:1,this.receiveShadow=void 0}function ie(t,e,i){ee.call(this,t,i),this.type="HemisphereLight",this.castShadow=void 0,this.position.copy(X.DefaultUp),this.updateMatrix(),this.groundColor=new w(e)}function ne(t){this.camera=t,this.bias=0,this.radius=1,this.mapSize=new i(512,512),this.map=null,this.matrix=new a}function re(){ne.call(this,new mt(50,1,.5,500))}function ae(t,e,i,n,r,a){ee.call(this,t,e),this.type="SpotLight",this.position.copy(X.DefaultUp),this.updateMatrix(),this.target=new X,Object.defineProperty(this,"power",{get:function(){return this.intensity*Math.PI},set:function(t){this.intensity=t/Math.PI}}),this.distance=void 0!==i?i:0,this.angle=void 0!==n?n:Math.PI/3,this.penumbra=void 0!==r?r:0,this.decay=void 0!==a?a:1,this.shadow=new re}function oe(t,e,i,n){ee.call(this,t,e),this.type="PointLight",Object.defineProperty(this,"power",{get:function(){return 4*this.intensity*Math.PI},set:function(t){this.intensity=t/(4*Math.PI)}}),this.distance=void 0!==i?i:0,this.decay=void 0!==n?n:1,this.shadow=new ne(new mt(90,1,.5,500))}function se(t){ne.call(this,new vt((-5),5,5,(-5),.5,500))}function ce(t,e){ee.call(this,t,e),this.type="DirectionalLight",this.position.copy(X.DefaultUp),this.updateMatrix(),this.target=new X,this.shadow=new se}function he(t,e){ee.call(this,t,e),this.type="AmbientLight",this.castShadow=void 0}function le(t,e,i,n){this.parameterPositions=t,this._cachedIndex=0,this.resultBuffer=void 0!==n?n:new e.constructor(i),this.sampleValues=e,this.valueSize=i}function ue(t,e,i,n){le.call(this,t,e,i,n),this._weightPrev=-0,this._offsetPrev=-0,this._weightNext=-0,this._offsetNext=-0}function pe(t,e,i,n){le.call(this,t,e,i,n)}function de(t,e,i,n){le.call(this,t,e,i,n)}function fe(e,i,n,r){if(void 0===e)throw new Error("track name is undefined");if(void 0===i||0===i.length)throw new Error("no keyframes in track named "+e);this.name=e,this.times=t.AnimationUtils.convertArray(i,this.TimeBufferType),this.values=t.AnimationUtils.convertArray(n,this.ValueBufferType),this.setInterpolation(r||this.DefaultInterpolation), -this.validate(),this.optimize()}function me(t,e,i,n){fe.call(this,t,e,i,n)}function ve(t,e,i,n){le.call(this,t,e,i,n)}function ge(t,e,i,n){fe.call(this,t,e,i,n)}function ye(t,e,i,n){fe.call(this,t,e,i,n)}function xe(t,e,i,n){fe.call(this,t,e,i,n)}function _e(t,e,i){fe.call(this,t,e,i)}function be(t,e,i,n){fe.call(this,t,e,i,n)}function we(t,e,i,n){fe.apply(this,arguments)}function Me(e,i,n){this.name=e,this.tracks=n,this.duration=void 0!==i?i:-1,this.uuid=t.Math.generateUUID(),this.duration<0&&this.resetDuration(),this.trim(),this.optimize()}function Ee(e){this.manager=void 0!==e?e:t.DefaultLoadingManager,this.textures={}}function Te(e){this.manager=void 0!==e?e:t.DefaultLoadingManager}function Se(){this.onLoadStart=function(){},this.onLoadProgress=function(){},this.onLoadComplete=function(){}}function Ae(e){"boolean"==typeof e&&(console.warn("THREE.JSONLoader: showStatus parameter has been removed from constructor."),e=void 0),this.manager=void 0!==e?e:t.DefaultLoadingManager,this.withCredentials=!1}function Le(e){this.manager=void 0!==e?e:t.DefaultLoadingManager,this.texturePath=""}function Re(){}function Pe(t,e){this.v1=t,this.v2=e}function Ce(){this.curves=[],this.autoClose=!1}function Ue(t,e,i,n,r,a,o,s){this.aX=t,this.aY=e,this.xRadius=i,this.yRadius=n,this.aStartAngle=r,this.aEndAngle=a,this.aClockwise=o,this.aRotation=s||0}function Ie(t){this.points=void 0==t?[]:t}function De(t,e,i,n){this.v0=t,this.v1=e,this.v2=i,this.v3=n}function Ne(t,e,i){this.v0=t,this.v1=e,this.v2=i}function Oe(t,e,n,r,a,o){function c(t,e,i){return C.vertices.push(new s(t,e,i))-1}q.call(this),this.type="TubeGeometry",this.parameters={path:t,segments:e,radius:n,radialSegments:r,closed:a,taper:o},e=e||64,n=n||1,r=r||8,a=a||!1,o=o||Oe.NoTaper;var h,l,u,p,d,f,m,v,g,y,x,_,b,w,M,E,T,S,A,L,R,P=[],C=this,U=e+1,I=new s,D=new Oe.FrenetFrames(t,e,a),N=D.tangents,O=D.normals,F=D.binormals;for(this.tangents=N,this.normals=O,this.binormals=F,y=0;ythis.points.length-2?this.points.length-1:n+1,p[3]=n>this.points.length-3?this.points.length-1:n+2,c=this.points[p[0]],h=this.points[p[1]],l=this.points[p[2]],u=this.points[p[3]],a=r*r,o=r*a,d.x=e(c.x,h.x,l.x,u.x,r,a,o),d.y=e(c.y,h.y,l.y,u.y,r,a,o),d.z=e(c.z,h.z,l.z,u.z,r,a,o),d},this.getControlPointsArray=function(){var t,e,i=this.points.length,n=[];for(t=0;t0)&&E.push(S,A,R),(v!==i-1||c65535?z:F)(E,1)),this.addAttribute("position",l),this.addAttribute("normal",u),this.addAttribute("uv",p),this.boundingSphere=new T(new s,t)}function Mi(t,e){this.light=t,this.light.updateMatrixWorld();var i=new wi(e,4,2),n=new ut({wireframe:!0,fog:!1});n.color.copy(this.light.color).multiplyScalar(this.light.intensity),pt.call(this,i,n),this.matrix=this.light.matrixWorld,this.matrixAutoUpdate=!1}function Ei(t,e,i,n,r,a,o){q.call(this),this.type="SphereGeometry",this.parameters={radius:t,widthSegments:e,heightSegments:i,phiStart:n,phiLength:r,thetaStart:a,thetaLength:o},this.fromBufferGeometry(new wi(t,e,i,n,r,a,o))}function Ti(t,e){X.call(this),this.light=t,this.light.updateMatrixWorld(),this.matrix=t.matrixWorld,this.matrixAutoUpdate=!1,this.colors=[new w,new w];var i=new Ei(e,4,2);i.rotateX(-Math.PI/2);for(var n=0,r=8;n0&&m++,e>0&&m++);var v=l(),g=u(),y=new U(new(g>65535?Uint32Array:Uint16Array)(g),1),x=new U(new Float32Array(3*v),3),_=new U(new Float32Array(3*v),3),b=new U(new Float32Array(2*v),2),w=0,M=0,E=[],T=n/2,S=0;p(),o===!1&&(t>0&&d(!0),e>0&&d(!1)),this.setIndex(y),this.addAttribute("position",x),this.addAttribute("normal",_),this.addAttribute("uv",b)}function Oi(t){t=t||1;var e=new Float32Array([0,0,0,t,0,0,0,0,0,0,t,0,0,0,0,0,0,t]),i=new Float32Array([1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1]),n=new Q;n.addAttribute("position",new U(e,3)),n.addAttribute("color",new U(i,3));var r=new Rt({vertexColors:Tn});Ct.call(this,n,r)}function Fi(t,e,n){q.call(this),this.type="ParametricGeometry",this.parameters={func:t,slices:e,stacks:n};var r,a,o,s,c,h=this.vertices,l=this.faces,u=this.faceVertexUvs[0],p=e+1;for(r=0;r<=n;r++)for(c=r/n,a=0;a<=e;a++)s=a/e,o=t(s,c),h.push(o);var d,f,m,v,g,y,x,_;for(r=0;r.9&&L<.1&&(M<.2&&(w[0].x+=1),E<.2&&(w[1].x+=1),S<.2&&(w[2].x+=1))}for(var d=0,f=this.vertices.length;d65535?Uint32Array:Uint16Array)(p),1),f=new U(new Float32Array(3*u),3),m=new U(new Float32Array(3*u),3),v=new U(new Float32Array(2*u),2),g=0,y=0,x=new s,_=new s,b=new i,w=new s,M=new s,E=new s,T=new s,S=new s;for(h=0;h<=n;++h){var A=h/n*a*Math.PI*2;for(c(A,a,o,t,w),c(A+.01,a,o,t,M),T.subVectors(M,w),S.addVectors(M,w),E.crossVectors(T,S),S.crossVectors(E,T),E.normalize(),S.normalize(),l=0;l<=r;++l){var L=l/r*Math.PI*2,R=-e*Math.cos(L),P=e*Math.sin(L);x.x=w.x+(R*S.x+P*E.x),x.y=w.y+(R*S.y+P*E.y),x.z=w.z+(R*S.z+P*E.z),f.setXYZ(g,x.x,x.y,x.z),_.subVectors(x,w).normalize(),m.setXYZ(g,_.x,_.y,_.z),b.x=h/n,b.y=l/r,v.setXY(g,b.x,b.y),g++}}for(l=1;l<=n;l++)for(h=1;h<=r;h++){var C=(r+1)*(l-1)+(h-1),I=(r+1)*l+(h-1),D=(r+1)*l+h,N=(r+1)*(l-1)+h;d.setX(y,C),y++,d.setX(y,I),y++,d.setX(y,N),y++,d.setX(y,I),y++,d.setX(y,D),y++,d.setX(y,N),y++}this.setIndex(d),this.addAttribute("position",f),this.addAttribute("normal",m),this.addAttribute("uv",v)}function ji(t,e,i,n,r,a,o){q.call(this),this.type="TorusKnotGeometry",this.parameters={radius:t,tube:e,tubularSegments:i,radialSegments:n,p:r,q:a},void 0!==o&&console.warn("THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead."),this.fromBufferGeometry(new ki(t,e,i,n,r,a)),this.mergeVertices()}function Wi(t,e,i,n,r){Q.call(this),this.type="TorusBufferGeometry",this.parameters={radius:t,tube:e,radialSegments:i,tubularSegments:n,arc:r},t=t||100,e=e||40,i=Math.floor(i)||8,n=Math.floor(n)||6,r=r||2*Math.PI;var a,o,c=(i+1)*(n+1),h=i*n*2*3,l=new(h>65535?Uint32Array:Uint16Array)(h),u=new Float32Array(3*c),p=new Float32Array(3*c),d=new Float32Array(2*c),f=0,m=0,v=0,g=new s,y=new s,x=new s;for(a=0;a<=i;a++)for(o=0;o<=n;o++){var _=o/n*r,b=a/i*Math.PI*2;y.x=(t+e*Math.cos(b))*Math.cos(_),y.y=(t+e*Math.cos(b))*Math.sin(_),y.z=e*Math.sin(b),u[f]=y.x,u[f+1]=y.y,u[f+2]=y.z,g.x=t*Math.cos(_),g.y=t*Math.sin(_),x.subVectors(y,g).normalize(),p[f]=x.x,p[f+1]=x.y,p[f+2]=x.z,d[m]=o/n,d[m+1]=a/i,f+=3,m+=2}for(a=1;a<=i;a++)for(o=1;o<=n;o++){var w=(n+1)*a+o-1,M=(n+1)*(a-1)+o-1,E=(n+1)*(a-1)+o,T=(n+1)*a+o;l[v]=w,l[v+1]=M,l[v+2]=T,l[v+3]=M,l[v+4]=E,l[v+5]=T,v+=6}this.setIndex(new U(l,1)),this.addAttribute("position",new U(u,3)),this.addAttribute("normal",new U(p,3)),this.addAttribute("uv",new U(d,2))}function Xi(t,e,i,n,r){q.call(this),this.type="TorusGeometry",this.parameters={radius:t,tube:e,radialSegments:i,tubularSegments:n,arc:r},this.fromBufferGeometry(new Wi(t,e,i,n,r))}function Yi(t,e){e=e||{};var i=e.font;if((i&&i.isFont)===!1)return console.error("THREE.TextGeometry: font parameter is not an instance of THREE.Font."),new q;var n=i.generateShapes(t,e.size,e.curveSegments);e.amount=void 0!==e.height?e.height:50,void 0===e.bevelThickness&&(e.bevelThickness=10),void 0===e.bevelSize&&(e.bevelSize=8),void 0===e.bevelEnabled&&(e.bevelEnabled=!1),Fe.call(this,n,e),this.type="TextGeometry"}function qi(t,e,n,r,a,o){Q.call(this),this.type="RingBufferGeometry",this.parameters={innerRadius:t,outerRadius:e,thetaSegments:n,phiSegments:r,thetaStart:a,thetaLength:o},t=t||20,e=e||50,a=void 0!==a?a:0,o=void 0!==o?o:2*Math.PI,n=void 0!==n?Math.max(3,n):8,r=void 0!==r?Math.max(1,r):1;var c,h,l,u=(n+1)*(r+1),p=n*r*2*3,d=new U(new(p>65535?Uint32Array:Uint16Array)(p),1),f=new U(new Float32Array(3*u),3),m=new U(new Float32Array(3*u),3),v=new U(new Float32Array(2*u),2),g=0,y=0,x=t,_=(e-t)/r,b=new s,w=new i;for(h=0;h<=r;h++){for(l=0;l<=n;l++)c=a+l/n*o,b.x=x*Math.cos(c),b.y=x*Math.sin(c),f.setXYZ(g,b.x,b.y,b.z),m.setXYZ(g,0,0,1),w.x=(b.x/e+1)/2,w.y=(b.y/e+1)/2,v.setXY(g,w.x,w.y),g++;x+=_}for(h=0;h65535?Uint32Array:Uint16Array)(u),1),d=new U(new Float32Array(3*l),3),f=new U(new Float32Array(2*l),2),m=0,v=0,g=1/n,y=new s,x=new i;for(c=0;c<=n;c++){var _=r+c*g*a,b=Math.sin(_),w=Math.cos(_);for(h=0;h<=e.length-1;h++)y.x=e[h].x*b,y.y=e[h].y,y.z=e[h].x*w,d.setXYZ(m,y.x,y.y,y.z),x.x=c/n,x.y=h/(e.length-1),f.setXY(m,x.x,x.y),m++}for(c=0;c0?1:+t}),void 0===Function.prototype.name&&Object.defineProperty(Function.prototype,"name",{get:function(){return this.toString().match(/^\s*function\s*(\S*)\s*\(/)[1]}}),void 0===Object.assign&&!function(){Object.assign=function(t){if(void 0===t||null===t)throw new TypeError("Cannot convert undefined or null to object");for(var e=Object(t),i=1;i>=4,i[r]=e[19===r?3&t|8:t]);return i.join("")}}(),clamp:function(t,e,i){return Math.max(e,Math.min(i,t))},euclideanModulo:function(t,e){return(t%e+e)%e},mapLinear:function(t,e,i,n,r){return n+(t-e)*(r-n)/(i-e)},smoothstep:function(t,e,i){return t<=e?0:t>=i?1:(t=(t-e)/(i-e),t*t*(3-2*t))},smootherstep:function(t,e,i){return t<=e?0:t>=i?1:(t=(t-e)/(i-e),t*t*t*(t*(6*t-15)+10))},random16:function(){return console.warn("THREE.Math.random16() has been deprecated. Use Math.random() instead."),Math.random()},randInt:function(t,e){return t+Math.floor(Math.random()*(e-t+1))},randFloat:function(t,e){return t+Math.random()*(e-t)},randFloatSpread:function(t){return t*(.5-Math.random())},degToRad:function(e){return e*t.Math.DEG2RAD},radToDeg:function(e){return e*t.Math.RAD2DEG},isPowerOfTwo:function(t){return 0===(t&t-1)&&0!==t},nearestPowerOfTwo:function(t){return Math.pow(2,Math.round(Math.log(t)/Math.LN2))},nextPowerOfTwo:function(t){return t--,t|=t>>1,t|=t>>2,t|=t>>4,t|=t>>8,t|=t>>16,t++,t}},i.prototype={constructor:i,isVector2:!0,get width(){return this.x},set width(t){this.x=t},get height(){return this.y},set height(t){this.y=t},set:function(t,e){return this.x=t,this.y=e,this},setScalar:function(t){return this.x=t,this.y=t,this},setX:function(t){return this.x=t,this},setY:function(t){return this.y=t,this},setComponent:function(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;default:throw new Error("index is out of range: "+t)}},getComponent:function(t){switch(t){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+t)}},clone:function(){return new this.constructor(this.x,this.y)},copy:function(t){return this.x=t.x,this.y=t.y,this},add:function(t,e){return void 0!==e?(console.warn("THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(t,e)):(this.x+=t.x,this.y+=t.y,this)},addScalar:function(t){return this.x+=t,this.y+=t,this},addVectors:function(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this},addScaledVector:function(t,e){return this.x+=t.x*e,this.y+=t.y*e,this},sub:function(t,e){return void 0!==e?(console.warn("THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(t,e)):(this.x-=t.x,this.y-=t.y,this)},subScalar:function(t){return this.x-=t,this.y-=t,this},subVectors:function(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this},multiply:function(t){return this.x*=t.x,this.y*=t.y,this},multiplyScalar:function(t){return isFinite(t)?(this.x*=t,this.y*=t):(this.x=0,this.y=0),this},divide:function(t){return this.x/=t.x,this.y/=t.y,this},divideScalar:function(t){return this.multiplyScalar(1/t)},min:function(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this},max:function(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this},clamp:function(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this},clampScalar:function(){var t,e;return function(n,r){return void 0===t&&(t=new i,e=new i),t.set(n,n),e.set(r,r),this.clamp(t,e)}}(),clampLength:function(t,e){var i=this.length();return this.multiplyScalar(Math.max(t,Math.min(e,i))/i)},floor:function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this},ceil:function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this},round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},roundToZero:function(){return this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x),this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y),this},negate:function(){return this.x=-this.x,this.y=-this.y,this},dot:function(t){return this.x*t.x+this.y*t.y},lengthSq:function(){return this.x*this.x+this.y*this.y},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},lengthManhattan:function(){return Math.abs(this.x)+Math.abs(this.y)},normalize:function(){return this.divideScalar(this.length())},angle:function(){var t=Math.atan2(this.y,this.x);return t<0&&(t+=2*Math.PI),t},distanceTo:function(t){return Math.sqrt(this.distanceToSquared(t))},distanceToSquared:function(t){var e=this.x-t.x,i=this.y-t.y;return e*e+i*i},distanceToManhattan:function(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)},setLength:function(t){return this.multiplyScalar(t/this.length())},lerp:function(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this},lerpVectors:function(t,e,i){return this.subVectors(e,t).multiplyScalar(i).add(t)},equals:function(t){return t.x===this.x&&t.y===this.y},fromArray:function(t,e){return void 0===e&&(e=0),this.x=t[e],this.y=t[e+1],this},toArray:function(t,e){return void 0===t&&(t=[]),void 0===e&&(e=0),t[e]=this.x,t[e+1]=this.y,t},fromAttribute:function(t,e,i){return void 0===i&&(i=0),e=e*t.itemSize+i,this.x=t.array[e],this.y=t.array[e+1],this},rotateAround:function(t,e){var i=Math.cos(e),n=Math.sin(e),r=this.x-t.x,a=this.y-t.y;return this.x=r*i-a*n+t.x,this.y=r*n+a*i+t.y,this}},n.DEFAULT_IMAGE=void 0,n.DEFAULT_MAPPING=lr,n.prototype={constructor:n,isTexture:!0,set needsUpdate(t){t===!0&&this.version++},clone:function(){return(new this.constructor).copy(this)},copy:function(t){return this.image=t.image,this.mipmaps=t.mipmaps.slice(0),this.mapping=t.mapping,this.wrapS=t.wrapS,this.wrapT=t.wrapT,this.magFilter=t.magFilter,this.minFilter=t.minFilter,this.anisotropy=t.anisotropy,this.format=t.format,this.type=t.type,this.offset.copy(t.offset),this.repeat.copy(t.repeat),this.generateMipmaps=t.generateMipmaps,this.premultiplyAlpha=t.premultiplyAlpha,this.flipY=t.flipY,this.unpackAlignment=t.unpackAlignment,this.encoding=t.encoding,this},toJSON:function(e){function i(t){var e;return void 0!==t.toDataURL?e=t:(e=document.createElementNS("http://www.w3.org/1999/xhtml","canvas"),e.width=t.width,e.height=t.height,e.getContext("2d").drawImage(t,0,0,t.width,t.height)),e.width>2048||e.height>2048?e.toDataURL("image/jpeg",.6):e.toDataURL("image/png")}if(void 0!==e.textures[this.uuid])return e.textures[this.uuid];var n={metadata:{version:4.4,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,mapping:this.mapping,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],wrap:[this.wrapS,this.wrapT],minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY};if(void 0!==this.image){var r=this.image;void 0===r.uuid&&(r.uuid=t.Math.generateUUID()),void 0===e.images[r.uuid]&&(e.images[r.uuid]={uuid:r.uuid,url:i(r)}),n.image=r.uuid}return e.textures[this.uuid]=n,n},dispose:function(){this.dispatchEvent({type:"dispose"})},transformUv:function(t){if(this.mapping===lr){if(t.multiply(this.repeat),t.add(this.offset),t.x<0||t.x>1)switch(this.wrapS){case yr:t.x=t.x-Math.floor(t.x);break;case xr:t.x=t.x<0?0:1;break;case _r:1===Math.abs(Math.floor(t.x)%2)?t.x=Math.ceil(t.x)-t.x:t.x=t.x-Math.floor(t.x)}if(t.y<0||t.y>1)switch(this.wrapT){case yr:t.y=t.y-Math.floor(t.y);break;case xr:t.y=t.y<0?0:1;break;case _r:1===Math.abs(Math.floor(t.y)%2)?t.y=Math.ceil(t.y)-t.y:t.y=t.y-Math.floor(t.y)}this.flipY&&(t.y=1-t.y)}}},Object.assign(n.prototype,e.prototype);var Ea=0;a.prototype={constructor:a,isMatrix4:!0,set:function(t,e,i,n,r,a,o,s,c,h,l,u,p,d,f,m){var v=this.elements;return v[0]=t,v[4]=e,v[8]=i,v[12]=n,v[1]=r,v[5]=a,v[9]=o,v[13]=s,v[2]=c,v[6]=h,v[10]=l,v[14]=u,v[3]=p,v[7]=d,v[11]=f,v[15]=m,this},identity:function(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this},clone:function(){return(new a).fromArray(this.elements)},copy:function(t){return this.elements.set(t.elements),this},copyPosition:function(t){var e=this.elements,i=t.elements;return e[12]=i[12],e[13]=i[13],e[14]=i[14],this},extractBasis:function(t,e,i){return t.setFromMatrixColumn(this,0),e.setFromMatrixColumn(this,1),i.setFromMatrixColumn(this,2),this},makeBasis:function(t,e,i){return this.set(t.x,e.x,i.x,0,t.y,e.y,i.y,0,t.z,e.z,i.z,0,0,0,0,1),this},extractRotation:function(){var t;return function(e){void 0===t&&(t=new s);var i=this.elements,n=e.elements,r=1/t.setFromMatrixColumn(e,0).length(),a=1/t.setFromMatrixColumn(e,1).length(),o=1/t.setFromMatrixColumn(e,2).length();return i[0]=n[0]*r,i[1]=n[1]*r,i[2]=n[2]*r,i[4]=n[4]*a,i[5]=n[5]*a,i[6]=n[6]*a,i[8]=n[8]*o,i[9]=n[9]*o,i[10]=n[10]*o,this}}(),makeRotationFromEuler:function(t){(t&&t.isEuler)===!1&&console.error("THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.");var e=this.elements,i=t.x,n=t.y,r=t.z,a=Math.cos(i),o=Math.sin(i),s=Math.cos(n),c=Math.sin(n),h=Math.cos(r),l=Math.sin(r);if("XYZ"===t.order){var u=a*h,p=a*l,d=o*h,f=o*l;e[0]=s*h,e[4]=-s*l,e[8]=c,e[1]=p+d*c,e[5]=u-f*c,e[9]=-o*s,e[2]=f-u*c,e[6]=d+p*c,e[10]=a*s}else if("YXZ"===t.order){var m=s*h,v=s*l,g=c*h,y=c*l;e[0]=m+y*o,e[4]=g*o-v,e[8]=a*c,e[1]=a*l,e[5]=a*h,e[9]=-o,e[2]=v*o-g,e[6]=y+m*o,e[10]=a*s}else if("ZXY"===t.order){var m=s*h,v=s*l,g=c*h,y=c*l;e[0]=m-y*o,e[4]=-a*l,e[8]=g+v*o,e[1]=v+g*o,e[5]=a*h,e[9]=y-m*o,e[2]=-a*c,e[6]=o,e[10]=a*s}else if("ZYX"===t.order){var u=a*h,p=a*l,d=o*h,f=o*l;e[0]=s*h,e[4]=d*c-p,e[8]=u*c+f,e[1]=s*l,e[5]=f*c+u,e[9]=p*c-d,e[2]=-c,e[6]=o*s,e[10]=a*s}else if("YZX"===t.order){var x=a*s,_=a*c,b=o*s,w=o*c;e[0]=s*h,e[4]=w-x*l,e[8]=b*l+_,e[1]=l,e[5]=a*h,e[9]=-o*h,e[2]=-c*h,e[6]=_*l+b,e[10]=x-w*l}else if("XZY"===t.order){var x=a*s,_=a*c,b=o*s,w=o*c;e[0]=s*h,e[4]=-l,e[8]=c*h,e[1]=x*l+w,e[5]=a*h,e[9]=_*l-b,e[2]=b*l-_,e[6]=o*h,e[10]=w*l+x}return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this},makeRotationFromQuaternion:function(t){var e=this.elements,i=t.x,n=t.y,r=t.z,a=t.w,o=i+i,s=n+n,c=r+r,h=i*o,l=i*s,u=i*c,p=n*s,d=n*c,f=r*c,m=a*o,v=a*s,g=a*c;return e[0]=1-(p+f),e[4]=l-g,e[8]=u+v,e[1]=l+g,e[5]=1-(h+f),e[9]=d-m,e[2]=u-v,e[6]=d+m,e[10]=1-(h+p),e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this},lookAt:function(){var t,e,i;return function(n,r,a){void 0===t&&(t=new s,e=new s,i=new s);var o=this.elements;return i.subVectors(n,r).normalize(),0===i.lengthSq()&&(i.z=1),t.crossVectors(a,i).normalize(),0===t.lengthSq()&&(i.z+=1e-4,t.crossVectors(a,i).normalize()),e.crossVectors(i,t),o[0]=t.x,o[4]=e.x,o[8]=i.x,o[1]=t.y,o[5]=e.y,o[9]=i.y,o[2]=t.z,o[6]=e.z,o[10]=i.z,this}}(),multiply:function(t,e){return void 0!==e?(console.warn("THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead."),this.multiplyMatrices(t,e)):this.multiplyMatrices(this,t)},premultiply:function(t){return this.multiplyMatrices(t,this)},multiplyMatrices:function(t,e){var i=t.elements,n=e.elements,r=this.elements,a=i[0],o=i[4],s=i[8],c=i[12],h=i[1],l=i[5],u=i[9],p=i[13],d=i[2],f=i[6],m=i[10],v=i[14],g=i[3],y=i[7],x=i[11],_=i[15],b=n[0],w=n[4],M=n[8],E=n[12],T=n[1],S=n[5],A=n[9],L=n[13],R=n[2],P=n[6],C=n[10],U=n[14],I=n[3],D=n[7],N=n[11],O=n[15];return r[0]=a*b+o*T+s*R+c*I,r[4]=a*w+o*S+s*P+c*D,r[8]=a*M+o*A+s*C+c*N,r[12]=a*E+o*L+s*U+c*O,r[1]=h*b+l*T+u*R+p*I,r[5]=h*w+l*S+u*P+p*D,r[9]=h*M+l*A+u*C+p*N,r[13]=h*E+l*L+u*U+p*O,r[2]=d*b+f*T+m*R+v*I,r[6]=d*w+f*S+m*P+v*D,r[10]=d*M+f*A+m*C+v*N,r[14]=d*E+f*L+m*U+v*O,r[3]=g*b+y*T+x*R+_*I,r[7]=g*w+y*S+x*P+_*D,r[11]=g*M+y*A+x*C+_*N,r[15]=g*E+y*L+x*U+_*O,this},multiplyToArray:function(t,e,i){var n=this.elements;return this.multiplyMatrices(t,e),i[0]=n[0],i[1]=n[1],i[2]=n[2],i[3]=n[3],i[4]=n[4],i[5]=n[5],i[6]=n[6],i[7]=n[7],i[8]=n[8],i[9]=n[9],i[10]=n[10],i[11]=n[11],i[12]=n[12],i[13]=n[13],i[14]=n[14],i[15]=n[15],this},multiplyScalar:function(t){var e=this.elements;return e[0]*=t,e[4]*=t,e[8]*=t,e[12]*=t,e[1]*=t,e[5]*=t,e[9]*=t,e[13]*=t,e[2]*=t,e[6]*=t,e[10]*=t,e[14]*=t,e[3]*=t,e[7]*=t,e[11]*=t,e[15]*=t,this},applyToVector3Array:function(){var t;return function(e,i,n){void 0===t&&(t=new s),void 0===i&&(i=0),void 0===n&&(n=e.length);for(var r=0,a=i;r0?(e=.5/Math.sqrt(p+1),this._w=.25/e,this._x=(l-c)*e,this._y=(a-h)*e,this._z=(o-r)*e):n>s&&n>u?(e=2*Math.sqrt(1+n-s-u),this._w=(l-c)/e,this._x=.25*e,this._y=(r+o)/e,this._z=(a+h)/e):s>u?(e=2*Math.sqrt(1+s-n-u),this._w=(a-h)/e,this._x=(r+o)/e,this._y=.25*e,this._z=(c+l)/e):(e=2*Math.sqrt(1+u-n-s),this._w=(o-r)/e,this._x=(a+h)/e,this._y=(c+l)/e,this._z=.25*e),this.onChangeCallback(),this},setFromUnitVectors:function(){var t,e,i=1e-6;return function(n,r){return void 0===t&&(t=new s),e=n.dot(r)+1,eMath.abs(n.z)?t.set(-n.y,n.x,0):t.set(0,-n.z,n.y)):t.crossVectors(n,r),this._x=t.x,this._y=t.y,this._z=t.z,this._w=e,this.normalize()}}(),inverse:function(){return this.conjugate().normalize()},conjugate:function(){return this._x*=-1,this._y*=-1,this._z*=-1,this.onChangeCallback(),this},dot:function(t){return this._x*t._x+this._y*t._y+this._z*t._z+this._w*t._w},lengthSq:function(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w},length:function(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)},normalize:function(){var t=this.length();return 0===t?(this._x=0,this._y=0,this._z=0,this._w=1):(t=1/t,this._x=this._x*t,this._y=this._y*t,this._z=this._z*t,this._w=this._w*t),this.onChangeCallback(),this},multiply:function(t,e){return void 0!==e?(console.warn("THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead."),this.multiplyQuaternions(t,e)):this.multiplyQuaternions(this,t)},premultiply:function(t){return this.multiplyQuaternions(t,this)},multiplyQuaternions:function(t,e){var i=t._x,n=t._y,r=t._z,a=t._w,o=e._x,s=e._y,c=e._z,h=e._w;return this._x=i*h+a*o+n*c-r*s,this._y=n*h+a*s+r*o-i*c,this._z=r*h+a*c+i*s-n*o,this._w=a*h-i*o-n*s-r*c,this.onChangeCallback(),this},slerp:function(t,e){if(0===e)return this;if(1===e)return this.copy(t);var i=this._x,n=this._y,r=this._z,a=this._w,o=a*t._w+i*t._x+n*t._y+r*t._z;if(o<0?(this._w=-t._w,this._x=-t._x,this._y=-t._y,this._z=-t._z,o=-o):this.copy(t),o>=1)return this._w=a,this._x=i,this._y=n,this._z=r,this;var s=Math.sqrt(1-o*o);if(Math.abs(s)<.001)return this._w=.5*(a+this._w),this._x=.5*(i+this._x),this._y=.5*(n+this._y),this._z=.5*(r+this._z),this;var c=Math.atan2(s,o),h=Math.sin((1-e)*c)/s,l=Math.sin(e*c)/s;return this._w=a*h+this._w*l,this._x=i*h+this._x*l,this._y=n*h+this._y*l,this._z=r*h+this._z*l,this.onChangeCallback(),this},equals:function(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._w===this._w},fromArray:function(t,e){return void 0===e&&(e=0),this._x=t[e],this._y=t[e+1],this._z=t[e+2],this._w=t[e+3],this.onChangeCallback(),this},toArray:function(t,e){return void 0===t&&(t=[]),void 0===e&&(e=0),t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._w,t},onChange:function(t){return this.onChangeCallback=t,this},onChangeCallback:function(){}},Object.assign(o,{slerp:function(t,e,i,n){return i.copy(t).slerp(e,n)},slerpFlat:function(t,e,i,n,r,a,o){var s=i[n+0],c=i[n+1],h=i[n+2],l=i[n+3],u=r[a+0],p=r[a+1],d=r[a+2],f=r[a+3];if(l!==f||s!==u||c!==p||h!==d){var m=1-o,v=s*u+c*p+h*d+l*f,g=v>=0?1:-1,y=1-v*v;if(y>Number.EPSILON){var x=Math.sqrt(y),_=Math.atan2(x,v*g);m=Math.sin(m*_)/x,o=Math.sin(o*_)/x}var b=o*g;if(s=s*m+u*b,c=c*m+p*b,h=h*m+d*b,l=l*m+f*b,m===1-o){var w=1/Math.sqrt(s*s+c*c+h*h+l*l);s*=w,c*=w,h*=w,l*=w}}t[e]=s,t[e+1]=c,t[e+2]=h,t[e+3]=l}}),s.prototype={constructor:s,isVector3:!0,set:function(t,e,i){return this.x=t,this.y=e,this.z=i,this},setScalar:function(t){return this.x=t,this.y=t,this.z=t,this},setX:function(t){return this.x=t,this},setY:function(t){return this.y=t,this},setZ:function(t){return this.z=t,this},setComponent:function(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;default:throw new Error("index is out of range: "+t)}},getComponent:function(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+t)}},clone:function(){return new this.constructor(this.x,this.y,this.z)},copy:function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},add:function(t,e){return void 0!==e?(console.warn("THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(t,e)):(this.x+=t.x,this.y+=t.y,this.z+=t.z,this)},addScalar:function(t){return this.x+=t,this.y+=t,this.z+=t,this},addVectors:function(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this},addScaledVector:function(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this},sub:function(t,e){return void 0!==e?(console.warn("THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(t,e)):(this.x-=t.x,this.y-=t.y,this.z-=t.z,this)},subScalar:function(t){return this.x-=t,this.y-=t,this.z-=t,this},subVectors:function(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this},multiply:function(t,e){return void 0!==e?(console.warn("THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead."),this.multiplyVectors(t,e)):(this.x*=t.x,this.y*=t.y,this.z*=t.z,this)},multiplyScalar:function(t){return isFinite(t)?(this.x*=t,this.y*=t,this.z*=t):(this.x=0,this.y=0,this.z=0),this},multiplyVectors:function(t,e){return this.x=t.x*e.x,this.y=t.y*e.y,this.z=t.z*e.z,this},applyEuler:function(){var t;return function(e){return(e&&e.isEuler)===!1&&console.error("THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order."),void 0===t&&(t=new o),this.applyQuaternion(t.setFromEuler(e))}}(),applyAxisAngle:function(){var t;return function(e,i){return void 0===t&&(t=new o),this.applyQuaternion(t.setFromAxisAngle(e,i))}}(),applyMatrix3:function(t){var e=this.x,i=this.y,n=this.z,r=t.elements;return this.x=r[0]*e+r[3]*i+r[6]*n,this.y=r[1]*e+r[4]*i+r[7]*n,this.z=r[2]*e+r[5]*i+r[8]*n,this},applyMatrix4:function(t){var e=this.x,i=this.y,n=this.z,r=t.elements;return this.x=r[0]*e+r[4]*i+r[8]*n+r[12],this.y=r[1]*e+r[5]*i+r[9]*n+r[13],this.z=r[2]*e+r[6]*i+r[10]*n+r[14],this},applyProjection:function(t){var e=this.x,i=this.y,n=this.z,r=t.elements,a=1/(r[3]*e+r[7]*i+r[11]*n+r[15]);return this.x=(r[0]*e+r[4]*i+r[8]*n+r[12])*a,this.y=(r[1]*e+r[5]*i+r[9]*n+r[13])*a,this.z=(r[2]*e+r[6]*i+r[10]*n+r[14])*a,this},applyQuaternion:function(t){var e=this.x,i=this.y,n=this.z,r=t.x,a=t.y,o=t.z,s=t.w,c=s*e+a*n-o*i,h=s*i+o*e-r*n,l=s*n+r*i-a*e,u=-r*e-a*i-o*n;return this.x=c*s+u*-r+h*-o-l*-a,this.y=h*s+u*-a+l*-r-c*-o,this.z=l*s+u*-o+c*-a-h*-r,this},project:function(){var t;return function(e){return void 0===t&&(t=new a),t.multiplyMatrices(e.projectionMatrix,t.getInverse(e.matrixWorld)),this.applyProjection(t)}}(),unproject:function(){var t;return function(e){return void 0===t&&(t=new a),t.multiplyMatrices(e.matrixWorld,t.getInverse(e.projectionMatrix)),this.applyProjection(t)}}(),transformDirection:function(t){var e=this.x,i=this.y,n=this.z,r=t.elements;return this.x=r[0]*e+r[4]*i+r[8]*n,this.y=r[1]*e+r[5]*i+r[9]*n,this.z=r[2]*e+r[6]*i+r[10]*n,this.normalize()},divide:function(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this},divideScalar:function(t){return this.multiplyScalar(1/t)},min:function(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this},max:function(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this},clamp:function(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this.z=Math.max(t.z,Math.min(e.z,this.z)),this},clampScalar:function(){var t,e;return function(i,n){return void 0===t&&(t=new s,e=new s),t.set(i,i,i),e.set(n,n,n),this.clamp(t,e)}}(),clampLength:function(t,e){var i=this.length();return this.multiplyScalar(Math.max(t,Math.min(e,i))/i)},floor:function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this},ceil:function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this},round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this},roundToZero:function(){return this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x),this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y),this.z=this.z<0?Math.ceil(this.z):Math.floor(this.z),this},negate:function(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this},dot:function(t){return this.x*t.x+this.y*t.y+this.z*t.z},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},lengthManhattan:function(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)},normalize:function(){return this.divideScalar(this.length())},setLength:function(t){return this.multiplyScalar(t/this.length())},lerp:function(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this},lerpVectors:function(t,e,i){return this.subVectors(e,t).multiplyScalar(i).add(t)},cross:function(t,e){if(void 0!==e)return console.warn("THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead."),this.crossVectors(t,e);var i=this.x,n=this.y,r=this.z;return this.x=n*t.z-r*t.y,this.y=r*t.x-i*t.z,this.z=i*t.y-n*t.x,this},crossVectors:function(t,e){var i=t.x,n=t.y,r=t.z,a=e.x,o=e.y,s=e.z;return this.x=n*s-r*o,this.y=r*a-i*s,this.z=i*o-n*a,this},projectOnVector:function(t){var e=t.dot(this)/t.lengthSq();return this.copy(t).multiplyScalar(e)},projectOnPlane:function(){var t;return function(e){return void 0===t&&(t=new s),t.copy(this).projectOnVector(e),this.sub(t)}}(),reflect:function(){var t;return function(e){return void 0===t&&(t=new s),this.sub(t.copy(e).multiplyScalar(2*this.dot(e)))}}(),angleTo:function(e){var i=this.dot(e)/Math.sqrt(this.lengthSq()*e.lengthSq());return Math.acos(t.Math.clamp(i,-1,1))},distanceTo:function(t){return Math.sqrt(this.distanceToSquared(t))},distanceToSquared:function(t){var e=this.x-t.x,i=this.y-t.y,n=this.z-t.z;return e*e+i*i+n*n},distanceToManhattan:function(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)+Math.abs(this.z-t.z)},setFromSpherical:function(t){var e=Math.sin(t.phi)*t.radius;return this.x=e*Math.sin(t.theta),this.y=Math.cos(t.phi)*t.radius,this.z=e*Math.cos(t.theta),this},setFromMatrixPosition:function(t){return this.setFromMatrixColumn(t,3)},setFromMatrixScale:function(t){var e=this.setFromMatrixColumn(t,0).length(),i=this.setFromMatrixColumn(t,1).length(),n=this.setFromMatrixColumn(t,2).length();return this.x=e,this.y=i,this.z=n,this},setFromMatrixColumn:function(t,e){if("number"==typeof t){console.warn("THREE.Vector3: setFromMatrixColumn now expects ( matrix, index ).");var i=t;t=e,e=i}return this.fromArray(t.elements,4*e)},equals:function(t){return t.x===this.x&&t.y===this.y&&t.z===this.z},fromArray:function(t,e){return void 0===e&&(e=0),this.x=t[e],this.y=t[e+1],this.z=t[e+2],this},toArray:function(t,e){return void 0===t&&(t=[]),void 0===e&&(e=0),t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t},fromAttribute:function(t,e,i){return void 0===i&&(i=0),e=e*t.itemSize+i,this.x=t.array[e],this.y=t.array[e+1],this.z=t.array[e+2],this}},h.prototype={constructor:h,set:function(t,e){return this.min.copy(t),this.max.copy(e),this},setFromPoints:function(t){this.makeEmpty();for(var e=0,i=t.length;ethis.max.x||t.ythis.max.y)},containsBox:function(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y},getParameter:function(t,e){var n=e||new i;return n.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y))},intersectsBox:function(t){return!(t.max.xthis.max.x||t.max.ythis.max.y)},clampPoint:function(t,e){var n=e||new i;return n.copy(t).clamp(this.min,this.max)},distanceToPoint:function(){var t=new i;return function(e){var i=t.copy(e).clamp(this.min,this.max);return i.sub(e).length()}}(),intersect:function(t){return this.min.max(t.min),this.max.min(t.max),this},union:function(t){return this.min.min(t.min),this.max.max(t.max),this},translate:function(t){return this.min.add(t),this.max.add(t),this},equals:function(t){return t.min.equals(this.min)&&t.max.equals(this.max)}},u.prototype=Object.create(n.prototype),u.prototype.constructor=u,u.prototype.isCubeTexture=!0,Object.defineProperty(u.prototype,"images",{get:function(){return this.image},set:function(t){this.image=t}}),t.WebGLUniforms=function(){var t=new n,e=new u,i=function(){this.seq=[],this.map={}},r=[],a=[],o=function(t,e,i){var n=t[0];if(n<=0||n>0)return t;var a=e*i,o=r[a];if(void 0===o&&(o=new Float32Array(a),r[a]=o),0!==e){n.toArray(o,0);for(var s=1,c=0;s!==e;++s)c+=i,t[s].toArray(o,c)}return o},s=function(t,e){var i=a[e];void 0===i&&(i=new Int32Array(e),a[e]=i);for(var n=0;n!==e;++n)i[n]=t.allocTextureUnit();return i},c=function(t,e){t.uniform1f(this.addr,e)},h=function(t,e){t.uniform1i(this.addr,e)},l=function(t,e){void 0===e.x?t.uniform2fv(this.addr,e):t.uniform2f(this.addr,e.x,e.y)},p=function(t,e){void 0!==e.x?t.uniform3f(this.addr,e.x,e.y,e.z):void 0!==e.r?t.uniform3f(this.addr,e.r,e.g,e.b):t.uniform3fv(this.addr,e)},d=function(t,e){void 0===e.x?t.uniform4fv(this.addr,e):t.uniform4f(this.addr,e.x,e.y,e.z,e.w)},f=function(t,e){t.uniformMatrix2fv(this.addr,!1,e.elements||e)},m=function(t,e){t.uniformMatrix3fv(this.addr,!1,e.elements||e)},v=function(t,e){t.uniformMatrix4fv(this.addr,!1,e.elements||e)},g=function(e,i,n){var r=n.allocTextureUnit();e.uniform1i(this.addr,r),n.setTexture2D(i||t,r)},y=function(t,i,n){var r=n.allocTextureUnit();t.uniform1i(this.addr,r),n.setTextureCube(i||e,r)},x=function(t,e){t.uniform2iv(this.addr,e)},_=function(t,e){t.uniform3iv(this.addr,e)},b=function(t,e){t.uniform4iv(this.addr,e)},w=function(t){switch(t){case 5126:return c;case 35664:return l;case 35665:return p;case 35666:return d;case 35674:return f;case 35675:return m;case 35676:return v;case 35678:return g;case 35680:return y;case 5124:case 35670:return h;case 35667:case 35671:return x;case 35668:case 35672:return _;case 35669:case 35673:return b}},M=function(t,e){t.uniform1fv(this.addr,e)},E=function(t,e){t.uniform1iv(this.addr,e)},T=function(t,e){t.uniform2fv(this.addr,o(e,this.size,2))},S=function(t,e){t.uniform3fv(this.addr,o(e,this.size,3))},A=function(t,e){t.uniform4fv(this.addr,o(e,this.size,4))},L=function(t,e){t.uniformMatrix2fv(this.addr,!1,o(e,this.size,4))},R=function(t,e){t.uniformMatrix3fv(this.addr,!1,o(e,this.size,9))},P=function(t,e){t.uniformMatrix4fv(this.addr,!1,o(e,this.size,16))},C=function(e,i,n){var r=i.length,a=s(n,r);e.uniform1iv(this.addr,a);for(var o=0;o!==r;++o)n.setTexture2D(i[o]||t,a[o])},U=function(t,i,n){var r=i.length,a=s(n,r);t.uniform1iv(this.addr,a);for(var o=0;o!==r;++o)n.setTextureCube(i[o]||e,a[o])},I=function(t){switch(t){case 5126:return M;case 35664:return T;case 35665:return S;case 35666:return A;case 35674:return L;case 35675:return R;case 35676:return P;case 35678:return C;case 35680:return U;case 5124:case 35670:return E;case 35667:case 35671:return x;case 35668:case 35672:return _;case 35669:case 35673:return b}},D=function(t,e,i){this.id=t,this.addr=i,this.setValue=w(e.type)},N=function(t,e,i){this.id=t,this.addr=i,this.size=e.size,this.setValue=I(e.type)},O=function(t){this.id=t,i.call(this)};O.prototype.setValue=function(t,e){for(var i=this.seq,n=0,r=i.length;n!==r;++n){var a=i[n];a.setValue(t,e[a.id])}};var F=/([\w\d_]+)(\])?(\[|\.)?/g,B=function(t,e){t.seq.push(e),t.map[e.id]=e},z=function(t,e,i){var n=t.name,r=n.length;for(F.lastIndex=0;;){var a=F.exec(n),o=F.lastIndex,s=a[1],c="]"===a[2],h=a[3];if(c&&(s=0|s),void 0===h||"["===h&&o+2===r){B(i,void 0===h?new D(s,t,e):new N(s,t,e));break}var l=i.map,u=l[s];void 0===u&&(u=new O(s),B(i,u)),i=u}},G=function(t,e,n){i.call(this),this.renderer=n;for(var r=t.getProgramParameter(e,t.ACTIVE_UNIFORMS),a=0;a!==r;++a){var o=t.getActiveUniform(e,a),s=o.name,c=t.getUniformLocation(e,s);z(o,c,this)}};return G.prototype.setValue=function(t,e,i){var n=this.map[e];void 0!==n&&n.setValue(t,i,this.renderer)},G.prototype.set=function(t,e,i){var n=this.map[i];void 0!==n&&n.setValue(t,e[i],this.renderer)},G.prototype.setOptional=function(t,e,i){var n=e[i];void 0!==n&&this.setValue(t,i,n)},G.upload=function(t,e,i,n){for(var r=0,a=e.length;r!==a;++r){var o=e[r],s=i[o.id];s.needsUpdate!==!1&&o.setValue(t,s.value,n)}},G.seqWithValue=function(t,e){for(var i=[],n=0,r=t.length;n!==r;++n){var a=t[n];a.id in e&&i.push(a)}return i},G.splitDynamic=function(t,e){for(var i=null,n=t.length,r=0,a=0;a!==n;++a){var o=t[a],s=e[o.id];s&&s.dynamic===!0?(null===i&&(i=[]),i.push(o)):(ry&&g>x?gx?y0&&(n.alphaTest=this.alphaTest),this.premultipliedAlpha===!0&&(n.premultipliedAlpha=this.premultipliedAlpha),this.wireframe===!0&&(n.wireframe=this.wireframe),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),i){var r=e(t.textures),a=e(t.images);r.length>0&&(n.textures=r),a.length>0&&(n.images=a)}return n},clone:function(){return(new this.constructor).copy(this)},copy:function(t){this.name=t.name,this.fog=t.fog,this.lights=t.lights,this.blending=t.blending,this.side=t.side,this.shading=t.shading,this.vertexColors=t.vertexColors,this.opacity=t.opacity,this.transparent=t.transparent,this.blendSrc=t.blendSrc,this.blendDst=t.blendDst,this.blendEquation=t.blendEquation,this.blendSrcAlpha=t.blendSrcAlpha,this.blendDstAlpha=t.blendDstAlpha,this.blendEquationAlpha=t.blendEquationAlpha,this.depthFunc=t.depthFunc,this.depthTest=t.depthTest,this.depthWrite=t.depthWrite,this.colorWrite=t.colorWrite,this.precision=t.precision,this.polygonOffset=t.polygonOffset,this.polygonOffsetFactor=t.polygonOffsetFactor,this.polygonOffsetUnits=t.polygonOffsetUnits,this.alphaTest=t.alphaTest,this.premultipliedAlpha=t.premultipliedAlpha,this.overdraw=t.overdraw,this.visible=t.visible,this.clipShadows=t.clipShadows;var e=t.clippingPlanes,i=null;if(null!==e){var n=e.length;i=new Array(n);for(var r=0;r!==n;++r)i[r]=e[r].clone()}return this.clippingPlanes=i,this},update:function(){this.dispatchEvent({type:"update"})},dispose:function(){this.dispatchEvent({type:"dispose"})}},Object.assign(x.prototype,e.prototype);var Ta=0;t.UniformsUtils={merge:function(t){for(var e={},i=0;i>16&255)/255,this.g=(t>>8&255)/255,this.b=(255&t)/255,this},setRGB:function(t,e,i){return this.r=t,this.g=e,this.b=i,this},setHSL:function(){function e(t,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+6*(e-t)*(2/3-i):t}return function(i,n,r){if(i=t.Math.euclideanModulo(i,1),n=t.Math.clamp(n,0,1),r=t.Math.clamp(r,0,1),0===n)this.r=this.g=this.b=r;else{var a=r<=.5?r*(1+n):r+n-r*n,o=2*r-a;this.r=e(o,a,i+1/3),this.g=e(o,a,i),this.b=e(o,a,i-1/3)}return this}}(),setStyle:function(e){function i(t){void 0!==t&&parseFloat(t)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}var n;if(n=/^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec(e)){var r,a=n[1],o=n[2];switch(a){case"rgb":case"rgba":if(r=/^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(o))return this.r=Math.min(255,parseInt(r[1],10))/255,this.g=Math.min(255,parseInt(r[2],10))/255,this.b=Math.min(255,parseInt(r[3],10))/255,i(r[5]),this;if(r=/^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(o))return this.r=Math.min(100,parseInt(r[1],10))/100,this.g=Math.min(100,parseInt(r[2],10))/100,this.b=Math.min(100,parseInt(r[3],10))/100,i(r[5]),this;break;case"hsl":case"hsla":if(r=/^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(o)){var s=parseFloat(r[1])/360,c=parseInt(r[2],10)/100,h=parseInt(r[3],10)/100;return i(r[5]),this.setHSL(s,c,h)}}}else if(n=/^\#([A-Fa-f0-9]+)$/.exec(e)){var l=n[1],u=l.length;if(3===u)return this.r=parseInt(l.charAt(0)+l.charAt(0),16)/255,this.g=parseInt(l.charAt(1)+l.charAt(1),16)/255,this.b=parseInt(l.charAt(2)+l.charAt(2),16)/255,this;if(6===u)return this.r=parseInt(l.charAt(0)+l.charAt(1),16)/255,this.g=parseInt(l.charAt(2)+l.charAt(3),16)/255,this.b=parseInt(l.charAt(4)+l.charAt(5),16)/255,this}if(e&&e.length>0){var l=t.ColorKeywords[e];void 0!==l?this.setHex(l):console.warn("THREE.Color: Unknown color "+e)}return this},clone:function(){return new this.constructor(this.r,this.g,this.b)},copy:function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},copyGammaToLinear:function(t,e){return void 0===e&&(e=2),this.r=Math.pow(t.r,e),this.g=Math.pow(t.g,e),this.b=Math.pow(t.b,e),this},copyLinearToGamma:function(t,e){void 0===e&&(e=2);var i=e>0?1/e:1;return this.r=Math.pow(t.r,i),this.g=Math.pow(t.g,i),this.b=Math.pow(t.b,i),this},convertGammaToLinear:function(){var t=this.r,e=this.g,i=this.b;return this.r=t*t,this.g=e*e,this.b=i*i,this},convertLinearToGamma:function(){return this.r=Math.sqrt(this.r),this.g=Math.sqrt(this.g),this.b=Math.sqrt(this.b),this},getHex:function(){return 255*this.r<<16^255*this.g<<8^255*this.b<<0},getHexString:function(){return("000000"+this.getHex().toString(16)).slice(-6)},getHSL:function(t){var e,i,n=t||{h:0,s:0,l:0},r=this.r,a=this.g,o=this.b,s=Math.max(r,a,o),c=Math.min(r,a,o),h=(c+s)/2;if(c===s)e=0,i=0;else{var l=s-c;switch(i=h<=.5?l/(s+c):l/(2-s-c),s){case r:e=(a-o)/l+(ar&&(r=h),l>a&&(a=l),u>o&&(o=u)}this.min.set(e,i,n),this.max.set(r,a,o)},setFromPoints:function(t){this.makeEmpty();for(var e=0,i=t.length;ethis.max.x||t.ythis.max.y||t.zthis.max.z)},containsBox:function(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y&&this.min.z<=t.min.z&&t.max.z<=this.max.z},getParameter:function(t,e){var i=e||new s;return i.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y),(t.z-this.min.z)/(this.max.z-this.min.z))},intersectsBox:function(t){return!(t.max.xthis.max.x||t.max.ythis.max.y||t.max.zthis.max.z)},intersectsSphere:function(){var t;return function(e){return void 0===t&&(t=new s),this.clampPoint(e.center,t),t.distanceToSquared(e.center)<=e.radius*e.radius}}(),intersectsPlane:function(t){var e,i;return t.normal.x>0?(e=t.normal.x*this.min.x,i=t.normal.x*this.max.x):(e=t.normal.x*this.max.x,i=t.normal.x*this.min.x),t.normal.y>0?(e+=t.normal.y*this.min.y,i+=t.normal.y*this.max.y):(e+=t.normal.y*this.max.y,i+=t.normal.y*this.min.y),t.normal.z>0?(e+=t.normal.z*this.min.z,i+=t.normal.z*this.max.z):(e+=t.normal.z*this.max.z,i+=t.normal.z*this.min.z),e<=t.constant&&i>=t.constant},clampPoint:function(t,e){var i=e||new s;return i.copy(t).clamp(this.min,this.max)},distanceToPoint:function(){var t=new s;return function(e){var i=t.copy(e).clamp(this.min,this.max);return i.sub(e).length()}}(),getBoundingSphere:function(){var t=new s;return function(e){var i=e||new T;return i.center=this.center(),i.radius=.5*this.size(t).length(),i}}(),intersect:function(t){return this.min.max(t.min),this.max.min(t.max),this.isEmpty()&&this.makeEmpty(),this},union:function(t){return this.min.min(t.min),this.max.max(t.max),this},applyMatrix4:function(){var t=[new s,new s,new s,new s,new s,new s,new s,new s];return function(e){return this.isEmpty()?this:(t[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),t[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),t[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),t[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),t[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),t[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),t[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),t[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(t),this)}}(),translate:function(t){return this.min.add(t),this.max.add(t),this},equals:function(t){return t.min.equals(this.min)&&t.max.equals(this.max)}},T.prototype={constructor:T,set:function(t,e){return this.center.copy(t),this.radius=e,this},setFromPoints:function(){var t=new E;return function(e,i){var n=this.center;void 0!==i?n.copy(i):t.setFromPoints(e).center(n);for(var r=0,a=0,o=e.length;athis.radius*this.radius&&(n.sub(this.center).normalize(),n.multiplyScalar(this.radius).add(this.center)),n},getBoundingBox:function(t){var e=t||new E;return e.set(this.center,this.center),e.expandByScalar(this.radius),e},applyMatrix4:function(t){return this.center.applyMatrix4(t),this.radius=this.radius*t.getMaxScaleOnAxis(),this},translate:function(t){return this.center.add(t),this},equals:function(t){return t.center.equals(this.center)&&t.radius===this.radius}},S.prototype={constructor:S,isMatrix3:!0,set:function(t,e,i,n,r,a,o,s,c){var h=this.elements;return h[0]=t,h[1]=n,h[2]=o,h[3]=e,h[4]=r,h[5]=s,h[6]=i,h[7]=a,h[8]=c,this},identity:function(){return this.set(1,0,0,0,1,0,0,0,1),this},clone:function(){return(new this.constructor).fromArray(this.elements)},copy:function(t){var e=t.elements;return this.set(e[0],e[3],e[6],e[1],e[4],e[7],e[2],e[5],e[8]),this},setFromMatrix4:function(t){var e=t.elements;return this.set(e[0],e[4],e[8],e[1],e[5],e[9],e[2],e[6],e[10]),this},applyToVector3Array:function(){var t;return function(e,i,n){void 0===t&&(t=new s),void 0===i&&(i=0),void 0===n&&(n=e.length);for(var r=0,a=i;r1))return n.copy(r).multiplyScalar(o).add(e.start)}else if(0===this.distanceToPoint(e.start))return n.copy(e.start)}}(),intersectsLine:function(t){var e=this.distanceToPoint(t.start),i=this.distanceToPoint(t.end);return e<0&&i>0||i<0&&e>0},intersectsBox:function(t){return t.intersectsPlane(this)},intersectsSphere:function(t){return t.intersectsPlane(this)},coplanarPoint:function(t){var e=t||new s;return e.copy(this.normal).multiplyScalar(-this.constant)},applyMatrix4:function(){var t=new s,e=new S;return function(i,n){var r=this.coplanarPoint(t).applyMatrix4(i),a=n||e.getNormalMatrix(i),o=this.normal.applyMatrix3(a).normalize();return this.constant=-r.dot(o),this}}(),translate:function(t){return this.constant=this.constant-t.dot(this.normal),this},equals:function(t){return t.normal.equals(this.normal)&&t.constant===this.constant}},L.prototype={constructor:L,set:function(t,e,i,n,r,a){var o=this.planes;return o[0].copy(t),o[1].copy(e),o[2].copy(i),o[3].copy(n),o[4].copy(r),o[5].copy(a),this},clone:function(){return(new this.constructor).copy(this)},copy:function(t){for(var e=this.planes,i=0;i<6;i++)e[i].copy(t.planes[i]);return this},setFromMatrix:function(t){var e=this.planes,i=t.elements,n=i[0],r=i[1],a=i[2],o=i[3],s=i[4],c=i[5],h=i[6],l=i[7],u=i[8],p=i[9],d=i[10],f=i[11],m=i[12],v=i[13],g=i[14],y=i[15];return e[0].setComponents(o-n,l-s,f-u,y-m).normalize(),e[1].setComponents(o+n,l+s,f+u,y+m).normalize(),e[2].setComponents(o+r,l+c,f+p,y+v).normalize(),e[3].setComponents(o-r,l-c,f-p,y-v).normalize(),e[4].setComponents(o-a,l-h,f-d,y-g).normalize(),e[5].setComponents(o+a,l+h,f+d,y+g).normalize(),this},intersectsObject:function(){var t=new T;return function(e){var i=e.geometry;return null===i.boundingSphere&&i.computeBoundingSphere(),t.copy(i.boundingSphere).applyMatrix4(e.matrixWorld),this.intersectsSphere(t)}}(),intersectsSprite:function(){var t=new T;return function(e){return t.center.set(0,0,0),t.radius=.7071067811865476,t.applyMatrix4(e.matrixWorld),this.intersectsSphere(t)}}(),intersectsSphere:function(t){for(var e=this.planes,i=t.center,n=-t.radius,r=0;r<6;r++){var a=e[r].distanceToPoint(i);if(a0?i.min.x:i.max.x,e.x=a.normal.x>0?i.max.x:i.min.x,t.y=a.normal.y>0?i.min.y:i.max.y,e.y=a.normal.y>0?i.max.y:i.min.y,t.z=a.normal.z>0?i.min.z:i.max.z,e.z=a.normal.z>0?i.max.z:i.min.z;var o=a.distanceToPoint(t),s=a.distanceToPoint(e);if(o<0&&s<0)return!1}return!0}}(),containsPoint:function(t){for(var e=this.planes,i=0;i<6;i++)if(e[i].distanceToPoint(t)<0)return!1;return!0}},t.WebGLShader=function(){function t(t){for(var e=t.split("\n"),i=0;i");return l(i)}var i=/#include +<([\w\d.]+)>/g;return t.replace(i,e)}function u(t){function e(t,e,i,n){for(var r="",a=parseInt(e);a0?e.gammaFactor:1,L=a(g,m,e.extensions),R=o(y),P=v.createProgram();f&&f.isRawShaderMaterial?(T=[R].filter(c).join("\n"),S=[R].filter(c).join("\n")):(T=["precision "+m.precision+" float;","precision "+m.precision+" int;","#define SHADER_NAME "+f.__webglShader.name,R,m.supportsVertexTextures?"#define VERTEX_TEXTURES":"","#define GAMMA_FACTOR "+A,"#define MAX_BONES "+m.maxBones,m.map?"#define USE_MAP":"",m.envMap?"#define USE_ENVMAP":"",m.envMap?"#define "+M:"",m.lightMap?"#define USE_LIGHTMAP":"",m.aoMap?"#define USE_AOMAP":"",m.emissiveMap?"#define USE_EMISSIVEMAP":"",m.bumpMap?"#define USE_BUMPMAP":"",m.normalMap?"#define USE_NORMALMAP":"",m.displacementMap&&m.supportsVertexTextures?"#define USE_DISPLACEMENTMAP":"",m.specularMap?"#define USE_SPECULARMAP":"",m.roughnessMap?"#define USE_ROUGHNESSMAP":"",m.metalnessMap?"#define USE_METALNESSMAP":"",m.alphaMap?"#define USE_ALPHAMAP":"",m.vertexColors?"#define USE_COLOR":"",m.flatShading?"#define FLAT_SHADED":"",m.skinning?"#define USE_SKINNING":"",m.useVertexTexture?"#define BONE_TEXTURE":"",m.morphTargets?"#define USE_MORPHTARGETS":"",m.morphNormals&&m.flatShading===!1?"#define USE_MORPHNORMALS":"",m.doubleSided?"#define DOUBLE_SIDED":"",m.flipSided?"#define FLIP_SIDED":"","#define NUM_CLIPPING_PLANES "+m.numClippingPlanes,m.shadowMapEnabled?"#define USE_SHADOWMAP":"",m.shadowMapEnabled?"#define "+b:"",m.sizeAttenuation?"#define USE_SIZEATTENUATION":"",m.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",m.logarithmicDepthBuffer&&e.extensions.get("EXT_frag_depth")?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_COLOR","\tattribute vec3 color;","#endif","#ifdef USE_MORPHTARGETS","\tattribute vec3 morphTarget0;","\tattribute vec3 morphTarget1;","\tattribute vec3 morphTarget2;","\tattribute vec3 morphTarget3;","\t#ifdef USE_MORPHNORMALS","\t\tattribute vec3 morphNormal0;","\t\tattribute vec3 morphNormal1;","\t\tattribute vec3 morphNormal2;","\t\tattribute vec3 morphNormal3;","\t#else","\t\tattribute vec3 morphTarget4;","\t\tattribute vec3 morphTarget5;","\t\tattribute vec3 morphTarget6;","\t\tattribute vec3 morphTarget7;","\t#endif","#endif","#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif","\n"].filter(c).join("\n"), -S=[L,"precision "+m.precision+" float;","precision "+m.precision+" int;","#define SHADER_NAME "+f.__webglShader.name,R,m.alphaTest?"#define ALPHATEST "+m.alphaTest:"","#define GAMMA_FACTOR "+A,m.useFog&&m.fog?"#define USE_FOG":"",m.useFog&&m.fogExp?"#define FOG_EXP2":"",m.map?"#define USE_MAP":"",m.envMap?"#define USE_ENVMAP":"",m.envMap?"#define "+w:"",m.envMap?"#define "+M:"",m.envMap?"#define "+E:"",m.lightMap?"#define USE_LIGHTMAP":"",m.aoMap?"#define USE_AOMAP":"",m.emissiveMap?"#define USE_EMISSIVEMAP":"",m.bumpMap?"#define USE_BUMPMAP":"",m.normalMap?"#define USE_NORMALMAP":"",m.specularMap?"#define USE_SPECULARMAP":"",m.roughnessMap?"#define USE_ROUGHNESSMAP":"",m.metalnessMap?"#define USE_METALNESSMAP":"",m.alphaMap?"#define USE_ALPHAMAP":"",m.vertexColors?"#define USE_COLOR":"",m.flatShading?"#define FLAT_SHADED":"",m.doubleSided?"#define DOUBLE_SIDED":"",m.flipSided?"#define FLIP_SIDED":"","#define NUM_CLIPPING_PLANES "+m.numClippingPlanes,m.shadowMapEnabled?"#define USE_SHADOWMAP":"",m.shadowMapEnabled?"#define "+b:"",m.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",m.physicallyCorrectLights?"#define PHYSICALLY_CORRECT_LIGHTS":"",m.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",m.logarithmicDepthBuffer&&e.extensions.get("EXT_frag_depth")?"#define USE_LOGDEPTHBUF_EXT":"",m.envMap&&e.extensions.get("EXT_shader_texture_lod")?"#define TEXTURE_LOD_EXT":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;",m.toneMapping!==ar?"#define TONE_MAPPING":"",m.toneMapping!==ar?Es.tonemapping_pars_fragment:"",m.toneMapping!==ar?r("toneMapping",m.toneMapping):"",m.outputEncoding||m.mapEncoding||m.envMapEncoding||m.emissiveMapEncoding?Es.encodings_pars_fragment:"",m.mapEncoding?i("mapTexelToLinear",m.mapEncoding):"",m.envMapEncoding?i("envMapTexelToLinear",m.envMapEncoding):"",m.emissiveMapEncoding?i("emissiveMapTexelToLinear",m.emissiveMapEncoding):"",m.outputEncoding?n("linearToOutputTexel",m.outputEncoding):"",m.depthPacking?"#define DEPTH_PACKING "+f.depthPacking:"","\n"].filter(c).join("\n")),x=l(x,m),x=h(x,m),_=l(_,m),_=h(_,m),(f&&f.isShaderMaterial)===!1&&(x=u(x),_=u(_));var C=T+x,U=S+_,I=t.WebGLShader(v,v.VERTEX_SHADER,C),D=t.WebGLShader(v,v.FRAGMENT_SHADER,U);v.attachShader(P,I),v.attachShader(P,D),void 0!==f.index0AttributeName?v.bindAttribLocation(P,0,f.index0AttributeName):m.morphTargets===!0&&v.bindAttribLocation(P,0,"position"),v.linkProgram(P);var N=v.getProgramInfoLog(P),O=v.getShaderInfoLog(I),F=v.getShaderInfoLog(D),B=!0,z=!0;v.getProgramParameter(P,v.LINK_STATUS)===!1?(B=!1,console.error("THREE.WebGLProgram: shader error: ",v.getError(),"gl.VALIDATE_STATUS",v.getProgramParameter(P,v.VALIDATE_STATUS),"gl.getProgramInfoLog",N,O,F)):""!==N?console.warn("THREE.WebGLProgram: gl.getProgramInfoLog()",N):""!==O&&""!==F||(z=!1),z&&(this.diagnostics={runnable:B,material:f,programLog:N,vertexShader:{log:O,prefix:T},fragmentShader:{log:F,prefix:S}}),v.deleteShader(I),v.deleteShader(D);var G;this.getUniforms=function(){return void 0===G&&(G=new t.WebGLUniforms(v,P,e)),G};var H;return this.getAttributes=function(){return void 0===H&&(H=s(v,P)),H},this.destroy=function(){v.deleteProgram(P),this.program=void 0},Object.defineProperties(this,{uniforms:{get:function(){return console.warn("THREE.WebGLProgram: .uniforms is now .getUniforms()."),this.getUniforms()}},attributes:{get:function(){return console.warn("THREE.WebGLProgram: .attributes is now .getAttributes()."),this.getAttributes()}}}),this.id=p++,this.code=d,this.usedTimes=1,this.program=P,this.vertexShader=I,this.fragmentShader=D,this}}(),U.prototype={constructor:U,isBufferAttribute:!0,get count(){return this.array.length/this.itemSize},set needsUpdate(t){t===!0&&this.version++},setDynamic:function(t){return this.dynamic=t,this},copy:function(t){return this.array=new t.array.constructor(t.array),this.itemSize=t.itemSize,this.dynamic=t.dynamic,this},copyAt:function(t,e,i){t*=this.itemSize,i*=e.itemSize;for(var n=0,r=this.itemSize;n1){for(var e=0;e1)for(var e=0;e0){r.children=[];for(var a=0;a0&&(n.geometries=o),s.length>0&&(n.materials=s),c.length>0&&(n.textures=c),h.length>0&&(n.images=h)}return n.object=r,n},clone:function(t){return(new this.constructor).copy(this,t)},copy:function(t,e){if(void 0===e&&(e=!0),this.name=t.name,this.up.copy(t.up),this.position.copy(t.position),this.quaternion.copy(t.quaternion),this.scale.copy(t.scale),this.matrix.copy(t.matrix),this.matrixWorld.copy(t.matrixWorld),this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrixWorldNeedsUpdate=t.matrixWorldNeedsUpdate,this.visible=t.visible,this.castShadow=t.castShadow,this.receiveShadow=t.receiveShadow,this.frustumCulled=t.frustumCulled,this.renderOrder=t.renderOrder,this.userData=JSON.parse(JSON.stringify(t.userData)),e===!0)for(var i=0;i0)for(var m=0;m0&&(this.normalsNeedUpdate=!0)},computeMorphNormals:function(){var t,e,i,n,r;for(i=0,n=this.faces.length;i0&&(t+=e[i].distanceTo(e[i-1])),this.lineDistances[i]=t},computeBoundingBox:function(){null===this.boundingBox&&(this.boundingBox=new E),this.boundingBox.setFromPoints(this.vertices)},computeBoundingSphere:function(){null===this.boundingSphere&&(this.boundingSphere=new T),this.boundingSphere.setFromPoints(this.vertices)},merge:function(t,e,i){if((t&&t.isGeometry)===!1)return void console.error("THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.",t);var n,r=this.vertices.length,a=this.vertices,o=t.vertices,s=this.faces,c=t.faces,h=this.faceVertexUvs[0],l=t.faceVertexUvs[0];void 0===i&&(i=0),void 0!==e&&(n=(new S).getNormalMatrix(e));for(var u=0,p=o.length;u=0;i--){var v=d[i];for(this.faces.splice(v,1),o=0,s=this.faceVertexUvs.length;o0,w=g.vertexNormals.length>0,M=1!==g.color.r||1!==g.color.g||1!==g.color.b,E=g.vertexColors.length>0,T=0;if(T=t(T,0,0),T=t(T,1,y),T=t(T,2,x),T=t(T,3,_),T=t(T,4,b),T=t(T,5,w),T=t(T,6,M),T=t(T,7,E),l.push(T),l.push(g.a,g.b,g.c),l.push(g.materialIndex),_){var S=this.faceVertexUvs[0][c];l.push(n(S[0]),n(S[1]),n(S[2]))}if(b&&l.push(e(g.normal)),w){var A=g.vertexNormals;l.push(e(A[0]),e(A[1]),e(A[2]))}if(M&&l.push(i(g.color)),E){var L=g.vertexColors;l.push(i(L[0]),i(L[1]),i(L[2]))}}return r.data={},r.data.vertices=s,r.data.normals=u,d.length>0&&(r.data.colors=d),m.length>0&&(r.data.uvs=[m]),r.data.faces=l,r},clone:function(){return(new q).copy(this)},copy:function(t){this.vertices=[],this.faces=[],this.faceVertexUvs=[[]];for(var e=t.vertices,i=0,n=e.length;i0,s=a[1]&&a[1].length>0,c=t.morphTargets,h=c.length;if(h>0){e=[];for(var l=0;l0){u=[];for(var l=0;l0){var i=new Float32Array(3*t.normals.length);this.addAttribute("normal",new U(i,3).copyVector3sArray(t.normals))}if(t.colors.length>0){var n=new Float32Array(3*t.colors.length);this.addAttribute("color",new U(n,3).copyColorsArray(t.colors))}if(t.uvs.length>0){var r=new Float32Array(2*t.uvs.length);this.addAttribute("uv",new U(r,2).copyVector2sArray(t.uvs))}if(t.uvs2.length>0){var a=new Float32Array(2*t.uvs2.length);this.addAttribute("uv2",new U(a,2).copyVector2sArray(t.uvs2))}if(t.indices.length>0){var o=t.vertices.length>65535?Uint32Array:Uint16Array,s=new o(3*t.indices.length);this.setIndex(new U(s,1).copyIndicesArray(t.indices))}this.groups=t.groups;for(var c in t.morphTargets){for(var h=[],l=t.morphTargets[c],u=0,p=l.length;u0){var m=new G(4*t.skinIndices.length,4);this.addAttribute("skinIndex",m.copyVector4sArray(t.skinIndices))}if(t.skinWeights.length>0){var v=new G(4*t.skinWeights.length,4);this.addAttribute("skinWeight",v.copyVector4sArray(t.skinWeights))}return null!==t.boundingSphere&&(this.boundingSphere=t.boundingSphere.clone()),null!==t.boundingBox&&(this.boundingBox=t.boundingBox.clone()),this},computeBoundingBox:function(){null===this.boundingBox&&(this.boundingBox=new E);var t=this.attributes.position.array;void 0!==t?this.boundingBox.setFromArray(t):this.boundingBox.makeEmpty(),(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&console.error('THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)},computeBoundingSphere:function(){var t=new E,e=new s;return function(){null===this.boundingSphere&&(this.boundingSphere=new T);var i=this.attributes.position;if(i){var n=i.array,r=this.boundingSphere.center;t.setFromArray(n),t.center(r);for(var a=0,o=0,s=n.length;o0&&(t.data.groups=JSON.parse(JSON.stringify(s)));var c=this.boundingSphere;return null!==c&&(t.data.boundingSphere={center:c.center.toArray(),radius:c.radius}),t},clone:function(){return(new Q).copy(this)},copy:function(t){var e=t.index;null!==e&&this.setIndex(e.clone());var i=t.attributes;for(var n in i){var r=i[n];this.addAttribute(n,r.clone())}for(var a=t.groups,o=0,s=a.length;o0)if(s=p*f-d,c=p*d-f,l=u*v,s>=0)if(c>=-l)if(c<=l){var g=1/v;s*=g,c*=g,h=s*(s+p*c+2*d)+c*(p*s+c+2*f)+m}else c=u,s=Math.max(0,-(p*c+d)),h=-s*s+c*(c+2*f)+m;else c=-u,s=Math.max(0,-(p*c+d)),h=-s*s+c*(c+2*f)+m;else c<=-l?(s=Math.max(0,-(-p*u+d)),c=s>0?-u:Math.min(Math.max(-u,-f),u),h=-s*s+c*(c+2*f)+m):c<=l?(s=0,c=Math.min(Math.max(-u,-f),u),h=c*(c+2*f)+m):(s=Math.max(0,-(p*u+d)),c=s>0?u:Math.min(Math.max(-u,-f),u),h=-s*s+c*(c+2*f)+m);else c=p>0?-u:u,s=Math.max(0,-(p*c+d)),h=-s*s+c*(c+2*f)+m;return a&&a.copy(this.direction).multiplyScalar(s).add(this.origin),o&&o.copy(e).multiplyScalar(c).add(t),h}}(),intersectSphere:function(){var t=new s;return function(e,i){t.subVectors(e.center,this.origin);var n=t.dot(this.direction),r=t.dot(t)-n*n,a=e.radius*e.radius;if(r>a)return null;var o=Math.sqrt(a-r),s=n-o,c=n+o;return s<0&&c<0?null:s<0?this.at(c,i):this.at(s,i)}}(),intersectsSphere:function(t){return this.distanceToPoint(t.center)<=t.radius},distanceToPlane:function(t){var e=t.normal.dot(this.direction);if(0===e)return 0===t.distanceToPoint(this.origin)?0:null;var i=-(this.origin.dot(t.normal)+t.constant)/e;return i>=0?i:null},intersectPlane:function(t,e){var i=this.distanceToPlane(t);return null===i?null:this.at(i,e)},intersectsPlane:function(t){var e=t.distanceToPoint(this.origin);if(0===e)return!0;var i=t.normal.dot(this.direction);return i*e<0},intersectBox:function(t,e){var i,n,r,a,o,s,c=1/this.direction.x,h=1/this.direction.y,l=1/this.direction.z,u=this.origin;return c>=0?(i=(t.min.x-u.x)*c,n=(t.max.x-u.x)*c):(i=(t.max.x-u.x)*c,n=(t.min.x-u.x)*c),h>=0?(r=(t.min.y-u.y)*h,a=(t.max.y-u.y)*h):(r=(t.max.y-u.y)*h,a=(t.min.y-u.y)*h),i>a||r>n?null:((r>i||i!==i)&&(i=r),(a=0?(o=(t.min.z-u.z)*l,s=(t.max.z-u.z)*l):(o=(t.max.z-u.z)*l,s=(t.min.z-u.z)*l),i>s||o>n?null:((o>i||i!==i)&&(i=o),(s=0?i:n,e)))},intersectsBox:function(){var t=new s;return function(e){return null!==this.intersectBox(e,t)}}(),intersectTriangle:function(){var t=new s,e=new s,i=new s,n=new s;return function(r,a,o,s,c){e.subVectors(a,r),i.subVectors(o,r),n.crossVectors(e,i);var h,l=this.direction.dot(n);if(l>0){if(s)return null;h=1}else{if(!(l<0))return null;h=-1,l=-l}t.subVectors(this.origin,r);var u=h*this.direction.dot(i.crossVectors(t,i));if(u<0)return null;var p=h*this.direction.dot(e.cross(t));if(p<0)return null;if(u+p>l)return null;var d=-h*t.dot(n);return d<0?null:this.at(d/l,c)}}(),applyMatrix4:function(t){return this.direction.add(this.origin).applyMatrix4(t),this.origin.applyMatrix4(t),this.direction.sub(this.origin),this.direction.normalize(),this},equals:function(t){return t.origin.equals(this.origin)&&t.direction.equals(this.direction)}},ht.prototype={constructor:ht,set:function(t,e){return this.start.copy(t),this.end.copy(e),this},clone:function(){return(new this.constructor).copy(this)},copy:function(t){return this.start.copy(t.start),this.end.copy(t.end),this},center:function(t){var e=t||new s;return e.addVectors(this.start,this.end).multiplyScalar(.5)},delta:function(t){var e=t||new s;return e.subVectors(this.end,this.start)},distanceSq:function(){return this.start.distanceToSquared(this.end)},distance:function(){return this.start.distanceTo(this.end)},at:function(t,e){var i=e||new s;return this.delta(i).multiplyScalar(t).add(this.start)},closestPointToPointParameter:function(){var e=new s,i=new s;return function(n,r){e.subVectors(n,this.start),i.subVectors(this.end,this.start);var a=i.dot(i),o=i.dot(e),s=o/a;return r&&(s=t.Math.clamp(s,0,1)),s}}(),closestPointToPoint:function(t,e,i){var n=this.closestPointToPointParameter(t,e),r=i||new s;return this.delta(r).multiplyScalar(n).add(this.start)},applyMatrix4:function(t){return this.start.applyMatrix4(t),this.end.applyMatrix4(t),this},equals:function(t){return t.start.equals(this.start)&&t.end.equals(this.end)}},lt.normal=function(){var t=new s;return function(e,i,n,r){var a=r||new s;a.subVectors(n,i),t.subVectors(e,i),a.cross(t);var o=a.lengthSq();return o>0?a.multiplyScalar(1/Math.sqrt(o)):a.set(0,0,0)}}(),lt.barycoordFromPoint=function(){var t=new s,e=new s,i=new s;return function(n,r,a,o,c){t.subVectors(o,r),e.subVectors(a,r),i.subVectors(n,r);var h=t.dot(t),l=t.dot(e),u=t.dot(i),p=e.dot(e),d=e.dot(i),f=h*p-l*l,m=c||new s;if(0===f)return m.set(-2,-1,-1);var v=1/f,g=(p*u-l*d)*v,y=(h*d-l*u)*v;return m.set(1-g-y,y,g)}}(),lt.containsPoint=function(){var t=new s;return function(e,i,n,r){var a=lt.barycoordFromPoint(e,i,n,r,t);return a.x>=0&&a.y>=0&&a.x+a.y<=1}}(),lt.prototype={constructor:lt,set:function(t,e,i){return this.a.copy(t),this.b.copy(e),this.c.copy(i),this},setFromPointsAndIndices:function(t,e,i,n){return this.a.copy(t[e]),this.b.copy(t[i]),this.c.copy(t[n]),this},clone:function(){return(new this.constructor).copy(this)},copy:function(t){return this.a.copy(t.a),this.b.copy(t.b),this.c.copy(t.c),this},area:function(){var t=new s,e=new s;return function(){return t.subVectors(this.c,this.b),e.subVectors(this.a,this.b),.5*t.cross(e).length()}}(),midpoint:function(t){var e=t||new s;return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)},normal:function(t){return lt.normal(this.a,this.b,this.c,t)},plane:function(t){var e=t||new A;return e.setFromCoplanarPoints(this.a,this.b,this.c)},barycoordFromPoint:function(t,e){return lt.barycoordFromPoint(t,this.a,this.b,this.c,e)},containsPoint:function(t){return lt.containsPoint(t,this.a,this.b,this.c)},closestPointToPoint:function(){var t,e,i,n;return function(r,a){void 0===t&&(t=new A,e=[new ht,new ht,new ht],i=new s,n=new s);var o=a||new s,c=1/0;if(t.setFromCoplanarPoints(this.a,this.b,this.c),t.projectPoint(r,i),this.containsPoint(i)===!0)o.copy(i);else{e[0].set(this.a,this.b),e[1].set(this.b,this.c),e[2].set(this.c,this.a);for(var h=0;h0){this.morphTargetBase=-1,this.morphTargetInfluences=[],this.morphTargetDictionary={};for(var t=0,e=this.geometry.morphTargets.length;te.far?null:{distance:h,point:_.clone(),object:t}}function n(i,n,r,a,o,s,c,p){h.fromArray(a,3*s),l.fromArray(a,3*c),u.fromArray(a,3*p);var d=e(i,n,r,h,l,u,x);return d&&(o&&(m.fromArray(o,2*s),v.fromArray(o,2*c),g.fromArray(o,2*p),d.uv=t(x,h,l,u,m,v,g)),d.face=new k(s,c,p,lt.normal(h,l,u)),d.faceIndex=s),d}var r=new a,o=new ct,c=new T,h=new s,l=new s,u=new s,p=new s,d=new s,f=new s,m=new i,v=new i,g=new i,y=new s,x=new s,_=new s;return function(i,a){var s=this.geometry,y=this.material,_=this.matrixWorld;if(void 0!==y&&(null===s.boundingSphere&&s.computeBoundingSphere(),c.copy(s.boundingSphere),c.applyMatrix4(_),i.ray.intersectsSphere(c)!==!1&&(r.getInverse(_),o.copy(i.ray).applyMatrix4(r),null===s.boundingBox||o.intersectsBox(s.boundingBox)!==!1))){var b,w;if(s&&s.isBufferGeometry){var M,E,T,S=s.index,A=s.attributes,L=A.position.array;if(void 0!==A.uv&&(b=A.uv.array),null!==S)for(var R=S.array,P=0,C=R.length;P0&&(b=z);for(var G=0,H=B.length;Gr||i.push({distance:Math.sqrt(n),point:this.position,face:null,object:this})}}(),clone:function(){return new this.constructor(this.material).copy(this)}}),Et.prototype=Object.assign(Object.create(X.prototype),{constructor:Et,copy:function(t){X.prototype.copy.call(this,t,!1);for(var e=t.levels,i=0,n=e.length;i1){t.setFromMatrixPosition(i.matrixWorld),e.setFromMatrixPosition(this.matrixWorld);var r=t.distanceTo(e);n[0].object.visible=!0;for(var a=1,o=n.length;a=n[a].distance;a++)n[a-1].object.visible=!1,n[a].object.visible=!0;for(;ao)){d.applyMatrix4(this.matrixWorld);var E=n.ray.origin.distanceTo(d);En.far||r.push({distance:E,point:p.clone().applyMatrix4(this.matrixWorld),index:x,face:null,faceIndex:null,object:this})}}else for(var x=0,_=g.length/3-1;x<_;x+=f){l.fromArray(g,3*x),u.fromArray(g,3*x+3);var M=e.distanceSqToSegment(l,u,d,p);if(!(M>o)){d.applyMatrix4(this.matrixWorld);var E=n.ray.origin.distanceTo(d);En.far||r.push({distance:E,point:p.clone().applyMatrix4(this.matrixWorld),index:x,face:null,faceIndex:null,object:this})}}}else if(c&&c.isGeometry)for(var T=c.vertices,S=T.length,x=0;xo)){d.applyMatrix4(this.matrixWorld);var E=n.ray.origin.distanceTo(d);En.far||r.push({distance:E,point:p.clone().applyMatrix4(this.matrixWorld),index:x,face:null,faceIndex:null,object:this})}}}}}(),clone:function(){return new this.constructor(this.geometry,this.material).copy(this)}}),Ct.prototype=Object.assign(Object.create(Pt.prototype),{constructor:Ct,isLineSegments:!0}),Ut.prototype=Object.create(x.prototype),Ut.prototype.constructor=Ut,Ut.prototype.isPointsMaterial=!0,Ut.prototype.copy=function(t){return x.prototype.copy.call(this,t),this.color.copy(t.color),this.map=t.map,this.size=t.size,this.sizeAttenuation=t.sizeAttenuation,this},It.prototype=Object.assign(Object.create(X.prototype),{constructor:It,isPoints:!0,raycast:function(){var t=new a,e=new ct,i=new T;return function(n,r){function a(t,i){var a=e.distanceSqToPoint(t);if(an.far)return;r.push({distance:c,distanceToRay:Math.sqrt(a),point:s.clone(),index:i,face:null,object:o})}}var o=this,c=this.geometry,h=this.matrixWorld,l=n.params.Points.threshold;if(null===c.boundingSphere&&c.computeBoundingSphere(),i.copy(c.boundingSphere),i.applyMatrix4(h),n.ray.intersectsSphere(i)!==!1){t.getInverse(h),e.copy(n.ray).applyMatrix4(t);var u=l/((this.scale.x+this.scale.y+this.scale.z)/3),p=u*u,d=new s;if(c&&c.isBufferGeometry){var f=c.index,m=c.attributes,v=m.position.array;if(null!==f)for(var g=f.array,y=0,x=g.length;y0||0===t.search(/^data\:image\/jpeg/);a.format=n?Gr:Hr,a.image=i,a.needsUpdate=!0,void 0!==e&&e(a)},i,r),a},setCrossOrigin:function(t){return this.crossOrigin=t,this},setWithCredentials:function(t){return this.withCredentials=t,this},setPath:function(t){return this.path=t,this}}),ee.prototype=Object.assign(Object.create(X.prototype),{constructor:ee,isLight:!0,copy:function(t){return X.prototype.copy.call(this,t),this.color.copy(t.color),this.intensity=t.intensity,this},toJSON:function(t){var e=X.prototype.toJSON.call(this,t);return e.object.color=this.color.getHex(),e.object.intensity=this.intensity,void 0!==this.groundColor&&(e.object.groundColor=this.groundColor.getHex()),void 0!==this.distance&&(e.object.distance=this.distance),void 0!==this.angle&&(e.object.angle=this.angle),void 0!==this.decay&&(e.object.decay=this.decay),void 0!==this.penumbra&&(e.object.penumbra=this.penumbra),e}}),ie.prototype=Object.assign(Object.create(ee.prototype),{constructor:ie,isHemisphereLight:!0,copy:function(t){return ee.prototype.copy.call(this,t),this.groundColor.copy(t.groundColor),this}}),Object.assign(ne.prototype,{copy:function(t){return this.camera=t.camera.clone(),this.bias=t.bias,this.radius=t.radius,this.mapSize.copy(t.mapSize),this},clone:function(){return(new this.constructor).copy(this)}}),re.prototype=Object.assign(Object.create(ne.prototype),{constructor:re,isSpotLightShadow:!0,update:function(e){var i=2*t.Math.RAD2DEG*e.angle,n=this.mapSize.width/this.mapSize.height,r=e.distance||500,a=this.camera;i===a.fov&&n===a.aspect&&r===a.far||(a.fov=i,a.aspect=n,a.far=r,a.updateProjectionMatrix())}}),ae.prototype=Object.assign(Object.create(ee.prototype),{constructor:ae,isSpotLight:!0,copy:function(t){return ee.prototype.copy.call(this,t),this.distance=t.distance,this.angle=t.angle,this.penumbra=t.penumbra,this.decay=t.decay,this.target=t.target.clone(),this.shadow=t.shadow.clone(),this}}),oe.prototype=Object.assign(Object.create(ee.prototype),{constructor:oe,isPointLight:!0,copy:function(t){return ee.prototype.copy.call(this,t),this.distance=t.distance,this.decay=t.decay,this.shadow=t.shadow.clone(),this}}),se.prototype=Object.assign(Object.create(ne.prototype),{constructor:se}),ce.prototype=Object.assign(Object.create(ee.prototype),{constructor:ce,isDirectionalLight:!0,copy:function(t){return ee.prototype.copy.call(this,t),this.target=t.target.clone(),this.shadow=t.shadow.clone(),this}}),he.prototype=Object.assign(Object.create(ee.prototype),{constructor:he,isAmbientLight:!0}),t.AnimationUtils={arraySlice:function(e,i,n){return t.AnimationUtils.isTypedArray(e)?new e.constructor(e.subarray(i,n)):e.slice(i,n)},convertArray:function(t,e,i){return!t||!i&&t.constructor===e?t:"number"==typeof e.BYTES_PER_ELEMENT?new e(t):Array.prototype.slice.call(t)},isTypedArray:function(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)},getKeyframeOrder:function(t){function e(e,i){return t[e]-t[i]}for(var i=t.length,n=new Array(i),r=0;r!==i;++r)n[r]=r;return n.sort(e),n},sortedArray:function(t,e,i){for(var n=t.length,r=new t.constructor(n),a=0,o=0;o!==n;++a)for(var s=i[a]*e,c=0;c!==e;++c)r[o++]=t[s+c];return r},flattenJSON:function(t,e,i,n){for(var r=1,a=t[0];void 0!==a&&void 0===a[n];)a=t[r++];if(void 0!==a){var o=a[n];if(void 0!==o)if(Array.isArray(o)){do o=a[n],void 0!==o&&(e.push(a.time),i.push.apply(i,o)),a=t[r++];while(void 0!==a)}else if(void 0!==o.toArray){do o=a[n],void 0!==o&&(e.push(a.time),o.toArray(i,i.length)),a=t[r++];while(void 0!==a)}else do o=a[n],void 0!==o&&(e.push(a.time),i.push(o)),a=t[r++];while(void 0!==a)}}},le.prototype={constructor:le,evaluate:function(t){var e=this.parameterPositions,i=this._cachedIndex,n=e[i],r=e[i-1];t:{e:{var a;i:{n:if(!(t=r)break t;var s=e[1];t=r)break e}a=i,i=0}}for(;i>>1;ti;)--o;if(++o,0!==a||o!==r){a>=o&&(o=Math.max(o,1),a=o-1);var s=this.getValueSize();this.times=t.AnimationUtils.arraySlice(n,a,o),this.values=t.AnimationUtils.arraySlice(this.values,a*s,o*s)}return this},validate:function(){var e=!0,i=this.getValueSize();i-Math.floor(i)!==0&&(console.error("invalid value size in track",this),e=!1);var n=this.times,r=this.values,a=n.length;0===a&&(console.error("track is empty",this),e=!1);for(var o=null,s=0;s!==a;s++){var c=n[s];if("number"==typeof c&&isNaN(c)){console.error("time is not a valid number",this,s,c),e=!1;break}if(null!==o&&o>c){console.error("out of order keys",this,s,c,o),e=!1;break}o=c}if(void 0!==r&&t.AnimationUtils.isTypedArray(r))for(var s=0,h=r.length;s!==h;++s){var l=r[s];if(isNaN(l)){console.error("value is not a valid number",this,s,l),e=!1;break}}return e},optimize:function(){for(var e=this.times,i=this.values,n=this.getValueSize(),r=1,a=1,o=e.length-1;a<=o;++a){var s=!1,c=e[a],h=e[a+1];if(c!==h&&(1!==a||c!==c[0]))for(var l=a*n,u=l-n,p=l+n,d=0;d!==n;++d){var f=i[l+d];if(f!==i[u+d]||f!==i[p+d]){s=!0;break}}if(s){if(a!==r){e[r]=e[a];for(var m=a*n,v=r*n,d=0;d!==n;++d)i[v+d]=i[m+d]}++r}}return r!==e.length&&(this.times=t.AnimationUtils.arraySlice(e,0,r),this.values=t.AnimationUtils.arraySlice(i,0,r*n)),this}},me.prototype=Object.assign(Object.create(Ls),{constructor:me,ValueTypeName:"vector"}),ve.prototype=Object.assign(Object.create(le.prototype),{constructor:ve,interpolate_:function(t,e,i,n){for(var r=this.resultBuffer,a=this.sampleValues,s=this.valueSize,c=t*s,h=(i-e)/(n-e),l=c+s;c!==l;c+=4)o.slerpFlat(r,0,a,c-s,a,c,h);return r}}),ge.prototype=Object.assign(Object.create(Ls),{constructor:ge,ValueTypeName:"quaternion",DefaultInterpolation:oa,InterpolantFactoryMethodLinear:function(t){return new ve(this.times,this.values,this.getValueSize(),t)},InterpolantFactoryMethodSmooth:void 0}),ye.prototype=Object.assign(Object.create(Ls),{constructor:ye,ValueTypeName:"number"}),xe.prototype=Object.assign(Object.create(Ls),{constructor:xe,ValueTypeName:"string",ValueBufferType:Array,DefaultInterpolation:aa,InterpolantFactoryMethodLinear:void 0,InterpolantFactoryMethodSmooth:void 0}),_e.prototype=Object.assign(Object.create(Ls),{constructor:_e,ValueTypeName:"bool",ValueBufferType:Array,DefaultInterpolation:aa,InterpolantFactoryMethodLinear:void 0,InterpolantFactoryMethodSmooth:void 0}),be.prototype=Object.assign(Object.create(Ls),{constructor:be,ValueTypeName:"color"}),we.prototype=Ls,Ls.constructor=we,Object.assign(we,{parse:function(e){if(void 0===e.type)throw new Error("track type undefined, can not parse");var i=we._getTrackTypeForValueTypeName(e.type);if(void 0===e.times){var n=[],r=[];t.AnimationUtils.flattenJSON(e.keys,n,r,"value"),e.times=n,e.values=r}return void 0!==i.parse?i.parse(e):new i(e.name,e.times,e.values,e.interpolation)},toJSON:function(e){var i,n=e.constructor;if(void 0!==n.toJSON)i=n.toJSON(e);else{i={name:e.name,times:t.AnimationUtils.convertArray(e.times,Array),values:t.AnimationUtils.convertArray(e.values,Array)};var r=e.getInterpolation();r!==e.DefaultInterpolation&&(i.interpolation=r)}return i.type=e.ValueTypeName,i},_getTrackTypeForValueTypeName:function(t){switch(t.toLowerCase()){case"scalar":case"double":case"float":case"number":case"integer":return ye;case"vector":case"vector2":case"vector3":case"vector4":return me;case"color":return be;case"quaternion":return ge;case"bool":case"boolean":return _e;case"string":return xe}throw new Error("Unsupported typeName: "+t)}}),Me.prototype={constructor:Me,resetDuration:function(){for(var t=this.tracks,e=0,i=0,n=t.length;i!==n;++i){var r=this.tracks[i];e=Math.max(e,r.times[r.times.length-1])}this.duration=e},trim:function(){for(var t=0;t1){var h=c[1],l=n[h];l||(n[h]=l=[]),l.push(s)}}var u=[];for(var h in n)u.push(Me.CreateFromMorphTargetSequence(h,n[h],e,i));return u},parseAnimation:function(e,i,n){if(!e)return console.error(" no animation in JSONLoader data"),null;for(var r=function(e,i,n,r,a){if(0!==n.length){var o=[],s=[];t.AnimationUtils.flattenJSON(n,o,s,r),0!==o.length&&a.push(new e(i,o,s))}},a=[],o=e.name||"default",s=e.length||-1,c=e.fps||30,h=e.hierarchy||[],l=0;l1?t.skinWeights[i+1]:0,o=e>2?t.skinWeights[i+2]:0,s=e>3?t.skinWeights[i+3]:0;c.skinWeights.push(new d(r,a,o,s))}if(t.skinIndices)for(var i=0,n=t.skinIndices.length;i1?t.skinIndices[i+1]:0,u=e>2?t.skinIndices[i+2]:0,p=e>3?t.skinIndices[i+3]:0;c.skinIndices.push(new d(h,l,u,p))}c.bones=t.bones,c.bones&&c.bones.length>0&&(c.skinWeights.length!==c.skinIndices.length||c.skinIndices.length!==c.vertices.length)&&console.warn("When skinning, number of vertices ("+c.vertices.length+"), skinIndices ("+c.skinIndices.length+"), and skinWeights ("+c.skinWeights.length+") should match.")}function a(e){if(void 0!==t.morphTargets)for(var i=0,n=t.morphTargets.length;i0){console.warn('THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.');for(var u=c.faces,p=t.morphColors[0].colors,i=0,n=u.length;i0&&(c.animations=e)}var c=new q,h=void 0!==t.scale?1/t.scale:1;if(n(h),r(),a(h),o(),c.computeFaceNormals(),c.computeBoundingSphere(),void 0===t.materials||0===t.materials.length)return{geometry:c};var l=Se.prototype.initMaterials(t.materials,e,this.crossOrigin);return{geometry:c,materials:l}}}),Object.assign(Le.prototype,{load:function(t,e,i,n){""===this.texturePath&&(this.texturePath=t.substring(0,t.lastIndexOf("/")+1));var r=this,a=new Zt(r.manager);a.load(t,function(t){r.parse(JSON.parse(t),e)},i,n)},setTexturePath:function(t){this.texturePath=t},setCrossOrigin:function(t){this.crossOrigin=t},parse:function(t,e){var i=this.parseGeometries(t.geometries),n=this.parseImages(t.images,function(){void 0!==e&&e(o)}),r=this.parseTextures(t.textures,n),a=this.parseMaterials(t.materials,r),o=this.parseObject(t.object,i,a);return t.animations&&(o.animations=this.parseAnimations(t.animations)),void 0!==t.images&&0!==t.images.length||void 0!==e&&e(o),o},parseGeometries:function(t){var e={};if(void 0!==t)for(var i=new Ae,n=new Te,r=0,a=t.length;r0){var a=new qt(e),o=new Kt(a);o.setCrossOrigin(this.crossOrigin);for(var s=0,c=t.length;s0?new Lt(s,c):new pt(s,c);break;case"LOD":o=new Et;break;case"Line":o=new Pt(r(e.geometry),a(e.material),e.mode);break;case"LineSegments":o=new Ct(r(e.geometry),a(e.material));break;case"PointCloud":case"Points":o=new It(r(e.geometry),a(e.material));break;case"Sprite":o=new Mt(a(e.material));break;case"Group":o=new Dt;break;default:o=new X}if(o.uuid=e.uuid,void 0!==e.name&&(o.name=e.name),void 0!==e.matrix?(t.fromArray(e.matrix),t.decompose(o.position,o.quaternion,o.scale)):(void 0!==e.position&&o.position.fromArray(e.position),void 0!==e.rotation&&o.rotation.fromArray(e.rotation),void 0!==e.quaternion&&o.quaternion.fromArray(e.quaternion),void 0!==e.scale&&o.scale.fromArray(e.scale)),void 0!==e.castShadow&&(o.castShadow=e.castShadow),void 0!==e.receiveShadow&&(o.receiveShadow=e.receiveShadow),void 0!==e.visible&&(o.visible=e.visible),void 0!==e.userData&&(o.userData=e.userData),void 0!==e.children)for(var h in e.children)o.add(this.parseObject(e.children[h],i,n));if("LOD"===e.type)for(var l=e.levels,u=0;u(h-s)*(p-c)-(l-c)*(u-s))return!1;var m,v,g,y,x,_,b,w,M,E,T,S,A,L,R;for(m=u-h,v=p-l,g=s-u,y=c-p,x=h-s,_=l-c,o=0;o=-Number.EPSILON&&L>=-Number.EPSILON&&A>=-Number.EPSILON))return!1;return!0}return function(i,n){var r=i.length;if(r<3)return null;var a,o,s,c=[],h=[],l=[];if(t.ShapeUtils.area(i)>0)for(o=0;o2;){if(p--<=0)return console.warn("THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()"),n?l:c;if(a=o,u<=a&&(a=0),o=a+1,u<=o&&(o=0),s=o+1,u<=s&&(s=0),e(i,a,o,s,u,h)){var d,f,m,v,g;for(d=h[a],f=h[o],m=h[s],c.push([i[d],i[f],i[m]]),l.push([h[a],h[o],h[s]]),v=o,g=o+1;g2&&t[e-1].equals(t[0])&&t.pop()}function r(t,e,i){return t.x!==e.x?t.xNumber.EPSILON){var f;if(p>0){if(d<0||d>p)return[];if(f=h*l-c*u,f<0||f>p)return[]}else{if(d>0||d0||fT?[]:_===T?a?[]:[y]:b<=T?[y,x]:[y,M]}function o(t,e,i,n){var r=e.x-t.x,a=e.y-t.y,o=i.x-t.x,s=i.y-t.y,c=n.x-t.x,h=n.y-t.y,l=r*s-a*o,u=r*h-a*c;if(Math.abs(l)>Number.EPSILON){var p=c*s-h*o;return l>0?u>=0&&p>=0:u>=0||p>=0}return u>0}function s(t,e){function i(t,e){var i=y.length-1,n=t-1;n<0&&(n=i);var r=t+1;r>i&&(r=0);var a=o(y[t],y[n],y[r],s[e]);if(!a)return!1;var c=s.length-1,h=e-1;h<0&&(h=c);var l=e+1;return l>c&&(l=0),a=o(s[e],s[h],s[l],y[t]),!!a}function n(t,e){var i,n,r;for(i=0;i0)return!0;return!1}function r(t,i){var n,r,o,s,c;for(n=0;n0)return!0;return!1}for(var s,c,h,l,u,p,d,f,m,v,g,y=t.concat(),x=[],_=[],b=0,w=e.length;b0;){if(E--,E<0){console.log("Infinite Loop! Holes left:"+x.length+", Probably Hole outside Shape!");break}for(h=M;h=0)break;_[d]=!0}if(c>=0)break}}return y}n(e),i.forEach(n);for(var c,h,l,u,p,d,f={},m=e.concat(),v=0,g=i.length;v0)){c=r;break}c=r-1}if(r=c,n[r]===i){var h=r/(a-1);return h}var l=n[r],u=n[r+1],p=u-l,d=(i-l)/p,h=(r+d)/(a-1);return h},getTangent:function(t){var e=1e-4,i=t-e,n=t+e;i<0&&(i=0),n>1&&(n=1);var r=this.getPoint(i),a=this.getPoint(n),o=a.clone().sub(r);return o.normalize()},getTangentAt:function(t){var e=this.getUtoTmapping(t);return this.getTangent(e)}},Re.create=function(t,e){return t.prototype=Object.create(Re.prototype),t.prototype.constructor=t,t.prototype.getPoint=e,t},Pe.prototype=Object.create(Re.prototype),Pe.prototype.constructor=Pe,Pe.prototype.isLineCurve=!0,Pe.prototype.getPoint=function(t){if(1===t)return this.v2.clone();var e=this.v2.clone().sub(this.v1);return e.multiplyScalar(t).add(this.v1),e},Pe.prototype.getPointAt=function(t){return this.getPoint(t)},Pe.prototype.getTangent=function(t){var e=this.v2.clone().sub(this.v1);return e.normalize()},Ce.prototype=Object.assign(Object.create(Re.prototype),{constructor:Ce,add:function(t){this.curves.push(t)},closePath:function(){var t=this.curves[0].getPoint(0),e=this.curves[this.curves.length-1].getPoint(1);t.equals(e)||this.curves.push(new Pe(e,t))},getPoint:function(t){for(var e=t*this.getLength(),i=this.getCurveLengths(),n=0;n=e){var r=i[n]-e,a=this.curves[n],o=a.getLength(),s=0===o?0:1-r/o;return a.getPointAt(s)}n++}return null},getLength:function(){var t=this.getCurveLengths();return t[t.length-1]},updateArcLengths:function(){this.needsUpdate=!0,this.cacheLengths=null,this.getLengths()},getCurveLengths:function(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;for(var t=[],e=0,i=0,n=this.curves.length;i1&&!i[i.length-1].equals(i[0])&&i.push(i[0]),i},createPointsGeometry:function(t){var e=this.getPoints(t);return this.createGeometry(e)},createSpacedPointsGeometry:function(t){var e=this.getSpacedPoints(t);return this.createGeometry(e)},createGeometry:function(t){for(var e=new q,i=0,n=t.length;ie;)n-=e;nn.length-2?n.length-1:a+1],l=n[a>n.length-3?n.length-1:a+2],u=t.CurveUtils.interpolate;return new i(u(s.x,c.x,h.x,l.x,o),u(s.y,c.y,h.y,l.y,o))},De.prototype=Object.create(Re.prototype),De.prototype.constructor=De,De.prototype.getPoint=function(e){var n=t.ShapeUtils.b3;return new i(n(e,this.v0.x,this.v1.x,this.v2.x,this.v3.x),n(e,this.v0.y,this.v1.y,this.v2.y,this.v3.y))},De.prototype.getTangent=function(e){var n=t.CurveUtils.tangentCubicBezier;return new i(n(e,this.v0.x,this.v1.x,this.v2.x,this.v3.x),n(e,this.v0.y,this.v1.y,this.v2.y,this.v3.y)).normalize()},Ne.prototype=Object.create(Re.prototype),Ne.prototype.constructor=Ne,Ne.prototype.getPoint=function(e){var n=t.ShapeUtils.b2;return new i(n(e,this.v0.x,this.v1.x,this.v2.x),n(e,this.v0.y,this.v1.y,this.v2.y))},Ne.prototype.getTangent=function(e){var n=t.CurveUtils.tangentQuadraticBezier;return new i(n(e,this.v0.x,this.v1.x,this.v2.x),n(e,this.v0.y,this.v1.y,this.v2.y)).normalize()};var Rs=Object.assign(Object.create(Ce.prototype),{fromPoints:function(t){this.moveTo(t[0].x,t[0].y);for(var e=1,i=t.length;e0){var h=c.getPoint(0);h.equals(this.currentPoint)||this.lineTo(h.x,h.y)}this.curves.push(c);var l=c.getPoint(1);this.currentPoint.copy(l)}});Oe.prototype=Object.create(q.prototype),Oe.prototype.constructor=Oe,Oe.NoTaper=function(t){return 1},Oe.SinusoidalTaper=function(t){return Math.sin(Math.PI*t)},Oe.FrenetFrames=function(e,i,n){function r(){v[0]=new s,g[0]=new s,c=Number.MAX_VALUE,h=Math.abs(m[0].x),l=Math.abs(m[0].y),u=Math.abs(m[0].z),h<=c&&(c=h,f.set(1,0,0)),l<=c&&(c=l,f.set(0,1,0)),u<=c&&f.set(0,0,1),y.crossVectors(m[0],f).normalize(),v[0].crossVectors(m[0],y),g[0].crossVectors(m[0],v[0])}var o,c,h,l,u,p,d,f=new s,m=[],v=[],g=[],y=new s,x=new a,_=i+1;for(this.tangents=m,this.normals=v,this.binormals=g,p=0;p<_;p++)d=p/(_-1),m[p]=e.getTangentAt(d),m[p].normalize();for(r(),p=1;p<_;p++)v[p]=v[p-1].clone(),g[p]=g[p-1].clone(),y.crossVectors(m[p-1],m[p]),y.length()>Number.EPSILON&&(y.normalize(),o=Math.acos(t.Math.clamp(m[p-1].dot(m[p]),-1,1)),v[p].applyMatrix4(x.makeRotationAxis(y,o))),g[p].crossVectors(m[p],v[p]);if(n)for(o=Math.acos(t.Math.clamp(v[0].dot(v[_-1]),-1,1)),o/=_-1,m[0].dot(y.crossVectors(v[0],v[_-1]))>0&&(o=-o),p=1;p<_;p++)v[p].applyMatrix4(x.makeRotationAxis(m[p],o*p)),g[p].crossVectors(m[p],v[p])},Fe.prototype=Object.create(q.prototype),Fe.prototype.constructor=Fe,Fe.prototype.addShapeList=function(t,e){for(var i=t.length,n=0;nNumber.EPSILON){var d=Math.sqrt(u),f=Math.sqrt(h*h+l*l),m=e.x-c/d,v=e.y+s/d,g=n.x-l/f,y=n.y+h/f,x=((g-m)*l-(y-v)*h)/(s*l-c*h);r=m+s*x-t.x,a=v+c*x-t.y;var _=r*r+a*a;if(_<=2)return new i(r,a);o=Math.sqrt(_/2)}else{var b=!1;s>Number.EPSILON?h>Number.EPSILON&&(b=!0):s<-Number.EPSILON?h<-Number.EPSILON&&(b=!0):Math.sign(c)===Math.sign(l)&&(b=!0),b?(r=-c,a=s,o=Math.sqrt(u)):(r=s,a=c,o=Math.sqrt(u/2))}return new i(r/o,a/o)}function o(){if(w){var t=0,e=X*t;for(Z=0;Z=0;){i=Z,n=Z-1,n<0&&(n=t.length-1);var r=0,a=E+2*b;for(r=0;r=0;z--){for(H=z/b,V=x*Math.cos(H*Math.PI/2),G=_*Math.sin(H*Math.PI/2),Z=0,J=B.length;ZNumber.EPSILON){if(h<0&&(o=e[a],c=-c,s=e[r],h=-h),t.ys.y)continue;if(t.y===o.y){if(t.x===o.x)return!0}else{var l=h*(t.x-o.x)-c*(t.y-o.y);if(0===l)return!0;if(l<0)continue;n=!n}}else{if(t.y!==o.y)continue;if(s.x<=t.x&&t.x<=o.x||o.x<=t.x&&t.x<=s.x)return!0}}return n}var a=t.ShapeUtils.isClockWise,o=this.subPaths;if(0===o.length)return[];if(i===!0)return n(o);var s,c,h,l=[];if(1===o.length)return c=o[0],h=new ze,h.curves=c.curves,l.push(h),l;var u=!a(o[0].getPoints());u=e?!u:u;var p,d=[],f=[],m=[],v=0;f[v]=void 0,m[v]=[];for(var g=0,y=o.length;g1){for(var x=!1,_=[],b=0,w=f.length;b0&&(x||(m=d))}for(var L,g=0,R=f.length;g0){this.source.connect(this.filters[0]);for(var t=1,e=this.filters.length;t0){this.source.disconnect(this.filters[0]);for(var t=1,e=this.filters.length;t=.5)for(var a=0;a!==r;++a)t[e+a]=t[i+a]},_slerp:function(t,e,i,n,r){o.slerpFlat(t,e,t,e,t,i,n)},_lerp:function(t,e,i,n,r){for(var a=1-n,o=0;o!==r;++o){var s=e+o;t[s]=t[s]*a+t[i+o]*n}}},$e.prototype={constructor:$e,getValue:function(t,e){this.bind(),this.getValue(t,e)},setValue:function(t,e){this.bind(),this.setValue(t,e)},bind:function(){var t=this.node,e=this.parsedPath,i=e.objectName,n=e.propertyName,r=e.propertyIndex;if(t||(t=$e.findNode(this.rootNode,e.nodeName)||this.rootNode,this.node=t),this.getValue=this._getValue_unavailable,this.setValue=this._setValue_unavailable,!t)return void console.error(" trying to update node for track: "+this.path+" but it wasn't found.");if(i){var a=e.objectIndex;switch(i){case"materials":if(!t.material)return void console.error(" can not bind to material as node does not have a material",this);if(!t.material.materials)return void console.error(" can not bind to material.materials as node.material does not have a materials array",this);t=t.material.materials;break;case"bones":if(!t.skeleton)return void console.error(" can not bind to bones as node does not have a skeleton",this);t=t.skeleton.bones;for(var o=0;o=i){var u=i++,p=e[u];n[p.uuid]=l,e[l]=p,n[h]=u,e[u]=c;for(var d=0,f=a;d!==f;++d){var m=r[d],v=m[u],g=m[l];m[l]=v,m[u]=g}}}this.nCachedObjects_=i},uncache:function(t){for(var e=this._objects,i=e.length,n=this.nCachedObjects_,r=this._indicesByUUID,a=this._bindings,o=a.length,s=0,c=arguments.length;s!==c;++s){var h=arguments[s],l=h.uuid,u=r[l];if(void 0!==u)if(delete r[l],u0)for(var c=this._interpolants,h=this._propertyBindings,l=0,u=c.length;l!==u;++l)c[l].evaluate(o),h[l].accumulate(n,s)},_updateWeight:function(t){var e=0;if(this.enabled){e=this.weight;var i=this._weightInterpolant;if(null!==i){var n=i.evaluate(t)[0];e*=n,t>i.parameterPositions[1]&&(this.stopFading(),0===n&&(this.enabled=!1))}}return this._effectiveWeight=e,e},_updateTimeScale:function(t){var e=0;if(!this.paused){e=this.timeScale;var i=this._timeScaleInterpolant;if(null!==i){var n=i.evaluate(t)[0];e*=n,t>i.parameterPositions[1]&&(this.stopWarping(),0===e?this.paused=!0:this.timeScale=e)}}return this._effectiveTimeScale=e,e},_updateTime:function(t){var e=this.time+t;if(0===t)return e;var i=this._clip.duration,n=this.loop,r=this._loopCount;if(n===ia){r===-1&&(this.loopCount=0,this._setEndings(!0,!0,!1));t:{if(e>=i)e=i;else{if(!(e<0))break t;e=0}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this._mixer.dispatchEvent({type:"finished",action:this,direction:t<0?-1:1})}}else{var a=n===ra;if(r===-1&&(t>=0?(r=0,this._setEndings(!0,0===this.repetitions,a)):this._setEndings(0===this.repetitions,!0,a)),e>=i||e<0){var o=Math.floor(e/i);e-=i*o,r+=Math.abs(o);var s=this.repetitions-r;if(s<0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,e=t>0?i:0,this._mixer.dispatchEvent({type:"finished",action:this,direction:t>0?1:-1});else{if(0===s){var c=t<0;this._setEndings(c,!c,a)}else this._setEndings(!1,!1,a);this._loopCount=r,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:o})}}if(a&&1===(1&r))return this.time=e,i-e}return this.time=e,e},_setEndings:function(t,e,i){var n=this._interpolantSettings;i?(n.endingStart=ha,n.endingEnd=ha):(t?n.endingStart=this.zeroSlopeAtStart?ha:ca:n.endingStart=la,e?n.endingEnd=this.zeroSlopeAtEnd?ha:ca:n.endingEnd=la)},_scheduleFading:function(t,e,i){var n=this._mixer,r=n.time,a=this._weightInterpolant;null===a&&(a=n._lendControlInterpolant(),this._weightInterpolant=a);var o=a.parameterPositions,s=a.sampleValues;return o[0]=r,s[0]=e,o[1]=r+t,s[1]=i,this}},Object.assign(ii.prototype,e.prototype,{clipAction:function(t,e){var i=e||this._root,n=i.uuid,r="string"==typeof t?Me.findByName(i,t):t,a=null!==r?r.uuid:t,o=this._actionsByClip[a],s=null;if(void 0!==o){var c=o.actionByRoot[n];if(void 0!==c)return c;s=o.knownActions[0],null===r&&(r=s._clip)}if(null===r)return null;var h=new ii._Action(this,r,e);return this._bindAction(h,s),this._addInactiveAction(h,a,n),h},existingAction:function(t,e){var i=e||this._root,n=i.uuid,r="string"==typeof t?Me.findByName(i,t):t,a=r?r.uuid:t,o=this._actionsByClip[a];return void 0!==o?o.actionByRoot[n]||null:null},stopAllAction:function(){var t=this._actions,e=this._nActiveActions,i=this._bindings,n=this._nActiveBindings;this._nActiveActions=0,this._nActiveBindings=0;for(var r=0;r!==e;++r)t[r].reset();for(var r=0;r!==n;++r)i[r].useCount=0;return this},update:function(t){t*=this.timeScale;for(var e=this._actions,i=this._nActiveActions,n=this.time+=t,r=Math.sign(t),a=this._accuIndex^=1,o=0;o!==i;++o){var s=e[o];s.enabled&&s._update(n,t,r,a)}for(var c=this._bindings,h=this._nActiveBindings,o=0;o!==h;++o)c[o].apply(a);return this},getRoot:function(){return this._root},uncacheClip:function(t){var e=this._actions,i=t.uuid,n=this._actionsByClip,r=n[i];if(void 0!==r){for(var a=r.knownActions,o=0,s=a.length;o!==s;++o){var c=a[o];this._deactivateAction(c);var h=c._cacheIndex,l=e[e.length-1];c._cacheIndex=null,c._byClipCacheIndex=null,l._cacheIndex=h,e[h]=l,e.pop(),this._removeInactiveBindingsForAction(c)}delete n[i]}},uncacheRoot:function(t){var e=t.uuid,i=this._actionsByClip;for(var n in i){var r=i[n].actionByRoot,a=r[e];void 0!==a&&(this._deactivateAction(a),this._removeInactiveAction(a))}var o=this._bindingsByRootAndName,s=o[e];if(void 0!==s)for(var c in s){var h=s[c];h.restoreOriginalState(),this._removeInactiveBinding(h)}},uncacheAction:function(t,e){var i=this.existingAction(t,e);null!==i&&(this._deactivateAction(i),this._removeInactiveAction(i))}}),ii._Action=ei._new,Object.assign(ii.prototype,{_bindAction:function(t,e){var i=t._localRoot||this._root,n=t._clip.tracks,r=n.length,a=t._propertyBindings,o=t._interpolants,s=i.uuid,c=this._bindingsByRootAndName,h=c[s];void 0===h&&(h={},c[s]=h);for(var l=0;l!==r;++l){var u=n[l],p=u.name,d=h[p];if(void 0!==d)a[l]=d;else{if(d=a[l],void 0!==d){null===d._cacheIndex&&(++d.referenceCount,this._addInactiveBinding(d,s,p));continue}var f=e&&e._propertyBindings[l].binding.parsedPath;d=new Ke($e.create(i,p,f),u.ValueTypeName,u.getValueSize()),++d.referenceCount,this._addInactiveBinding(d,s,p),a[l]=d}o[l].resultBuffer=d.buffer}},_activateAction:function(t){if(!this._isActiveAction(t)){if(null===t._cacheIndex){var e=(t._localRoot||this._root).uuid,i=t._clip.uuid,n=this._actionsByClip[i];this._bindAction(t,n&&n.knownActions[0]),this._addInactiveAction(t,i,e)}for(var r=t._propertyBindings,a=0,o=r.length;a!==o;++a){var s=r[a];0===s.useCount++&&(this._lendBinding(s),s.saveOriginalState())}this._lendAction(t)}},_deactivateAction:function(t){if(this._isActiveAction(t)){for(var e=t._propertyBindings,i=0,n=e.length;i!==n;++i){var r=e[i];0===--r.useCount&&(r.restoreOriginalState(),this._takeBackBinding(r))}this._takeBackAction(t)}},_initMemoryManager:function(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;var t=this;this.stats={actions:{get total(){return t._actions.length},get inUse(){return t._nActiveActions}},bindings:{get total(){return t._bindings.length},get inUse(){return t._nActiveBindings}},controlInterpolants:{get total(){return t._controlInterpolants.length},get inUse(){return t._nActiveControlInterpolants}}}},_isActiveAction:function(t){var e=t._cacheIndex;return null!==e&&e1){var h=c[1];n[h]||(n[h]={start:1/0,end:-(1/0)});var l=n[h];al.end&&(l.end=a),e||(e=h)}}for(var h in n){var l=n[h];this.createAnimation(h,l.start,l.end,t)}this.firstAnimation=e},mi.prototype.setAnimationDirectionForward=function(t){var e=this.animationsMap[t];e&&(e.direction=1,e.directionBackwards=!1)},mi.prototype.setAnimationDirectionBackward=function(t){var e=this.animationsMap[t];e&&(e.direction=-1,e.directionBackwards=!0)},mi.prototype.setAnimationFPS=function(t,e){var i=this.animationsMap[t];i&&(i.fps=e,i.duration=(i.end-i.start)/i.fps)},mi.prototype.setAnimationDuration=function(t,e){var i=this.animationsMap[t];i&&(i.duration=e,i.fps=(i.end-i.start)/i.duration)},mi.prototype.setAnimationWeight=function(t,e){var i=this.animationsMap[t];i&&(i.weight=e)},mi.prototype.setAnimationTime=function(t,e){var i=this.animationsMap[t];i&&(i.time=e)},mi.prototype.getAnimationTime=function(t){var e=0,i=this.animationsMap[t];return i&&(e=i.time),e},mi.prototype.getAnimationDuration=function(t){var e=-1,i=this.animationsMap[t];return i&&(e=i.duration),e},mi.prototype.playAnimation=function(t){var e=this.animationsMap[t];e?(e.time=0,e.active=!0):console.warn("THREE.MorphBlendMesh: animation["+t+"] undefined in .playAnimation()")},mi.prototype.stopAnimation=function(t){var e=this.animationsMap[t];e&&(e.active=!1)},mi.prototype.update=function(e){for(var i=0,n=this.animationsList.length;ir.duration||r.time<0)&&(r.direction*=-1,r.time>r.duration&&(r.time=r.duration,r.directionBackwards=!0),r.time<0&&(r.time=0,r.directionBackwards=!1)):(r.time=r.time%r.duration,r.time<0&&(r.time+=r.duration));var o=r.start+t.Math.clamp(Math.floor(r.time/a),0,r.length-1),s=r.weight;o!==r.currentFrame&&(this.morphTargetInfluences[r.lastFrame]=0,this.morphTargetInfluences[r.currentFrame]=1*s,this.morphTargetInfluences[o]=0,r.lastFrame=r.currentFrame, -r.currentFrame=o);var c=r.time%a/a;r.directionBackwards&&(c=1-c),r.currentFrame!==r.lastFrame?(this.morphTargetInfluences[r.currentFrame]=c*s,this.morphTargetInfluences[r.lastFrame]=(1-c)*s):this.morphTargetInfluences[r.currentFrame]=s}}},vi.prototype=Object.create(X.prototype),vi.prototype.constructor=vi,vi.prototype.isImmediateRenderObject=!0,gi.prototype=Object.create(Q.prototype),gi.prototype.constructor=gi,yi.prototype=Object.create(Ct.prototype),yi.prototype.constructor=yi,xi.prototype=Object.create(Ct.prototype),xi.prototype.constructor=xi,xi.prototype.update=function(){var t=new s,e=new s,i=new S;return function(){var n=["a","b","c"];this.object.updateMatrixWorld(!0),i.getNormalMatrix(this.object.matrixWorld);var r=this.object.matrixWorld,a=this.geometry.attributes.position,o=this.object.geometry;if(o&&o.isGeometry)for(var s=o.vertices,c=o.faces,h=0,l=0,u=c.length;l.99999?this.quaternion.set(0,0,0,1):i.y<-.99999?this.quaternion.set(1,0,0,0):(e.set(i.z,0,-i.x).normalize(),t=Math.acos(i.y),this.quaternion.setFromAxisAngle(e,t))}}(),t.ArrowHelper.prototype.setLength=function(t,e,i){void 0===e&&(e=.2*t),void 0===i&&(i=.2*e),this.line.scale.set(1,Math.max(0,t-e),1),this.line.updateMatrix(),this.cone.scale.set(i,e,i),this.cone.position.y=t,this.cone.updateMatrix()},t.ArrowHelper.prototype.setColor=function(t){this.line.material.color.copy(t),this.cone.material.color.copy(t)},Oi.prototype=Object.create(Ct.prototype),Oi.prototype.constructor=Oi,Fi.prototype=Object.create(q.prototype),Fi.prototype.constructor=Fi,Bi.prototype=Object.create(q.prototype),Bi.prototype.constructor=Bi,zi.prototype=Object.create(Bi.prototype),zi.prototype.constructor=zi,Gi.prototype=Object.create(Bi.prototype),Gi.prototype.constructor=Gi,Hi.prototype=Object.create(Bi.prototype),Hi.prototype.constructor=Hi,Vi.prototype=Object.create(Bi.prototype),Vi.prototype.constructor=Vi,ki.prototype=Object.create(Q.prototype),ki.prototype.constructor=ki,ji.prototype=Object.create(q.prototype),ji.prototype.constructor=ji,Wi.prototype=Object.create(Q.prototype),Wi.prototype.constructor=Wi,Xi.prototype=Object.create(q.prototype),Xi.prototype.constructor=Xi,Yi.prototype=Object.create(Fe.prototype),Yi.prototype.constructor=Yi,qi.prototype=Object.create(Q.prototype),qi.prototype.constructor=qi,Zi.prototype=Object.create(q.prototype),Zi.prototype.constructor=Zi,Ji.prototype=Object.create(q.prototype),Ji.prototype.constructor=Ji,Qi.prototype=Object.create(Q.prototype),Qi.prototype.constructor=Qi,Ki.prototype=Object.create(q.prototype),Ki.prototype.constructor=Ki,$i.prototype=Object.create(q.prototype),$i.prototype.constructor=$i,tn.prototype=Object.create($i.prototype),tn.prototype.constructor=tn,en.prototype=Object.create(Q.prototype),en.prototype.constructor=en,nn.prototype=Object.create(Q.prototype),nn.prototype.constructor=nn,rn.prototype=Object.create(q.prototype),rn.prototype.constructor=rn,t.CatmullRomCurve3=function(){function t(){}var e=new s,i=new t,n=new t,r=new t;return t.prototype.init=function(t,e,i,n){this.c0=t,this.c1=i,this.c2=-3*t+3*e-2*i-n,this.c3=2*t-2*e+i+n},t.prototype.initNonuniformCatmullRom=function(t,e,i,n,r,a,o){var s=(e-t)/r-(i-t)/(r+a)+(i-e)/a,c=(i-e)/a-(n-e)/(a+o)+(n-i)/o;s*=a,c*=a,this.init(e,i,s,c)},t.prototype.initCatmullRom=function(t,e,i,n,r){this.init(e,i,r*(i-t),r*(n-e))},t.prototype.calc=function(t){var e=t*t,i=e*t;return this.c0+this.c1*t+this.c2*e+this.c3*i},Re.create(function(t){this.points=t||[],this.closed=!1},function(t){var a,o,c,h,l=this.points;h=l.length,h<2&&console.log("duh, you need at least 2 points"),a=(h-(this.closed?0:1))*t,o=Math.floor(a),c=a-o,this.closed?o+=o>0?0:(Math.floor(Math.abs(o)/l.length)+1)*l.length:0===c&&o===h-1&&(o=h-2,c=1);var u,p,d,f;if(this.closed||o>0?u=l[(o-1)%h]:(e.subVectors(l[0],l[1]).add(l[0]),u=e),p=l[o%h],d=l[(o+1)%h],this.closed||o+2i.length-2?i.length-1:r+1],l=i[r>i.length-3?i.length-1:r+2],u=t.CurveUtils.interpolate;return new s(u(o.x,c.x,h.x,l.x,a),u(o.y,c.y,h.y,l.y,a),u(o.z,c.z,h.z,l.z,a))});t.CubicBezierCurve3=Re.create(function(t,e,i,n){this.v0=t,this.v1=e,this.v2=i,this.v3=n},function(e){var i=t.ShapeUtils.b3;return new s(i(e,this.v0.x,this.v1.x,this.v2.x,this.v3.x),i(e,this.v0.y,this.v1.y,this.v2.y,this.v3.y),i(e,this.v0.z,this.v1.z,this.v2.z,this.v3.z))}),t.QuadraticBezierCurve3=Re.create(function(t,e,i){this.v0=t,this.v1=e,this.v2=i},function(e){var i=t.ShapeUtils.b2;return new s(i(e,this.v0.x,this.v1.x,this.v2.x),i(e,this.v0.y,this.v1.y,this.v2.y),i(e,this.v0.z,this.v1.z,this.v2.z))}),t.LineCurve3=Re.create(function(t,e){this.v1=t,this.v2=e},function(t){if(1===t)return this.v2.clone();var e=new s;return e.subVectors(this.v2,this.v1),e.multiplyScalar(t),e.add(this.v1),e}),on.prototype=Object.create(Ue.prototype),on.prototype.constructor=on,t.SceneUtils={createMultiMaterialObject:function(t,e){for(var i=new Dt,n=0,r=e.length;n0&&console.error("THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.")}function A(t,e){this.normal=void 0!==t?t:new s(1,0,0),this.constant=void 0!==e?e:0}function L(t,e,i,n,r,a){this.planes=[void 0!==t?t:new A,void 0!==e?e:new A,void 0!==i?i:new A,void 0!==n?n:new A,void 0!==r?r:new A,void 0!==a?a:new A]}function R(e,n,r,o){function c(t,i,n,r){var a=t.geometry,o=null,s=A,c=t.customDepthMaterial;if(n&&(s=R,c=t.customDistanceMaterial),c)o=c;else{var h=!1;i.morphTargets&&(a&&a.isBufferGeometry?h=a.morphAttributes&&a.morphAttributes.position&&a.morphAttributes.position.length>0:a&&a.isGeometry&&(h=a.morphTargets&&a.morphTargets.length>0));var l=t.isSkinnedMesh&&i.skinning,u=0;h&&(u|=E),l&&(u|=T),o=s[u]}if(e.localClippingEnabled&&i.clipShadows===!0&&0!==i.clippingPlanes.length){var p=o.uuid,d=i.uuid,f=P[p];void 0===f&&(f={},P[p]=f);var m=f[d];void 0===m&&(m=o.clone(),f[d]=m),o=m}o.visible=i.visible,o.wireframe=i.wireframe;var v=i.side;return V.renderSingleSided&&v==_n&&(v=yn),V.renderReverseSided&&(v===yn?v=xn:v===xn&&(v=yn)),o.side=v,o.clipShadows=i.clipShadows,o.clippingPlanes=i.clippingPlanes,o.wireframeLinewidth=i.wireframeLinewidth,o.linewidth=i.linewidth,n&&void 0!==o.uniforms.lightPos&&o.uniforms.lightPos.value.copy(r),o}function h(t,e,i){if(t.visible!==!1){var n=0!==(t.layers.mask&e.layers.mask);if(n&&(t.isMesh||t.isLine||t.isPoints)&&t.castShadow&&(t.frustumCulled===!1||p.intersectsObject(t)===!0)){var r=t.material;r.visible===!0&&(t.modelViewMatrix.multiplyMatrices(i.matrixWorldInverse,t.matrixWorld),w.push(t))}for(var a=t.children,o=0,s=a.length;o0,shadowMapType:e.shadowMap.type,toneMapping:e.toneMapping,physicallyCorrectLights:e.physicallyCorrectLights,premultipliedAlpha:t.premultipliedAlpha,alphaTest:t.alphaTest,doubleSided:t.side===_n,flipSided:t.side===xn,depthPacking:void 0!==t.depthPacking&&t.depthPacking};return f},this.getProgramCode=function(t,e){var i=[];if(e.shaderID?i.push(e.shaderID):(i.push(t.fragmentShader),i.push(t.vertexShader)),void 0!==t.defines)for(var n in t.defines)i.push(n),i.push(t.defines[n]);for(var r=0;r65535?Uint32Array:Uint16Array,y=new U(new g(a),1);return r(y,t.ELEMENT_ARRAY_BUFFER),n.wireframe=y,y}function h(t,e,i){if(e>i){var n=e;e=i,i=n}var r=t[e];return void 0===r?(t[e]=[i],!0):r.indexOf(i)===-1&&(r.push(i),!0)}var l=new K(t,e,i);this.getAttributeBuffer=s,this.getWireframeAttribute=c,this.update=n}function tt(){var t={};this.get=function(e){if(void 0!==t[e.id])return t[e.id];var n;switch(e.type){case"DirectionalLight":n={direction:new s,color:new w,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new i};break;case"SpotLight":n={position:new s,direction:new s,color:new w,distance:0,coneCos:0,penumbraCos:0,decay:0,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new i};break;case"PointLight":n={position:new s,color:new w,distance:0,decay:0,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new i};break;case"HemisphereLight":n={direction:new s,skyColor:new w,groundColor:new w}}return t[e.id]=n,n}}function et(t,e,i){function n(){if(void 0!==a)return a;var i=e.get("EXT_texture_filter_anisotropic");return a=null!==i?t.getParameter(i.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0}function r(e){if("highp"===e){if(t.getShaderPrecisionFormat(t.VERTEX_SHADER,t.HIGH_FLOAT).precision>0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.HIGH_FLOAT).precision>0)return"highp";e="mediump"}return"mediump"===e&&t.getShaderPrecisionFormat(t.VERTEX_SHADER,t.MEDIUM_FLOAT).precision>0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}var a;this.getMaxAnisotropy=n,this.getMaxPrecision=r,this.precision=void 0!==i.precision?i.precision:"highp",this.logarithmicDepthBuffer=void 0!==i.logarithmicDepthBuffer&&i.logarithmicDepthBuffer,this.maxTextures=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS),this.maxVertexTextures=t.getParameter(t.MAX_VERTEX_TEXTURE_IMAGE_UNITS),this.maxTextureSize=t.getParameter(t.MAX_TEXTURE_SIZE),this.maxCubemapSize=t.getParameter(t.MAX_CUBE_MAP_TEXTURE_SIZE),this.maxAttributes=t.getParameter(t.MAX_VERTEX_ATTRIBS),this.maxVertexUniforms=t.getParameter(t.MAX_VERTEX_UNIFORM_VECTORS),this.maxVaryings=t.getParameter(t.MAX_VARYING_VECTORS),this.maxFragmentUniforms=t.getParameter(t.MAX_FRAGMENT_UNIFORM_VECTORS),this.vertexTextures=this.maxVertexTextures>0,this.floatFragmentTextures=!!e.get("OES_texture_float"),this.floatVertexTextures=this.vertexTextures&&this.floatFragmentTextures;var o=r(this.precision);o!==this.precision&&(console.warn("THREE.WebGLRenderer:",this.precision,"not supported, using",o,"instead."),this.precision=o),this.logarithmicDepthBuffer&&(this.logarithmicDepthBuffer=!!e.get("EXT_frag_depth"))}function it(t){var e={};this.get=function(i){if(void 0!==e[i])return e[i];var n;switch(i){case"WEBGL_depth_texture":n=t.getExtension("WEBGL_depth_texture")||t.getExtension("MOZ_WEBGL_depth_texture")||t.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":n=t.getExtension("EXT_texture_filter_anisotropic")||t.getExtension("MOZ_EXT_texture_filter_anisotropic")||t.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":n=t.getExtension("WEBGL_compressed_texture_s3tc")||t.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||t.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":n=t.getExtension("WEBGL_compressed_texture_pvrtc")||t.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;case"WEBGL_compressed_texture_etc1":n=t.getExtension("WEBGL_compressed_texture_etc1");break;default:n=t.getExtension(i)}return null===n&&console.warn("THREE.WebGLRenderer: "+i+" extension not supported."),e[i]=n,n}}function nt(t,e,i){function n(t){s=t}function r(i){i.array instanceof Uint32Array&&e.get("OES_element_index_uint")?(c=t.UNSIGNED_INT,h=4):(c=t.UNSIGNED_SHORT,h=2)}function a(e,n){t.drawElements(s,n,c,e*h),i.calls++,i.vertices+=n,s===t.TRIANGLES&&(i.faces+=n/3)}function o(n,r,a){var o=e.get("ANGLE_instanced_arrays");return null===o?void console.error("THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays."):(o.drawElementsInstancedANGLE(s,a,c,r*h,n.maxInstancedCount),i.calls++,i.vertices+=a*n.maxInstancedCount,void(s===t.TRIANGLES&&(i.faces+=n.maxInstancedCount*a/3)))}var s,c,h;this.setMode=n,this.setIndex=r,this.render=a,this.renderInstances=o}function rt(){function t(){h.value!==n&&(h.value=n,h.needsUpdate=r>0),i.numPlanes=r}function e(t,e,n,r){var a=null!==t?t.length:0,o=null;if(0!==a){if(o=h.value,r!==!0||null===o){var l=n+4*a,u=e.matrixWorldInverse;c.getNormalMatrix(u),(null===o||o.length0?1:-1,m[g]=C.x,m[g+1]=C.y,m[g+2]=C.z,v[y]=D/h,v[y+1]=1-U/u,g+=3,y+=2,R+=1}for(U=0;U65535?Uint32Array:Uint16Array)(p),f=new Float32Array(3*u),m=new Float32Array(3*u),v=new Float32Array(2*u),g=0,y=0,x=0,_=0,b=0;h("z","y","x",-1,-1,i,e,t,a,r,0),h("z","y","x",1,-1,i,e,-t,a,r,1),h("x","z","y",1,1,t,i,e,n,a,2),h("x","z","y",1,-1,t,i,-e,n,a,3),h("x","y","z",1,-1,t,e,i,n,r,4),h("x","y","z",-1,-1,t,e,-i,n,r,5),this.setIndex(new U(d,1)),this.addAttribute("position",new U(f,3)),this.addAttribute("normal",new U(m,3)),this.addAttribute("uv",new U(v,2))}function ct(t,e){this.origin=void 0!==t?t:new s,this.direction=void 0!==e?e:new s}function ht(t,e){this.start=void 0!==t?t:new s,this.end=void 0!==e?e:new s}function lt(t,e,i){this.a=void 0!==t?t:new s,this.b=void 0!==e?e:new s,this.c=void 0!==i?i:new s}function ut(t){x.call(this),this.type="MeshBasicMaterial",this.color=new w(16777215),this.map=null,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=ir,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.skinning=!1,this.morphTargets=!1,this.lights=!1,this.setValues(t)}function pt(t,e){X.call(this),this.type="Mesh",this.geometry=void 0!==t?t:new Q,this.material=void 0!==e?e:new ut({color:16777215*Math.random()}),this.drawMode=ua,this.updateMorphTargets()}function dt(t,e,i,n){Q.call(this),this.type="PlaneBufferGeometry",this.parameters={width:t,height:e,widthSegments:i,heightSegments:n};for(var r=t/2,a=e/2,o=Math.floor(i)||1,s=Math.floor(n)||1,c=o+1,h=s+1,l=t/o,u=e/s,p=new Float32Array(c*h*3),d=new Float32Array(c*h*3),f=new Float32Array(c*h*2),m=0,v=0,g=0;g65535?Uint32Array:Uint16Array)(o*s*6),g=0;g=0){var l=a[c];if(void 0!==l){var u=ee.FLOAT,p=l.array,d=l.normalized;p instanceof Float32Array?u=ee.FLOAT:p instanceof Float64Array?console.warn("Unsupported data buffer format: Float64Array"):p instanceof Uint16Array?u=ee.UNSIGNED_SHORT:p instanceof Int16Array?u=ee.SHORT:p instanceof Uint32Array?u=ee.UNSIGNED_INT:p instanceof Int32Array?u=ee.INT:p instanceof Int8Array?u=ee.BYTE:p instanceof Uint8Array&&(u=ee.UNSIGNED_BYTE);var f=l.itemSize,m=ce.getAttributeBuffer(l);if(l&&l.isInterleavedBufferAttribute){var v=l.data,g=v.stride,y=l.offset;v&&v.isInstancedInterleavedBuffer?(ae.enableAttributeAndDivisor(h,v.meshPerAttribute,r),void 0===i.maxInstancedCount&&(i.maxInstancedCount=v.meshPerAttribute*v.count)):ae.enableAttribute(h),ee.bindBuffer(ee.ARRAY_BUFFER,m),ee.vertexAttribPointer(h,f,u,d,g*v.array.BYTES_PER_ELEMENT,(n*g+y)*v.array.BYTES_PER_ELEMENT)}else l&&l.isInstancedBufferAttribute?(ae.enableAttributeAndDivisor(h,l.meshPerAttribute,r),void 0===i.maxInstancedCount&&(i.maxInstancedCount=l.meshPerAttribute*l.count)):ae.enableAttribute(h),ee.bindBuffer(ee.ARRAY_BUFFER,m),ee.vertexAttribPointer(h,f,u,d,0,n*f*l.array.BYTES_PER_ELEMENT)}else if(void 0!==s){var x=s[c];if(void 0!==x)switch(x.length){case 2:ee.vertexAttrib2fv(h,x);break;case 3:ee.vertexAttrib3fv(h,x);break;case 4:ee.vertexAttrib4fv(h,x);break;default:ee.vertexAttrib1fv(h,x)}}}}ae.disableUnusedAttributes()}function y(t,e){return Math.abs(e[0])-Math.abs(t[0])}function x(t,e){return t.object.renderOrder!==e.object.renderOrder?t.object.renderOrder-e.object.renderOrder:t.material.program&&e.material.program&&t.material.program!==e.material.program?t.material.program.id-e.material.program.id:t.material.id!==e.material.id?t.material.id-e.material.id:t.z!==e.z?t.z-e.z:t.id-e.id}function _(t,e){return t.object.renderOrder!==e.object.renderOrder?t.object.renderOrder-e.object.renderOrder:t.z!==e.z?e.z-t.z:t.id-e.id}function M(t,e,i,n,r){var a,o;i.transparent?(a=wt,o=++Mt):(a=_t,o=++bt);var s=a[o];void 0!==s?(s.id=t.id,s.object=t,s.geometry=e,s.material=i,s.z=Kt.z,s.group=r):(s={id:t.id,object:t,geometry:e,material:i,z:Kt.z,group:r},a.push(s))}function E(t){var e=t.geometry;return null===e.boundingSphere&&e.computeBoundingSphere(),Jt.copy(e.boundingSphere).applyMatrix4(t.matrixWorld),A(Jt)}function S(t){return Jt.center.set(0,0,0),Jt.radius=.7071067811865476,Jt.applyMatrix4(t.matrixWorld),A(Jt)}function A(t){if(!Xt.intersectsSphere(t))return!1;var e=Yt.numPlanes;if(0===e)return!0;var i=At.clippingPlanes,n=t.center,r=-t.radius,a=0;do if(i[a].distanceToPoint(n)=0&&e.numSupportedMorphTargets++}if(e.morphNormals){e.numSupportedMorphNormals=0;for(var p=0;p=0&&e.numSupportedMorphNormals++}var d=r.__webglShader.uniforms;(e&&e.isShaderMaterial||e&&e.isRawShaderMaterial)&&e.clipping!==!0||(r.numClippingPlanes=Yt.numPlanes,d.clippingPlanes=Yt.uniform),r.fog=i,r.lightsHash=$t.hash,e.lights&&(d.ambientLightColor.value=$t.ambient,d.directionalLights.value=$t.directional,d.spotLights.value=$t.spot,d.pointLights.value=$t.point,d.hemisphereLights.value=$t.hemi,d.directionalShadowMap.value=$t.directionalShadowMap,d.directionalShadowMatrix.value=$t.directionalShadowMatrix,d.spotShadowMap.value=$t.spotShadowMap,d.spotShadowMatrix.value=$t.spotShadowMatrix,d.pointShadowMap.value=$t.pointShadowMap,d.pointShadowMatrix.value=$t.pointShadowMatrix);var f=r.program.getUniforms(),m=t.WebGLUniforms.seqWithValue(f.seq,d);r.uniformsList=m,r.dynamicUniforms=t.WebGLUniforms.splitDynamic(m,d)}function N(t){t.side!==_n?ae.enable(ee.CULL_FACE):ae.disable(ee.CULL_FACE),ae.setFlipSided(t.side===xn),t.transparent===!0?ae.setBlending(t.blending,t.blendEquation,t.blendSrc,t.blendDst,t.blendEquationAlpha,t.blendSrcAlpha,t.blendDstAlpha,t.premultipliedAlpha):ae.setBlending(Sn),ae.setDepthFunc(t.depthFunc),ae.setDepthTest(t.depthTest),ae.setDepthWrite(t.depthWrite),ae.setColorWrite(t.colorWrite),ae.setPolygonOffset(t.polygonOffset,t.polygonOffsetFactor,t.polygonOffsetUnits)}function O(e,i,n,r){Ft=0;var a=oe.get(n);if(qt){if(Zt||e!==It){var o=e===It&&n.id===Ct;Yt.setState(n.clippingPlanes,n.clipShadows,e,a,o)}void 0!==a.numClippingPlanes&&a.numClippingPlanes!==Yt.numPlanes&&(n.needsUpdate=!0)}n.needsUpdate===!1&&(void 0===a.program?n.needsUpdate=!0:n.fog&&a.fog!==i?n.needsUpdate=!0:n.lights&&a.lightsHash!==$t.hash&&(n.needsUpdate=!0)),n.needsUpdate&&(D(n,i,r),n.needsUpdate=!1);var s=!1,c=!1,h=!1,l=a.program,u=l.getUniforms(),p=a.__webglShader.uniforms;if(l.id!==Lt&&(ee.useProgram(l.program),Lt=l.id, +s=!0,c=!0,h=!0),n.id!==Ct&&(Ct=n.id,c=!0),s||e!==It){if(u.set(ee,e,"projectionMatrix"),re.logarithmicDepthBuffer&&u.setValue(ee,"logDepthBufFC",2/(Math.log(e.far+1)/Math.LN2)),e!==It&&(It=e,c=!0,h=!0),n&&n.isShaderMaterial||n&&n.isMeshPhongMaterial||n&&n.isMeshStandardMaterial||n.envMap){var d=u.map.cameraPosition;void 0!==d&&d.setValue(ee,Kt.setFromMatrixPosition(e.matrixWorld))}(n&&n.isMeshPhongMaterial||n&&n.isMeshLambertMaterial||n&&n.isMeshBasicMaterial||n&&n.isMeshStandardMaterial||n&&n.isShaderMaterial||n.skinning)&&u.setValue(ee,"viewMatrix",e.matrixWorldInverse),u.set(ee,At,"toneMappingExposure"),u.set(ee,At,"toneMappingWhitePoint")}if(n.skinning){u.setOptional(ee,r,"bindMatrix"),u.setOptional(ee,r,"bindMatrixInverse");var f=r.skeleton;f&&(re.floatVertexTextures&&f.useVertexTexture?(u.set(ee,f,"boneTexture"),u.set(ee,f,"boneTextureWidth"),u.set(ee,f,"boneTextureHeight")):u.setOptional(ee,f,"boneMatrices"))}c&&(n.lights&&X(p,h),i&&n.fog&&H(p,i),(n&&n.isMeshBasicMaterial||n&&n.isMeshLambertMaterial||n&&n.isMeshPhongMaterial||n&&n.isMeshStandardMaterial||n&&n.isMeshDepthMaterial)&&F(p,n),n&&n.isLineBasicMaterial?z(p,n):n&&n.isLineDashedMaterial?(z(p,n),B(p,n)):n&&n.isPointsMaterial?G(p,n):n&&n.isMeshLambertMaterial?V(p,n):n&&n.isMeshPhongMaterial?k(p,n):n&&n.isMeshPhysicalMaterial?W(p,n):n&&n.isMeshStandardMaterial?j(p,n):n&&n.isMeshDepthMaterial?n.displacementMap&&(p.displacementMap.value=n.displacementMap,p.displacementScale.value=n.displacementScale,p.displacementBias.value=n.displacementBias):n&&n.isMeshNormalMaterial&&(p.opacity.value=n.opacity),t.WebGLUniforms.upload(ee,a.uniformsList,p,At)),u.set(ee,r,"modelViewMatrix"),u.set(ee,r,"normalMatrix"),u.setValue(ee,"modelMatrix",r.matrixWorld);var m=a.dynamicUniforms;return null!==m&&(t.WebGLUniforms.evalDynamic(m,p,r,e),t.WebGLUniforms.upload(ee,m,p,At)),l}function F(t,e){t.opacity.value=e.opacity,t.diffuse.value=e.color,e.emissive&&t.emissive.value.copy(e.emissive).multiplyScalar(e.emissiveIntensity),t.map.value=e.map,t.specularMap.value=e.specularMap,t.alphaMap.value=e.alphaMap,e.aoMap&&(t.aoMap.value=e.aoMap,t.aoMapIntensity.value=e.aoMapIntensity);var i;if(e.map?i=e.map:e.specularMap?i=e.specularMap:e.displacementMap?i=e.displacementMap:e.normalMap?i=e.normalMap:e.bumpMap?i=e.bumpMap:e.roughnessMap?i=e.roughnessMap:e.metalnessMap?i=e.metalnessMap:e.alphaMap?i=e.alphaMap:e.emissiveMap&&(i=e.emissiveMap),void 0!==i){i&&i.isWebGLRenderTarget&&(i=i.texture);var n=i.offset,r=i.repeat;t.offsetRepeat.value.set(n.x,n.y,r.x,r.y)}t.envMap.value=e.envMap,t.flipEnvMap.value=e.envMap&&e.envMap.isCubeTexture?-1:1,t.reflectivity.value=e.reflectivity,t.refractionRatio.value=e.refractionRatio}function z(t,e){t.diffuse.value=e.color,t.opacity.value=e.opacity}function B(t,e){t.dashSize.value=e.dashSize,t.totalSize.value=e.dashSize+e.gapSize,t.scale.value=e.scale}function G(t,e){if(t.diffuse.value=e.color,t.opacity.value=e.opacity,t.size.value=e.size*Vt,t.scale.value=.5*K.clientHeight,t.map.value=e.map,null!==e.map){var i=e.map.offset,n=e.map.repeat;t.offsetRepeat.value.set(i.x,i.y,n.x,n.y)}}function H(t,e){t.fogColor.value=e.color,e&&e.isFog?(t.fogNear.value=e.near,t.fogFar.value=e.far):e&&e.isFogExp2&&(t.fogDensity.value=e.density)}function V(t,e){e.lightMap&&(t.lightMap.value=e.lightMap,t.lightMapIntensity.value=e.lightMapIntensity),e.emissiveMap&&(t.emissiveMap.value=e.emissiveMap)}function k(t,e){t.specular.value=e.specular,t.shininess.value=Math.max(e.shininess,1e-4),e.lightMap&&(t.lightMap.value=e.lightMap,t.lightMapIntensity.value=e.lightMapIntensity),e.emissiveMap&&(t.emissiveMap.value=e.emissiveMap),e.bumpMap&&(t.bumpMap.value=e.bumpMap,t.bumpScale.value=e.bumpScale),e.normalMap&&(t.normalMap.value=e.normalMap,t.normalScale.value.copy(e.normalScale)),e.displacementMap&&(t.displacementMap.value=e.displacementMap,t.displacementScale.value=e.displacementScale,t.displacementBias.value=e.displacementBias)}function j(t,e){t.roughness.value=e.roughness,t.metalness.value=e.metalness,e.roughnessMap&&(t.roughnessMap.value=e.roughnessMap),e.metalnessMap&&(t.metalnessMap.value=e.metalnessMap),e.lightMap&&(t.lightMap.value=e.lightMap,t.lightMapIntensity.value=e.lightMapIntensity),e.emissiveMap&&(t.emissiveMap.value=e.emissiveMap),e.bumpMap&&(t.bumpMap.value=e.bumpMap,t.bumpScale.value=e.bumpScale),e.normalMap&&(t.normalMap.value=e.normalMap,t.normalScale.value.copy(e.normalScale)),e.displacementMap&&(t.displacementMap.value=e.displacementMap,t.displacementScale.value=e.displacementScale,t.displacementBias.value=e.displacementBias),e.envMap&&(t.envMapIntensity.value=e.envMapIntensity)}function W(t,e){t.clearCoat.value=e.clearCoat,t.clearCoatRoughness.value=e.clearCoatRoughness,j(t,e)}function X(t,e){t.ambientLightColor.needsUpdate=e,t.directionalLights.needsUpdate=e,t.pointLights.needsUpdate=e,t.spotLights.needsUpdate=e,t.hemisphereLights.needsUpdate=e}function Y(t){for(var e=0,i=0,n=t.length;i=re.maxTextures&&console.warn("WebGLRenderer: trying to use "+t+" texture units while this GPU supports only "+re.maxTextures),Ft+=1,t}function J(t){var e;if(t===yr)return ee.REPEAT;if(t===xr)return ee.CLAMP_TO_EDGE;if(t===_r)return ee.MIRRORED_REPEAT;if(t===br)return ee.NEAREST;if(t===wr)return ee.NEAREST_MIPMAP_NEAREST;if(t===Mr)return ee.NEAREST_MIPMAP_LINEAR;if(t===Er)return ee.LINEAR;if(t===Tr)return ee.LINEAR_MIPMAP_NEAREST;if(t===Sr)return ee.LINEAR_MIPMAP_LINEAR;if(t===Ar)return ee.UNSIGNED_BYTE;if(t===Nr)return ee.UNSIGNED_SHORT_4_4_4_4;if(t===Or)return ee.UNSIGNED_SHORT_5_5_5_1;if(t===Fr)return ee.UNSIGNED_SHORT_5_6_5;if(t===Lr)return ee.BYTE;if(t===Rr)return ee.SHORT;if(t===Pr)return ee.UNSIGNED_SHORT;if(t===Cr)return ee.INT;if(t===Ur)return ee.UNSIGNED_INT;if(t===Ir)return ee.FLOAT;if(e=ne.get("OES_texture_half_float"),null!==e&&t===Dr)return e.HALF_FLOAT_OES;if(t===Br)return ee.ALPHA;if(t===Gr)return ee.RGB;if(t===Hr)return ee.RGBA;if(t===Vr)return ee.LUMINANCE;if(t===kr)return ee.LUMINANCE_ALPHA;if(t===Wr)return ee.DEPTH_COMPONENT;if(t===Xr)return ee.DEPTH_STENCIL;if(t===Un)return ee.FUNC_ADD;if(t===In)return ee.FUNC_SUBTRACT;if(t===Dn)return ee.FUNC_REVERSE_SUBTRACT;if(t===Fn)return ee.ZERO;if(t===zn)return ee.ONE;if(t===Bn)return ee.SRC_COLOR;if(t===Gn)return ee.ONE_MINUS_SRC_COLOR;if(t===Hn)return ee.SRC_ALPHA;if(t===Vn)return ee.ONE_MINUS_SRC_ALPHA;if(t===kn)return ee.DST_ALPHA;if(t===jn)return ee.ONE_MINUS_DST_ALPHA;if(t===Wn)return ee.DST_COLOR;if(t===Xn)return ee.ONE_MINUS_DST_COLOR;if(t===Yn)return ee.SRC_ALPHA_SATURATE;if(e=ne.get("WEBGL_compressed_texture_s3tc"),null!==e){if(t===Yr)return e.COMPRESSED_RGB_S3TC_DXT1_EXT;if(t===qr)return e.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(t===Zr)return e.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(t===Jr)return e.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(e=ne.get("WEBGL_compressed_texture_pvrtc"),null!==e){if(t===Qr)return e.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(t===Kr)return e.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(t===$r)return e.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(t===ta)return e.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(e=ne.get("WEBGL_compressed_texture_etc1"),null!==e&&t===ea)return e.COMPRESSED_RGB_ETC1_WEBGL;if(e=ne.get("EXT_blend_minmax"),null!==e){if(t===Nn)return e.MIN_EXT;if(t===On)return e.MAX_EXT}return e=ne.get("WEBGL_depth_texture"),null!==e&&t===THREE.UnsignedInt248Type?e.UNSIGNED_INT_24_8_WEBGL:0}console.log("THREE.WebGLRenderer",sn),e=e||{};var K=void 0!==e.canvas?e.canvas:document.createElementNS("http://www.w3.org/1999/xhtml","canvas"),ot=void 0!==e.context?e.context:null,ct=void 0!==e.alpha&&e.alpha,ht=void 0===e.depth||e.depth,lt=void 0===e.stencil||e.stencil,ft=void 0!==e.antialias&&e.antialias,gt=void 0===e.premultipliedAlpha||e.premultipliedAlpha,yt=void 0!==e.preserveDrawingBuffer&&e.preserveDrawingBuffer,xt=[],_t=[],bt=-1,wt=[],Mt=-1,Et=new Float32Array(8),Tt=[],St=[];this.domElement=K,this.context=null,this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.gammaFactor=2,this.gammaInput=!1,this.gammaOutput=!1,this.physicallyCorrectLights=!1,this.toneMapping=or,this.toneMappingExposure=1,this.toneMappingWhitePoint=1,this.maxMorphTargets=8,this.maxMorphNormals=4;var At=this,Lt=null,Rt=null,Pt=null,Ct=-1,Ut="",It=null,Dt=new d,Nt=null,Ot=new d,Ft=0,zt=new w(0),Bt=0,Gt=K.width,Ht=K.height,Vt=1,kt=new d(0,0,Gt,Ht),jt=!1,Wt=new d(0,0,Gt,Ht),Xt=new L,Yt=new rt,qt=!1,Zt=!1,Jt=new T,Qt=new a,Kt=new s,$t={hash:"",ambient:[0,0,0],directional:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotShadowMap:[],spotShadowMatrix:[],point:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],shadows:[]},te={calls:0,vertices:0,faces:0,points:0};this.info={render:te,memory:{geometries:0,textures:0},programs:null};var ee;try{var ie={alpha:ct,depth:ht,stencil:lt,antialias:ft,premultipliedAlpha:gt,preserveDrawingBuffer:yt};if(ee=ot||K.getContext("webgl",ie)||K.getContext("experimental-webgl",ie),null===ee)throw null!==K.getContext("webgl")?"Error creating WebGL context with your selected attributes.":"Error creating WebGL context.";void 0===ee.getShaderPrecisionFormat&&(ee.getShaderPrecisionFormat=function(){return{rangeMin:1,rangeMax:1,precision:1}}),K.addEventListener("webglcontextlost",h,!1)}catch(t){console.error("THREE.WebGLRenderer: "+t)}var ne=new it(ee);ne.get("WEBGL_depth_texture"),ne.get("OES_texture_float"),ne.get("OES_texture_float_linear"),ne.get("OES_texture_half_float"),ne.get("OES_texture_half_float_linear"),ne.get("OES_standard_derivatives"),ne.get("ANGLE_instanced_arrays"),ne.get("OES_element_index_uint")&&(Q.MaxIndex=4294967296);var re=new et(ee,ne,e),ae=new f(ee,ne,J),oe=new P,se=new p(ee,ne,ae,oe,re,J,this.info),ce=new $(ee,oe,this.info),he=new C(this,re),le=new tt;this.info.programs=he.programs;var ue=new at(ee,ne,te),pe=new nt(ee,ne,te),de=new vt((-1),1,1,(-1),0,1),fe=new mt,me=new pt(new dt(2,2),new ut({depthTest:!1,depthWrite:!1,fog:!1})),ve=t.ShaderLib.cube,ge=new pt(new st(5,5,5),new b({uniforms:ve.uniforms,vertexShader:ve.vertexShader,fragmentShader:ve.fragmentShader,side:xn,depthTest:!1,depthWrite:!1,fog:!1}));r(),this.context=ee,this.capabilities=re,this.extensions=ne,this.properties=oe,this.state=ae;var ye=new R(this,$t,ce,re);this.shadowMap=ye;var xe=new c(this,Tt),_e=new l(this,St);this.getContext=function(){return ee},this.getContextAttributes=function(){return ee.getContextAttributes()},this.forceContextLoss=function(){ne.get("WEBGL_lose_context").loseContext()},this.getMaxAnisotropy=function(){return re.getMaxAnisotropy()},this.getPrecision=function(){return re.precision},this.getPixelRatio=function(){return Vt},this.setPixelRatio=function(t){void 0!==t&&(Vt=t,this.setSize(Wt.z,Wt.w,!1))},this.getSize=function(){return{width:Gt,height:Ht}},this.setSize=function(t,e,i){Gt=t,Ht=e,K.width=t*Vt,K.height=e*Vt,i!==!1&&(K.style.width=t+"px",K.style.height=e+"px"),this.setViewport(0,0,t,e)},this.setViewport=function(t,e,i,n){ae.viewport(Wt.set(t,e,i,n))},this.setScissor=function(t,e,i,n){ae.scissor(kt.set(t,e,i,n))},this.setScissorTest=function(t){ae.setScissorTest(jt=t)},this.getClearColor=function(){return zt},this.setClearColor=function(t,e){zt.set(t),Bt=void 0!==e?e:1,n(zt.r,zt.g,zt.b,Bt)},this.getClearAlpha=function(){return Bt},this.setClearAlpha=function(t){Bt=t,n(zt.r,zt.g,zt.b,Bt)},this.clear=function(t,e,i){var n=0;(void 0===t||t)&&(n|=ee.COLOR_BUFFER_BIT),(void 0===e||e)&&(n|=ee.DEPTH_BUFFER_BIT),(void 0===i||i)&&(n|=ee.STENCIL_BUFFER_BIT),ee.clear(n)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.clearTarget=function(t,e,i,n){this.setRenderTarget(t),this.clear(e,i,n)},this.resetGLState=o,this.dispose=function(){wt=[],Mt=-1,_t=[],bt=-1,K.removeEventListener("webglcontextlost",h,!1)},this.renderBufferImmediate=function(t,e,i){ae.initAttributes();var n=oe.get(t);t.hasPositions&&!n.position&&(n.position=ee.createBuffer()),t.hasNormals&&!n.normal&&(n.normal=ee.createBuffer()),t.hasUvs&&!n.uv&&(n.uv=ee.createBuffer()),t.hasColors&&!n.color&&(n.color=ee.createBuffer());var r=e.getAttributes();if(t.hasPositions&&(ee.bindBuffer(ee.ARRAY_BUFFER,n.position),ee.bufferData(ee.ARRAY_BUFFER,t.positionArray,ee.DYNAMIC_DRAW),ae.enableAttribute(r.position),ee.vertexAttribPointer(r.position,3,ee.FLOAT,!1,0,0)),t.hasNormals){if(ee.bindBuffer(ee.ARRAY_BUFFER,n.normal),"MeshPhongMaterial"!==i.type&&"MeshStandardMaterial"!==i.type&&"MeshPhysicalMaterial"!==i.type&&i.shading===bn)for(var a=0,o=3*t.count;a8&&(u.length=8);for(var m=n.morphAttributes,p=0,d=u.length;p0&&_.renderInstances(n,A,R):_.render(A,R)},this.render=function(t,e,i,r){if((e&&e.isCamera)===!1)return void console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");var a=t.fog;Ut="",Ct=-1,It=null,t.autoUpdate===!0&&t.updateMatrixWorld(),null===e.parent&&e.updateMatrixWorld(),e.matrixWorldInverse.getInverse(e.matrixWorld),Qt.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),Xt.setFromMatrix(Qt),xt.length=0,bt=-1,Mt=-1,Tt.length=0,St.length=0,Zt=this.localClippingEnabled,qt=Yt.init(this.clippingPlanes,Zt,e),U(t,e),_t.length=bt+1,wt.length=Mt+1,At.sortObjects===!0&&(_t.sort(x),wt.sort(_)),qt&&Yt.beginShadows(),Y(xt),ye.render(t,e),q(xt,e),qt&&Yt.endShadows(),te.calls=0,te.vertices=0,te.faces=0,te.points=0,void 0===i&&(i=null),this.setRenderTarget(i);var o=t.background;if(null===o?n(zt.r,zt.g,zt.b,Bt):o&&o.isColor&&(n(o.r,o.g,o.b,1),r=!0),(this.autoClear||r)&&this.clear(this.autoClearColor,this.autoClearDepth,this.autoClearStencil),o&&o.isCubeTexture?(fe.projectionMatrix.copy(e.projectionMatrix),fe.matrixWorld.extractRotation(e.matrixWorld),fe.matrixWorldInverse.getInverse(fe.matrixWorld),ge.material.uniforms.tCube.value=o,ge.modelViewMatrix.multiplyMatrices(fe.matrixWorldInverse,ge.matrixWorld),ce.update(ge),At.renderBufferDirect(fe,null,ge.geometry,ge.material,ge,null)):o&&o.isTexture&&(me.material.map=o,ce.update(me),At.renderBufferDirect(de,null,me.geometry,me.material,me,null)),t.overrideMaterial){var s=t.overrideMaterial;I(_t,e,a,s),I(wt,e,a,s)}else ae.setBlending(Sn),I(_t,e,a),I(wt,e,a);xe.render(t,e),_e.render(t,e,Ot),i&&se.updateRenderTargetMipmap(i),ae.setDepthTest(!0),ae.setDepthWrite(!0),ae.setColorWrite(!0)},this.setFaceCulling=function(t,e){ae.setCullFace(t),ae.setFlipSided(e===dn)},this.allocTextureUnit=Z,this.setTexture2D=function(){var t=!1;return function(e,i){e&&e.isWebGLRenderTarget&&(t||(console.warn("THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead."),t=!0),e=e.texture),se.setTexture2D(e,i)}}(),this.setTexture=function(){var t=!1;return function(e,i){t||(console.warn("THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead."),t=!0),se.setTexture2D(e,i)}}(),this.setTextureCube=function(){var t=!1;return function(e,i){e&&e.isWebGLRenderTargetCube&&(t||(console.warn("THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead."),t=!0),e=e.texture),e&&e.isCubeTexture||Array.isArray(e.image)&&6===e.image.length?se.setTextureCube(e,i):se.setTextureCubeDynamic(e,i)}}(),this.getCurrentRenderTarget=function(){return Rt},this.setRenderTarget=function(t){Rt=t,t&&void 0===oe.get(t).__webglFramebuffer&&se.setupRenderTarget(t);var e,i=t&&t.isWebGLRenderTargetCube;if(t){var n=oe.get(t);e=i?n.__webglFramebuffer[t.activeCubeFace]:n.__webglFramebuffer,Dt.copy(t.scissor),Nt=t.scissorTest,Ot.copy(t.viewport)}else e=null,Dt.copy(kt).multiplyScalar(Vt),Nt=jt,Ot.copy(Wt).multiplyScalar(Vt);if(Pt!==e&&(ee.bindFramebuffer(ee.FRAMEBUFFER,e),Pt=e),ae.scissor(Dt),ae.setScissorTest(Nt),ae.viewport(Ot),i){var r=oe.get(t.texture);ee.framebufferTexture2D(ee.FRAMEBUFFER,ee.COLOR_ATTACHMENT0,ee.TEXTURE_CUBE_MAP_POSITIVE_X+t.activeCubeFace,r.__webglTexture,t.activeMipMapLevel)}},this.readRenderTargetPixels=function(t,e,i,n,r,a){if((t&&t.isWebGLRenderTarget)===!1)return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");var o=oe.get(t).__webglFramebuffer;if(o){var s=!1;o!==Pt&&(ee.bindFramebuffer(ee.FRAMEBUFFER,o),s=!0);try{var c=t.texture;if(c.format!==Hr&&J(c.format)!==ee.getParameter(ee.IMPLEMENTATION_COLOR_READ_FORMAT))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");if(!(c.type===Ar||J(c.type)===ee.getParameter(ee.IMPLEMENTATION_COLOR_READ_TYPE)||c.type===Ir&&ne.get("WEBGL_color_buffer_float")||c.type===Dr&&ne.get("EXT_color_buffer_half_float")))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");ee.checkFramebufferStatus(ee.FRAMEBUFFER)===ee.FRAMEBUFFER_COMPLETE?e>=0&&e<=t.width-n&&i>=0&&i<=t.height-r&&ee.readPixels(e,i,n,r,J(c.format),J(c.type),a):console.error("THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.")}finally{s&&ee.bindFramebuffer(ee.FRAMEBUFFER,Pt)}}}}function yt(t,e){this.name="",this.color=new w(t),this.density=void 0!==e?e:25e-5}function xt(t,e,i){this.name="",this.color=new w(t),this.near=void 0!==e?e:1,this.far=void 0!==i?i:1e3}function _t(){X.call(this),this.type="Scene",this.background=null,this.fog=null,this.overrideMaterial=null,this.autoUpdate=!0}function bt(t,e,i,n,r){X.call(this),this.lensFlares=[],this.positionScreen=new s,this.customUpdateCallback=void 0,void 0!==t&&this.add(t,e,i,n,r)}function wt(t){x.call(this),this.type="SpriteMaterial",this.color=new w(16777215),this.map=null,this.rotation=0,this.fog=!1,this.lights=!1,this.setValues(t)}function Mt(t){X.call(this),this.type="Sprite",this.material=void 0!==t?t:new wt}function Et(){X.call(this),this.type="LOD",Object.defineProperties(this,{levels:{enumerable:!0,value:[]}})}function Tt(t,e,i,r,a,o,s,c,h,l,u,p){n.call(this,null,o,s,c,h,l,r,a,u,p),this.image={data:t,width:e,height:i},this.magFilter=void 0!==h?h:br,this.minFilter=void 0!==l?l:br,this.flipY=!1,this.generateMipmaps=!1}function St(e,i,n){if(this.useVertexTexture=void 0===n||n,this.identityMatrix=new a,e=e||[],this.bones=e.slice(0),this.useVertexTexture){var r=Math.sqrt(4*this.bones.length);r=t.Math.nextPowerOfTwo(Math.ceil(r)),r=Math.max(r,4),this.boneTextureWidth=r,this.boneTextureHeight=r,this.boneMatrices=new Float32Array(this.boneTextureWidth*this.boneTextureHeight*4),this.boneTexture=new Tt(this.boneMatrices,this.boneTextureWidth,this.boneTextureHeight,Hr,Ir)}else this.boneMatrices=new Float32Array(16*this.bones.length);if(void 0===i)this.calculateInverses();else if(this.bones.length===i.length)this.boneInverses=i.slice(0);else{console.warn("THREE.Skeleton bonInverses is the wrong length."),this.boneInverses=[];for(var o=0,s=this.bones.length;o=t.HAVE_CURRENT_DATA&&(u.needsUpdate=!0)}n.call(this,t,e,i,r,a,o,s,c,h),this.generateMipmaps=!1;var u=this;l()}function Ot(t,e,i,r,a,o,s,c,h,l,u,p){n.call(this,null,o,s,c,h,l,r,a,u,p),this.image={width:e,height:i},this.mipmaps=t,this.flipY=!1,this.generateMipmaps=!1}function Ft(t,e,i,r,a,o,s,c,h){n.call(this,t,e,i,r,a,o,s,c,h),this.needsUpdate=!0}function zt(t,e,i,r,a,o,s,c,h,l){if(l=void 0!==l?l:Wr,l!==Wr&&l!==Xr)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");n.call(this,null,r,a,o,s,c,l,i,h),this.image={width:t,height:e},this.type=void 0!==i?i:Pr,this.magFilter=void 0!==s?s:br,this.minFilter=void 0!==c?c:br,this.flipY=!1,this.generateMipmaps=!1}function Bt(){b.call(this,{uniforms:t.UniformsUtils.merge([t.UniformsLib.lights,{opacity:{value:1}}]),vertexShader:Es.shadow_vert,fragmentShader:Es.shadow_frag}),this.lights=!0,this.transparent=!0,Object.defineProperties(this,{opacity:{enumerable:!0,get:function(){return this.uniforms.opacity.value},set:function(t){this.uniforms.opacity.value=t}}})}function Gt(t){b.call(this,t),this.type="RawShaderMaterial"}function Ht(e){this.uuid=t.Math.generateUUID(),this.type="MultiMaterial",this.materials=e instanceof Array?e:[],this.visible=!0}function Vt(t){x.call(this),this.defines={STANDARD:""},this.type="MeshStandardMaterial",this.color=new w(16777215),this.roughness=.5,this.metalness=.5,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new w(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalScale=new i(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapIntensity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.skinning=!1,this.morphTargets=!1,this.morphNormals=!1,this.setValues(t)}function kt(t){Vt.call(this),this.defines={PHYSICAL:""},this.type="MeshPhysicalMaterial",this.reflectivity=.5,this.clearCoat=0,this.clearCoatRoughness=0,this.setValues(t)}function jt(t){x.call(this),this.type="MeshPhongMaterial",this.color=new w(16777215),this.specular=new w(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new w(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalScale=new i(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=ir,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.skinning=!1,this.morphTargets=!1,this.morphNormals=!1,this.setValues(t)}function Wt(t){x.call(this,t),this.type="MeshNormalMaterial",this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.morphTargets=!1,this.setValues(t)}function Xt(t){x.call(this),this.type="MeshLambertMaterial",this.color=new w(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new w(0),this.emissiveIntensity=1,this.emissiveMap=null,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=ir,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.skinning=!1,this.morphTargets=!1,this.morphNormals=!1,this.setValues(t)}function Yt(t){x.call(this),this.type="LineDashedMaterial",this.color=new w(16777215),this.linewidth=1,this.scale=1,this.dashSize=3,this.gapSize=1,this.lights=!1,this.setValues(t)}function qt(t,e,i){var n=this,r=!1,a=0,o=0;this.onStart=void 0,this.onLoad=t,this.onProgress=e,this.onError=i,this.itemStart=function(t){o++,r===!1&&void 0!==n.onStart&&n.onStart(t,a,o),r=!0},this.itemEnd=function(t){a++,void 0!==n.onProgress&&n.onProgress(t,a,o),a===o&&(r=!1,void 0!==n.onLoad&&n.onLoad())},this.itemError=function(t){void 0!==n.onError&&n.onError(t)}}function Zt(e){this.manager=void 0!==e?e:t.DefaultLoadingManager}function Jt(e){this.manager=void 0!==e?e:t.DefaultLoadingManager,this._parser=null}function Qt(e){this.manager=void 0!==e?e:t.DefaultLoadingManager,this._parser=null}function Kt(e){this.manager=void 0!==e?e:t.DefaultLoadingManager}function $t(e){this.manager=void 0!==e?e:t.DefaultLoadingManager}function te(e){this.manager=void 0!==e?e:t.DefaultLoadingManager}function ee(t,e){X.call(this),this.type="Light",this.color=new w(t),this.intensity=void 0!==e?e:1,this.receiveShadow=void 0}function ie(t,e,i){ee.call(this,t,i),this.type="HemisphereLight",this.castShadow=void 0,this.position.copy(X.DefaultUp),this.updateMatrix(),this.groundColor=new w(e)}function ne(t){this.camera=t,this.bias=0,this.radius=1,this.mapSize=new i(512,512),this.map=null,this.matrix=new a}function re(){ne.call(this,new mt(50,1,.5,500))}function ae(t,e,i,n,r,a){ee.call(this,t,e),this.type="SpotLight",this.position.copy(X.DefaultUp),this.updateMatrix(),this.target=new X,Object.defineProperty(this,"power",{get:function(){return this.intensity*Math.PI},set:function(t){this.intensity=t/Math.PI}}),this.distance=void 0!==i?i:0,this.angle=void 0!==n?n:Math.PI/3,this.penumbra=void 0!==r?r:0,this.decay=void 0!==a?a:1,this.shadow=new re}function oe(t,e,i,n){ee.call(this,t,e),this.type="PointLight",Object.defineProperty(this,"power",{get:function(){return 4*this.intensity*Math.PI},set:function(t){this.intensity=t/(4*Math.PI)}}),this.distance=void 0!==i?i:0,this.decay=void 0!==n?n:1,this.shadow=new ne(new mt(90,1,.5,500))}function se(t){ne.call(this,new vt((-5),5,5,(-5),.5,500))}function ce(t,e){ee.call(this,t,e),this.type="DirectionalLight",this.position.copy(X.DefaultUp),this.updateMatrix(),this.target=new X,this.shadow=new se}function he(t,e){ee.call(this,t,e),this.type="AmbientLight",this.castShadow=void 0}function le(t,e,i,n){this.parameterPositions=t,this._cachedIndex=0,this.resultBuffer=void 0!==n?n:new e.constructor(i),this.sampleValues=e,this.valueSize=i}function ue(t,e,i,n){le.call(this,t,e,i,n),this._weightPrev=-0,this._offsetPrev=-0,this._weightNext=-0,this._offsetNext=-0}function pe(t,e,i,n){le.call(this,t,e,i,n)}function de(t,e,i,n){le.call(this,t,e,i,n)}function fe(e,i,n,r){if(void 0===e)throw new Error("track name is undefined");if(void 0===i||0===i.length)throw new Error("no keyframes in track named "+e); +this.name=e,this.times=t.AnimationUtils.convertArray(i,this.TimeBufferType),this.values=t.AnimationUtils.convertArray(n,this.ValueBufferType),this.setInterpolation(r||this.DefaultInterpolation),this.validate(),this.optimize()}function me(t,e,i,n){fe.call(this,t,e,i,n)}function ve(t,e,i,n){le.call(this,t,e,i,n)}function ge(t,e,i,n){fe.call(this,t,e,i,n)}function ye(t,e,i,n){fe.call(this,t,e,i,n)}function xe(t,e,i,n){fe.call(this,t,e,i,n)}function _e(t,e,i){fe.call(this,t,e,i)}function be(t,e,i,n){fe.call(this,t,e,i,n)}function we(t,e,i,n){fe.apply(this,arguments)}function Me(e,i,n){this.name=e,this.tracks=n,this.duration=void 0!==i?i:-1,this.uuid=t.Math.generateUUID(),this.duration<0&&this.resetDuration(),this.trim(),this.optimize()}function Ee(e){this.manager=void 0!==e?e:t.DefaultLoadingManager,this.textures={}}function Te(e){this.manager=void 0!==e?e:t.DefaultLoadingManager}function Se(){this.onLoadStart=function(){},this.onLoadProgress=function(){},this.onLoadComplete=function(){}}function Ae(e){"boolean"==typeof e&&(console.warn("THREE.JSONLoader: showStatus parameter has been removed from constructor."),e=void 0),this.manager=void 0!==e?e:t.DefaultLoadingManager,this.withCredentials=!1}function Le(e){this.manager=void 0!==e?e:t.DefaultLoadingManager,this.texturePath=""}function Re(){}function Pe(t,e){this.v1=t,this.v2=e}function Ce(){this.curves=[],this.autoClose=!1}function Ue(t,e,i,n,r,a,o,s){this.aX=t,this.aY=e,this.xRadius=i,this.yRadius=n,this.aStartAngle=r,this.aEndAngle=a,this.aClockwise=o,this.aRotation=s||0}function Ie(t){this.points=void 0===t?[]:t}function De(t,e,i,n){this.v0=t,this.v1=e,this.v2=i,this.v3=n}function Ne(t,e,i){this.v0=t,this.v1=e,this.v2=i}function Oe(t,e,n,r,a,o){function c(t,e,i){return C.vertices.push(new s(t,e,i))-1}q.call(this),this.type="TubeGeometry",this.parameters={path:t,segments:e,radius:n,radialSegments:r,closed:a,taper:o},e=e||64,n=n||1,r=r||8,a=a||!1,o=o||Oe.NoTaper;var h,l,u,p,d,f,m,v,g,y,x,_,b,w,M,E,T,S,A,L,R,P=[],C=this,U=e+1,I=new s,D=new Oe.FrenetFrames(t,e,a),N=D.tangents,O=D.normals,F=D.binormals;for(this.tangents=N,this.normals=O,this.binormals=F,y=0;ythis.points.length-2?this.points.length-1:n+1,p[3]=n>this.points.length-3?this.points.length-1:n+2,c=this.points[p[0]],h=this.points[p[1]],l=this.points[p[2]],u=this.points[p[3]],a=r*r,o=r*a,d.x=e(c.x,h.x,l.x,u.x,r,a,o),d.y=e(c.y,h.y,l.y,u.y,r,a,o),d.z=e(c.z,h.z,l.z,u.z,r,a,o),d},this.getControlPointsArray=function(){var t,e,i=this.points.length,n=[];for(t=0;t0)&&E.push(S,A,R),(v!==i-1||c65535?B:F)(E,1)),this.addAttribute("position",l),this.addAttribute("normal",u),this.addAttribute("uv",p),this.boundingSphere=new T(new s,t)}function Mi(t,e){this.light=t,this.light.updateMatrixWorld();var i=new wi(e,4,2),n=new ut({wireframe:!0,fog:!1});n.color.copy(this.light.color).multiplyScalar(this.light.intensity),pt.call(this,i,n),this.matrix=this.light.matrixWorld,this.matrixAutoUpdate=!1}function Ei(t,e,i,n,r,a,o){q.call(this),this.type="SphereGeometry",this.parameters={radius:t,widthSegments:e,heightSegments:i,phiStart:n,phiLength:r,thetaStart:a,thetaLength:o},this.fromBufferGeometry(new wi(t,e,i,n,r,a,o))}function Ti(t,e){X.call(this),this.light=t,this.light.updateMatrixWorld(),this.matrix=t.matrixWorld,this.matrixAutoUpdate=!1,this.colors=[new w,new w];var i=new Ei(e,4,2);i.rotateX(-Math.PI/2);for(var n=0,r=8;n0&&m++,e>0&&m++);var v=l(),g=u(),y=new U(new(g>65535?Uint32Array:Uint16Array)(g),1),x=new U(new Float32Array(3*v),3),_=new U(new Float32Array(3*v),3),b=new U(new Float32Array(2*v),2),w=0,M=0,E=[],T=n/2,S=0;p(),o===!1&&(t>0&&d(!0),e>0&&d(!1)),this.setIndex(y),this.addAttribute("position",x),this.addAttribute("normal",_),this.addAttribute("uv",b)}function Oi(t){t=t||1;var e=new Float32Array([0,0,0,t,0,0,0,0,0,0,t,0,0,0,0,0,0,t]),i=new Float32Array([1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1]),n=new Q;n.addAttribute("position",new U(e,3)),n.addAttribute("color",new U(i,3));var r=new Rt({vertexColors:Tn});Ct.call(this,n,r)}function Fi(t,e,n){q.call(this),this.type="ParametricGeometry",this.parameters={func:t,slices:e,stacks:n};var r,a,o,s,c,h=this.vertices,l=this.faces,u=this.faceVertexUvs[0],p=e+1;for(r=0;r<=n;r++)for(c=r/n,a=0;a<=e;a++)s=a/e,o=t(s,c),h.push(o);var d,f,m,v,g,y,x,_;for(r=0;r.9&&L<.1&&(M<.2&&(w[0].x+=1),E<.2&&(w[1].x+=1),S<.2&&(w[2].x+=1))}for(var d=0,f=this.vertices.length;d65535?Uint32Array:Uint16Array)(p),1),f=new U(new Float32Array(3*u),3),m=new U(new Float32Array(3*u),3),v=new U(new Float32Array(2*u),2),g=0,y=0,x=new s,_=new s,b=new i,w=new s,M=new s,E=new s,T=new s,S=new s;for(h=0;h<=n;++h){var A=h/n*a*Math.PI*2;for(c(A,a,o,t,w),c(A+.01,a,o,t,M),T.subVectors(M,w),S.addVectors(M,w),E.crossVectors(T,S),S.crossVectors(E,T),E.normalize(),S.normalize(),l=0;l<=r;++l){var L=l/r*Math.PI*2,R=-e*Math.cos(L),P=e*Math.sin(L);x.x=w.x+(R*S.x+P*E.x),x.y=w.y+(R*S.y+P*E.y),x.z=w.z+(R*S.z+P*E.z),f.setXYZ(g,x.x,x.y,x.z),_.subVectors(x,w).normalize(),m.setXYZ(g,_.x,_.y,_.z),b.x=h/n,b.y=l/r,v.setXY(g,b.x,b.y),g++}}for(l=1;l<=n;l++)for(h=1;h<=r;h++){var C=(r+1)*(l-1)+(h-1),I=(r+1)*l+(h-1),D=(r+1)*l+h,N=(r+1)*(l-1)+h;d.setX(y,C),y++,d.setX(y,I),y++,d.setX(y,N),y++,d.setX(y,I),y++,d.setX(y,D),y++,d.setX(y,N),y++}this.setIndex(d),this.addAttribute("position",f),this.addAttribute("normal",m),this.addAttribute("uv",v)}function ji(t,e,i,n,r,a,o){q.call(this),this.type="TorusKnotGeometry",this.parameters={radius:t,tube:e,tubularSegments:i,radialSegments:n,p:r,q:a},void 0!==o&&console.warn("THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead."),this.fromBufferGeometry(new ki(t,e,i,n,r,a)),this.mergeVertices()}function Wi(t,e,i,n,r){Q.call(this),this.type="TorusBufferGeometry",this.parameters={radius:t,tube:e,radialSegments:i,tubularSegments:n,arc:r},t=t||100,e=e||40,i=Math.floor(i)||8,n=Math.floor(n)||6,r=r||2*Math.PI;var a,o,c=(i+1)*(n+1),h=i*n*2*3,l=new(h>65535?Uint32Array:Uint16Array)(h),u=new Float32Array(3*c),p=new Float32Array(3*c),d=new Float32Array(2*c),f=0,m=0,v=0,g=new s,y=new s,x=new s;for(a=0;a<=i;a++)for(o=0;o<=n;o++){var _=o/n*r,b=a/i*Math.PI*2;y.x=(t+e*Math.cos(b))*Math.cos(_),y.y=(t+e*Math.cos(b))*Math.sin(_),y.z=e*Math.sin(b),u[f]=y.x,u[f+1]=y.y,u[f+2]=y.z,g.x=t*Math.cos(_),g.y=t*Math.sin(_),x.subVectors(y,g).normalize(),p[f]=x.x,p[f+1]=x.y,p[f+2]=x.z,d[m]=o/n,d[m+1]=a/i,f+=3,m+=2}for(a=1;a<=i;a++)for(o=1;o<=n;o++){var w=(n+1)*a+o-1,M=(n+1)*(a-1)+o-1,E=(n+1)*(a-1)+o,T=(n+1)*a+o;l[v]=w,l[v+1]=M,l[v+2]=T,l[v+3]=M,l[v+4]=E,l[v+5]=T,v+=6}this.setIndex(new U(l,1)),this.addAttribute("position",new U(u,3)),this.addAttribute("normal",new U(p,3)),this.addAttribute("uv",new U(d,2))}function Xi(t,e,i,n,r){q.call(this),this.type="TorusGeometry",this.parameters={radius:t,tube:e,radialSegments:i,tubularSegments:n,arc:r},this.fromBufferGeometry(new Wi(t,e,i,n,r))}function Yi(t,e){e=e||{};var i=e.font;if((i&&i.isFont)===!1)return console.error("THREE.TextGeometry: font parameter is not an instance of THREE.Font."),new q;var n=i.generateShapes(t,e.size,e.curveSegments);e.amount=void 0!==e.height?e.height:50,void 0===e.bevelThickness&&(e.bevelThickness=10),void 0===e.bevelSize&&(e.bevelSize=8),void 0===e.bevelEnabled&&(e.bevelEnabled=!1),Fe.call(this,n,e),this.type="TextGeometry"}function qi(t,e,n,r,a,o){Q.call(this),this.type="RingBufferGeometry",this.parameters={innerRadius:t,outerRadius:e,thetaSegments:n,phiSegments:r,thetaStart:a,thetaLength:o},t=t||20,e=e||50,a=void 0!==a?a:0,o=void 0!==o?o:2*Math.PI,n=void 0!==n?Math.max(3,n):8,r=void 0!==r?Math.max(1,r):1;var c,h,l,u=(n+1)*(r+1),p=n*r*2*3,d=new U(new(p>65535?Uint32Array:Uint16Array)(p),1),f=new U(new Float32Array(3*u),3),m=new U(new Float32Array(3*u),3),v=new U(new Float32Array(2*u),2),g=0,y=0,x=t,_=(e-t)/r,b=new s,w=new i;for(h=0;h<=r;h++){for(l=0;l<=n;l++)c=a+l/n*o,b.x=x*Math.cos(c),b.y=x*Math.sin(c),f.setXYZ(g,b.x,b.y,b.z),m.setXYZ(g,0,0,1),w.x=(b.x/e+1)/2,w.y=(b.y/e+1)/2,v.setXY(g,w.x,w.y),g++;x+=_}for(h=0;h65535?Uint32Array:Uint16Array)(u),1),d=new U(new Float32Array(3*l),3),f=new U(new Float32Array(2*l),2),m=0,v=0,g=1/n,y=new s,x=new i;for(c=0;c<=n;c++){var _=r+c*g*a,b=Math.sin(_),w=Math.cos(_);for(h=0;h<=e.length-1;h++)y.x=e[h].x*b,y.y=e[h].y,y.z=e[h].x*w,d.setXYZ(m,y.x,y.y,y.z),x.x=c/n,x.y=h/(e.length-1),f.setXY(m,x.x,x.y),m++}for(c=0;c0?1:+t}),void 0===Function.prototype.name&&Object.defineProperty(Function.prototype,"name",{get:function(){return this.toString().match(/^\s*function\s*(\S*)\s*\(/)[1]; +}}),void 0===Object.assign&&!function(){Object.assign=function(t){if(void 0===t||null===t)throw new TypeError("Cannot convert undefined or null to object");for(var e=Object(t),i=1;i>=4,i[r]=e[19===r?3&t|8:t]);return i.join("")}}(),clamp:function(t,e,i){return Math.max(e,Math.min(i,t))},euclideanModulo:function(t,e){return(t%e+e)%e},mapLinear:function(t,e,i,n,r){return n+(t-e)*(r-n)/(i-e)},smoothstep:function(t,e,i){return t<=e?0:t>=i?1:(t=(t-e)/(i-e),t*t*(3-2*t))},smootherstep:function(t,e,i){return t<=e?0:t>=i?1:(t=(t-e)/(i-e),t*t*t*(t*(6*t-15)+10))},random16:function(){return console.warn("THREE.Math.random16() has been deprecated. Use Math.random() instead."),Math.random()},randInt:function(t,e){return t+Math.floor(Math.random()*(e-t+1))},randFloat:function(t,e){return t+Math.random()*(e-t)},randFloatSpread:function(t){return t*(.5-Math.random())},degToRad:function(e){return e*t.Math.DEG2RAD},radToDeg:function(e){return e*t.Math.RAD2DEG},isPowerOfTwo:function(t){return 0===(t&t-1)&&0!==t},nearestPowerOfTwo:function(t){return Math.pow(2,Math.round(Math.log(t)/Math.LN2))},nextPowerOfTwo:function(t){return t--,t|=t>>1,t|=t>>2,t|=t>>4,t|=t>>8,t|=t>>16,t++,t}},i.prototype={constructor:i,isVector2:!0,get width(){return this.x},set width(t){this.x=t},get height(){return this.y},set height(t){this.y=t},set:function(t,e){return this.x=t,this.y=e,this},setScalar:function(t){return this.x=t,this.y=t,this},setX:function(t){return this.x=t,this},setY:function(t){return this.y=t,this},setComponent:function(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;default:throw new Error("index is out of range: "+t)}},getComponent:function(t){switch(t){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+t)}},clone:function(){return new this.constructor(this.x,this.y)},copy:function(t){return this.x=t.x,this.y=t.y,this},add:function(t,e){return void 0!==e?(console.warn("THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(t,e)):(this.x+=t.x,this.y+=t.y,this)},addScalar:function(t){return this.x+=t,this.y+=t,this},addVectors:function(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this},addScaledVector:function(t,e){return this.x+=t.x*e,this.y+=t.y*e,this},sub:function(t,e){return void 0!==e?(console.warn("THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(t,e)):(this.x-=t.x,this.y-=t.y,this)},subScalar:function(t){return this.x-=t,this.y-=t,this},subVectors:function(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this},multiply:function(t){return this.x*=t.x,this.y*=t.y,this},multiplyScalar:function(t){return isFinite(t)?(this.x*=t,this.y*=t):(this.x=0,this.y=0),this},divide:function(t){return this.x/=t.x,this.y/=t.y,this},divideScalar:function(t){return this.multiplyScalar(1/t)},min:function(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this},max:function(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this},clamp:function(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this},clampScalar:function(){var t,e;return function(n,r){return void 0===t&&(t=new i,e=new i),t.set(n,n),e.set(r,r),this.clamp(t,e)}}(),clampLength:function(t,e){var i=this.length();return this.multiplyScalar(Math.max(t,Math.min(e,i))/i)},floor:function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this},ceil:function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this},round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},roundToZero:function(){return this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x),this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y),this},negate:function(){return this.x=-this.x,this.y=-this.y,this},dot:function(t){return this.x*t.x+this.y*t.y},lengthSq:function(){return this.x*this.x+this.y*this.y},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},lengthManhattan:function(){return Math.abs(this.x)+Math.abs(this.y)},normalize:function(){return this.divideScalar(this.length())},angle:function(){var t=Math.atan2(this.y,this.x);return t<0&&(t+=2*Math.PI),t},distanceTo:function(t){return Math.sqrt(this.distanceToSquared(t))},distanceToSquared:function(t){var e=this.x-t.x,i=this.y-t.y;return e*e+i*i},distanceToManhattan:function(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)},setLength:function(t){return this.multiplyScalar(t/this.length())},lerp:function(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this},lerpVectors:function(t,e,i){return this.subVectors(e,t).multiplyScalar(i).add(t)},equals:function(t){return t.x===this.x&&t.y===this.y},fromArray:function(t,e){return void 0===e&&(e=0),this.x=t[e],this.y=t[e+1],this},toArray:function(t,e){return void 0===t&&(t=[]),void 0===e&&(e=0),t[e]=this.x,t[e+1]=this.y,t},fromAttribute:function(t,e,i){return void 0===i&&(i=0),e=e*t.itemSize+i,this.x=t.array[e],this.y=t.array[e+1],this},rotateAround:function(t,e){var i=Math.cos(e),n=Math.sin(e),r=this.x-t.x,a=this.y-t.y;return this.x=r*i-a*n+t.x,this.y=r*n+a*i+t.y,this}},n.DEFAULT_IMAGE=void 0,n.DEFAULT_MAPPING=lr,n.prototype={constructor:n,isTexture:!0,set needsUpdate(t){t===!0&&this.version++},clone:function(){return(new this.constructor).copy(this)},copy:function(t){return this.image=t.image,this.mipmaps=t.mipmaps.slice(0),this.mapping=t.mapping,this.wrapS=t.wrapS,this.wrapT=t.wrapT,this.magFilter=t.magFilter,this.minFilter=t.minFilter,this.anisotropy=t.anisotropy,this.format=t.format,this.type=t.type,this.offset.copy(t.offset),this.repeat.copy(t.repeat),this.generateMipmaps=t.generateMipmaps,this.premultiplyAlpha=t.premultiplyAlpha,this.flipY=t.flipY,this.unpackAlignment=t.unpackAlignment,this.encoding=t.encoding,this},toJSON:function(e){function i(t){var e;return void 0!==t.toDataURL?e=t:(e=document.createElementNS("http://www.w3.org/1999/xhtml","canvas"),e.width=t.width,e.height=t.height,e.getContext("2d").drawImage(t,0,0,t.width,t.height)),e.width>2048||e.height>2048?e.toDataURL("image/jpeg",.6):e.toDataURL("image/png")}if(void 0!==e.textures[this.uuid])return e.textures[this.uuid];var n={metadata:{version:4.4,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,mapping:this.mapping,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],wrap:[this.wrapS,this.wrapT],minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY};if(void 0!==this.image){var r=this.image;void 0===r.uuid&&(r.uuid=t.Math.generateUUID()),void 0===e.images[r.uuid]&&(e.images[r.uuid]={uuid:r.uuid,url:i(r)}),n.image=r.uuid}return e.textures[this.uuid]=n,n},dispose:function(){this.dispatchEvent({type:"dispose"})},transformUv:function(t){if(this.mapping===lr){if(t.multiply(this.repeat),t.add(this.offset),t.x<0||t.x>1)switch(this.wrapS){case yr:t.x=t.x-Math.floor(t.x);break;case xr:t.x=t.x<0?0:1;break;case _r:1===Math.abs(Math.floor(t.x)%2)?t.x=Math.ceil(t.x)-t.x:t.x=t.x-Math.floor(t.x)}if(t.y<0||t.y>1)switch(this.wrapT){case yr:t.y=t.y-Math.floor(t.y);break;case xr:t.y=t.y<0?0:1;break;case _r:1===Math.abs(Math.floor(t.y)%2)?t.y=Math.ceil(t.y)-t.y:t.y=t.y-Math.floor(t.y)}this.flipY&&(t.y=1-t.y)}}},Object.assign(n.prototype,e.prototype);var Ea=0;a.prototype={constructor:a,isMatrix4:!0,set:function(t,e,i,n,r,a,o,s,c,h,l,u,p,d,f,m){var v=this.elements;return v[0]=t,v[4]=e,v[8]=i,v[12]=n,v[1]=r,v[5]=a,v[9]=o,v[13]=s,v[2]=c,v[6]=h,v[10]=l,v[14]=u,v[3]=p,v[7]=d,v[11]=f,v[15]=m,this},identity:function(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this},clone:function(){return(new a).fromArray(this.elements)},copy:function(t){return this.elements.set(t.elements),this},copyPosition:function(t){var e=this.elements,i=t.elements;return e[12]=i[12],e[13]=i[13],e[14]=i[14],this},extractBasis:function(t,e,i){return t.setFromMatrixColumn(this,0),e.setFromMatrixColumn(this,1),i.setFromMatrixColumn(this,2),this},makeBasis:function(t,e,i){return this.set(t.x,e.x,i.x,0,t.y,e.y,i.y,0,t.z,e.z,i.z,0,0,0,0,1),this},extractRotation:function(){var t;return function(e){void 0===t&&(t=new s);var i=this.elements,n=e.elements,r=1/t.setFromMatrixColumn(e,0).length(),a=1/t.setFromMatrixColumn(e,1).length(),o=1/t.setFromMatrixColumn(e,2).length();return i[0]=n[0]*r,i[1]=n[1]*r,i[2]=n[2]*r,i[4]=n[4]*a,i[5]=n[5]*a,i[6]=n[6]*a,i[8]=n[8]*o,i[9]=n[9]*o,i[10]=n[10]*o,this}}(),makeRotationFromEuler:function(t){(t&&t.isEuler)===!1&&console.error("THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.");var e=this.elements,i=t.x,n=t.y,r=t.z,a=Math.cos(i),o=Math.sin(i),s=Math.cos(n),c=Math.sin(n),h=Math.cos(r),l=Math.sin(r);if("XYZ"===t.order){var u=a*h,p=a*l,d=o*h,f=o*l;e[0]=s*h,e[4]=-s*l,e[8]=c,e[1]=p+d*c,e[5]=u-f*c,e[9]=-o*s,e[2]=f-u*c,e[6]=d+p*c,e[10]=a*s}else if("YXZ"===t.order){var m=s*h,v=s*l,g=c*h,y=c*l;e[0]=m+y*o,e[4]=g*o-v,e[8]=a*c,e[1]=a*l,e[5]=a*h,e[9]=-o,e[2]=v*o-g,e[6]=y+m*o,e[10]=a*s}else if("ZXY"===t.order){var m=s*h,v=s*l,g=c*h,y=c*l;e[0]=m-y*o,e[4]=-a*l,e[8]=g+v*o,e[1]=v+g*o,e[5]=a*h,e[9]=y-m*o,e[2]=-a*c,e[6]=o,e[10]=a*s}else if("ZYX"===t.order){var u=a*h,p=a*l,d=o*h,f=o*l;e[0]=s*h,e[4]=d*c-p,e[8]=u*c+f,e[1]=s*l,e[5]=f*c+u,e[9]=p*c-d,e[2]=-c,e[6]=o*s,e[10]=a*s}else if("YZX"===t.order){var x=a*s,_=a*c,b=o*s,w=o*c;e[0]=s*h,e[4]=w-x*l,e[8]=b*l+_,e[1]=l,e[5]=a*h,e[9]=-o*h,e[2]=-c*h,e[6]=_*l+b,e[10]=x-w*l}else if("XZY"===t.order){var x=a*s,_=a*c,b=o*s,w=o*c;e[0]=s*h,e[4]=-l,e[8]=c*h,e[1]=x*l+w,e[5]=a*h,e[9]=_*l-b,e[2]=b*l-_,e[6]=o*h,e[10]=w*l+x}return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this},makeRotationFromQuaternion:function(t){var e=this.elements,i=t.x,n=t.y,r=t.z,a=t.w,o=i+i,s=n+n,c=r+r,h=i*o,l=i*s,u=i*c,p=n*s,d=n*c,f=r*c,m=a*o,v=a*s,g=a*c;return e[0]=1-(p+f),e[4]=l-g,e[8]=u+v,e[1]=l+g,e[5]=1-(h+f),e[9]=d-m,e[2]=u-v,e[6]=d+m,e[10]=1-(h+p),e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this},lookAt:function(){var t,e,i;return function(n,r,a){void 0===t&&(t=new s,e=new s,i=new s);var o=this.elements;return i.subVectors(n,r).normalize(),0===i.lengthSq()&&(i.z=1),t.crossVectors(a,i).normalize(),0===t.lengthSq()&&(i.z+=1e-4,t.crossVectors(a,i).normalize()),e.crossVectors(i,t),o[0]=t.x,o[4]=e.x,o[8]=i.x,o[1]=t.y,o[5]=e.y,o[9]=i.y,o[2]=t.z,o[6]=e.z,o[10]=i.z,this}}(),multiply:function(t,e){return void 0!==e?(console.warn("THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead."),this.multiplyMatrices(t,e)):this.multiplyMatrices(this,t)},premultiply:function(t){return this.multiplyMatrices(t,this)},multiplyMatrices:function(t,e){var i=t.elements,n=e.elements,r=this.elements,a=i[0],o=i[4],s=i[8],c=i[12],h=i[1],l=i[5],u=i[9],p=i[13],d=i[2],f=i[6],m=i[10],v=i[14],g=i[3],y=i[7],x=i[11],_=i[15],b=n[0],w=n[4],M=n[8],E=n[12],T=n[1],S=n[5],A=n[9],L=n[13],R=n[2],P=n[6],C=n[10],U=n[14],I=n[3],D=n[7],N=n[11],O=n[15];return r[0]=a*b+o*T+s*R+c*I,r[4]=a*w+o*S+s*P+c*D,r[8]=a*M+o*A+s*C+c*N,r[12]=a*E+o*L+s*U+c*O,r[1]=h*b+l*T+u*R+p*I,r[5]=h*w+l*S+u*P+p*D,r[9]=h*M+l*A+u*C+p*N,r[13]=h*E+l*L+u*U+p*O,r[2]=d*b+f*T+m*R+v*I,r[6]=d*w+f*S+m*P+v*D,r[10]=d*M+f*A+m*C+v*N,r[14]=d*E+f*L+m*U+v*O,r[3]=g*b+y*T+x*R+_*I,r[7]=g*w+y*S+x*P+_*D,r[11]=g*M+y*A+x*C+_*N,r[15]=g*E+y*L+x*U+_*O,this},multiplyToArray:function(t,e,i){var n=this.elements;return this.multiplyMatrices(t,e),i[0]=n[0],i[1]=n[1],i[2]=n[2],i[3]=n[3],i[4]=n[4],i[5]=n[5],i[6]=n[6],i[7]=n[7],i[8]=n[8],i[9]=n[9],i[10]=n[10],i[11]=n[11],i[12]=n[12],i[13]=n[13],i[14]=n[14],i[15]=n[15],this},multiplyScalar:function(t){var e=this.elements;return e[0]*=t,e[4]*=t,e[8]*=t,e[12]*=t,e[1]*=t,e[5]*=t,e[9]*=t,e[13]*=t,e[2]*=t,e[6]*=t,e[10]*=t,e[14]*=t,e[3]*=t,e[7]*=t,e[11]*=t,e[15]*=t,this},applyToVector3Array:function(){var t;return function(e,i,n){void 0===t&&(t=new s),void 0===i&&(i=0),void 0===n&&(n=e.length);for(var r=0,a=i;r0?(e=.5/Math.sqrt(p+1),this._w=.25/e,this._x=(l-c)*e,this._y=(a-h)*e,this._z=(o-r)*e):n>s&&n>u?(e=2*Math.sqrt(1+n-s-u),this._w=(l-c)/e,this._x=.25*e,this._y=(r+o)/e,this._z=(a+h)/e):s>u?(e=2*Math.sqrt(1+s-n-u),this._w=(a-h)/e,this._x=(r+o)/e,this._y=.25*e,this._z=(c+l)/e):(e=2*Math.sqrt(1+u-n-s),this._w=(o-r)/e,this._x=(a+h)/e,this._y=(c+l)/e,this._z=.25*e),this.onChangeCallback(),this},setFromUnitVectors:function(){var t,e,i=1e-6;return function(n,r){return void 0===t&&(t=new s),e=n.dot(r)+1,eMath.abs(n.z)?t.set(-n.y,n.x,0):t.set(0,-n.z,n.y)):t.crossVectors(n,r),this._x=t.x,this._y=t.y,this._z=t.z,this._w=e,this.normalize()}}(),inverse:function(){return this.conjugate().normalize()},conjugate:function(){return this._x*=-1,this._y*=-1,this._z*=-1,this.onChangeCallback(),this},dot:function(t){return this._x*t._x+this._y*t._y+this._z*t._z+this._w*t._w},lengthSq:function(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w},length:function(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)},normalize:function(){var t=this.length();return 0===t?(this._x=0,this._y=0,this._z=0,this._w=1):(t=1/t,this._x=this._x*t,this._y=this._y*t,this._z=this._z*t,this._w=this._w*t),this.onChangeCallback(),this},multiply:function(t,e){return void 0!==e?(console.warn("THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead."),this.multiplyQuaternions(t,e)):this.multiplyQuaternions(this,t)},premultiply:function(t){return this.multiplyQuaternions(t,this)},multiplyQuaternions:function(t,e){var i=t._x,n=t._y,r=t._z,a=t._w,o=e._x,s=e._y,c=e._z,h=e._w;return this._x=i*h+a*o+n*c-r*s,this._y=n*h+a*s+r*o-i*c,this._z=r*h+a*c+i*s-n*o,this._w=a*h-i*o-n*s-r*c,this.onChangeCallback(),this},slerp:function(t,e){if(0===e)return this;if(1===e)return this.copy(t);var i=this._x,n=this._y,r=this._z,a=this._w,o=a*t._w+i*t._x+n*t._y+r*t._z;if(o<0?(this._w=-t._w,this._x=-t._x,this._y=-t._y,this._z=-t._z,o=-o):this.copy(t),o>=1)return this._w=a,this._x=i,this._y=n,this._z=r,this;var s=Math.sqrt(1-o*o);if(Math.abs(s)<.001)return this._w=.5*(a+this._w),this._x=.5*(i+this._x),this._y=.5*(n+this._y),this._z=.5*(r+this._z),this;var c=Math.atan2(s,o),h=Math.sin((1-e)*c)/s,l=Math.sin(e*c)/s;return this._w=a*h+this._w*l,this._x=i*h+this._x*l,this._y=n*h+this._y*l,this._z=r*h+this._z*l,this.onChangeCallback(),this},equals:function(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._w===this._w},fromArray:function(t,e){return void 0===e&&(e=0),this._x=t[e],this._y=t[e+1],this._z=t[e+2],this._w=t[e+3],this.onChangeCallback(),this},toArray:function(t,e){return void 0===t&&(t=[]),void 0===e&&(e=0),t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._w,t},onChange:function(t){return this.onChangeCallback=t,this},onChangeCallback:function(){}},Object.assign(o,{slerp:function(t,e,i,n){return i.copy(t).slerp(e,n)},slerpFlat:function(t,e,i,n,r,a,o){var s=i[n+0],c=i[n+1],h=i[n+2],l=i[n+3],u=r[a+0],p=r[a+1],d=r[a+2],f=r[a+3];if(l!==f||s!==u||c!==p||h!==d){var m=1-o,v=s*u+c*p+h*d+l*f,g=v>=0?1:-1,y=1-v*v;if(y>Number.EPSILON){var x=Math.sqrt(y),_=Math.atan2(x,v*g);m=Math.sin(m*_)/x,o=Math.sin(o*_)/x}var b=o*g;if(s=s*m+u*b,c=c*m+p*b,h=h*m+d*b,l=l*m+f*b,m===1-o){var w=1/Math.sqrt(s*s+c*c+h*h+l*l);s*=w,c*=w,h*=w,l*=w}}t[e]=s,t[e+1]=c,t[e+2]=h,t[e+3]=l}}),s.prototype={constructor:s,isVector3:!0,set:function(t,e,i){return this.x=t,this.y=e,this.z=i,this},setScalar:function(t){return this.x=t,this.y=t,this.z=t,this},setX:function(t){return this.x=t,this},setY:function(t){return this.y=t,this},setZ:function(t){return this.z=t,this},setComponent:function(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;default:throw new Error("index is out of range: "+t)}},getComponent:function(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+t)}},clone:function(){return new this.constructor(this.x,this.y,this.z)},copy:function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},add:function(t,e){return void 0!==e?(console.warn("THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(t,e)):(this.x+=t.x,this.y+=t.y,this.z+=t.z,this)},addScalar:function(t){return this.x+=t,this.y+=t,this.z+=t,this},addVectors:function(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this},addScaledVector:function(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this},sub:function(t,e){return void 0!==e?(console.warn("THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(t,e)):(this.x-=t.x,this.y-=t.y,this.z-=t.z,this)},subScalar:function(t){return this.x-=t,this.y-=t,this.z-=t,this},subVectors:function(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this},multiply:function(t,e){return void 0!==e?(console.warn("THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead."),this.multiplyVectors(t,e)):(this.x*=t.x,this.y*=t.y,this.z*=t.z,this)},multiplyScalar:function(t){return isFinite(t)?(this.x*=t,this.y*=t,this.z*=t):(this.x=0,this.y=0,this.z=0),this},multiplyVectors:function(t,e){return this.x=t.x*e.x,this.y=t.y*e.y,this.z=t.z*e.z,this},applyEuler:function(){var t;return function(e){return(e&&e.isEuler)===!1&&console.error("THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order."),void 0===t&&(t=new o),this.applyQuaternion(t.setFromEuler(e))}}(),applyAxisAngle:function(){var t;return function(e,i){return void 0===t&&(t=new o),this.applyQuaternion(t.setFromAxisAngle(e,i))}}(),applyMatrix3:function(t){var e=this.x,i=this.y,n=this.z,r=t.elements;return this.x=r[0]*e+r[3]*i+r[6]*n,this.y=r[1]*e+r[4]*i+r[7]*n,this.z=r[2]*e+r[5]*i+r[8]*n,this},applyMatrix4:function(t){var e=this.x,i=this.y,n=this.z,r=t.elements;return this.x=r[0]*e+r[4]*i+r[8]*n+r[12],this.y=r[1]*e+r[5]*i+r[9]*n+r[13],this.z=r[2]*e+r[6]*i+r[10]*n+r[14],this},applyProjection:function(t){var e=this.x,i=this.y,n=this.z,r=t.elements,a=1/(r[3]*e+r[7]*i+r[11]*n+r[15]);return this.x=(r[0]*e+r[4]*i+r[8]*n+r[12])*a,this.y=(r[1]*e+r[5]*i+r[9]*n+r[13])*a,this.z=(r[2]*e+r[6]*i+r[10]*n+r[14])*a,this},applyQuaternion:function(t){var e=this.x,i=this.y,n=this.z,r=t.x,a=t.y,o=t.z,s=t.w,c=s*e+a*n-o*i,h=s*i+o*e-r*n,l=s*n+r*i-a*e,u=-r*e-a*i-o*n;return this.x=c*s+u*-r+h*-o-l*-a,this.y=h*s+u*-a+l*-r-c*-o,this.z=l*s+u*-o+c*-a-h*-r,this},project:function(){var t;return function(e){return void 0===t&&(t=new a),t.multiplyMatrices(e.projectionMatrix,t.getInverse(e.matrixWorld)),this.applyProjection(t)}}(),unproject:function(){var t;return function(e){return void 0===t&&(t=new a),t.multiplyMatrices(e.matrixWorld,t.getInverse(e.projectionMatrix)),this.applyProjection(t)}}(),transformDirection:function(t){var e=this.x,i=this.y,n=this.z,r=t.elements;return this.x=r[0]*e+r[4]*i+r[8]*n,this.y=r[1]*e+r[5]*i+r[9]*n,this.z=r[2]*e+r[6]*i+r[10]*n,this.normalize()},divide:function(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this},divideScalar:function(t){return this.multiplyScalar(1/t)},min:function(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this},max:function(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this},clamp:function(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this.z=Math.max(t.z,Math.min(e.z,this.z)),this},clampScalar:function(){var t,e;return function(i,n){return void 0===t&&(t=new s,e=new s),t.set(i,i,i),e.set(n,n,n),this.clamp(t,e)}}(),clampLength:function(t,e){var i=this.length();return this.multiplyScalar(Math.max(t,Math.min(e,i))/i)},floor:function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this},ceil:function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this},round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this},roundToZero:function(){return this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x),this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y),this.z=this.z<0?Math.ceil(this.z):Math.floor(this.z),this},negate:function(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this},dot:function(t){return this.x*t.x+this.y*t.y+this.z*t.z},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},lengthManhattan:function(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)},normalize:function(){return this.divideScalar(this.length())},setLength:function(t){return this.multiplyScalar(t/this.length())},lerp:function(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this},lerpVectors:function(t,e,i){return this.subVectors(e,t).multiplyScalar(i).add(t)},cross:function(t,e){if(void 0!==e)return console.warn("THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead."),this.crossVectors(t,e);var i=this.x,n=this.y,r=this.z;return this.x=n*t.z-r*t.y,this.y=r*t.x-i*t.z,this.z=i*t.y-n*t.x,this},crossVectors:function(t,e){var i=t.x,n=t.y,r=t.z,a=e.x,o=e.y,s=e.z;return this.x=n*s-r*o,this.y=r*a-i*s,this.z=i*o-n*a,this},projectOnVector:function(t){var e=t.dot(this)/t.lengthSq();return this.copy(t).multiplyScalar(e)},projectOnPlane:function(){var t;return function(e){return void 0===t&&(t=new s),t.copy(this).projectOnVector(e),this.sub(t)}}(),reflect:function(){var t;return function(e){return void 0===t&&(t=new s),this.sub(t.copy(e).multiplyScalar(2*this.dot(e)))}}(),angleTo:function(e){var i=this.dot(e)/Math.sqrt(this.lengthSq()*e.lengthSq());return Math.acos(t.Math.clamp(i,-1,1))},distanceTo:function(t){return Math.sqrt(this.distanceToSquared(t))},distanceToSquared:function(t){var e=this.x-t.x,i=this.y-t.y,n=this.z-t.z;return e*e+i*i+n*n},distanceToManhattan:function(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)+Math.abs(this.z-t.z)},setFromSpherical:function(t){var e=Math.sin(t.phi)*t.radius;return this.x=e*Math.sin(t.theta),this.y=Math.cos(t.phi)*t.radius,this.z=e*Math.cos(t.theta),this},setFromMatrixPosition:function(t){return this.setFromMatrixColumn(t,3)},setFromMatrixScale:function(t){var e=this.setFromMatrixColumn(t,0).length(),i=this.setFromMatrixColumn(t,1).length(),n=this.setFromMatrixColumn(t,2).length();return this.x=e,this.y=i,this.z=n,this},setFromMatrixColumn:function(t,e){if("number"==typeof t){console.warn("THREE.Vector3: setFromMatrixColumn now expects ( matrix, index ).");var i=t;t=e,e=i}return this.fromArray(t.elements,4*e)},equals:function(t){return t.x===this.x&&t.y===this.y&&t.z===this.z},fromArray:function(t,e){return void 0===e&&(e=0),this.x=t[e],this.y=t[e+1],this.z=t[e+2],this},toArray:function(t,e){return void 0===t&&(t=[]),void 0===e&&(e=0),t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t},fromAttribute:function(t,e,i){return void 0===i&&(i=0),e=e*t.itemSize+i,this.x=t.array[e],this.y=t.array[e+1], +this.z=t.array[e+2],this}},h.prototype={constructor:h,set:function(t,e){return this.min.copy(t),this.max.copy(e),this},setFromPoints:function(t){this.makeEmpty();for(var e=0,i=t.length;ethis.max.x||t.ythis.max.y)},containsBox:function(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y},getParameter:function(t,e){var n=e||new i;return n.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y))},intersectsBox:function(t){return!(t.max.xthis.max.x||t.max.ythis.max.y)},clampPoint:function(t,e){var n=e||new i;return n.copy(t).clamp(this.min,this.max)},distanceToPoint:function(){var t=new i;return function(e){var i=t.copy(e).clamp(this.min,this.max);return i.sub(e).length()}}(),intersect:function(t){return this.min.max(t.min),this.max.min(t.max),this},union:function(t){return this.min.min(t.min),this.max.max(t.max),this},translate:function(t){return this.min.add(t),this.max.add(t),this},equals:function(t){return t.min.equals(this.min)&&t.max.equals(this.max)}},u.prototype=Object.create(n.prototype),u.prototype.constructor=u,u.prototype.isCubeTexture=!0,Object.defineProperty(u.prototype,"images",{get:function(){return this.image},set:function(t){this.image=t}}),t.WebGLUniforms=function(){var t=new n,e=new u,i=function(){this.seq=[],this.map={}},r=[],a=[],o=function(t,e,i){var n=t[0];if(n<=0||n>0)return t;var a=e*i,o=r[a];if(void 0===o&&(o=new Float32Array(a),r[a]=o),0!==e){n.toArray(o,0);for(var s=1,c=0;s!==e;++s)c+=i,t[s].toArray(o,c)}return o},s=function(t,e){var i=a[e];void 0===i&&(i=new Int32Array(e),a[e]=i);for(var n=0;n!==e;++n)i[n]=t.allocTextureUnit();return i},c=function(t,e){t.uniform1f(this.addr,e)},h=function(t,e){t.uniform1i(this.addr,e)},l=function(t,e){void 0===e.x?t.uniform2fv(this.addr,e):t.uniform2f(this.addr,e.x,e.y)},p=function(t,e){void 0!==e.x?t.uniform3f(this.addr,e.x,e.y,e.z):void 0!==e.r?t.uniform3f(this.addr,e.r,e.g,e.b):t.uniform3fv(this.addr,e)},d=function(t,e){void 0===e.x?t.uniform4fv(this.addr,e):t.uniform4f(this.addr,e.x,e.y,e.z,e.w)},f=function(t,e){t.uniformMatrix2fv(this.addr,!1,e.elements||e)},m=function(t,e){t.uniformMatrix3fv(this.addr,!1,e.elements||e)},v=function(t,e){t.uniformMatrix4fv(this.addr,!1,e.elements||e)},g=function(e,i,n){var r=n.allocTextureUnit();e.uniform1i(this.addr,r),n.setTexture2D(i||t,r)},y=function(t,i,n){var r=n.allocTextureUnit();t.uniform1i(this.addr,r),n.setTextureCube(i||e,r)},x=function(t,e){t.uniform2iv(this.addr,e)},_=function(t,e){t.uniform3iv(this.addr,e)},b=function(t,e){t.uniform4iv(this.addr,e)},w=function(t){switch(t){case 5126:return c;case 35664:return l;case 35665:return p;case 35666:return d;case 35674:return f;case 35675:return m;case 35676:return v;case 35678:return g;case 35680:return y;case 5124:case 35670:return h;case 35667:case 35671:return x;case 35668:case 35672:return _;case 35669:case 35673:return b}},M=function(t,e){t.uniform1fv(this.addr,e)},E=function(t,e){t.uniform1iv(this.addr,e)},T=function(t,e){t.uniform2fv(this.addr,o(e,this.size,2))},S=function(t,e){t.uniform3fv(this.addr,o(e,this.size,3))},A=function(t,e){t.uniform4fv(this.addr,o(e,this.size,4))},L=function(t,e){t.uniformMatrix2fv(this.addr,!1,o(e,this.size,4))},R=function(t,e){t.uniformMatrix3fv(this.addr,!1,o(e,this.size,9))},P=function(t,e){t.uniformMatrix4fv(this.addr,!1,o(e,this.size,16))},C=function(e,i,n){var r=i.length,a=s(n,r);e.uniform1iv(this.addr,a);for(var o=0;o!==r;++o)n.setTexture2D(i[o]||t,a[o])},U=function(t,i,n){var r=i.length,a=s(n,r);t.uniform1iv(this.addr,a);for(var o=0;o!==r;++o)n.setTextureCube(i[o]||e,a[o])},I=function(t){switch(t){case 5126:return M;case 35664:return T;case 35665:return S;case 35666:return A;case 35674:return L;case 35675:return R;case 35676:return P;case 35678:return C;case 35680:return U;case 5124:case 35670:return E;case 35667:case 35671:return x;case 35668:case 35672:return _;case 35669:case 35673:return b}},D=function(t,e,i){this.id=t,this.addr=i,this.setValue=w(e.type)},N=function(t,e,i){this.id=t,this.addr=i,this.size=e.size,this.setValue=I(e.type)},O=function(t){this.id=t,i.call(this)};O.prototype.setValue=function(t,e){for(var i=this.seq,n=0,r=i.length;n!==r;++n){var a=i[n];a.setValue(t,e[a.id])}};var F=/([\w\d_]+)(\])?(\[|\.)?/g,z=function(t,e){t.seq.push(e),t.map[e.id]=e},B=function(t,e,i){var n=t.name,r=n.length;for(F.lastIndex=0;;){var a=F.exec(n),o=F.lastIndex,s=a[1],c="]"===a[2],h=a[3];if(c&&(s=0|s),void 0===h||"["===h&&o+2===r){z(i,void 0===h?new D(s,t,e):new N(s,t,e));break}var l=i.map,u=l[s];void 0===u&&(u=new O(s),z(i,u)),i=u}},G=function(t,e,n){i.call(this),this.renderer=n;for(var r=t.getProgramParameter(e,t.ACTIVE_UNIFORMS),a=0;a!==r;++a){var o=t.getActiveUniform(e,a),s=o.name,c=t.getUniformLocation(e,s);B(o,c,this)}};return G.prototype.setValue=function(t,e,i){var n=this.map[e];void 0!==n&&n.setValue(t,i,this.renderer)},G.prototype.set=function(t,e,i){var n=this.map[i];void 0!==n&&n.setValue(t,e[i],this.renderer)},G.prototype.setOptional=function(t,e,i){var n=e[i];void 0!==n&&this.setValue(t,i,n)},G.upload=function(t,e,i,n){for(var r=0,a=e.length;r!==a;++r){var o=e[r],s=i[o.id];s.needsUpdate!==!1&&o.setValue(t,s.value,n)}},G.seqWithValue=function(t,e){for(var i=[],n=0,r=t.length;n!==r;++n){var a=t[n];a.id in e&&i.push(a)}return i},G.splitDynamic=function(t,e){for(var i=null,n=t.length,r=0,a=0;a!==n;++a){var o=t[a],s=e[o.id];s&&s.dynamic===!0?(null===i&&(i=[]),i.push(o)):(ry&&g>x?gx?y0&&(n.alphaTest=this.alphaTest),this.premultipliedAlpha===!0&&(n.premultipliedAlpha=this.premultipliedAlpha),this.wireframe===!0&&(n.wireframe=this.wireframe),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),"round"!==this.wireframeLinecap&&(n.wireframeLinecap=this.wireframeLinecap),"round"!==this.wireframeLinejoin&&(n.wireframeLinejoin=this.wireframeLinejoin),n.skinning=this.skinning,n.morphTargets=this.morphTargets,i){var r=e(t.textures),a=e(t.images);r.length>0&&(n.textures=r),a.length>0&&(n.images=a)}return n},clone:function(){return(new this.constructor).copy(this)},copy:function(t){this.name=t.name,this.fog=t.fog,this.lights=t.lights,this.blending=t.blending,this.side=t.side,this.shading=t.shading,this.vertexColors=t.vertexColors,this.opacity=t.opacity,this.transparent=t.transparent,this.blendSrc=t.blendSrc,this.blendDst=t.blendDst,this.blendEquation=t.blendEquation,this.blendSrcAlpha=t.blendSrcAlpha,this.blendDstAlpha=t.blendDstAlpha,this.blendEquationAlpha=t.blendEquationAlpha,this.depthFunc=t.depthFunc,this.depthTest=t.depthTest,this.depthWrite=t.depthWrite,this.colorWrite=t.colorWrite,this.precision=t.precision,this.polygonOffset=t.polygonOffset,this.polygonOffsetFactor=t.polygonOffsetFactor,this.polygonOffsetUnits=t.polygonOffsetUnits,this.alphaTest=t.alphaTest,this.premultipliedAlpha=t.premultipliedAlpha,this.overdraw=t.overdraw,this.visible=t.visible,this.clipShadows=t.clipShadows;var e=t.clippingPlanes,i=null;if(null!==e){var n=e.length;i=new Array(n);for(var r=0;r!==n;++r)i[r]=e[r].clone()}return this.clippingPlanes=i,this},update:function(){this.dispatchEvent({type:"update"})},dispose:function(){this.dispatchEvent({type:"dispose"})}},Object.assign(x.prototype,e.prototype);var Ta=0;t.UniformsUtils={merge:function(t){for(var e={},i=0;i>16&255)/255,this.g=(t>>8&255)/255,this.b=(255&t)/255,this},setRGB:function(t,e,i){return this.r=t,this.g=e,this.b=i,this},setHSL:function(){function e(t,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+6*(e-t)*(2/3-i):t}return function(i,n,r){if(i=t.Math.euclideanModulo(i,1),n=t.Math.clamp(n,0,1),r=t.Math.clamp(r,0,1),0===n)this.r=this.g=this.b=r;else{var a=r<=.5?r*(1+n):r+n-r*n,o=2*r-a;this.r=e(o,a,i+1/3),this.g=e(o,a,i),this.b=e(o,a,i-1/3)}return this}}(),setStyle:function(e){function i(t){void 0!==t&&parseFloat(t)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}var n;if(n=/^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec(e)){var r,a=n[1],o=n[2];switch(a){case"rgb":case"rgba":if(r=/^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(o))return this.r=Math.min(255,parseInt(r[1],10))/255,this.g=Math.min(255,parseInt(r[2],10))/255,this.b=Math.min(255,parseInt(r[3],10))/255,i(r[5]),this;if(r=/^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(o))return this.r=Math.min(100,parseInt(r[1],10))/100,this.g=Math.min(100,parseInt(r[2],10))/100,this.b=Math.min(100,parseInt(r[3],10))/100,i(r[5]),this;break;case"hsl":case"hsla":if(r=/^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(o)){var s=parseFloat(r[1])/360,c=parseInt(r[2],10)/100,h=parseInt(r[3],10)/100;return i(r[5]),this.setHSL(s,c,h)}}}else if(n=/^\#([A-Fa-f0-9]+)$/.exec(e)){var l=n[1],u=l.length;if(3===u)return this.r=parseInt(l.charAt(0)+l.charAt(0),16)/255,this.g=parseInt(l.charAt(1)+l.charAt(1),16)/255,this.b=parseInt(l.charAt(2)+l.charAt(2),16)/255,this;if(6===u)return this.r=parseInt(l.charAt(0)+l.charAt(1),16)/255,this.g=parseInt(l.charAt(2)+l.charAt(3),16)/255,this.b=parseInt(l.charAt(4)+l.charAt(5),16)/255,this}if(e&&e.length>0){var l=t.ColorKeywords[e];void 0!==l?this.setHex(l):console.warn("THREE.Color: Unknown color "+e)}return this},clone:function(){return new this.constructor(this.r,this.g,this.b)},copy:function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},copyGammaToLinear:function(t,e){return void 0===e&&(e=2),this.r=Math.pow(t.r,e),this.g=Math.pow(t.g,e),this.b=Math.pow(t.b,e),this},copyLinearToGamma:function(t,e){void 0===e&&(e=2);var i=e>0?1/e:1;return this.r=Math.pow(t.r,i),this.g=Math.pow(t.g,i),this.b=Math.pow(t.b,i),this},convertGammaToLinear:function(){var t=this.r,e=this.g,i=this.b;return this.r=t*t,this.g=e*e,this.b=i*i,this},convertLinearToGamma:function(){return this.r=Math.sqrt(this.r),this.g=Math.sqrt(this.g),this.b=Math.sqrt(this.b),this},getHex:function(){return 255*this.r<<16^255*this.g<<8^255*this.b<<0},getHexString:function(){return("000000"+this.getHex().toString(16)).slice(-6)},getHSL:function(t){var e,i,n=t||{h:0,s:0,l:0},r=this.r,a=this.g,o=this.b,s=Math.max(r,a,o),c=Math.min(r,a,o),h=(c+s)/2;if(c===s)e=0,i=0;else{var l=s-c;switch(i=h<=.5?l/(s+c):l/(2-s-c),s){case r:e=(a-o)/l+(ar&&(r=h),l>a&&(a=l),u>o&&(o=u)}this.min.set(e,i,n),this.max.set(r,a,o)},setFromPoints:function(t){this.makeEmpty();for(var e=0,i=t.length;ethis.max.x||t.ythis.max.y||t.zthis.max.z)},containsBox:function(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y&&this.min.z<=t.min.z&&t.max.z<=this.max.z},getParameter:function(t,e){var i=e||new s;return i.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y),(t.z-this.min.z)/(this.max.z-this.min.z))},intersectsBox:function(t){return!(t.max.xthis.max.x||t.max.ythis.max.y||t.max.zthis.max.z)},intersectsSphere:function(){var t;return function(e){return void 0===t&&(t=new s),this.clampPoint(e.center,t),t.distanceToSquared(e.center)<=e.radius*e.radius}}(),intersectsPlane:function(t){var e,i;return t.normal.x>0?(e=t.normal.x*this.min.x,i=t.normal.x*this.max.x):(e=t.normal.x*this.max.x,i=t.normal.x*this.min.x),t.normal.y>0?(e+=t.normal.y*this.min.y,i+=t.normal.y*this.max.y):(e+=t.normal.y*this.max.y,i+=t.normal.y*this.min.y),t.normal.z>0?(e+=t.normal.z*this.min.z,i+=t.normal.z*this.max.z):(e+=t.normal.z*this.max.z,i+=t.normal.z*this.min.z),e<=t.constant&&i>=t.constant},clampPoint:function(t,e){var i=e||new s;return i.copy(t).clamp(this.min,this.max)},distanceToPoint:function(){var t=new s;return function(e){var i=t.copy(e).clamp(this.min,this.max);return i.sub(e).length()}}(),getBoundingSphere:function(){var t=new s;return function(e){var i=e||new T;return i.center=this.center(),i.radius=.5*this.size(t).length(),i}}(),intersect:function(t){return this.min.max(t.min),this.max.min(t.max),this.isEmpty()&&this.makeEmpty(),this},union:function(t){return this.min.min(t.min),this.max.max(t.max),this},applyMatrix4:function(){var t=[new s,new s,new s,new s,new s,new s,new s,new s];return function(e){return this.isEmpty()?this:(t[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),t[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),t[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),t[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),t[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),t[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),t[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),t[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(t),this)}}(),translate:function(t){return this.min.add(t),this.max.add(t),this},equals:function(t){return t.min.equals(this.min)&&t.max.equals(this.max)}},T.prototype={constructor:T,set:function(t,e){return this.center.copy(t),this.radius=e,this},setFromPoints:function(){var t=new E;return function(e,i){var n=this.center;void 0!==i?n.copy(i):t.setFromPoints(e).center(n);for(var r=0,a=0,o=e.length;athis.radius*this.radius&&(n.sub(this.center).normalize(),n.multiplyScalar(this.radius).add(this.center)),n},getBoundingBox:function(t){var e=t||new E;return e.set(this.center,this.center),e.expandByScalar(this.radius),e},applyMatrix4:function(t){return this.center.applyMatrix4(t),this.radius=this.radius*t.getMaxScaleOnAxis(),this},translate:function(t){return this.center.add(t),this},equals:function(t){return t.center.equals(this.center)&&t.radius===this.radius}},S.prototype={constructor:S,isMatrix3:!0,set:function(t,e,i,n,r,a,o,s,c){var h=this.elements;return h[0]=t,h[1]=n,h[2]=o,h[3]=e,h[4]=r,h[5]=s,h[6]=i,h[7]=a,h[8]=c,this},identity:function(){return this.set(1,0,0,0,1,0,0,0,1),this},clone:function(){return(new this.constructor).fromArray(this.elements)},copy:function(t){var e=t.elements;return this.set(e[0],e[3],e[6],e[1],e[4],e[7],e[2],e[5],e[8]),this},setFromMatrix4:function(t){var e=t.elements;return this.set(e[0],e[4],e[8],e[1],e[5],e[9],e[2],e[6],e[10]),this},applyToVector3Array:function(){var t;return function(e,i,n){void 0===t&&(t=new s),void 0===i&&(i=0),void 0===n&&(n=e.length);for(var r=0,a=i;r1))return n.copy(r).multiplyScalar(o).add(e.start)}else if(0===this.distanceToPoint(e.start))return n.copy(e.start)}}(),intersectsLine:function(t){var e=this.distanceToPoint(t.start),i=this.distanceToPoint(t.end);return e<0&&i>0||i<0&&e>0},intersectsBox:function(t){return t.intersectsPlane(this)},intersectsSphere:function(t){return t.intersectsPlane(this)},coplanarPoint:function(t){var e=t||new s;return e.copy(this.normal).multiplyScalar(-this.constant)},applyMatrix4:function(){var t=new s,e=new S;return function(i,n){var r=this.coplanarPoint(t).applyMatrix4(i),a=n||e.getNormalMatrix(i),o=this.normal.applyMatrix3(a).normalize();return this.constant=-r.dot(o),this}}(),translate:function(t){return this.constant=this.constant-t.dot(this.normal),this},equals:function(t){return t.normal.equals(this.normal)&&t.constant===this.constant}},L.prototype={constructor:L,set:function(t,e,i,n,r,a){var o=this.planes;return o[0].copy(t),o[1].copy(e),o[2].copy(i),o[3].copy(n),o[4].copy(r),o[5].copy(a),this},clone:function(){return(new this.constructor).copy(this)},copy:function(t){for(var e=this.planes,i=0;i<6;i++)e[i].copy(t.planes[i]);return this},setFromMatrix:function(t){var e=this.planes,i=t.elements,n=i[0],r=i[1],a=i[2],o=i[3],s=i[4],c=i[5],h=i[6],l=i[7],u=i[8],p=i[9],d=i[10],f=i[11],m=i[12],v=i[13],g=i[14],y=i[15];return e[0].setComponents(o-n,l-s,f-u,y-m).normalize(),e[1].setComponents(o+n,l+s,f+u,y+m).normalize(),e[2].setComponents(o+r,l+c,f+p,y+v).normalize(),e[3].setComponents(o-r,l-c,f-p,y-v).normalize(),e[4].setComponents(o-a,l-h,f-d,y-g).normalize(),e[5].setComponents(o+a,l+h,f+d,y+g).normalize(),this},intersectsObject:function(){var t=new T;return function(e){var i=e.geometry;return null===i.boundingSphere&&i.computeBoundingSphere(),t.copy(i.boundingSphere).applyMatrix4(e.matrixWorld),this.intersectsSphere(t)}}(),intersectsSprite:function(){var t=new T;return function(e){return t.center.set(0,0,0),t.radius=.7071067811865476,t.applyMatrix4(e.matrixWorld),this.intersectsSphere(t)}}(),intersectsSphere:function(t){for(var e=this.planes,i=t.center,n=-t.radius,r=0;r<6;r++){var a=e[r].distanceToPoint(i);if(a0?i.min.x:i.max.x,e.x=a.normal.x>0?i.max.x:i.min.x,t.y=a.normal.y>0?i.min.y:i.max.y,e.y=a.normal.y>0?i.max.y:i.min.y,t.z=a.normal.z>0?i.min.z:i.max.z,e.z=a.normal.z>0?i.max.z:i.min.z;var o=a.distanceToPoint(t),s=a.distanceToPoint(e);if(o<0&&s<0)return!1}return!0}}(),containsPoint:function(t){for(var e=this.planes,i=0;i<6;i++)if(e[i].distanceToPoint(t)<0)return!1;return!0}},t.WebGLShader=function(){function t(t){for(var e=t.split("\n"),i=0;i");return l(i)}var i=/#include +<([\w\d.]+)>/g;return t.replace(i,e)}function u(t){function e(t,e,i,n){for(var r="",a=parseInt(e);a0?e.gammaFactor:1,L=a(g,m,e.extensions),R=o(y),P=v.createProgram();f&&f.isRawShaderMaterial?(T=[R].filter(c).join("\n"),S=[R].filter(c).join("\n")):(T=["precision "+m.precision+" float;","precision "+m.precision+" int;","#define SHADER_NAME "+f.__webglShader.name,R,m.supportsVertexTextures?"#define VERTEX_TEXTURES":"","#define GAMMA_FACTOR "+A,"#define MAX_BONES "+m.maxBones,m.map?"#define USE_MAP":"",m.envMap?"#define USE_ENVMAP":"",m.envMap?"#define "+M:"",m.lightMap?"#define USE_LIGHTMAP":"",m.aoMap?"#define USE_AOMAP":"",m.emissiveMap?"#define USE_EMISSIVEMAP":"",m.bumpMap?"#define USE_BUMPMAP":"",m.normalMap?"#define USE_NORMALMAP":"",m.displacementMap&&m.supportsVertexTextures?"#define USE_DISPLACEMENTMAP":"",m.specularMap?"#define USE_SPECULARMAP":"",m.roughnessMap?"#define USE_ROUGHNESSMAP":"",m.metalnessMap?"#define USE_METALNESSMAP":"",m.alphaMap?"#define USE_ALPHAMAP":"",m.vertexColors?"#define USE_COLOR":"",m.flatShading?"#define FLAT_SHADED":"",m.skinning?"#define USE_SKINNING":"",m.useVertexTexture?"#define BONE_TEXTURE":"",m.morphTargets?"#define USE_MORPHTARGETS":"",m.morphNormals&&m.flatShading===!1?"#define USE_MORPHNORMALS":"",m.doubleSided?"#define DOUBLE_SIDED":"",m.flipSided?"#define FLIP_SIDED":"","#define NUM_CLIPPING_PLANES "+m.numClippingPlanes,m.shadowMapEnabled?"#define USE_SHADOWMAP":"",m.shadowMapEnabled?"#define "+b:"",m.sizeAttenuation?"#define USE_SIZEATTENUATION":"",m.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",m.logarithmicDepthBuffer&&e.extensions.get("EXT_frag_depth")?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_COLOR","\tattribute vec3 color;","#endif","#ifdef USE_MORPHTARGETS","\tattribute vec3 morphTarget0;","\tattribute vec3 morphTarget1;","\tattribute vec3 morphTarget2;","\tattribute vec3 morphTarget3;","\t#ifdef USE_MORPHNORMALS","\t\tattribute vec3 morphNormal0;","\t\tattribute vec3 morphNormal1;","\t\tattribute vec3 morphNormal2;","\t\tattribute vec3 morphNormal3;","\t#else","\t\tattribute vec3 morphTarget4;","\t\tattribute vec3 morphTarget5;","\t\tattribute vec3 morphTarget6;","\t\tattribute vec3 morphTarget7;","\t#endif","#endif","#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif","\n"].filter(c).join("\n"), +S=[L,"precision "+m.precision+" float;","precision "+m.precision+" int;","#define SHADER_NAME "+f.__webglShader.name,R,m.alphaTest?"#define ALPHATEST "+m.alphaTest:"","#define GAMMA_FACTOR "+A,m.useFog&&m.fog?"#define USE_FOG":"",m.useFog&&m.fogExp?"#define FOG_EXP2":"",m.map?"#define USE_MAP":"",m.envMap?"#define USE_ENVMAP":"",m.envMap?"#define "+w:"",m.envMap?"#define "+M:"",m.envMap?"#define "+E:"",m.lightMap?"#define USE_LIGHTMAP":"",m.aoMap?"#define USE_AOMAP":"",m.emissiveMap?"#define USE_EMISSIVEMAP":"",m.bumpMap?"#define USE_BUMPMAP":"",m.normalMap?"#define USE_NORMALMAP":"",m.specularMap?"#define USE_SPECULARMAP":"",m.roughnessMap?"#define USE_ROUGHNESSMAP":"",m.metalnessMap?"#define USE_METALNESSMAP":"",m.alphaMap?"#define USE_ALPHAMAP":"",m.vertexColors?"#define USE_COLOR":"",m.flatShading?"#define FLAT_SHADED":"",m.doubleSided?"#define DOUBLE_SIDED":"",m.flipSided?"#define FLIP_SIDED":"","#define NUM_CLIPPING_PLANES "+m.numClippingPlanes,m.shadowMapEnabled?"#define USE_SHADOWMAP":"",m.shadowMapEnabled?"#define "+b:"",m.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",m.physicallyCorrectLights?"#define PHYSICALLY_CORRECT_LIGHTS":"",m.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",m.logarithmicDepthBuffer&&e.extensions.get("EXT_frag_depth")?"#define USE_LOGDEPTHBUF_EXT":"",m.envMap&&e.extensions.get("EXT_shader_texture_lod")?"#define TEXTURE_LOD_EXT":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;",m.toneMapping!==ar?"#define TONE_MAPPING":"",m.toneMapping!==ar?Es.tonemapping_pars_fragment:"",m.toneMapping!==ar?r("toneMapping",m.toneMapping):"",m.outputEncoding||m.mapEncoding||m.envMapEncoding||m.emissiveMapEncoding?Es.encodings_pars_fragment:"",m.mapEncoding?i("mapTexelToLinear",m.mapEncoding):"",m.envMapEncoding?i("envMapTexelToLinear",m.envMapEncoding):"",m.emissiveMapEncoding?i("emissiveMapTexelToLinear",m.emissiveMapEncoding):"",m.outputEncoding?n("linearToOutputTexel",m.outputEncoding):"",m.depthPacking?"#define DEPTH_PACKING "+f.depthPacking:"","\n"].filter(c).join("\n")),x=l(x,m),x=h(x,m),_=l(_,m),_=h(_,m),(f&&f.isShaderMaterial)===!1&&(x=u(x),_=u(_));var C=T+x,U=S+_,I=t.WebGLShader(v,v.VERTEX_SHADER,C),D=t.WebGLShader(v,v.FRAGMENT_SHADER,U);v.attachShader(P,I),v.attachShader(P,D),void 0!==f.index0AttributeName?v.bindAttribLocation(P,0,f.index0AttributeName):m.morphTargets===!0&&v.bindAttribLocation(P,0,"position"),v.linkProgram(P);var N=v.getProgramInfoLog(P),O=v.getShaderInfoLog(I),F=v.getShaderInfoLog(D),z=!0,B=!0;v.getProgramParameter(P,v.LINK_STATUS)===!1?(z=!1,console.error("THREE.WebGLProgram: shader error: ",v.getError(),"gl.VALIDATE_STATUS",v.getProgramParameter(P,v.VALIDATE_STATUS),"gl.getProgramInfoLog",N,O,F)):""!==N?console.warn("THREE.WebGLProgram: gl.getProgramInfoLog()",N):""!==O&&""!==F||(B=!1),B&&(this.diagnostics={runnable:z,material:f,programLog:N,vertexShader:{log:O,prefix:T},fragmentShader:{log:F,prefix:S}}),v.deleteShader(I),v.deleteShader(D);var G;this.getUniforms=function(){return void 0===G&&(G=new t.WebGLUniforms(v,P,e)),G};var H;return this.getAttributes=function(){return void 0===H&&(H=s(v,P)),H},this.destroy=function(){v.deleteProgram(P),this.program=void 0},Object.defineProperties(this,{uniforms:{get:function(){return console.warn("THREE.WebGLProgram: .uniforms is now .getUniforms()."),this.getUniforms()}},attributes:{get:function(){return console.warn("THREE.WebGLProgram: .attributes is now .getAttributes()."),this.getAttributes()}}}),this.id=p++,this.code=d,this.usedTimes=1,this.program=P,this.vertexShader=I,this.fragmentShader=D,this}}(),U.prototype={constructor:U,isBufferAttribute:!0,get count(){return this.array.length/this.itemSize},set needsUpdate(t){t===!0&&this.version++},setDynamic:function(t){return this.dynamic=t,this},copy:function(t){return this.array=new t.array.constructor(t.array),this.itemSize=t.itemSize,this.normalized=t.normalized,this.dynamic=t.dynamic,this},copyAt:function(t,e,i){t*=this.itemSize,i*=e.itemSize;for(var n=0,r=this.itemSize;n1){for(var e=0;e1)for(var e=0;e0){r.children=[];for(var a=0;a0&&(n.geometries=o),s.length>0&&(n.materials=s),c.length>0&&(n.textures=c),h.length>0&&(n.images=h)}return n.object=r,n},clone:function(t){return(new this.constructor).copy(this,t)},copy:function(t,e){if(void 0===e&&(e=!0),this.name=t.name,this.up.copy(t.up),this.position.copy(t.position),this.quaternion.copy(t.quaternion),this.scale.copy(t.scale),this.matrix.copy(t.matrix),this.matrixWorld.copy(t.matrixWorld),this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrixWorldNeedsUpdate=t.matrixWorldNeedsUpdate,this.visible=t.visible,this.castShadow=t.castShadow,this.receiveShadow=t.receiveShadow,this.frustumCulled=t.frustumCulled,this.renderOrder=t.renderOrder,this.userData=JSON.parse(JSON.stringify(t.userData)),e===!0)for(var i=0;i0)for(var m=0;m0&&(this.normalsNeedUpdate=!0)},computeMorphNormals:function(){var t,e,i,n,r;for(i=0,n=this.faces.length;i0&&(t+=e[i].distanceTo(e[i-1])),this.lineDistances[i]=t},computeBoundingBox:function(){null===this.boundingBox&&(this.boundingBox=new E),this.boundingBox.setFromPoints(this.vertices)},computeBoundingSphere:function(){null===this.boundingSphere&&(this.boundingSphere=new T),this.boundingSphere.setFromPoints(this.vertices)},merge:function(t,e,i){if((t&&t.isGeometry)===!1)return void console.error("THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.",t);var n,r=this.vertices.length,a=this.vertices,o=t.vertices,s=this.faces,c=t.faces,h=this.faceVertexUvs[0],l=t.faceVertexUvs[0];void 0===i&&(i=0),void 0!==e&&(n=(new S).getNormalMatrix(e));for(var u=0,p=o.length;u=0;i--){var v=d[i];for(this.faces.splice(v,1),o=0,s=this.faceVertexUvs.length;o0,w=g.vertexNormals.length>0,M=1!==g.color.r||1!==g.color.g||1!==g.color.b,E=g.vertexColors.length>0,T=0;if(T=t(T,0,0),T=t(T,1,y),T=t(T,2,x),T=t(T,3,_),T=t(T,4,b),T=t(T,5,w),T=t(T,6,M),T=t(T,7,E),l.push(T),l.push(g.a,g.b,g.c),l.push(g.materialIndex),_){var S=this.faceVertexUvs[0][c];l.push(n(S[0]),n(S[1]),n(S[2]))}if(b&&l.push(e(g.normal)),w){var A=g.vertexNormals;l.push(e(A[0]),e(A[1]),e(A[2]))}if(M&&l.push(i(g.color)),E){var L=g.vertexColors;l.push(i(L[0]),i(L[1]),i(L[2]))}}return r.data={},r.data.vertices=s,r.data.normals=u,d.length>0&&(r.data.colors=d),m.length>0&&(r.data.uvs=[m]),r.data.faces=l,r},clone:function(){return(new q).copy(this)},copy:function(t){this.vertices=[],this.faces=[],this.faceVertexUvs=[[]];for(var e=t.vertices,i=0,n=e.length;i0,s=a[1]&&a[1].length>0,c=t.morphTargets,h=c.length;if(h>0){e=[];for(var l=0;l0){u=[];for(var l=0;l0){var i=new Float32Array(3*t.normals.length);this.addAttribute("normal",new U(i,3).copyVector3sArray(t.normals))}if(t.colors.length>0){var n=new Float32Array(3*t.colors.length);this.addAttribute("color",new U(n,3).copyColorsArray(t.colors))}if(t.uvs.length>0){var r=new Float32Array(2*t.uvs.length);this.addAttribute("uv",new U(r,2).copyVector2sArray(t.uvs))}if(t.uvs2.length>0){var a=new Float32Array(2*t.uvs2.length);this.addAttribute("uv2",new U(a,2).copyVector2sArray(t.uvs2))}if(t.indices.length>0){var o=t.vertices.length>65535?Uint32Array:Uint16Array,s=new o(3*t.indices.length);this.setIndex(new U(s,1).copyIndicesArray(t.indices))}this.groups=t.groups;for(var c in t.morphTargets){for(var h=[],l=t.morphTargets[c],u=0,p=l.length;u0){var m=new G(4*t.skinIndices.length,4);this.addAttribute("skinIndex",m.copyVector4sArray(t.skinIndices))}if(t.skinWeights.length>0){var v=new G(4*t.skinWeights.length,4);this.addAttribute("skinWeight",v.copyVector4sArray(t.skinWeights))}return null!==t.boundingSphere&&(this.boundingSphere=t.boundingSphere.clone()),null!==t.boundingBox&&(this.boundingBox=t.boundingBox.clone()),this},computeBoundingBox:function(){null===this.boundingBox&&(this.boundingBox=new E);var t=this.attributes.position.array;void 0!==t?this.boundingBox.setFromArray(t):this.boundingBox.makeEmpty(),(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&console.error('THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)},computeBoundingSphere:function(){var t=new E,e=new s;return function(){null===this.boundingSphere&&(this.boundingSphere=new T);var i=this.attributes.position;if(i){var n=i.array,r=this.boundingSphere.center;t.setFromArray(n),t.center(r);for(var a=0,o=0,s=n.length;o0&&(t.data.groups=JSON.parse(JSON.stringify(s)));var c=this.boundingSphere;return null!==c&&(t.data.boundingSphere={center:c.center.toArray(),radius:c.radius}),t},clone:function(){return(new Q).copy(this)},copy:function(t){var e=t.index;null!==e&&this.setIndex(e.clone());var i=t.attributes;for(var n in i){var r=i[n];this.addAttribute(n,r.clone())}for(var a=t.groups,o=0,s=a.length;o0)if(s=p*f-d,c=p*d-f,l=u*v,s>=0)if(c>=-l)if(c<=l){var g=1/v;s*=g,c*=g,h=s*(s+p*c+2*d)+c*(p*s+c+2*f)+m}else c=u,s=Math.max(0,-(p*c+d)),h=-s*s+c*(c+2*f)+m;else c=-u,s=Math.max(0,-(p*c+d)),h=-s*s+c*(c+2*f)+m;else c<=-l?(s=Math.max(0,-(-p*u+d)),c=s>0?-u:Math.min(Math.max(-u,-f),u),h=-s*s+c*(c+2*f)+m):c<=l?(s=0,c=Math.min(Math.max(-u,-f),u),h=c*(c+2*f)+m):(s=Math.max(0,-(p*u+d)),c=s>0?u:Math.min(Math.max(-u,-f),u),h=-s*s+c*(c+2*f)+m);else c=p>0?-u:u,s=Math.max(0,-(p*c+d)),h=-s*s+c*(c+2*f)+m;return a&&a.copy(this.direction).multiplyScalar(s).add(this.origin),o&&o.copy(e).multiplyScalar(c).add(t),h}}(),intersectSphere:function(){var t=new s;return function(e,i){t.subVectors(e.center,this.origin);var n=t.dot(this.direction),r=t.dot(t)-n*n,a=e.radius*e.radius;if(r>a)return null;var o=Math.sqrt(a-r),s=n-o,c=n+o;return s<0&&c<0?null:s<0?this.at(c,i):this.at(s,i)}}(),intersectsSphere:function(t){return this.distanceToPoint(t.center)<=t.radius},distanceToPlane:function(t){var e=t.normal.dot(this.direction);if(0===e)return 0===t.distanceToPoint(this.origin)?0:null;var i=-(this.origin.dot(t.normal)+t.constant)/e;return i>=0?i:null},intersectPlane:function(t,e){var i=this.distanceToPlane(t);return null===i?null:this.at(i,e)},intersectsPlane:function(t){var e=t.distanceToPoint(this.origin);if(0===e)return!0;var i=t.normal.dot(this.direction);return i*e<0},intersectBox:function(t,e){var i,n,r,a,o,s,c=1/this.direction.x,h=1/this.direction.y,l=1/this.direction.z,u=this.origin;return c>=0?(i=(t.min.x-u.x)*c,n=(t.max.x-u.x)*c):(i=(t.max.x-u.x)*c,n=(t.min.x-u.x)*c),h>=0?(r=(t.min.y-u.y)*h,a=(t.max.y-u.y)*h):(r=(t.max.y-u.y)*h,a=(t.min.y-u.y)*h),i>a||r>n?null:((r>i||i!==i)&&(i=r),(a=0?(o=(t.min.z-u.z)*l,s=(t.max.z-u.z)*l):(o=(t.max.z-u.z)*l,s=(t.min.z-u.z)*l),i>s||o>n?null:((o>i||i!==i)&&(i=o),(s=0?i:n,e)))},intersectsBox:function(){var t=new s;return function(e){return null!==this.intersectBox(e,t)}}(),intersectTriangle:function(){var t=new s,e=new s,i=new s,n=new s;return function(r,a,o,s,c){e.subVectors(a,r),i.subVectors(o,r),n.crossVectors(e,i);var h,l=this.direction.dot(n);if(l>0){if(s)return null;h=1}else{if(!(l<0))return null;h=-1,l=-l}t.subVectors(this.origin,r);var u=h*this.direction.dot(i.crossVectors(t,i));if(u<0)return null;var p=h*this.direction.dot(e.cross(t));if(p<0)return null;if(u+p>l)return null;var d=-h*t.dot(n);return d<0?null:this.at(d/l,c)}}(),applyMatrix4:function(t){return this.direction.add(this.origin).applyMatrix4(t),this.origin.applyMatrix4(t),this.direction.sub(this.origin),this.direction.normalize(),this},equals:function(t){return t.origin.equals(this.origin)&&t.direction.equals(this.direction)}},ht.prototype={constructor:ht,set:function(t,e){return this.start.copy(t),this.end.copy(e),this},clone:function(){return(new this.constructor).copy(this)},copy:function(t){return this.start.copy(t.start),this.end.copy(t.end),this},center:function(t){var e=t||new s;return e.addVectors(this.start,this.end).multiplyScalar(.5)},delta:function(t){var e=t||new s;return e.subVectors(this.end,this.start)},distanceSq:function(){return this.start.distanceToSquared(this.end)},distance:function(){return this.start.distanceTo(this.end)},at:function(t,e){var i=e||new s;return this.delta(i).multiplyScalar(t).add(this.start)},closestPointToPointParameter:function(){var e=new s,i=new s;return function(n,r){e.subVectors(n,this.start),i.subVectors(this.end,this.start);var a=i.dot(i),o=i.dot(e),s=o/a;return r&&(s=t.Math.clamp(s,0,1)),s}}(),closestPointToPoint:function(t,e,i){var n=this.closestPointToPointParameter(t,e),r=i||new s;return this.delta(r).multiplyScalar(n).add(this.start)},applyMatrix4:function(t){return this.start.applyMatrix4(t),this.end.applyMatrix4(t),this},equals:function(t){return t.start.equals(this.start)&&t.end.equals(this.end)}},lt.normal=function(){var t=new s;return function(e,i,n,r){var a=r||new s;a.subVectors(n,i),t.subVectors(e,i),a.cross(t);var o=a.lengthSq();return o>0?a.multiplyScalar(1/Math.sqrt(o)):a.set(0,0,0)}}(),lt.barycoordFromPoint=function(){var t=new s,e=new s,i=new s;return function(n,r,a,o,c){t.subVectors(o,r),e.subVectors(a,r),i.subVectors(n,r);var h=t.dot(t),l=t.dot(e),u=t.dot(i),p=e.dot(e),d=e.dot(i),f=h*p-l*l,m=c||new s;if(0===f)return m.set(-2,-1,-1);var v=1/f,g=(p*u-l*d)*v,y=(h*d-l*u)*v;return m.set(1-g-y,y,g)}}(),lt.containsPoint=function(){var t=new s;return function(e,i,n,r){var a=lt.barycoordFromPoint(e,i,n,r,t);return a.x>=0&&a.y>=0&&a.x+a.y<=1}}(),lt.prototype={constructor:lt,set:function(t,e,i){return this.a.copy(t),this.b.copy(e),this.c.copy(i),this},setFromPointsAndIndices:function(t,e,i,n){return this.a.copy(t[e]),this.b.copy(t[i]),this.c.copy(t[n]),this},clone:function(){return(new this.constructor).copy(this)},copy:function(t){return this.a.copy(t.a),this.b.copy(t.b),this.c.copy(t.c),this},area:function(){var t=new s,e=new s;return function(){return t.subVectors(this.c,this.b),e.subVectors(this.a,this.b),.5*t.cross(e).length()}}(),midpoint:function(t){var e=t||new s;return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)},normal:function(t){return lt.normal(this.a,this.b,this.c,t)},plane:function(t){var e=t||new A;return e.setFromCoplanarPoints(this.a,this.b,this.c)},barycoordFromPoint:function(t,e){return lt.barycoordFromPoint(t,this.a,this.b,this.c,e)},containsPoint:function(t){return lt.containsPoint(t,this.a,this.b,this.c)},closestPointToPoint:function(){var t,e,i,n;return function(r,a){void 0===t&&(t=new A,e=[new ht,new ht,new ht],i=new s,n=new s);var o=a||new s,c=1/0;if(t.setFromCoplanarPoints(this.a,this.b,this.c),t.projectPoint(r,i),this.containsPoint(i)===!0)o.copy(i);else{e[0].set(this.a,this.b),e[1].set(this.b,this.c),e[2].set(this.c,this.a);for(var h=0;h0){this.morphTargetBase=-1,this.morphTargetInfluences=[],this.morphTargetDictionary={};for(var t=0,e=this.geometry.morphTargets.length;te.far?null:{distance:h,point:_.clone(),object:t}}function n(i,n,r,a,o,s,c,p){h.fromArray(a,3*s),l.fromArray(a,3*c),u.fromArray(a,3*p);var d=e(i,n,r,h,l,u,x);return d&&(o&&(m.fromArray(o,2*s),v.fromArray(o,2*c),g.fromArray(o,2*p),d.uv=t(x,h,l,u,m,v,g)),d.face=new k(s,c,p,lt.normal(h,l,u)),d.faceIndex=s),d}var r=new a,o=new ct,c=new T,h=new s,l=new s,u=new s,p=new s,d=new s,f=new s,m=new i,v=new i,g=new i,y=new s,x=new s,_=new s;return function(i,a){var s=this.geometry,y=this.material,_=this.matrixWorld;if(void 0!==y&&(null===s.boundingSphere&&s.computeBoundingSphere(),c.copy(s.boundingSphere),c.applyMatrix4(_),i.ray.intersectsSphere(c)!==!1&&(r.getInverse(_),o.copy(i.ray).applyMatrix4(r),null===s.boundingBox||o.intersectsBox(s.boundingBox)!==!1))){var b,w;if(s&&s.isBufferGeometry){var M,E,T,S=s.index,A=s.attributes,L=A.position.array;if(void 0!==A.uv&&(b=A.uv.array),null!==S)for(var R=S.array,P=0,C=R.length;P0&&(b=B);for(var G=0,H=z.length;Gr||i.push({distance:Math.sqrt(n),point:this.position,face:null,object:this})}}(),clone:function(){return new this.constructor(this.material).copy(this)}}),Et.prototype=Object.assign(Object.create(X.prototype),{constructor:Et,copy:function(t){X.prototype.copy.call(this,t,!1);for(var e=t.levels,i=0,n=e.length;i1){t.setFromMatrixPosition(i.matrixWorld),e.setFromMatrixPosition(this.matrixWorld);var r=t.distanceTo(e);n[0].object.visible=!0;for(var a=1,o=n.length;a=n[a].distance;a++)n[a-1].object.visible=!1,n[a].object.visible=!0;for(;ao)){d.applyMatrix4(this.matrixWorld);var E=n.ray.origin.distanceTo(d);En.far||r.push({distance:E,point:p.clone().applyMatrix4(this.matrixWorld),index:x,face:null,faceIndex:null,object:this})}}else for(var x=0,_=g.length/3-1;x<_;x+=f){l.fromArray(g,3*x),u.fromArray(g,3*x+3);var M=e.distanceSqToSegment(l,u,d,p);if(!(M>o)){d.applyMatrix4(this.matrixWorld);var E=n.ray.origin.distanceTo(d);En.far||r.push({distance:E,point:p.clone().applyMatrix4(this.matrixWorld),index:x,face:null,faceIndex:null,object:this})}}}else if(c&&c.isGeometry)for(var T=c.vertices,S=T.length,x=0;xo)){d.applyMatrix4(this.matrixWorld);var E=n.ray.origin.distanceTo(d);En.far||r.push({distance:E,point:p.clone().applyMatrix4(this.matrixWorld),index:x,face:null,faceIndex:null,object:this})}}}}}(),clone:function(){return new this.constructor(this.geometry,this.material).copy(this)}}),Ct.prototype=Object.assign(Object.create(Pt.prototype),{constructor:Ct,isLineSegments:!0}),Ut.prototype=Object.create(x.prototype),Ut.prototype.constructor=Ut,Ut.prototype.isPointsMaterial=!0,Ut.prototype.copy=function(t){return x.prototype.copy.call(this,t),this.color.copy(t.color),this.map=t.map,this.size=t.size,this.sizeAttenuation=t.sizeAttenuation,this},It.prototype=Object.assign(Object.create(X.prototype),{constructor:It,isPoints:!0,raycast:function(){var t=new a,e=new ct,i=new T;return function(n,r){function a(t,i){var a=e.distanceSqToPoint(t);if(an.far)return;r.push({distance:c,distanceToRay:Math.sqrt(a),point:s.clone(),index:i,face:null,object:o})}}var o=this,c=this.geometry,h=this.matrixWorld,l=n.params.Points.threshold;if(null===c.boundingSphere&&c.computeBoundingSphere(),i.copy(c.boundingSphere),i.applyMatrix4(h),n.ray.intersectsSphere(i)!==!1){t.getInverse(h),e.copy(n.ray).applyMatrix4(t);var u=l/((this.scale.x+this.scale.y+this.scale.z)/3),p=u*u,d=new s;if(c&&c.isBufferGeometry){var f=c.index,m=c.attributes,v=m.position.array;if(null!==f)for(var g=f.array,y=0,x=g.length;y0||0===t.search(/^data\:image\/jpeg/);a.format=n?Gr:Hr,a.image=i,a.needsUpdate=!0,void 0!==e&&e(a)},i,r),a},setCrossOrigin:function(t){return this.crossOrigin=t,this},setWithCredentials:function(t){return this.withCredentials=t,this},setPath:function(t){return this.path=t,this}}),ee.prototype=Object.assign(Object.create(X.prototype),{constructor:ee,isLight:!0,copy:function(t){return X.prototype.copy.call(this,t),this.color.copy(t.color),this.intensity=t.intensity,this},toJSON:function(t){var e=X.prototype.toJSON.call(this,t);return e.object.color=this.color.getHex(),e.object.intensity=this.intensity,void 0!==this.groundColor&&(e.object.groundColor=this.groundColor.getHex()),void 0!==this.distance&&(e.object.distance=this.distance),void 0!==this.angle&&(e.object.angle=this.angle),void 0!==this.decay&&(e.object.decay=this.decay),void 0!==this.penumbra&&(e.object.penumbra=this.penumbra),void 0!==this.shadow&&(e.object.shadow=this.shadow.toJSON()),e}}),ie.prototype=Object.assign(Object.create(ee.prototype),{constructor:ie,isHemisphereLight:!0,copy:function(t){return ee.prototype.copy.call(this,t),this.groundColor.copy(t.groundColor),this}}),Object.assign(ne.prototype,{copy:function(t){return this.camera=t.camera.clone(),this.bias=t.bias,this.radius=t.radius,this.mapSize.copy(t.mapSize),this},clone:function(){return(new this.constructor).copy(this)},toJSON:function(){var t={};return 0!==this.bias&&(t.bias=this.bias),1!==this.radius&&(t.radius=this.radius),512===this.mapSize.x&&512===this.mapSize.y||(t.mapSize=this.mapSize.toArray()),t.camera=this.camera.toJSON(!1).object,delete t.camera.matrix,t}}),re.prototype=Object.assign(Object.create(ne.prototype),{constructor:re,isSpotLightShadow:!0,update:function(e){var i=2*t.Math.RAD2DEG*e.angle,n=this.mapSize.width/this.mapSize.height,r=e.distance||500,a=this.camera;i===a.fov&&n===a.aspect&&r===a.far||(a.fov=i,a.aspect=n,a.far=r,a.updateProjectionMatrix())}}),ae.prototype=Object.assign(Object.create(ee.prototype),{constructor:ae,isSpotLight:!0,copy:function(t){return ee.prototype.copy.call(this,t),this.distance=t.distance,this.angle=t.angle,this.penumbra=t.penumbra,this.decay=t.decay,this.target=t.target.clone(),this.shadow=t.shadow.clone(),this}}),oe.prototype=Object.assign(Object.create(ee.prototype),{constructor:oe,isPointLight:!0,copy:function(t){return ee.prototype.copy.call(this,t),this.distance=t.distance,this.decay=t.decay,this.shadow=t.shadow.clone(),this}}),se.prototype=Object.assign(Object.create(ne.prototype),{constructor:se}),ce.prototype=Object.assign(Object.create(ee.prototype),{constructor:ce,isDirectionalLight:!0,copy:function(t){return ee.prototype.copy.call(this,t),this.target=t.target.clone(),this.shadow=t.shadow.clone(),this}}),he.prototype=Object.assign(Object.create(ee.prototype),{constructor:he,isAmbientLight:!0}),t.AnimationUtils={arraySlice:function(e,i,n){return t.AnimationUtils.isTypedArray(e)?new e.constructor(e.subarray(i,n)):e.slice(i,n)},convertArray:function(t,e,i){return!t||!i&&t.constructor===e?t:"number"==typeof e.BYTES_PER_ELEMENT?new e(t):Array.prototype.slice.call(t)},isTypedArray:function(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)},getKeyframeOrder:function(t){function e(e,i){return t[e]-t[i]}for(var i=t.length,n=new Array(i),r=0;r!==i;++r)n[r]=r;return n.sort(e),n},sortedArray:function(t,e,i){for(var n=t.length,r=new t.constructor(n),a=0,o=0;o!==n;++a)for(var s=i[a]*e,c=0;c!==e;++c)r[o++]=t[s+c];return r},flattenJSON:function(t,e,i,n){for(var r=1,a=t[0];void 0!==a&&void 0===a[n];)a=t[r++];if(void 0!==a){var o=a[n];if(void 0!==o)if(Array.isArray(o)){do o=a[n],void 0!==o&&(e.push(a.time),i.push.apply(i,o)),a=t[r++];while(void 0!==a)}else if(void 0!==o.toArray){do o=a[n],void 0!==o&&(e.push(a.time),o.toArray(i,i.length)),a=t[r++];while(void 0!==a)}else do o=a[n],void 0!==o&&(e.push(a.time),i.push(o)),a=t[r++];while(void 0!==a)}}},le.prototype={constructor:le,evaluate:function(t){var e=this.parameterPositions,i=this._cachedIndex,n=e[i],r=e[i-1];t:{e:{var a;i:{n:if(!(t=r)break t;var s=e[1];t=r)break e}a=i,i=0}}for(;i>>1;ti;)--o;if(++o,0!==a||o!==r){a>=o&&(o=Math.max(o,1),a=o-1);var s=this.getValueSize();this.times=t.AnimationUtils.arraySlice(n,a,o),this.values=t.AnimationUtils.arraySlice(this.values,a*s,o*s)}return this},validate:function(){var e=!0,i=this.getValueSize();i-Math.floor(i)!==0&&(console.error("invalid value size in track",this),e=!1);var n=this.times,r=this.values,a=n.length;0===a&&(console.error("track is empty",this),e=!1);for(var o=null,s=0;s!==a;s++){var c=n[s];if("number"==typeof c&&isNaN(c)){console.error("time is not a valid number",this,s,c),e=!1;break}if(null!==o&&o>c){console.error("out of order keys",this,s,c,o),e=!1;break}o=c}if(void 0!==r&&t.AnimationUtils.isTypedArray(r))for(var s=0,h=r.length;s!==h;++s){var l=r[s];if(isNaN(l)){console.error("value is not a valid number",this,s,l),e=!1;break}}return e},optimize:function(){for(var e=this.times,i=this.values,n=this.getValueSize(),r=1,a=1,o=e.length-1;a<=o;++a){var s=!1,c=e[a],h=e[a+1];if(c!==h&&(1!==a||c!==c[0]))for(var l=a*n,u=l-n,p=l+n,d=0;d!==n;++d){var f=i[l+d];if(f!==i[u+d]||f!==i[p+d]){s=!0;break}}if(s){if(a!==r){e[r]=e[a];for(var m=a*n,v=r*n,d=0;d!==n;++d)i[v+d]=i[m+d]}++r}}return r!==e.length&&(this.times=t.AnimationUtils.arraySlice(e,0,r),this.values=t.AnimationUtils.arraySlice(i,0,r*n)),this}},me.prototype=Object.assign(Object.create(Ls),{constructor:me,ValueTypeName:"vector"}),ve.prototype=Object.assign(Object.create(le.prototype),{constructor:ve,interpolate_:function(t,e,i,n){for(var r=this.resultBuffer,a=this.sampleValues,s=this.valueSize,c=t*s,h=(i-e)/(n-e),l=c+s;c!==l;c+=4)o.slerpFlat(r,0,a,c-s,a,c,h);return r}}),ge.prototype=Object.assign(Object.create(Ls),{constructor:ge,ValueTypeName:"quaternion",DefaultInterpolation:oa,InterpolantFactoryMethodLinear:function(t){return new ve(this.times,this.values,this.getValueSize(),t)},InterpolantFactoryMethodSmooth:void 0}),ye.prototype=Object.assign(Object.create(Ls),{constructor:ye,ValueTypeName:"number"}),xe.prototype=Object.assign(Object.create(Ls),{constructor:xe,ValueTypeName:"string",ValueBufferType:Array,DefaultInterpolation:aa,InterpolantFactoryMethodLinear:void 0,InterpolantFactoryMethodSmooth:void 0}),_e.prototype=Object.assign(Object.create(Ls),{constructor:_e,ValueTypeName:"bool",ValueBufferType:Array,DefaultInterpolation:aa,InterpolantFactoryMethodLinear:void 0,InterpolantFactoryMethodSmooth:void 0}),be.prototype=Object.assign(Object.create(Ls),{constructor:be,ValueTypeName:"color"}),we.prototype=Ls,Ls.constructor=we,Object.assign(we,{parse:function(e){if(void 0===e.type)throw new Error("track type undefined, can not parse");var i=we._getTrackTypeForValueTypeName(e.type);if(void 0===e.times){var n=[],r=[];t.AnimationUtils.flattenJSON(e.keys,n,r,"value"),e.times=n,e.values=r}return void 0!==i.parse?i.parse(e):new i(e.name,e.times,e.values,e.interpolation)},toJSON:function(e){var i,n=e.constructor;if(void 0!==n.toJSON)i=n.toJSON(e);else{i={name:e.name,times:t.AnimationUtils.convertArray(e.times,Array),values:t.AnimationUtils.convertArray(e.values,Array)};var r=e.getInterpolation();r!==e.DefaultInterpolation&&(i.interpolation=r)}return i.type=e.ValueTypeName,i},_getTrackTypeForValueTypeName:function(t){switch(t.toLowerCase()){case"scalar":case"double":case"float":case"number":case"integer":return ye;case"vector":case"vector2":case"vector3":case"vector4":return me;case"color":return be;case"quaternion":return ge;case"bool":case"boolean":return _e;case"string":return xe}throw new Error("Unsupported typeName: "+t)}}),Me.prototype={constructor:Me,resetDuration:function(){for(var t=this.tracks,e=0,i=0,n=t.length;i!==n;++i){var r=this.tracks[i];e=Math.max(e,r.times[r.times.length-1])}this.duration=e},trim:function(){for(var t=0;t1){var h=c[1],l=n[h];l||(n[h]=l=[]),l.push(s)}}var u=[];for(var h in n)u.push(Me.CreateFromMorphTargetSequence(h,n[h],e,i));return u},parseAnimation:function(e,i,n){if(!e)return console.error(" no animation in JSONLoader data"),null;for(var r=function(e,i,n,r,a){if(0!==n.length){var o=[],s=[];t.AnimationUtils.flattenJSON(n,o,s,r),0!==o.length&&a.push(new e(i,o,s))}},a=[],o=e.name||"default",s=e.length||-1,c=e.fps||30,h=e.hierarchy||[],l=0;l1?t.skinWeights[i+1]:0,o=e>2?t.skinWeights[i+2]:0,s=e>3?t.skinWeights[i+3]:0;c.skinWeights.push(new d(r,a,o,s))}if(t.skinIndices)for(var i=0,n=t.skinIndices.length;i1?t.skinIndices[i+1]:0,u=e>2?t.skinIndices[i+2]:0,p=e>3?t.skinIndices[i+3]:0;c.skinIndices.push(new d(h,l,u,p))}c.bones=t.bones,c.bones&&c.bones.length>0&&(c.skinWeights.length!==c.skinIndices.length||c.skinIndices.length!==c.vertices.length)&&console.warn("When skinning, number of vertices ("+c.vertices.length+"), skinIndices ("+c.skinIndices.length+"), and skinWeights ("+c.skinWeights.length+") should match.")}function a(e){if(void 0!==t.morphTargets)for(var i=0,n=t.morphTargets.length;i0){console.warn('THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.');for(var u=c.faces,p=t.morphColors[0].colors,i=0,n=u.length;i0&&(c.animations=e)}var c=new q,h=void 0!==t.scale?1/t.scale:1;if(n(h),r(),a(h),o(),c.computeFaceNormals(),c.computeBoundingSphere(),void 0===t.materials||0===t.materials.length)return{geometry:c};var l=Se.prototype.initMaterials(t.materials,e,this.crossOrigin);return{geometry:c,materials:l}}}),Object.assign(Le.prototype,{load:function(t,e,i,n){""===this.texturePath&&(this.texturePath=t.substring(0,t.lastIndexOf("/")+1));var r=this,a=new Zt(r.manager);a.load(t,function(t){r.parse(JSON.parse(t),e)},i,n)},setTexturePath:function(t){this.texturePath=t},setCrossOrigin:function(t){this.crossOrigin=t},parse:function(t,e){var i=this.parseGeometries(t.geometries),n=this.parseImages(t.images,function(){void 0!==e&&e(o)}),r=this.parseTextures(t.textures,n),a=this.parseMaterials(t.materials,r),o=this.parseObject(t.object,i,a);return t.animations&&(o.animations=this.parseAnimations(t.animations)),void 0!==t.images&&0!==t.images.length||void 0!==e&&e(o),o},parseGeometries:function(t){var e={};if(void 0!==t)for(var i=new Ae,n=new Te,r=0,a=t.length;r0){var a=new qt(e),o=new Kt(a);o.setCrossOrigin(this.crossOrigin);for(var s=0,c=t.length;s0?new Lt(s,c):new pt(s,c);break;case"LOD":o=new Et;break;case"Line":o=new Pt(r(e.geometry),a(e.material),e.mode);break;case"LineSegments":o=new Ct(r(e.geometry),a(e.material));break;case"PointCloud":case"Points":o=new It(r(e.geometry),a(e.material));break;case"Sprite":o=new Mt(a(e.material));break;case"Group":o=new Dt;break;default:o=new X}if(o.uuid=e.uuid,void 0!==e.name&&(o.name=e.name),void 0!==e.matrix?(t.fromArray(e.matrix),t.decompose(o.position,o.quaternion,o.scale)):(void 0!==e.position&&o.position.fromArray(e.position),void 0!==e.rotation&&o.rotation.fromArray(e.rotation),void 0!==e.quaternion&&o.quaternion.fromArray(e.quaternion),void 0!==e.scale&&o.scale.fromArray(e.scale)),void 0!==e.castShadow&&(o.castShadow=e.castShadow),void 0!==e.receiveShadow&&(o.receiveShadow=e.receiveShadow),e.shadow&&(void 0!==e.shadow.bias&&(o.shadow.bias=e.shadow.bias),void 0!==e.shadow.radius&&(o.shadow.radius=e.shadow.radius),void 0!==e.shadow.mapSize&&o.shadow.mapSize.fromArray(e.shadow.mapSize),void 0!==e.shadow.camera&&(o.shadow.camera=this.parseObject(e.shadow.camera))),void 0!==e.visible&&(o.visible=e.visible),void 0!==e.userData&&(o.userData=e.userData),void 0!==e.children)for(var h in e.children)o.add(this.parseObject(e.children[h],i,n));if("LOD"===e.type)for(var l=e.levels,u=0;u(h-s)*(p-c)-(l-c)*(u-s))return!1;var m,v,g,y,x,_,b,w,M,E,T,S,A,L,R;for(m=u-h,v=p-l,g=s-u,y=c-p,x=h-s,_=l-c,o=0;o=-Number.EPSILON&&L>=-Number.EPSILON&&A>=-Number.EPSILON))return!1;return!0}return function(i,n){var r=i.length;if(r<3)return null;var a,o,s,c=[],h=[],l=[];if(t.ShapeUtils.area(i)>0)for(o=0;o2;){if(p--<=0)return console.warn("THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()"),n?l:c;if(a=o,u<=a&&(a=0),o=a+1,u<=o&&(o=0),s=o+1,u<=s&&(s=0),e(i,a,o,s,u,h)){var d,f,m,v,g;for(d=h[a],f=h[o],m=h[s],c.push([i[d],i[f],i[m]]),l.push([h[a],h[o],h[s]]),v=o,g=o+1;g2&&t[e-1].equals(t[0])&&t.pop()}function r(t,e,i){return t.x!==e.x?t.xNumber.EPSILON){var f;if(p>0){if(d<0||d>p)return[];if(f=h*l-c*u,f<0||f>p)return[]}else{if(d>0||d0||fT?[]:_===T?a?[]:[y]:b<=T?[y,x]:[y,M]}function o(t,e,i,n){var r=e.x-t.x,a=e.y-t.y,o=i.x-t.x,s=i.y-t.y,c=n.x-t.x,h=n.y-t.y,l=r*s-a*o,u=r*h-a*c;if(Math.abs(l)>Number.EPSILON){var p=c*s-h*o;return l>0?u>=0&&p>=0:u>=0||p>=0}return u>0}function s(t,e){function i(t,e){var i=y.length-1,n=t-1;n<0&&(n=i);var r=t+1;r>i&&(r=0);var a=o(y[t],y[n],y[r],s[e]);if(!a)return!1;var c=s.length-1,h=e-1;h<0&&(h=c);var l=e+1;return l>c&&(l=0),a=o(s[e],s[h],s[l],y[t]),!!a}function n(t,e){var i,n,r;for(i=0;i0)return!0;return!1}function r(t,i){var n,r,o,s,c;for(n=0;n0)return!0;return!1}for(var s,c,h,l,u,p,d,f,m,v,g,y=t.concat(),x=[],_=[],b=0,w=e.length;b0;){if(E--,E<0){console.log("Infinite Loop! Holes left:"+x.length+", Probably Hole outside Shape!");break}for(h=M;h=0)break;_[d]=!0}if(c>=0)break}}return y}n(e),i.forEach(n);for(var c,h,l,u,p,d,f={},m=e.concat(),v=0,g=i.length;v0)){c=r;break}c=r-1}if(r=c,n[r]===i){var h=r/(a-1);return h}var l=n[r],u=n[r+1],p=u-l,d=(i-l)/p,h=(r+d)/(a-1);return h},getTangent:function(t){var e=1e-4,i=t-e,n=t+e;i<0&&(i=0),n>1&&(n=1);var r=this.getPoint(i),a=this.getPoint(n),o=a.clone().sub(r);return o.normalize()},getTangentAt:function(t){var e=this.getUtoTmapping(t);return this.getTangent(e)}},Re.create=function(t,e){return t.prototype=Object.create(Re.prototype),t.prototype.constructor=t,t.prototype.getPoint=e,t},Pe.prototype=Object.create(Re.prototype),Pe.prototype.constructor=Pe,Pe.prototype.isLineCurve=!0,Pe.prototype.getPoint=function(t){if(1===t)return this.v2.clone();var e=this.v2.clone().sub(this.v1);return e.multiplyScalar(t).add(this.v1),e},Pe.prototype.getPointAt=function(t){return this.getPoint(t)},Pe.prototype.getTangent=function(t){var e=this.v2.clone().sub(this.v1);return e.normalize()},Ce.prototype=Object.assign(Object.create(Re.prototype),{constructor:Ce,add:function(t){this.curves.push(t)},closePath:function(){var t=this.curves[0].getPoint(0),e=this.curves[this.curves.length-1].getPoint(1);t.equals(e)||this.curves.push(new Pe(e,t))},getPoint:function(t){for(var e=t*this.getLength(),i=this.getCurveLengths(),n=0;n=e){var r=i[n]-e,a=this.curves[n],o=a.getLength(),s=0===o?0:1-r/o;return a.getPointAt(s)}n++}return null},getLength:function(){var t=this.getCurveLengths();return t[t.length-1]},updateArcLengths:function(){this.needsUpdate=!0,this.cacheLengths=null,this.getLengths()},getCurveLengths:function(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;for(var t=[],e=0,i=0,n=this.curves.length;i1&&!i[i.length-1].equals(i[0])&&i.push(i[0]),i},createPointsGeometry:function(t){var e=this.getPoints(t);return this.createGeometry(e)},createSpacedPointsGeometry:function(t){var e=this.getSpacedPoints(t);return this.createGeometry(e)},createGeometry:function(t){for(var e=new q,i=0,n=t.length;ie;)n-=e;nn.length-2?n.length-1:a+1],l=n[a>n.length-3?n.length-1:a+2],u=t.CurveUtils.interpolate;return new i(u(s.x,c.x,h.x,l.x,o),u(s.y,c.y,h.y,l.y,o))},De.prototype=Object.create(Re.prototype),De.prototype.constructor=De,De.prototype.getPoint=function(e){var n=t.ShapeUtils.b3;return new i(n(e,this.v0.x,this.v1.x,this.v2.x,this.v3.x),n(e,this.v0.y,this.v1.y,this.v2.y,this.v3.y))},De.prototype.getTangent=function(e){var n=t.CurveUtils.tangentCubicBezier;return new i(n(e,this.v0.x,this.v1.x,this.v2.x,this.v3.x),n(e,this.v0.y,this.v1.y,this.v2.y,this.v3.y)).normalize()},Ne.prototype=Object.create(Re.prototype),Ne.prototype.constructor=Ne,Ne.prototype.getPoint=function(e){var n=t.ShapeUtils.b2;return new i(n(e,this.v0.x,this.v1.x,this.v2.x),n(e,this.v0.y,this.v1.y,this.v2.y))},Ne.prototype.getTangent=function(e){var n=t.CurveUtils.tangentQuadraticBezier;return new i(n(e,this.v0.x,this.v1.x,this.v2.x),n(e,this.v0.y,this.v1.y,this.v2.y)).normalize()};var Rs=Object.assign(Object.create(Ce.prototype),{fromPoints:function(t){this.moveTo(t[0].x,t[0].y);for(var e=1,i=t.length;e0){var h=c.getPoint(0);h.equals(this.currentPoint)||this.lineTo(h.x,h.y)}this.curves.push(c);var l=c.getPoint(1);this.currentPoint.copy(l)}});Oe.prototype=Object.create(q.prototype),Oe.prototype.constructor=Oe,Oe.NoTaper=function(t){return 1},Oe.SinusoidalTaper=function(t){return Math.sin(Math.PI*t)},Oe.FrenetFrames=function(e,i,n){function r(){v[0]=new s,g[0]=new s,c=Number.MAX_VALUE,h=Math.abs(m[0].x),l=Math.abs(m[0].y),u=Math.abs(m[0].z),h<=c&&(c=h,f.set(1,0,0)),l<=c&&(c=l,f.set(0,1,0)),u<=c&&f.set(0,0,1),y.crossVectors(m[0],f).normalize(),v[0].crossVectors(m[0],y),g[0].crossVectors(m[0],v[0])}var o,c,h,l,u,p,d,f=new s,m=[],v=[],g=[],y=new s,x=new a,_=i+1;for(this.tangents=m,this.normals=v,this.binormals=g,p=0;p<_;p++)d=p/(_-1),m[p]=e.getTangentAt(d),m[p].normalize();for(r(),p=1;p<_;p++)v[p]=v[p-1].clone(),g[p]=g[p-1].clone(),y.crossVectors(m[p-1],m[p]),y.length()>Number.EPSILON&&(y.normalize(),o=Math.acos(t.Math.clamp(m[p-1].dot(m[p]),-1,1)),v[p].applyMatrix4(x.makeRotationAxis(y,o))),g[p].crossVectors(m[p],v[p]);if(n)for(o=Math.acos(t.Math.clamp(v[0].dot(v[_-1]),-1,1)),o/=_-1,m[0].dot(y.crossVectors(v[0],v[_-1]))>0&&(o=-o),p=1;p<_;p++)v[p].applyMatrix4(x.makeRotationAxis(m[p],o*p)),g[p].crossVectors(m[p],v[p])},Fe.prototype=Object.create(q.prototype),Fe.prototype.constructor=Fe,Fe.prototype.addShapeList=function(t,e){for(var i=t.length,n=0;nNumber.EPSILON){var d=Math.sqrt(u),f=Math.sqrt(h*h+l*l),m=e.x-c/d,v=e.y+s/d,g=n.x-l/f,y=n.y+h/f,x=((g-m)*l-(y-v)*h)/(s*l-c*h);r=m+s*x-t.x,a=v+c*x-t.y;var _=r*r+a*a;if(_<=2)return new i(r,a);o=Math.sqrt(_/2)}else{var b=!1;s>Number.EPSILON?h>Number.EPSILON&&(b=!0):s<-Number.EPSILON?h<-Number.EPSILON&&(b=!0):Math.sign(c)===Math.sign(l)&&(b=!0),b?(r=-c,a=s,o=Math.sqrt(u)):(r=s,a=c,o=Math.sqrt(u/2))}return new i(r/o,a/o)}function o(){if(w){var t=0,e=X*t;for(Z=0;Z=0;){i=Z,n=Z-1,n<0&&(n=t.length-1);var r=0,a=E+2*b;for(r=0;r=0;B--){for(H=B/b,V=x*Math.cos(H*Math.PI/2),G=_*Math.sin(H*Math.PI/2),Z=0,J=z.length;ZNumber.EPSILON){if(h<0&&(o=e[a],c=-c,s=e[r],h=-h),t.ys.y)continue;if(t.y===o.y){if(t.x===o.x)return!0}else{var l=h*(t.x-o.x)-c*(t.y-o.y);if(0===l)return!0;if(l<0)continue;n=!n}}else{if(t.y!==o.y)continue;if(s.x<=t.x&&t.x<=o.x||o.x<=t.x&&t.x<=s.x)return!0}}return n}var a=t.ShapeUtils.isClockWise,o=this.subPaths;if(0===o.length)return[];if(i===!0)return n(o);var s,c,h,l=[];if(1===o.length)return c=o[0],h=new Be,h.curves=c.curves,l.push(h),l;var u=!a(o[0].getPoints());u=e?!u:u;var p,d=[],f=[],m=[],v=0;f[v]=void 0,m[v]=[];for(var g=0,y=o.length;g1){for(var x=!1,_=[],b=0,w=f.length;b0&&(x||(m=d))}for(var L,g=0,R=f.length;g0){this.source.connect(this.filters[0]);for(var t=1,e=this.filters.length;t0){this.source.disconnect(this.filters[0]);for(var t=1,e=this.filters.length;t=.5)for(var a=0;a!==r;++a)t[e+a]=t[i+a]},_slerp:function(t,e,i,n,r){o.slerpFlat(t,e,t,e,t,i,n)},_lerp:function(t,e,i,n,r){for(var a=1-n,o=0;o!==r;++o){var s=e+o;t[s]=t[s]*a+t[i+o]*n}}},$e.prototype={constructor:$e,getValue:function(t,e){this.bind(),this.getValue(t,e)},setValue:function(t,e){this.bind(),this.setValue(t,e)},bind:function(){var t=this.node,e=this.parsedPath,i=e.objectName,n=e.propertyName,r=e.propertyIndex;if(t||(t=$e.findNode(this.rootNode,e.nodeName)||this.rootNode,this.node=t),this.getValue=this._getValue_unavailable,this.setValue=this._setValue_unavailable,!t)return void console.error(" trying to update node for track: "+this.path+" but it wasn't found.");if(i){var a=e.objectIndex;switch(i){case"materials":if(!t.material)return void console.error(" can not bind to material as node does not have a material",this);if(!t.material.materials)return void console.error(" can not bind to material.materials as node.material does not have a materials array",this);t=t.material.materials;break;case"bones":if(!t.skeleton)return void console.error(" can not bind to bones as node does not have a skeleton",this);t=t.skeleton.bones;for(var o=0;o=i){var u=i++,p=e[u];n[p.uuid]=l,e[l]=p,n[h]=u,e[u]=c;for(var d=0,f=a;d!==f;++d){var m=r[d],v=m[u],g=m[l];m[l]=v,m[u]=g}}}this.nCachedObjects_=i},uncache:function(t){for(var e=this._objects,i=e.length,n=this.nCachedObjects_,r=this._indicesByUUID,a=this._bindings,o=a.length,s=0,c=arguments.length;s!==c;++s){var h=arguments[s],l=h.uuid,u=r[l];if(void 0!==u)if(delete r[l],u0)for(var c=this._interpolants,h=this._propertyBindings,l=0,u=c.length;l!==u;++l)c[l].evaluate(o),h[l].accumulate(n,s)},_updateWeight:function(t){var e=0;if(this.enabled){e=this.weight;var i=this._weightInterpolant;if(null!==i){var n=i.evaluate(t)[0];e*=n,t>i.parameterPositions[1]&&(this.stopFading(),0===n&&(this.enabled=!1))}}return this._effectiveWeight=e,e},_updateTimeScale:function(t){var e=0;if(!this.paused){e=this.timeScale;var i=this._timeScaleInterpolant;if(null!==i){var n=i.evaluate(t)[0];e*=n,t>i.parameterPositions[1]&&(this.stopWarping(),0===e?this.paused=!0:this.timeScale=e)}}return this._effectiveTimeScale=e,e},_updateTime:function(t){var e=this.time+t;if(0===t)return e;var i=this._clip.duration,n=this.loop,r=this._loopCount;if(n===ia){r===-1&&(this.loopCount=0,this._setEndings(!0,!0,!1));t:{if(e>=i)e=i;else{if(!(e<0))break t;e=0}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this._mixer.dispatchEvent({type:"finished",action:this,direction:t<0?-1:1})}}else{var a=n===ra;if(r===-1&&(t>=0?(r=0,this._setEndings(!0,0===this.repetitions,a)):this._setEndings(0===this.repetitions,!0,a)),e>=i||e<0){var o=Math.floor(e/i);e-=i*o,r+=Math.abs(o);var s=this.repetitions-r;if(s<0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,e=t>0?i:0,this._mixer.dispatchEvent({type:"finished",action:this,direction:t>0?1:-1});else{if(0===s){var c=t<0;this._setEndings(c,!c,a)}else this._setEndings(!1,!1,a);this._loopCount=r,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:o})}}if(a&&1===(1&r))return this.time=e,i-e}return this.time=e,e},_setEndings:function(t,e,i){var n=this._interpolantSettings;i?(n.endingStart=ha,n.endingEnd=ha):(t?n.endingStart=this.zeroSlopeAtStart?ha:ca:n.endingStart=la,e?n.endingEnd=this.zeroSlopeAtEnd?ha:ca:n.endingEnd=la)},_scheduleFading:function(t,e,i){var n=this._mixer,r=n.time,a=this._weightInterpolant;null===a&&(a=n._lendControlInterpolant(),this._weightInterpolant=a);var o=a.parameterPositions,s=a.sampleValues;return o[0]=r,s[0]=e,o[1]=r+t,s[1]=i,this}},Object.assign(ii.prototype,e.prototype,{clipAction:function(t,e){var i=e||this._root,n=i.uuid,r="string"==typeof t?Me.findByName(i,t):t,a=null!==r?r.uuid:t,o=this._actionsByClip[a],s=null;if(void 0!==o){var c=o.actionByRoot[n];if(void 0!==c)return c;s=o.knownActions[0],null===r&&(r=s._clip)}if(null===r)return null;var h=new ii._Action(this,r,e);return this._bindAction(h,s),this._addInactiveAction(h,a,n),h},existingAction:function(t,e){var i=e||this._root,n=i.uuid,r="string"==typeof t?Me.findByName(i,t):t,a=r?r.uuid:t,o=this._actionsByClip[a];return void 0!==o?o.actionByRoot[n]||null:null},stopAllAction:function(){var t=this._actions,e=this._nActiveActions,i=this._bindings,n=this._nActiveBindings;this._nActiveActions=0,this._nActiveBindings=0;for(var r=0;r!==e;++r)t[r].reset();for(var r=0;r!==n;++r)i[r].useCount=0;return this},update:function(t){t*=this.timeScale;for(var e=this._actions,i=this._nActiveActions,n=this.time+=t,r=Math.sign(t),a=this._accuIndex^=1,o=0;o!==i;++o){var s=e[o];s.enabled&&s._update(n,t,r,a)}for(var c=this._bindings,h=this._nActiveBindings,o=0;o!==h;++o)c[o].apply(a);return this},getRoot:function(){return this._root},uncacheClip:function(t){var e=this._actions,i=t.uuid,n=this._actionsByClip,r=n[i];if(void 0!==r){for(var a=r.knownActions,o=0,s=a.length;o!==s;++o){var c=a[o];this._deactivateAction(c);var h=c._cacheIndex,l=e[e.length-1];c._cacheIndex=null,c._byClipCacheIndex=null,l._cacheIndex=h,e[h]=l,e.pop(),this._removeInactiveBindingsForAction(c)}delete n[i]}},uncacheRoot:function(t){var e=t.uuid,i=this._actionsByClip;for(var n in i){var r=i[n].actionByRoot,a=r[e];void 0!==a&&(this._deactivateAction(a),this._removeInactiveAction(a))}var o=this._bindingsByRootAndName,s=o[e];if(void 0!==s)for(var c in s){var h=s[c];h.restoreOriginalState(),this._removeInactiveBinding(h)}},uncacheAction:function(t,e){var i=this.existingAction(t,e);null!==i&&(this._deactivateAction(i),this._removeInactiveAction(i))}}),ii._Action=ei._new,Object.assign(ii.prototype,{_bindAction:function(t,e){var i=t._localRoot||this._root,n=t._clip.tracks,r=n.length,a=t._propertyBindings,o=t._interpolants,s=i.uuid,c=this._bindingsByRootAndName,h=c[s];void 0===h&&(h={},c[s]=h);for(var l=0;l!==r;++l){var u=n[l],p=u.name,d=h[p];if(void 0!==d)a[l]=d;else{if(d=a[l],void 0!==d){null===d._cacheIndex&&(++d.referenceCount,this._addInactiveBinding(d,s,p));continue}var f=e&&e._propertyBindings[l].binding.parsedPath;d=new Ke($e.create(i,p,f),u.ValueTypeName,u.getValueSize()),++d.referenceCount,this._addInactiveBinding(d,s,p),a[l]=d}o[l].resultBuffer=d.buffer}},_activateAction:function(t){if(!this._isActiveAction(t)){if(null===t._cacheIndex){var e=(t._localRoot||this._root).uuid,i=t._clip.uuid,n=this._actionsByClip[i];this._bindAction(t,n&&n.knownActions[0]),this._addInactiveAction(t,i,e)}for(var r=t._propertyBindings,a=0,o=r.length;a!==o;++a){var s=r[a];0===s.useCount++&&(this._lendBinding(s),s.saveOriginalState())}this._lendAction(t)}},_deactivateAction:function(t){if(this._isActiveAction(t)){for(var e=t._propertyBindings,i=0,n=e.length;i!==n;++i){var r=e[i];0===--r.useCount&&(r.restoreOriginalState(),this._takeBackBinding(r))}this._takeBackAction(t)}},_initMemoryManager:function(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;var t=this;this.stats={actions:{get total(){return t._actions.length},get inUse(){return t._nActiveActions}},bindings:{get total(){return t._bindings.length},get inUse(){return t._nActiveBindings}},controlInterpolants:{get total(){return t._controlInterpolants.length},get inUse(){return t._nActiveControlInterpolants}}}},_isActiveAction:function(t){var e=t._cacheIndex;return null!==e&&e1){var h=c[1];n[h]||(n[h]={start:1/0,end:-(1/0)});var l=n[h];al.end&&(l.end=a),e||(e=h)}}for(var h in n){var l=n[h];this.createAnimation(h,l.start,l.end,t)}this.firstAnimation=e},mi.prototype.setAnimationDirectionForward=function(t){var e=this.animationsMap[t];e&&(e.direction=1,e.directionBackwards=!1)},mi.prototype.setAnimationDirectionBackward=function(t){var e=this.animationsMap[t];e&&(e.direction=-1,e.directionBackwards=!0)},mi.prototype.setAnimationFPS=function(t,e){var i=this.animationsMap[t];i&&(i.fps=e,i.duration=(i.end-i.start)/i.fps)},mi.prototype.setAnimationDuration=function(t,e){var i=this.animationsMap[t];i&&(i.duration=e,i.fps=(i.end-i.start)/i.duration)},mi.prototype.setAnimationWeight=function(t,e){var i=this.animationsMap[t];i&&(i.weight=e)},mi.prototype.setAnimationTime=function(t,e){var i=this.animationsMap[t];i&&(i.time=e)},mi.prototype.getAnimationTime=function(t){var e=0,i=this.animationsMap[t];return i&&(e=i.time),e},mi.prototype.getAnimationDuration=function(t){var e=-1,i=this.animationsMap[t];return i&&(e=i.duration),e},mi.prototype.playAnimation=function(t){var e=this.animationsMap[t];e?(e.time=0,e.active=!0):console.warn("THREE.MorphBlendMesh: animation["+t+"] undefined in .playAnimation()"); +},mi.prototype.stopAnimation=function(t){var e=this.animationsMap[t];e&&(e.active=!1)},mi.prototype.update=function(e){for(var i=0,n=this.animationsList.length;ir.duration||r.time<0)&&(r.direction*=-1,r.time>r.duration&&(r.time=r.duration,r.directionBackwards=!0),r.time<0&&(r.time=0,r.directionBackwards=!1)):(r.time=r.time%r.duration,r.time<0&&(r.time+=r.duration));var o=r.start+t.Math.clamp(Math.floor(r.time/a),0,r.length-1),s=r.weight;o!==r.currentFrame&&(this.morphTargetInfluences[r.lastFrame]=0,this.morphTargetInfluences[r.currentFrame]=1*s,this.morphTargetInfluences[o]=0,r.lastFrame=r.currentFrame,r.currentFrame=o);var c=r.time%a/a;r.directionBackwards&&(c=1-c),r.currentFrame!==r.lastFrame?(this.morphTargetInfluences[r.currentFrame]=c*s,this.morphTargetInfluences[r.lastFrame]=(1-c)*s):this.morphTargetInfluences[r.currentFrame]=s}}},vi.prototype=Object.create(X.prototype),vi.prototype.constructor=vi,vi.prototype.isImmediateRenderObject=!0,gi.prototype=Object.create(Q.prototype),gi.prototype.constructor=gi,yi.prototype=Object.create(Ct.prototype),yi.prototype.constructor=yi,xi.prototype=Object.create(Ct.prototype),xi.prototype.constructor=xi,xi.prototype.update=function(){var t=new s,e=new s,i=new S;return function(){var n=["a","b","c"];this.object.updateMatrixWorld(!0),i.getNormalMatrix(this.object.matrixWorld);var r=this.object.matrixWorld,a=this.geometry.attributes.position,o=this.object.geometry;if(o&&o.isGeometry)for(var s=o.vertices,c=o.faces,h=0,l=0,u=c.length;l.99999?this.quaternion.set(0,0,0,1):i.y<-.99999?this.quaternion.set(1,0,0,0):(e.set(i.z,0,-i.x).normalize(),t=Math.acos(i.y),this.quaternion.setFromAxisAngle(e,t))}}(),t.ArrowHelper.prototype.setLength=function(t,e,i){void 0===e&&(e=.2*t),void 0===i&&(i=.2*e),this.line.scale.set(1,Math.max(0,t-e),1),this.line.updateMatrix(),this.cone.scale.set(i,e,i),this.cone.position.y=t,this.cone.updateMatrix()},t.ArrowHelper.prototype.setColor=function(t){this.line.material.color.copy(t),this.cone.material.color.copy(t)},Oi.prototype=Object.create(Ct.prototype),Oi.prototype.constructor=Oi,Fi.prototype=Object.create(q.prototype),Fi.prototype.constructor=Fi,zi.prototype=Object.create(q.prototype),zi.prototype.constructor=zi,Bi.prototype=Object.create(zi.prototype),Bi.prototype.constructor=Bi,Gi.prototype=Object.create(zi.prototype),Gi.prototype.constructor=Gi,Hi.prototype=Object.create(zi.prototype),Hi.prototype.constructor=Hi,Vi.prototype=Object.create(zi.prototype),Vi.prototype.constructor=Vi,ki.prototype=Object.create(Q.prototype),ki.prototype.constructor=ki,ji.prototype=Object.create(q.prototype),ji.prototype.constructor=ji,Wi.prototype=Object.create(Q.prototype),Wi.prototype.constructor=Wi,Xi.prototype=Object.create(q.prototype),Xi.prototype.constructor=Xi,Yi.prototype=Object.create(Fe.prototype),Yi.prototype.constructor=Yi,qi.prototype=Object.create(Q.prototype),qi.prototype.constructor=qi,Zi.prototype=Object.create(q.prototype),Zi.prototype.constructor=Zi,Ji.prototype=Object.create(q.prototype),Ji.prototype.constructor=Ji,Qi.prototype=Object.create(Q.prototype),Qi.prototype.constructor=Qi,Ki.prototype=Object.create(q.prototype),Ki.prototype.constructor=Ki,$i.prototype=Object.create(q.prototype),$i.prototype.constructor=$i,tn.prototype=Object.create($i.prototype),tn.prototype.constructor=tn,en.prototype=Object.create(Q.prototype),en.prototype.constructor=en,nn.prototype=Object.create(Q.prototype),nn.prototype.constructor=nn,rn.prototype=Object.create(q.prototype),rn.prototype.constructor=rn,t.CatmullRomCurve3=function(){function t(){}var e=new s,i=new t,n=new t,r=new t;return t.prototype.init=function(t,e,i,n){this.c0=t,this.c1=i,this.c2=-3*t+3*e-2*i-n,this.c3=2*t-2*e+i+n},t.prototype.initNonuniformCatmullRom=function(t,e,i,n,r,a,o){var s=(e-t)/r-(i-t)/(r+a)+(i-e)/a,c=(i-e)/a-(n-e)/(a+o)+(n-i)/o;s*=a,c*=a,this.init(e,i,s,c)},t.prototype.initCatmullRom=function(t,e,i,n,r){this.init(e,i,r*(i-t),r*(n-e))},t.prototype.calc=function(t){var e=t*t,i=e*t;return this.c0+this.c1*t+this.c2*e+this.c3*i},Re.create(function(t){this.points=t||[],this.closed=!1},function(t){var a,o,c,h,l=this.points;h=l.length,h<2&&console.log("duh, you need at least 2 points"),a=(h-(this.closed?0:1))*t,o=Math.floor(a),c=a-o,this.closed?o+=o>0?0:(Math.floor(Math.abs(o)/l.length)+1)*l.length:0===c&&o===h-1&&(o=h-2,c=1);var u,p,d,f;if(this.closed||o>0?u=l[(o-1)%h]:(e.subVectors(l[0],l[1]).add(l[0]),u=e),p=l[o%h],d=l[(o+1)%h],this.closed||o+2i.length-2?i.length-1:r+1],l=i[r>i.length-3?i.length-1:r+2],u=t.CurveUtils.interpolate;return new s(u(o.x,c.x,h.x,l.x,a),u(o.y,c.y,h.y,l.y,a),u(o.z,c.z,h.z,l.z,a))});t.CubicBezierCurve3=Re.create(function(t,e,i,n){this.v0=t,this.v1=e,this.v2=i,this.v3=n},function(e){var i=t.ShapeUtils.b3;return new s(i(e,this.v0.x,this.v1.x,this.v2.x,this.v3.x),i(e,this.v0.y,this.v1.y,this.v2.y,this.v3.y),i(e,this.v0.z,this.v1.z,this.v2.z,this.v3.z))}),t.QuadraticBezierCurve3=Re.create(function(t,e,i){this.v0=t,this.v1=e,this.v2=i},function(e){var i=t.ShapeUtils.b2;return new s(i(e,this.v0.x,this.v1.x,this.v2.x),i(e,this.v0.y,this.v1.y,this.v2.y),i(e,this.v0.z,this.v1.z,this.v2.z))}),t.LineCurve3=Re.create(function(t,e){this.v1=t,this.v2=e},function(t){if(1===t)return this.v2.clone();var e=new s;return e.subVectors(this.v2,this.v1),e.multiplyScalar(t),e.add(this.v1),e}),on.prototype=Object.create(Ue.prototype),on.prototype.constructor=on,t.SceneUtils={createMultiMaterialObject:function(t,e){for(var i=new Dt,n=0,r=e.length;n[property:Integer itemSize] attribute is storing a 3-component vector (such as a position, normal, or color), then itemSize should be 3. -

[property:Integer length]

+

[property:Integer count]

Gives the total number of elements in the array.
diff --git a/docs/manual/introduction/Creating-a-scene.html b/docs/manual/introduction/Creating-a-scene.html index b80bfef2ccd8c7..060a0bffe80388 100644 --- a/docs/manual/introduction/Creating-a-scene.html +++ b/docs/manual/introduction/Creating-a-scene.html @@ -61,7 +61,7 @@

Creating the scene

In addition to creating the renderer instance, we also need to set the size at which we want it to render our app. It's a good idea to use the width and height of the area we want to fill with our app - in this case, the width and height of the browser window. For performance intensive apps, you can also give setSize smaller values, like window.innerWidth/2 and window.innerHeight/2, which will make the app render at half size.
-
If you wish to keep the size of your app but render it at a lower resolution, you can do so by calling setSize with false as updateStyle. For example, setSize(window.innerWidth/2, window.innerHeight/2, false) will render your app at half resolution, given that your <canvas> has 100% width and height.
+
If you wish to keep the size of your app but render it at a lower resolution, you can do so by calling setSize with false as updateStyle (the third arugment). For example, setSize(window.innerWidth/2, window.innerHeight/2, false) will render your app at half resolution, given that your <canvas> has 100% width and height.
Last but not least, we add the renderer element to our HTML document. This is a <canvas> element the renderer uses to display the scene to us.
diff --git a/editor/index.html b/editor/index.html index 9f8aef9e860676..5027d3a82ff96f 100644 --- a/editor/index.html +++ b/editor/index.html @@ -129,6 +129,7 @@ + @@ -253,6 +254,8 @@ signals.objectChanged.add( saveState ); signals.objectRemoved.add( saveState ); signals.materialChanged.add( saveState ); + signals.sceneBackgroundChanged.add( saveState ); + signals.sceneFogChanged.add( saveState ); signals.sceneGraphChanged.add( saveState ); signals.scriptChanged.add( saveState ); signals.historyChanged.add( saveState ); diff --git a/editor/js/Editor.js b/editor/js/Editor.js index 5a2380d2d24845..805cc9be01c1ba 100644 --- a/editor/js/Editor.js +++ b/editor/js/Editor.js @@ -47,6 +47,8 @@ var Editor = function () { spaceChanged: new Signal(), rendererChanged: new Signal(), + sceneBackgroundChanged: new Signal(), + sceneFogChanged: new Signal(), sceneGraphChanged: new Signal(), cameraChanged: new Signal(), @@ -69,9 +71,6 @@ var Editor = function () { scriptChanged: new Signal(), scriptRemoved: new Signal(), - fogTypeChanged: new Signal(), - fogColorChanged: new Signal(), - fogParametersChanged: new Signal(), windowResize: new Signal(), showGridChanged: new Signal(), @@ -90,6 +89,7 @@ var Editor = function () { this.scene = new THREE.Scene(); this.scene.name = 'Scene'; + this.scene.background = new THREE.Color( 0xaaaaaa ); this.sceneHelpers = new THREE.Scene(); @@ -120,6 +120,10 @@ Editor.prototype = { this.scene.uuid = scene.uuid; this.scene.name = scene.name; + + if ( scene.background !== null ) this.scene.background = scene.background.clone(); + if ( scene.fog !== null ) this.scene.fog = scene.fog.clone(); + this.scene.userData = JSON.parse( JSON.stringify( scene.userData ) ); // avoid render per object diff --git a/editor/js/Sidebar.Scene.js b/editor/js/Sidebar.Scene.js index 448f5859ba7fa3..2ce1ee22b2f929 100644 --- a/editor/js/Sidebar.Scene.js +++ b/editor/js/Sidebar.Scene.js @@ -76,34 +76,34 @@ Sidebar.Scene = function ( editor ) { container.add( outliner ); container.add( new UI.Break() ); - /* // background - var backgroundRow = new UI.Row(); - var background = new UI.Select().setOptions( { + function onBackgroundChanged() { - 'None': 'None', - 'Color': 'Color', - 'Texture': 'Texture' + signals.sceneBackgroundChanged.dispatch( backgroundColor.getHexValue() ); - } ).setWidth( '150px' ); - background.onChange( function () {} ); + } + + var backgroundRow = new UI.Row(); + + var backgroundColor = new UI.Color().setValue( '#aaaaaa' ).onChange( onBackgroundChanged ); backgroundRow.add( new UI.Text( 'Background' ).setWidth( '90px' ) ); - backgroundRow.add( background ); + backgroundRow.add( backgroundColor ); container.add( backgroundRow ); - */ // fog - function updateFogParameters() { - - var near = fogNear.getValue(); - var far = fogFar.getValue(); - var density = fogDensity.getValue(); + function onFogChanged() { - signals.fogParametersChanged.dispatch( near, far, density ); + signals.sceneFogChanged.dispatch( + fogType.getValue(), + fogColor.getHexValue(), + fogNear.getValue(), + fogFar.getValue(), + fogDensity.getValue() + ); } @@ -117,10 +117,7 @@ Sidebar.Scene = function ( editor ) { } ).setWidth( '150px' ); fogType.onChange( function () { - var type = fogType.getValue(); - - signals.fogTypeChanged.dispatch( type ); - + onFogChanged(); refreshFogUI(); } ); @@ -138,31 +135,27 @@ Sidebar.Scene = function ( editor ) { container.add( fogPropertiesRow ); var fogColor = new UI.Color().setValue( '#aaaaaa' ); - fogColor.onChange( function () { - - signals.fogColorChanged.dispatch( fogColor.getHexValue() ); - - } ); + fogColor.onChange( onFogChanged ); fogPropertiesRow.add( fogColor ); // fog near - var fogNear = new UI.Number( 0.1 ).setWidth( '40px' ).setRange( 0, Infinity ).onChange( updateFogParameters ); + var fogNear = new UI.Number( 0.1 ).setWidth( '40px' ).setRange( 0, Infinity ).onChange( onFogChanged ); fogPropertiesRow.add( fogNear ); // fog far - var fogFar = new UI.Number( 100 ).setWidth( '40px' ).setRange( 0, Infinity ).onChange( updateFogParameters ); + var fogFar = new UI.Number( 50 ).setWidth( '40px' ).setRange( 0, Infinity ).onChange( onFogChanged ); fogPropertiesRow.add( fogFar ); // fog density - var fogDensity = new UI.Number( 0.00025 ).setWidth( '40px' ).setRange( 0, 0.1 ).setPrecision( 5 ).onChange( updateFogParameters ); + var fogDensity = new UI.Number( 0.05 ).setWidth( '40px' ).setRange( 0, 0.1 ).setPrecision( 3 ).onChange( onFogChanged ); fogPropertiesRow.add( fogDensity ); // - var refreshUI = function () { + function refreshUI() { var camera = editor.camera; var scene = editor.scene; @@ -196,6 +189,12 @@ Sidebar.Scene = function ( editor ) { } + if ( scene.background ) { + + backgroundColor.setHexValue( scene.background.getHex() ); + + } + if ( scene.fog ) { fogColor.setHexValue( scene.fog.color.getHex() ); @@ -221,7 +220,7 @@ Sidebar.Scene = function ( editor ) { refreshFogUI(); - }; + } function refreshFogUI() { diff --git a/editor/js/Viewport.js b/editor/js/Viewport.js index d68501c124f25f..70a4d375db19cf 100644 --- a/editor/js/Viewport.js +++ b/editor/js/Viewport.js @@ -134,14 +134,6 @@ var Viewport = function ( editor ) { sceneHelpers.add( transformControls ); - // fog - - var oldFogType = "None"; - var oldFogColor = 0xaaaaaa; - var oldFogNear = 1; - var oldFogFar = 5000; - var oldFogDensity = 0.00025; - // object picking var raycaster = new THREE.Raycaster(); @@ -297,8 +289,6 @@ var Viewport = function ( editor ) { } ); - var clearColor; - signals.themeChanged.add( function ( value ) { switch ( value ) { @@ -307,19 +297,15 @@ var Viewport = function ( editor ) { sceneHelpers.remove( grid ); grid = new THREE.GridHelper( 30, 60, 0x444444, 0x888888 ); sceneHelpers.add( grid ); - clearColor = 0xaaaaaa; break; case 'css/dark.css': sceneHelpers.remove( grid ); grid = new THREE.GridHelper( 30, 60, 0xbbbbbb, 0x888888 ); sceneHelpers.add( grid ); - clearColor = 0x333333; break; } - renderer.setClearColor( clearColor ); - render(); } ); @@ -354,7 +340,6 @@ var Viewport = function ( editor ) { renderer.autoClear = false; renderer.autoUpdateScene = false; - renderer.setClearColor( clearColor ); renderer.setPixelRatio( window.devicePixelRatio ); renderer.setSize( container.dom.offsetWidth, container.dom.offsetHeight ); @@ -496,53 +481,58 @@ var Viewport = function ( editor ) { } ); - signals.fogTypeChanged.add( function ( fogType ) { + // fog + + signals.sceneBackgroundChanged.add( function ( backgroundColor ) { + + scene.background.setHex( backgroundColor ); - if ( fogType !== oldFogType ) { + render(); - if ( fogType === "None" ) { + } ); - scene.fog = null; + var currentFogType = null; - } else if ( fogType === "Fog" ) { + signals.sceneFogChanged.add( function ( fogType, fogColor, fogNear, fogFar, fogDensity ) { - scene.fog = new THREE.Fog( oldFogColor, oldFogNear, oldFogFar ); + if ( currentFogType !== fogType ) { - } else if ( fogType === "FogExp2" ) { + switch ( fogType ) { - scene.fog = new THREE.FogExp2( oldFogColor, oldFogDensity ); + case 'None': + scene.fog = null; + break; + case 'Fog': + scene.fog = new THREE.Fog(); + break; + case 'FogExp2': + scene.fog = new THREE.FogExp2(); + break; } - oldFogType = fogType; + currentFogType = fogType; } - render(); + if ( scene.fog instanceof THREE.Fog ) { - } ); + scene.fog.color.setHex( fogColor ); + scene.fog.near = fogNear; + scene.fog.far = fogFar; - signals.fogColorChanged.add( function ( fogColor ) { + } else if ( scene.fog instanceof THREE.FogExp2 ) { - oldFogColor = fogColor; + scene.fog.color.setHex( fogColor ); + scene.fog.density = fogDensity; - updateFog( scene ); + } render(); } ); - signals.fogParametersChanged.add( function ( near, far, density ) { - - oldFogNear = near; - oldFogFar = far; - oldFogDensity = density; - - updateFog( scene ); - - render(); - - } ); + // signals.windowResize.add( function () { @@ -569,20 +559,6 @@ var Viewport = function ( editor ) { // - function updateFog( root ) { - - if ( root.fog ) { - - root.fog.color.setHex( oldFogColor ); - - if ( root.fog.near !== undefined ) root.fog.near = oldFogNear; - if ( root.fog.far !== undefined ) root.fog.far = oldFogFar; - if ( root.fog.density !== undefined ) root.fog.density = oldFogDensity; - - } - - } - function animate() { requestAnimationFrame( animate ); @@ -628,14 +604,12 @@ var Viewport = function ( editor ) { vrControls.update(); camera.updateMatrixWorld(); - renderer.clear(); vrEffect.render( scene, vrCamera ); vrEffect.render( sceneHelpers, vrCamera ); } else { - renderer.clear(); renderer.render( scene, camera ); if ( renderer instanceof THREE.RaytracingRenderer === false ) { diff --git a/examples/files.js b/examples/files.js index 608ca183bfb23e..b691fe200eeeab 100644 --- a/examples/files.js +++ b/examples/files.js @@ -184,6 +184,7 @@ var files = { "webgl_physics_rope", "webgl_physics_cloth", "webgl_physics_volume", + "webgl_physics_convex_break", "webgl_points_billboards", "webgl_points_billboards_colors", "webgl_points_dynamic", diff --git a/examples/js/Cloth.js b/examples/js/Cloth.js index 647e811c6636e3..8175beb093340e 100644 --- a/examples/js/Cloth.js +++ b/examples/js/Cloth.js @@ -1,5 +1,5 @@ /* - * Cloth Simulation using a relaxed constrains solver + * Cloth Simulation using a relaxed constraints solver */ // Suggested Readings @@ -82,7 +82,7 @@ Particle.prototype.addForce = function( force ) { }; -// Performs verlet integration +// Performs Verlet integration Particle.prototype.integrate = function( timesq ) { @@ -101,7 +101,7 @@ Particle.prototype.integrate = function( timesq ) { var diff = new THREE.Vector3(); -function satisifyConstrains( p1, p2, distance ) { +function satisifyConstraints( p1, p2, distance ) { diff.subVectors( p2.position, p1.position ); var currentDist = diff.length(); @@ -122,7 +122,7 @@ function Cloth( w, h ) { this.h = h; var particles = []; - var constrains = []; + var constraints = []; var u, v; @@ -145,13 +145,13 @@ function Cloth( w, h ) { for ( u = 0; u < w; u ++ ) { - constrains.push( [ + constraints.push( [ particles[ index( u, v ) ], particles[ index( u, v + 1 ) ], restDistance ] ); - constrains.push( [ + constraints.push( [ particles[ index( u, v ) ], particles[ index( u + 1, v ) ], restDistance @@ -163,7 +163,7 @@ function Cloth( w, h ) { for ( u = w, v = 0; v < h; v ++ ) { - constrains.push( [ + constraints.push( [ particles[ index( u, v ) ], particles[ index( u, v + 1 ) ], restDistance @@ -174,7 +174,7 @@ function Cloth( w, h ) { for ( v = h, u = 0; u < w; u ++ ) { - constrains.push( [ + constraints.push( [ particles[ index( u, v ) ], particles[ index( u + 1, v ) ], restDistance @@ -183,8 +183,8 @@ function Cloth( w, h ) { } - // While many system uses shear and bend springs, - // the relax constrains model seem to be just fine + // While many systems use shear and bend springs, + // the relaxed constraints model seems to be just fine // using structural springs. // Shear // var diagonalDist = Math.sqrt(restDistance * restDistance * 2); @@ -193,13 +193,13 @@ function Cloth( w, h ) { // for (v=0;v 0 + + // Create vertices mark + var vertices = object.geometry.vertices; + for ( var i = 0, il = vertices.length; i < il; i++ ) { + vertices[ i ].mark = 0; + } + + var userData = object.userData; + userData.mass = mass; + userData.velocity = velocity.clone(); + userData.angularVelocity = angularVelocity.clone(); + userData.breakable = breakable; + + }, + + /* + * @param {int} maxRadialIterations Iterations for radial cuts. + * @param {int} maxRandomIterations Max random iterations for not-radial cuts + * @param {double} minSizeForRadialSubdivision Min size a debris can have to break in radial subdivision. + * + * Returns the array of pieces + */ + subdivideByImpact: function( object, pointOfImpact, normal, maxRadialIterations, maxRandomIterations, minSizeForRadialSubdivision ) { + + var debris = []; + + var tempPlane1 = this.tempPlane1; + var tempPlane2 = this.tempPlane2; + + this.tempVector3.addVectors( pointOfImpact, normal ); + tempPlane1.setFromCoplanarPoints( pointOfImpact, object.position, this.tempVector3 ); + + var maxTotalIterations = maxRandomIterations + maxRadialIterations; + + var scope = this; + + function subdivideRadial( subObject, startAngle, endAngle, numIterations ) { + + if ( Math.random() < numIterations * 0.05 || numIterations > maxTotalIterations ) { + + debris.push( subObject ); + + return; + + } + + var angle = Math.PI; + + if ( numIterations === 0 ) { + + tempPlane2.normal.copy( tempPlane1.normal ); + tempPlane2.constant = tempPlane1.constant; + + } + else { + + if ( numIterations <= maxRadialIterations ) { + + angle = ( endAngle - startAngle ) * ( 0.2 + 0.6 * Math.random() ) + startAngle; + + // Rotate tempPlane2 at impact point around normal axis and the angle + scope.tempVector3_2.copy( object.position ).sub( pointOfImpact ).applyAxisAngle( normal, angle ).add( pointOfImpact ); + tempPlane2.setFromCoplanarPoints( pointOfImpact, scope.tempVector3, scope.tempVector3_2 ); + + } + else { + + angle = ( ( 0.5 * ( numIterations & 1 ) ) + 0.2 * ( 2 - Math.random() ) ) * Math.PI; + + // Rotate tempPlane2 at object position around normal axis and the angle + scope.tempVector3_2.copy( pointOfImpact ).sub( subObject.position ).applyAxisAngle( normal, angle ).add( subObject.position ); + scope.tempVector3_3.copy( normal ).add( subObject.position ); + tempPlane2.setFromCoplanarPoints( subObject.position, scope.tempVector3_3, scope.tempVector3_2 ); + + } + + } + + // Perform the cut + scope.cutByPlane( subObject, tempPlane2, scope.tempResultObjects ); + + var obj1 = scope.tempResultObjects.object1; + var obj2 = scope.tempResultObjects.object2; + + if ( obj1 ) { + + subdivideRadial( obj1, startAngle, angle, numIterations + 1 ); + + } + + if ( obj2 ) { + + subdivideRadial( obj2, angle, endAngle, numIterations + 1 ); + + } + + } + + subdivideRadial( object, 0, 2 * Math.PI, 0 ); + + return debris; + + }, + + cutByPlane: function( object, plane, output ) { + + // Returns breakable objects in output.object1 and output.object2 members, the resulting 2 pieces of the cut. + // object2 can be null if the plane doesn't cut the object. + // object1 can be null only in case of internal error + // Returned value is number of pieces, 0 for error. + + var geometry = object.geometry; + var points = geometry.vertices; + var faces = geometry.faces; + + var numPoints = points.length; + + var points1 = []; + var points2 = []; + + var delta = this.smallDelta; + + // Reset vertices mark + for ( var i = 0; i < numPoints; i++ ) { + points[ i ].mark = 0; + } + + // Reset segments mark + var numPointPairs = numPoints * numPoints; + for ( var i = 0; i < numPointPairs; i++ ) { + this.segments[ i ] = false; + } + + // Iterate through the faces to mark edges shared by coplanar faces + for ( var i = 0, il = faces.length - 1; i < il; i++ ) { + + var face1 = faces[ i ]; + + for ( var j = i + 1, jl = faces.length; j < jl; j++ ) { + + var face2 = faces[ j ]; + + var coplanar = 1 - face1.normal.dot( face2.normal ) < delta; + + if ( coplanar ) { + + var a1 = face1.a; + var b1 = face1.b; + var c1 = face1.c; + var a2 = face2.a; + var b2 = face2.b; + var c2 = face2.c; + + + if ( a1 === a2 || a1 === b2 || a1 === c2 ) { + if ( b1 === a2 || b1 === b2 || b1 === c2 ) { + this.segments[ a1 * numPoints + b1 ] = true; + this.segments[ b1 * numPoints + a1 ] = true; + } + else { + this.segments[ c1 * numPoints + a1 ] = true; + this.segments[ a1 * numPoints + c1 ] = true; + } + } + else if ( b1 === a2 || b1 === b2 || b1 === c2 ) { + this.segments[ c1 * numPoints + b1 ] = true; + this.segments[ b1 * numPoints + c1 ] = true; + } + + } + + } + + } + + // Transform the plane to object local space + var localPlane = this.tempPlane1; + object.updateMatrix(); + THREE.ConvexObjectBreaker.transformPlaneToLocalSpace( plane, object.matrix, localPlane ); + + // Iterate through the faces adding points to both pieces + for ( var i = 0, il = faces.length; i < il; i ++ ) { + + var face = faces[ i ]; + + for ( var segment = 0; segment < 3; segment++ ) { + + var i0 = segment === 0 ? face.a : ( segment === 1 ? face.b : face.c ); + var i1 = segment === 0 ? face.b : ( segment === 1 ? face.c : face.a ); + + var segmentState = this.segments[ i0 * numPoints + i1 ]; + + if ( segmentState ) { + // The segment already has been processed in another face + continue; + } + + // Mark segment as processed (also inverted segment) + this.segments[ i0 * numPoints + i1 ] = true; + this.segments[ i1 * numPoints + i0 ] = true; + + var p0 = points[ i0 ]; + var p1 = points[ i1 ]; + + if ( p0.mark === 0 ) { + + var d = localPlane.distanceToPoint( p0 ); + + // mark: 1 for negative side, 2 for positive side, 3 for coplanar point + if ( d > delta ) { + p0.mark = 2; + points2.push( p0 ); + } + else if ( d < - delta ) { + p0.mark = 1; + points1.push( p0 ); + } + else { + p0.mark = 3; + points1.push( p0 ); + var p0_2 = p0.clone(); + p0_2.mark = 3; + points2.push( p0_2 ); + } + + } + + if ( p1.mark === 0 ) { + + var d = localPlane.distanceToPoint( p1 ); + + // mark: 1 for negative side, 2 for positive side, 3 for coplanar point + if ( d > delta ) { + p1.mark = 2; + points2.push( p1 ); + } + else if ( d < - delta ) { + p1.mark = 1; + points1.push( p1 ); + } + else { + p1.mark = 3; + points1.push( p1 ); + var p1_2 = p1.clone(); + p1_2.mark = 3; + points2.push( p1_2 ); + } + + } + + var mark0 = p0.mark; + var mark1 = p1.mark; + + if ( ( mark0 === 1 && mark1 === 2 ) || ( mark0 === 2 && mark1 === 1 ) ) { + + // Intersection of segment with the plane + + this.tempLine1.start.copy( p0 ); + this.tempLine1.end.copy( p1 ); + var intersection = localPlane.intersectLine( this.tempLine1 ); + if ( intersection === undefined ) { + // Shouldn't happen + console.error( "Internal error: segment does not intersect plane." ); + output.segmentedObject1 = null; + output.segmentedObject2 = null; + return 0; + } + + intersection.mark = 1; + points1.push( intersection ); + var intersection_2 = intersection.clone(); + intersection_2.mark = 2; + points2.push( intersection_2 ); + + } + + } + + } + + // Calculate debris mass (very fast and imprecise): + var newMass = object.userData.mass * 0.5; + + // Calculate debris Center of Mass (again fast and imprecise) + this.tempCM1.set( 0, 0, 0 ); + var radius1 = 0; + var numPoints1 = points1.length; + if ( numPoints1 > 0 ) { + for ( var i = 0; i < numPoints1; i++ ) { + this.tempCM1.add( points1[ i ] ); + } + this.tempCM1.divideScalar( numPoints1 ); + for ( var i = 0; i < numPoints1; i++ ) { + var p = points1[ i ]; + p.sub( this.tempCM1 ); + radius1 = Math.max( radius1, p.x, p.y, p.z ); + } + this.tempCM1.add( object.position ); + } + + this.tempCM2.set( 0, 0, 0 ); + var radius2 = 0; + var numPoints2 = points2.length; + if ( numPoints2 > 0 ) { + for ( var i = 0; i < numPoints2; i++ ) { + this.tempCM2.add( points2[ i ] ); + } + this.tempCM2.divideScalar( numPoints2 ); + for ( var i = 0; i < numPoints2; i++ ) { + var p = points2[ i ]; + p.sub( this.tempCM2 ); + radius2 = Math.max( radius2, p.x, p.y, p.z ); + } + this.tempCM2.add( object.position ); + } + + var object1 = null; + var object2 = null; + + var numObjects = 0; + + if ( numPoints1 > 4 ) { + + object1 = new THREE.Mesh( new THREE.ConvexGeometry( points1 ), object.material ); + object1.position.copy( this.tempCM1 ); + object1.quaternion.copy( object.quaternion ); + + this.prepareBreakableObject( object1, newMass, object.userData.velocity, object.userData.angularVelocity, 2 * radius1 > this.minSizeForBreak ); + + numObjects++; + + } + + if ( numPoints2 > 4 ) { + + object2 = new THREE.Mesh( new THREE.ConvexGeometry( points2 ), object.material ); + object2.position.copy( this.tempCM2 ); + object2.quaternion.copy( object.quaternion ); + + this.prepareBreakableObject( object2, newMass, object.userData.velocity, object.userData.angularVelocity, 2 * radius2 > this.minSizeForBreak ); + + numObjects++; + + } + + + output.object1 = object1; + output.object2 = object2; + + return numObjects; + + } + +}; + +THREE.ConvexObjectBreaker.transformFreeVector = function( v, m ) { + + // input: + // vector interpreted as a free vector + // THREE.Matrix4 orthogonal matrix (matrix without scale) + + var x = v.x, y = v.y, z = v.z; + var e = m.elements; + + v.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z; + v.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z; + v.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z; + + return v; + +}; + +THREE.ConvexObjectBreaker.transformFreeVectorInverse = function( v, m ) { + + // input: + // vector interpreted as a free vector + // THREE.Matrix4 orthogonal matrix (matrix without scale) + + var x = v.x, y = v.y, z = v.z; + var e = m.elements; + + v.x = e[ 0 ] * x + e[ 1 ] * y + e[ 2 ] * z; + v.y = e[ 4 ] * x + e[ 5 ] * y + e[ 6 ] * z; + v.z = e[ 8 ] * x + e[ 9 ] * y + e[ 10 ] * z; + + return v; + +}; + +THREE.ConvexObjectBreaker.transformTiedVectorInverse = function( v, m ) { + + // input: + // vector interpreted as a tied (ordinary) vector + // THREE.Matrix4 orthogonal matrix (matrix without scale) + + var x = v.x, y = v.y, z = v.z; + var e = m.elements; + + v.x = e[ 0 ] * x + e[ 1 ] * y + e[ 2 ] * z - e[ 12 ]; + v.y = e[ 4 ] * x + e[ 5 ] * y + e[ 6 ] * z - e[ 13 ]; + v.z = e[ 8 ] * x + e[ 9 ] * y + e[ 10 ] * z - e[ 14 ]; + + return v; + +}; + +THREE.ConvexObjectBreaker.transformPlaneToLocalSpace = function() { + + var v1 = new THREE.Vector3(); + var m1 = new THREE.Matrix3(); + + return function transformPlaneToLocalSpace( plane, m, resultPlane ) { + + resultPlane.normal.copy( plane.normal ); + resultPlane.constant = plane.constant; + + var referencePoint = THREE.ConvexObjectBreaker.transformTiedVectorInverse( plane.coplanarPoint( v1 ), m ); + + THREE.ConvexObjectBreaker.transformFreeVectorInverse( resultPlane.normal, m ); + + // recalculate constant (like in setFromNormalAndCoplanarPoint) + resultPlane.constant = - referencePoint.dot( resultPlane.normal ); + + + }; + +}(); diff --git a/examples/js/effects/StereoEffect.js b/examples/js/effects/StereoEffect.js index d2abecf31f10d2..7930491271f8a1 100644 --- a/examples/js/effects/StereoEffect.js +++ b/examples/js/effects/StereoEffect.js @@ -10,6 +10,12 @@ THREE.StereoEffect = function ( renderer ) { var _stereo = new THREE.StereoCamera(); _stereo.aspect = 0.5; + this.setEyeSeparation = function ( eyeSep ) { + + _stereo.eyeSep = eyeSep; + + }; + this.setSize = function ( width, height ) { renderer.setSize( width, height ); diff --git a/examples/js/effects/VREffect.js b/examples/js/effects/VREffect.js index 26882095faf004..b1305251d569ca 100644 --- a/examples/js/effects/VREffect.js +++ b/examples/js/effects/VREffect.js @@ -119,7 +119,7 @@ THREE.VREffect = function ( renderer, onError ) { var leftBounds = [ 0.0, 0.0, 0.5, 1.0 ]; var rightBounds = [ 0.5, 0.0, 0.5, 1.0 ]; - function onFullscreenChange () { + function onFullscreenChange() { var wasPresenting = scope.isPresenting; scope.isPresenting = vrDisplay !== undefined && ( vrDisplay.isPresenting || ( ! isWebVR1 && document[ fullscreenElement ] instanceof window.HTMLElement ) ); @@ -137,12 +137,13 @@ THREE.VREffect = function ( renderer, onError ) { if ( vrDisplay.getLayers ) { var layers = vrDisplay.getLayers(); - if (layers.length) { + if ( layers.length ) { leftBounds = layers[0].leftBounds || [ 0.0, 0.0, 0.5, 1.0 ]; rightBounds = layers[0].rightBounds || [ 0.5, 0.0, 0.5, 1.0 ]; } + } } else { @@ -271,7 +272,7 @@ THREE.VREffect = function ( renderer, onError ) { } }; - + this.cancelAnimationFrame = function ( h ) { if ( isWebVR1 && vrDisplay !== undefined ) { @@ -285,7 +286,7 @@ THREE.VREffect = function ( renderer, onError ) { } }; - + this.submitFrame = function () { if ( isWebVR1 && vrDisplay !== undefined && scope.isPresenting ) { @@ -361,13 +362,13 @@ THREE.VREffect = function ( renderer, onError ) { height: Math.round(size.height * rightBounds[ 3 ] ) }; - if (renderTarget) { - - renderer.setRenderTarget(renderTarget); + if ( renderTarget ) { + + renderer.setRenderTarget( renderTarget ); renderTarget.scissorTest = true; - + } else { - + renderer.setScissorTest( true ); } @@ -390,8 +391,8 @@ THREE.VREffect = function ( renderer, onError ) { // render left eye if ( renderTarget ) { - renderTarget.viewport.set(renderRectL.x, renderRectL.y, renderRectL.width, renderRectL.height); - renderTarget.scissor.set(renderRectL.x, renderRectL.y, renderRectL.width, renderRectL.height); + renderTarget.viewport.set( renderRectL.x, renderRectL.y, renderRectL.width, renderRectL.height ); + renderTarget.scissor.set( renderRectL.x, renderRectL.y, renderRectL.width, renderRectL.height ); } else { @@ -402,10 +403,10 @@ THREE.VREffect = function ( renderer, onError ) { renderer.render( scene, cameraL, renderTarget, forceClear ); // render right eye - if (renderTarget) { + if ( renderTarget ) { - renderTarget.viewport.set(renderRectR.x, renderRectR.y, renderRectR.width, renderRectR.height); - renderTarget.scissor.set(renderRectR.x, renderRectR.y, renderRectR.width, renderRectR.height); + renderTarget.viewport.set( renderRectR.x, renderRectR.y, renderRectR.width, renderRectR.height ); + renderTarget.scissor.set( renderRectR.x, renderRectR.y, renderRectR.width, renderRectR.height ); } else { @@ -415,7 +416,7 @@ THREE.VREffect = function ( renderer, onError ) { } renderer.render( scene, cameraR, renderTarget, forceClear ); - if (renderTarget) { + if ( renderTarget ) { renderTarget.viewport.set( 0, 0, size.width, size.height ); renderTarget.scissor.set( 0, 0, size.width, size.height ); diff --git a/examples/js/loaders/MMDLoader.js b/examples/js/loaders/MMDLoader.js index 4d60126b3beb4e..75006011bf7aa5 100644 --- a/examples/js/loaders/MMDLoader.js +++ b/examples/js/loaders/MMDLoader.js @@ -479,10 +479,7 @@ THREE.MMDLoader.prototype.parsePmd = function ( buffer ) { var parseBone = function () { var p = {}; - // Skinning animation doesn't work when bone name is Japanese Unicode in r73. - // So using charcode strings as workaround and keep original strings in .originalName. - p.originalName = dv.getSjisStringsAsUnicode( 20 ); - p.name = helper.toCharcodeStrings( p.originalName ); + p.name = dv.getSjisStringsAsUnicode( 20 ); p.parentIndex = dv.getInt16(); p.tailIndex = dv.getInt16(); p.type = dv.getUint8(); @@ -1085,10 +1082,7 @@ THREE.MMDLoader.prototype.parsePmx = function ( buffer ) { var parseBone = function () { var p = {}; - // Skinning animation doesn't work when bone name is Japanese Unicode in r73. - // So using charcode strings as workaround and keep original strings in .originalName. - p.originalName = dv.getTextBuffer(); - p.name = helper.toCharcodeStrings( p.originalName ); + p.name = dv.getTextBuffer(); p.englishName = dv.getTextBuffer(); p.position = dv.getFloat32Array( 3 ); p.parentIndex = dv.getIndex( pmx.metadata.boneIndexSize ); @@ -1428,10 +1422,7 @@ THREE.MMDLoader.prototype.parseVmd = function ( buffer ) { var parseMotion = function () { var p = {}; - // Skinning animation doesn't work when bone name is Japanese Unicode in r73. - // So using charcode strings as workaround and keep original strings in .originalName. - p.originalBoneName = dv.getSjisStringsAsUnicode( 15 ); - p.boneName = helper.toCharcodeStrings( p.originalBoneName ); + p.boneName = dv.getSjisStringsAsUnicode( 15 ); p.frameNum = dv.getUint32(); p.position = dv.getFloat32Array( 3 ); p.rotation = dv.getFloat32Array( 4 ); @@ -1649,8 +1640,7 @@ THREE.MMDLoader.prototype.parseVpd = function ( text ) { bones.push( { - originalName: n, - name: helper.toCharcodeStrings( n ), + name: n, translation: v, quaternion: q @@ -1808,9 +1798,7 @@ THREE.MMDLoader.prototype.createMesh = function ( model, texturePath, onProgress var link = {}; link.index = ik.links[ j ].index; - // Checking with .originalName, not .name. - // See parseBone() for the detail. - if ( model.bones[ link.index ].originalName.indexOf( 'ひざ' ) >= 0 ) { + if ( model.bones[ link.index ].name.indexOf( 'ひざ' ) >= 0 ) { link.limitation = new THREE.Vector3( 1.0, 0.0, 0.0 ); @@ -2590,21 +2578,6 @@ THREE.MMDLoader.prototype.createMesh = function ( model, texturePath, onProgress }; - function saveOriginalBoneNames ( mesh ) { - - var bones = mesh.skeleton.bones; - var bones2 = mesh.geometry.bones; - - for ( var i = 0; i < bones.length; i++ ) { - - var n = model.bones[ i ].originalName; - bones[ i ].originalName = n; - bones2[ i ].originalName = n; - - } - - }; - this.leftToRightModel( model ); initVartices(); @@ -2624,8 +2597,6 @@ THREE.MMDLoader.prototype.createMesh = function ( model, texturePath, onProgress var mesh = new THREE.SkinnedMesh( geometry, material ); - saveOriginalBoneNames( mesh ); - // console.log( mesh ); // for console debug return mesh; diff --git a/examples/js/loaders/STLLoader.js b/examples/js/loaders/STLLoader.js index 1040a253f9b573..bbcff10aa7026d 100644 --- a/examples/js/loaders/STLLoader.js +++ b/examples/js/loaders/STLLoader.js @@ -244,13 +244,13 @@ THREE.STLLoader.prototype = { if ( typeof buf !== "string" ) { var array_buffer = new Uint8Array( buf ); - var str = ''; + var strArray = []; for ( var i = 0; i < buf.byteLength; i ++ ) { - str += String.fromCharCode( array_buffer[ i ] ); // implicitly assumes little-endian + strArray.push(String.fromCharCode( array_buffer[ i ] )); // implicitly assumes little-endian } - return str; + return strArray.join(''); } else { diff --git a/examples/webgl_animation_cloth.html b/examples/webgl_animation_cloth.html index 0f690076296120..8a31649664ab97 100644 --- a/examples/webgl_animation_cloth.html +++ b/examples/webgl_animation_cloth.html @@ -30,7 +30,7 @@
Simple Cloth Simulation
- Verlet integration with Constrains relaxation
+ Verlet integration with relaxed constraints
Wind | Ball | Pins diff --git a/examples/webgl_lights_physical.html b/examples/webgl_lights_physical.html index 60059b2f9c891a..1f4ed40f0bf12e 100644 --- a/examples/webgl_lights_physical.html +++ b/examples/webgl_lights_physical.html @@ -41,9 +41,9 @@
- - - + + + - - - + + + - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + - + diff --git a/examples/webgl_physics_convex_break.html b/examples/webgl_physics_convex_break.html new file mode 100644 index 00000000000000..caa7a2e10556b0 --- /dev/null +++ b/examples/webgl_physics_convex_break.html @@ -0,0 +1,561 @@ + + + Convex object breaking example + + + + + +
Physics threejs demo with convex objects breaking in real time
Press mouse to throw balls and move the camera.
+





Loading...
+ + + + + + + + + + + + + diff --git a/examples/webgl_postprocessing_backgrounds.html b/examples/webgl_postprocessing_backgrounds.html index a694297c0ba838..af907f5cb95be1 100644 --- a/examples/webgl_postprocessing_backgrounds.html +++ b/examples/webgl_postprocessing_backgrounds.html @@ -190,14 +190,14 @@ composer.addPass( texturePass ); var textureLoader = new THREE.TextureLoader(); - textureLoader.load( "../examples/textures/hardwood2_diffuse.jpg", function( map ) { + textureLoader.load( "textures/hardwood2_diffuse.jpg", function( map ) { texturePass.map = map; }); cubeTexturePassP = new THREE.CubeTexturePass( cameraP ); composer.addPass( cubeTexturePassP ); - var ldrUrls = genCubeUrls( "./textures/cube/pisa/", ".png" ); + var ldrUrls = genCubeUrls( "textures/cube/pisa/", ".png" ); new THREE.CubeTextureLoader().load( ldrUrls, function ( ldrCubeMap ) { cubeTexturePassP.envMap = ldrCubeMap; console.log( "loaded envmap"); diff --git a/examples/webgl_tonemapping.html b/examples/webgl_tonemapping.html index 54bd4d7e57256f..28bdd70f46a8ba 100644 --- a/examples/webgl_tonemapping.html +++ b/examples/webgl_tonemapping.html @@ -32,24 +32,24 @@
threejs - Inline Tone Mapping (within a Material's fragment shader) without
using a pre-processing step or float/half buffers by Ben Houston.
- + - - + + - - - - - - - + + + + + + + - - - - - + + + + +