diff --git a/build/three.js b/build/three.js index a04e6e27827d261481bd87ac8853620fc9858a97..398a2e67975f685a56e389a05b73d232f466926e 100644 --- a/build/three.js +++ b/build/three.js @@ -4,40878 +4,40878 @@ (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 ) { - - return Math.max( min, Math.min( max, value ) ); - - }, - - // compute euclidian modulo of m % n - // https://en.wikipedia.org/wiki/Modulo_operation - - euclideanModulo: function ( n, m ) { - - return ( ( n % m ) + m ) % m; - - }, - - // Linear mapping from range to range - - mapLinear: function ( x, a1, a2, b1, b2 ) { - - return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 ); - - }, - - // 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 ); - - return x * x * ( 3 - 2 * x ); - - }, - - smootherstep: function ( x, min, max ) { - - if ( x <= min ) return 0; - if ( x >= max ) return 1; - - x = ( x - min ) / ( max - min ); - - return x * x * x * ( x * ( x * 6 - 15 ) + 10 ); - - }, - - random16: function () { - - console.warn( 'THREE.Math.random16() has been deprecated. Use Math.random() instead.' ); - return Math.random(); - - }, - - // Random integer from interval - - randInt: function ( low, high ) { - - return low + Math.floor( Math.random() * ( high - low + 1 ) ); - - }, - - // Random float from interval - - randFloat: function ( low, high ) { - - return low + Math.random() * ( high - low ); - - }, - - // Random float from <-range/2, range/2> interval - - randFloatSpread: function ( range ) { - - return range * ( 0.5 - Math.random() ); - - }, - - degToRad: function ( degrees ) { - - return degrees * exports.Math.DEG2RAD; - - }, - - radToDeg: function ( radians ) { - - return radians * exports.Math.RAD2DEG; - - }, + } - isPowerOfTwo: function ( value ) { + // - return ( value & ( value - 1 ) ) === 0 && value !== 0; + if ( Math.sign === undefined ) { - }, + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign - nearestPowerOfTwo: function ( value ) { + Math.sign = function ( x ) { - return Math.pow( 2, Math.round( Math.log( value ) / Math.LN2 ) ); + return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x; - }, + }; - nextPowerOfTwo: function ( value ) { + } - value --; - value |= value >> 1; - value |= value >> 2; - value |= value >> 4; - value |= value >> 8; - value |= value >> 16; - value ++; + if ( Function.prototype.name === undefined ) { - return value; + // 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 () { - /** - * @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 this.toString().match( /^\s*function\s*(\S*)\s*\(/ )[ 1 ]; - function Vector2( x, y ) { + } - this.x = x || 0; - this.y = y || 0; + } ); - }; + } - Vector2.prototype = { + if ( Object.assign === undefined ) { - constructor: Vector2, + // Missing in IE. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign - isVector2: true, + ( function () { - get width() { + Object.assign = function ( target ) { - return this.x; + 'use strict'; - }, + if ( target === undefined || target === null ) { - set width( value ) { + throw new TypeError( 'Cannot convert undefined or null to object' ); - this.x = value; + } - }, + var output = Object( target ); - get height() { + for ( var index = 1; index < arguments.length; index ++ ) { - return this.y; + var source = arguments[ index ]; - }, + if ( source !== undefined && source !== null ) { - set height( value ) { + for ( var nextKey in source ) { - this.y = value; + if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) { - }, + output[ nextKey ] = source[ nextKey ]; - // + } - set: function ( x, y ) { + } - this.x = x; - this.y = y; + } - return this; + } - }, + return output; - setScalar: function ( scalar ) { + }; - this.x = scalar; - this.y = scalar; + } )(); - return this; + } - }, + /** + * https://github.com/mrdoob/eventdispatcher.js/ + */ - setX: function ( x ) { + function EventDispatcher() {} - this.x = x; + Object.assign( EventDispatcher.prototype, { - return this; + addEventListener: function ( type, listener ) { - }, + if ( this._listeners === undefined ) this._listeners = {}; - setY: function ( y ) { + var listeners = this._listeners; - this.y = y; + if ( listeners[ type ] === undefined ) { - return this; + listeners[ type ] = []; - }, + } - setComponent: function ( index, value ) { + if ( listeners[ type ].indexOf( listener ) === - 1 ) { - switch ( index ) { + listeners[ type ].push( listener ); - case 0: this.x = value; break; - case 1: this.y = value; break; - default: throw new Error( 'index is out of range: ' + index ); + } - } + }, - }, + hasEventListener: function ( type, listener ) { - getComponent: function ( index ) { + if ( this._listeners === undefined ) return false; - switch ( index ) { + var listeners = this._listeners; - case 0: return this.x; - case 1: return this.y; - default: throw new Error( 'index is out of range: ' + index ); + if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) { - } + return true; - }, + } - clone: function () { + return false; - return new this.constructor( this.x, this.y ); + }, - }, + removeEventListener: function ( type, listener ) { - copy: function ( v ) { + if ( this._listeners === undefined ) return; - this.x = v.x; - this.y = v.y; + var listeners = this._listeners; + var listenerArray = listeners[ type ]; - return this; + if ( listenerArray !== undefined ) { - }, + var index = listenerArray.indexOf( listener ); - add: function ( v, w ) { + if ( index !== - 1 ) { - if ( w !== undefined ) { + listenerArray.splice( index, 1 ); - console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); - return this.addVectors( v, w ); + } - } + } - this.x += v.x; - this.y += v.y; + }, - return this; + dispatchEvent: function ( event ) { - }, + if ( this._listeners === undefined ) return; - addScalar: function ( s ) { + var listeners = this._listeners; + var listenerArray = listeners[ event.type ]; - this.x += s; - this.y += s; + if ( listenerArray !== undefined ) { - return this; + event.target = this; - }, + var array = [], i = 0; + var length = listenerArray.length; - addVectors: function ( a, b ) { + for ( i = 0; i < length; i ++ ) { - this.x = a.x + b.x; - this.y = a.y + b.y; + array[ i ] = listenerArray[ i ]; - return this; + } - }, + for ( i = 0; i < length; i ++ ) { - addScaledVector: function ( v, s ) { + array[ i ].call( this, event ); - this.x += v.x * s; - this.y += v.y * s; + } - return this; + } - }, + } - sub: function ( v, w ) { + } ); + + 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 ) ); - if ( w !== undefined ) { + }, - console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); - return this.subVectors( v, w ); + // compute euclidian modulo of m % n + // https://en.wikipedia.org/wiki/Modulo_operation - } + euclideanModulo: function ( n, m ) { - this.x -= v.x; - this.y -= v.y; + return ( ( n % m ) + m ) % m; - return this; + }, - }, + // Linear mapping from range to range - subScalar: function ( s ) { + mapLinear: function ( x, a1, a2, b1, b2 ) { - this.x -= s; - this.y -= s; + return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 ); - return this; + }, - }, + // http://en.wikipedia.org/wiki/Smoothstep - subVectors: function ( a, b ) { + smoothstep: function ( x, min, max ) { - this.x = a.x - b.x; - this.y = a.y - b.y; + if ( x <= min ) return 0; + if ( x >= max ) return 1; - return this; + x = ( x - min ) / ( max - min ); - }, + return x * x * ( 3 - 2 * x ); - multiply: function ( v ) { + }, - this.x *= v.x; - this.y *= v.y; + smootherstep: function ( x, min, max ) { - return this; + if ( x <= min ) return 0; + if ( x >= max ) return 1; - }, + x = ( x - min ) / ( max - min ); - multiplyScalar: function ( scalar ) { + return x * x * x * ( x * ( x * 6 - 15 ) + 10 ); - if ( isFinite( scalar ) ) { + }, - this.x *= scalar; - this.y *= scalar; + random16: function () { - } else { + console.warn( 'THREE.Math.random16() has been deprecated. Use Math.random() instead.' ); + return Math.random(); - this.x = 0; - this.y = 0; + }, - } + // Random integer from interval - return this; + randInt: function ( low, high ) { - }, + return low + Math.floor( Math.random() * ( high - low + 1 ) ); - divide: function ( v ) { + }, - this.x /= v.x; - this.y /= v.y; + // Random float from interval - return this; + randFloat: function ( low, high ) { - }, + return low + Math.random() * ( high - low ); - divideScalar: function ( scalar ) { + }, - return this.multiplyScalar( 1 / scalar ); + // Random float from <-range/2, range/2> interval - }, + randFloatSpread: function ( range ) { - min: function ( v ) { + return range * ( 0.5 - Math.random() ); - this.x = Math.min( this.x, v.x ); - this.y = Math.min( this.y, v.y ); + }, - return this; + degToRad: function ( degrees ) { - }, + return degrees * exports.Math.DEG2RAD; - max: function ( v ) { + }, - this.x = Math.max( this.x, v.x ); - this.y = Math.max( this.y, v.y ); + radToDeg: function ( radians ) { - return this; + return radians * exports.Math.RAD2DEG; - }, + }, - clamp: function ( min, max ) { + isPowerOfTwo: function ( value ) { - // This function assumes min < max, if this assumption isn't true it will not operate correctly + return ( value & ( value - 1 ) ) === 0 && value !== 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 ) ); + }, - return this; + nearestPowerOfTwo: function ( value ) { - }, + return Math.pow( 2, Math.round( Math.log( value ) / Math.LN2 ) ); - clampScalar: function () { + }, - var min, max; + nextPowerOfTwo: function ( value ) { - return function clampScalar( minVal, maxVal ) { + value --; + value |= value >> 1; + value |= value >> 2; + value |= value >> 4; + value |= value >> 8; + value |= value >> 16; + value ++; - if ( min === undefined ) { + return value; - min = new Vector2(); - max = new Vector2(); + } - } + }; - min.set( minVal, minVal ); - max.set( maxVal, maxVal ); + /** + * @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 this.clamp( min, max ); + function Vector2( x, y ) { - }; + this.x = x || 0; + this.y = y || 0; - }(), + }; - clampLength: function ( min, max ) { + Vector2.prototype = { - var length = this.length(); + constructor: Vector2, - return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length ); + isVector2: true, - }, + get width() { - floor: function () { + return this.x; - this.x = Math.floor( this.x ); - this.y = Math.floor( this.y ); + }, - return this; + set width( value ) { - }, + this.x = value; - ceil: function () { + }, - this.x = Math.ceil( this.x ); - this.y = Math.ceil( this.y ); + get height() { - return this; + return this.y; - }, + }, - round: function () { + set height( value ) { - this.x = Math.round( this.x ); - this.y = Math.round( this.y ); + this.y = value; - return this; + }, - }, + // - roundToZero: function () { + set: function ( x, y ) { - 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 = x; + this.y = y; - return this; + return this; - }, + }, - negate: function () { + setScalar: function ( scalar ) { - this.x = - this.x; - this.y = - this.y; + this.x = scalar; + this.y = scalar; - return this; + return this; - }, + }, - dot: function ( v ) { + setX: function ( x ) { - return this.x * v.x + this.y * v.y; + this.x = x; - }, + return this; - lengthSq: function () { + }, - return this.x * this.x + this.y * this.y; + setY: function ( y ) { - }, + this.y = y; - length: function () { + return this; - return Math.sqrt( this.x * this.x + this.y * this.y ); + }, - }, + setComponent: function ( index, value ) { - lengthManhattan: function() { + switch ( index ) { - return Math.abs( this.x ) + Math.abs( this.y ); + case 0: this.x = value; break; + case 1: this.y = value; break; + default: throw new Error( 'index is out of range: ' + index ); - }, + } - normalize: function () { + }, - return this.divideScalar( this.length() ); + getComponent: function ( index ) { - }, + switch ( index ) { - angle: function () { + case 0: return this.x; + case 1: return this.y; + default: throw new Error( 'index is out of range: ' + index ); - // computes the angle in radians with respect to the positive x-axis + } - var angle = Math.atan2( this.y, this.x ); + }, - if ( angle < 0 ) angle += 2 * Math.PI; + clone: function () { - return angle; + return new this.constructor( this.x, this.y ); - }, + }, - distanceTo: function ( v ) { + copy: function ( v ) { - return Math.sqrt( this.distanceToSquared( v ) ); + this.x = v.x; + this.y = v.y; - }, + return this; - distanceToSquared: function ( v ) { + }, - var dx = this.x - v.x, dy = this.y - v.y; - return dx * dx + dy * dy; + add: function ( v, w ) { - }, + if ( w !== undefined ) { - distanceToManhattan: function ( v ) { + console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); + return this.addVectors( v, w ); - return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ); + } - }, + this.x += v.x; + this.y += v.y; - setLength: function ( length ) { + return this; - return this.multiplyScalar( length / this.length() ); + }, - }, + addScalar: function ( s ) { - lerp: function ( v, alpha ) { + this.x += s; + this.y += s; - this.x += ( v.x - this.x ) * alpha; - this.y += ( v.y - this.y ) * alpha; + return this; - return this; + }, - }, + addVectors: function ( a, b ) { - lerpVectors: function ( v1, v2, alpha ) { + this.x = a.x + b.x; + this.y = a.y + b.y; - return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); + return this; - }, + }, - equals: function ( v ) { + addScaledVector: function ( v, s ) { - return ( ( v.x === this.x ) && ( v.y === this.y ) ); + this.x += v.x * s; + this.y += v.y * s; - }, + return this; - fromArray: function ( array, offset ) { + }, - if ( offset === undefined ) offset = 0; + sub: function ( v, w ) { - this.x = array[ offset ]; - this.y = array[ offset + 1 ]; + if ( w !== undefined ) { - return this; + console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); + return this.subVectors( v, w ); - }, + } - toArray: function ( array, offset ) { + this.x -= v.x; + this.y -= v.y; - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + return this; - array[ offset ] = this.x; - array[ offset + 1 ] = this.y; + }, - return array; + subScalar: function ( s ) { - }, + this.x -= s; + this.y -= s; - fromAttribute: function ( attribute, index, offset ) { + return this; - if ( offset === undefined ) offset = 0; + }, - index = index * attribute.itemSize + offset; + subVectors: function ( a, b ) { - this.x = attribute.array[ index ]; - this.y = attribute.array[ index + 1 ]; + this.x = a.x - b.x; + this.y = a.y - b.y; - return this; + return this; - }, + }, - rotateAround: function ( center, angle ) { + multiply: function ( v ) { - var c = Math.cos( angle ), s = Math.sin( angle ); + this.x *= v.x; + this.y *= v.y; - var x = this.x - center.x; - var y = this.y - center.y; + return this; - this.x = x * c - y * s + center.x; - this.y = x * s + y * c + center.y; + }, - return this; + multiplyScalar: function ( scalar ) { - } + if ( isFinite( scalar ) ) { - }; + this.x *= scalar; + this.y *= scalar; - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * @author szimek / https://github.com/szimek/ - */ + } else { - function Texture( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) { + this.x = 0; + this.y = 0; - Object.defineProperty( this, 'id', { value: TextureIdCount() } ); + } - this.uuid = exports.Math.generateUUID(); + return this; - this.name = ''; - this.sourceFile = ''; + }, - this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE; - this.mipmaps = []; + divide: function ( v ) { - this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING; + this.x /= v.x; + this.y /= v.y; - this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping; - this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping; + return this; - this.magFilter = magFilter !== undefined ? magFilter : LinearFilter; - this.minFilter = minFilter !== undefined ? minFilter : LinearMipMapLinearFilter; + }, - this.anisotropy = anisotropy !== undefined ? anisotropy : 1; + divideScalar: function ( scalar ) { - this.format = format !== undefined ? format : RGBAFormat; - this.type = type !== undefined ? type : UnsignedByteType; + return this.multiplyScalar( 1 / scalar ); - this.offset = new Vector2( 0, 0 ); - this.repeat = new Vector2( 1, 1 ); + }, - 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) + min: function ( v ) { + this.x = Math.min( this.x, v.x ); + this.y = Math.min( this.y, v.y ); - // 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; + return this; - this.version = 0; - this.onUpdate = null; + }, - }; + max: function ( v ) { - Texture.DEFAULT_IMAGE = undefined; - Texture.DEFAULT_MAPPING = UVMapping; + this.x = Math.max( this.x, v.x ); + this.y = Math.max( this.y, v.y ); - Texture.prototype = { + return this; - constructor: Texture, + }, - isTexture: true, + clamp: function ( min, max ) { - set needsUpdate( value ) { + // This function assumes min < max, if this assumption isn't true it will not operate correctly - if ( value === true ) this.version ++; + 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; - clone: function () { + }, - return new this.constructor().copy( this ); + clampScalar: function () { - }, + var min, max; - copy: function ( source ) { + return function clampScalar( minVal, maxVal ) { - this.image = source.image; - this.mipmaps = source.mipmaps.slice( 0 ); + if ( min === undefined ) { - this.mapping = source.mapping; + min = new Vector2(); + max = new Vector2(); - this.wrapS = source.wrapS; - this.wrapT = source.wrapT; + } - this.magFilter = source.magFilter; - this.minFilter = source.minFilter; + min.set( minVal, minVal ); + max.set( maxVal, maxVal ); - this.anisotropy = source.anisotropy; + return this.clamp( min, max ); - this.format = source.format; - this.type = source.type; + }; - this.offset.copy( source.offset ); - this.repeat.copy( source.repeat ); + }(), - this.generateMipmaps = source.generateMipmaps; - this.premultiplyAlpha = source.premultiplyAlpha; - this.flipY = source.flipY; - this.unpackAlignment = source.unpackAlignment; - this.encoding = source.encoding; + clampLength: function ( min, max ) { - return this; + var length = this.length(); - }, + return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length ); - toJSON: function ( meta ) { + }, - if ( meta.textures[ this.uuid ] !== undefined ) { + floor: function () { - return meta.textures[ this.uuid ]; + this.x = Math.floor( this.x ); + this.y = Math.floor( this.y ); - } + return this; - function getDataURL( image ) { + }, - var canvas; + ceil: function () { - if ( image.toDataURL !== undefined ) { + this.x = Math.ceil( this.x ); + this.y = Math.ceil( this.y ); - canvas = image; + return this; - } else { + }, - canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); - canvas.width = image.width; - canvas.height = image.height; + round: function () { - canvas.getContext( '2d' ).drawImage( image, 0, 0, image.width, image.height ); + this.x = Math.round( this.x ); + this.y = Math.round( this.y ); - } + return this; - if ( canvas.width > 2048 || canvas.height > 2048 ) { + }, - return canvas.toDataURL( 'image/jpeg', 0.6 ); + roundToZero: function () { - } else { + 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 ); - return canvas.toDataURL( 'image/png' ); + return this; - } + }, - } + negate: function () { - var output = { - metadata: { - version: 4.4, - type: 'Texture', - generator: 'Texture.toJSON' - }, + this.x = - this.x; + this.y = - this.y; - uuid: this.uuid, - name: this.name, + return this; - mapping: this.mapping, + }, - repeat: [ this.repeat.x, this.repeat.y ], - offset: [ this.offset.x, this.offset.y ], - wrap: [ this.wrapS, this.wrapT ], + dot: function ( v ) { - minFilter: this.minFilter, - magFilter: this.magFilter, - anisotropy: this.anisotropy, + return this.x * v.x + this.y * v.y; - flipY: this.flipY - }; + }, - if ( this.image !== undefined ) { + lengthSq: function () { - // TODO: Move to THREE.Image + return this.x * this.x + this.y * this.y; - var image = this.image; + }, - if ( image.uuid === undefined ) { + length: function () { - image.uuid = exports.Math.generateUUID(); // UGH + return Math.sqrt( this.x * this.x + this.y * this.y ); - } + }, - if ( meta.images[ image.uuid ] === undefined ) { + lengthManhattan: function() { - meta.images[ image.uuid ] = { - uuid: image.uuid, - url: getDataURL( image ) - }; + return Math.abs( this.x ) + Math.abs( this.y ); - } + }, - output.image = image.uuid; + normalize: function () { - } + return this.divideScalar( this.length() ); - meta.textures[ this.uuid ] = output; + }, - return output; + angle: function () { - }, + // computes the angle in radians with respect to the positive x-axis - dispose: function () { + var angle = Math.atan2( this.y, this.x ); - this.dispatchEvent( { type: 'dispose' } ); + if ( angle < 0 ) angle += 2 * Math.PI; - }, + return angle; - transformUv: function ( uv ) { + }, - if ( this.mapping !== UVMapping ) return; + distanceTo: function ( v ) { - uv.multiply( this.repeat ); - uv.add( this.offset ); + return Math.sqrt( this.distanceToSquared( v ) ); - if ( uv.x < 0 || uv.x > 1 ) { + }, - switch ( this.wrapS ) { + distanceToSquared: function ( v ) { - case RepeatWrapping: + var dx = this.x - v.x, dy = this.y - v.y; + return dx * dx + dy * dy; - uv.x = uv.x - Math.floor( uv.x ); - break; + }, - case ClampToEdgeWrapping: + distanceToManhattan: function ( v ) { - uv.x = uv.x < 0 ? 0 : 1; - break; + return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ); - case MirroredRepeatWrapping: + }, - if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) { + setLength: function ( length ) { - uv.x = Math.ceil( uv.x ) - uv.x; + return this.multiplyScalar( length / this.length() ); - } else { + }, - uv.x = uv.x - Math.floor( uv.x ); + lerp: function ( v, alpha ) { - } - break; + this.x += ( v.x - this.x ) * alpha; + this.y += ( v.y - this.y ) * alpha; - } + return this; - } + }, - if ( uv.y < 0 || uv.y > 1 ) { + lerpVectors: function ( v1, v2, alpha ) { - switch ( this.wrapT ) { + return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); - case RepeatWrapping: + }, - uv.y = uv.y - Math.floor( uv.y ); - break; + equals: function ( v ) { - case ClampToEdgeWrapping: + return ( ( v.x === this.x ) && ( v.y === this.y ) ); - uv.y = uv.y < 0 ? 0 : 1; - break; + }, - case MirroredRepeatWrapping: + fromArray: function ( array, offset ) { - if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) { + if ( offset === undefined ) offset = 0; - uv.y = Math.ceil( uv.y ) - uv.y; + this.x = array[ offset ]; + this.y = array[ offset + 1 ]; - } else { + return this; - uv.y = uv.y - Math.floor( uv.y ); + }, - } - break; + toArray: function ( array, offset ) { - } + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - } + array[ offset ] = this.x; + array[ offset + 1 ] = this.y; - if ( this.flipY ) { + return array; - uv.y = 1 - uv.y; + }, - } + fromAttribute: function ( attribute, index, offset ) { - } + if ( offset === undefined ) offset = 0; - }; + index = index * attribute.itemSize + offset; - Object.assign( Texture.prototype, EventDispatcher.prototype ); + this.x = attribute.array[ index ]; + this.y = attribute.array[ index + 1 ]; - var count = 0; - function TextureIdCount() { return count++; }; + return this; - /** - * @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 - */ + }, - function Matrix4() { + rotateAround: function ( center, angle ) { - this.elements = new Float32Array( [ + var c = Math.cos( angle ), s = Math.sin( angle ); - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 + var x = this.x - center.x; + var y = this.y - center.y; - ] ); + this.x = x * c - y * s + center.x; + this.y = x * s + y * c + center.y; - if ( arguments.length > 0 ) { + return this; - console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' ); + } - } + }; - }; + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * @author szimek / https://github.com/szimek/ + */ - Matrix4.prototype = { + function Texture( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) { - constructor: Matrix4, + Object.defineProperty( this, 'id', { value: TextureIdCount() } ); - isMatrix4: true, + this.uuid = exports.Math.generateUUID(); - set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) { + this.name = ''; + this.sourceFile = ''; - var te = this.elements; + this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE; + this.mipmaps = []; - 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; + this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING; - return this; + this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping; + this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping; - }, + this.magFilter = magFilter !== undefined ? magFilter : LinearFilter; + this.minFilter = minFilter !== undefined ? minFilter : LinearMipMapLinearFilter; - identity: function () { + this.anisotropy = anisotropy !== undefined ? anisotropy : 1; - this.set( + this.format = format !== undefined ? format : RGBAFormat; + this.type = type !== undefined ? type : UnsignedByteType; - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 + this.offset = new Vector2( 0, 0 ); + this.repeat = new Vector2( 1, 1 ); - ); + 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) - 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; - clone: function () { + this.version = 0; + this.onUpdate = null; - return new Matrix4().fromArray( this.elements ); + }; - }, + Texture.DEFAULT_IMAGE = undefined; + Texture.DEFAULT_MAPPING = UVMapping; - copy: function ( m ) { + Texture.prototype = { - this.elements.set( m.elements ); + constructor: Texture, - return this; + isTexture: true, - }, + set needsUpdate( value ) { - copyPosition: function ( m ) { + if ( value === true ) this.version ++; - var te = this.elements; - var me = m.elements; + }, - te[ 12 ] = me[ 12 ]; - te[ 13 ] = me[ 13 ]; - te[ 14 ] = me[ 14 ]; + clone: function () { - return this; + return new this.constructor().copy( this ); - }, + }, - extractBasis: function ( xAxis, yAxis, zAxis ) { + copy: function ( source ) { - xAxis.setFromMatrixColumn( this, 0 ); - yAxis.setFromMatrixColumn( this, 1 ); - zAxis.setFromMatrixColumn( this, 2 ); + this.image = source.image; + this.mipmaps = source.mipmaps.slice( 0 ); - return this; + this.mapping = source.mapping; - }, + this.wrapS = source.wrapS; + this.wrapT = source.wrapT; - makeBasis: function ( xAxis, yAxis, zAxis ) { + this.magFilter = source.magFilter; + this.minFilter = source.minFilter; - 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 - ); + this.anisotropy = source.anisotropy; - return this; + this.format = source.format; + this.type = source.type; - }, + this.offset.copy( source.offset ); + this.repeat.copy( source.repeat ); - extractRotation: function () { + this.generateMipmaps = source.generateMipmaps; + this.premultiplyAlpha = source.premultiplyAlpha; + this.flipY = source.flipY; + this.unpackAlignment = source.unpackAlignment; + this.encoding = source.encoding; - var v1; + return this; - return function extractRotation( m ) { + }, - if ( v1 === undefined ) v1 = new Vector3(); + toJSON: function ( meta ) { - var te = this.elements; - var me = m.elements; + if ( meta.textures[ this.uuid ] !== undefined ) { - var scaleX = 1 / v1.setFromMatrixColumn( m, 0 ).length(); - var scaleY = 1 / v1.setFromMatrixColumn( m, 1 ).length(); - var scaleZ = 1 / v1.setFromMatrixColumn( m, 2 ).length(); + return meta.textures[ this.uuid ]; - te[ 0 ] = me[ 0 ] * scaleX; - te[ 1 ] = me[ 1 ] * scaleX; - te[ 2 ] = me[ 2 ] * scaleX; + } - te[ 4 ] = me[ 4 ] * scaleY; - te[ 5 ] = me[ 5 ] * scaleY; - te[ 6 ] = me[ 6 ] * scaleY; + function getDataURL( image ) { - te[ 8 ] = me[ 8 ] * scaleZ; - te[ 9 ] = me[ 9 ] * scaleZ; - te[ 10 ] = me[ 10 ] * scaleZ; + var canvas; - return this; + if ( image.toDataURL !== undefined ) { - }; + canvas = image; - }(), + } else { - makeRotationFromEuler: function ( euler ) { + canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); + canvas.width = image.width; + canvas.height = image.height; - if ( (euler && euler.isEuler) === false ) { + canvas.getContext( '2d' ).drawImage( image, 0, 0, image.width, image.height ); - console.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' ); + } - } + if ( canvas.width > 2048 || canvas.height > 2048 ) { - var te = this.elements; + return canvas.toDataURL( 'image/jpeg', 0.6 ); - 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 ); + } else { - if ( euler.order === 'XYZ' ) { + return canvas.toDataURL( 'image/png' ); - var ae = a * e, af = a * f, be = b * e, bf = b * f; + } - 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; + var output = { + metadata: { + version: 4.4, + type: 'Texture', + generator: 'Texture.toJSON' + }, - te[ 2 ] = bf - ae * d; - te[ 6 ] = be + af * d; - te[ 10 ] = a * c; + uuid: this.uuid, + name: this.name, - } else if ( euler.order === 'YXZ' ) { + mapping: this.mapping, - var ce = c * e, cf = c * f, de = d * e, df = d * f; + repeat: [ this.repeat.x, this.repeat.y ], + offset: [ this.offset.x, this.offset.y ], + wrap: [ this.wrapS, this.wrapT ], - te[ 0 ] = ce + df * b; - te[ 4 ] = de * b - cf; - te[ 8 ] = a * d; + minFilter: this.minFilter, + magFilter: this.magFilter, + anisotropy: this.anisotropy, - te[ 1 ] = a * f; - te[ 5 ] = a * e; - te[ 9 ] = - b; + flipY: this.flipY + }; - te[ 2 ] = cf * b - de; - te[ 6 ] = df + ce * b; - te[ 10 ] = a * c; + if ( this.image !== undefined ) { - } else if ( euler.order === 'ZXY' ) { + // TODO: Move to THREE.Image - var ce = c * e, cf = c * f, de = d * e, df = d * f; + var image = this.image; - te[ 0 ] = ce - df * b; - te[ 4 ] = - a * f; - te[ 8 ] = de + cf * b; + if ( image.uuid === undefined ) { - te[ 1 ] = cf + de * b; - te[ 5 ] = a * e; - te[ 9 ] = df - ce * b; + image.uuid = exports.Math.generateUUID(); // UGH - te[ 2 ] = - a * d; - te[ 6 ] = b; - te[ 10 ] = a * c; + } - } else if ( euler.order === 'ZYX' ) { + if ( meta.images[ image.uuid ] === undefined ) { - var ae = a * e, af = a * f, be = b * e, bf = b * f; + meta.images[ image.uuid ] = { + uuid: image.uuid, + url: getDataURL( image ) + }; - 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; + output.image = image.uuid; - te[ 2 ] = - d; - te[ 6 ] = b * c; - te[ 10 ] = a * c; + } - } else if ( euler.order === 'YZX' ) { + meta.textures[ this.uuid ] = output; - var ac = a * c, ad = a * d, bc = b * c, bd = b * d; + return output; - 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; + dispose: function () { - te[ 2 ] = - d * e; - te[ 6 ] = ad * f + bc; - te[ 10 ] = ac - bd * f; + this.dispatchEvent( { type: 'dispose' } ); - } else if ( euler.order === 'XZY' ) { + }, - var ac = a * c, ad = a * d, bc = b * c, bd = b * d; + transformUv: function ( uv ) { - te[ 0 ] = c * e; - te[ 4 ] = - f; - te[ 8 ] = d * e; + if ( this.mapping !== UVMapping ) return; - te[ 1 ] = ac * f + bd; - te[ 5 ] = a * e; - te[ 9 ] = ad * f - bc; + uv.multiply( this.repeat ); + uv.add( this.offset ); - te[ 2 ] = bc * f - ad; - te[ 6 ] = b * e; - te[ 10 ] = bd * f + ac; + if ( uv.x < 0 || uv.x > 1 ) { - } + switch ( this.wrapS ) { - // last column - te[ 3 ] = 0; - te[ 7 ] = 0; - te[ 11 ] = 0; + case RepeatWrapping: - // bottom row - te[ 12 ] = 0; - te[ 13 ] = 0; - te[ 14 ] = 0; - te[ 15 ] = 1; + uv.x = uv.x - Math.floor( uv.x ); + break; - return this; + case ClampToEdgeWrapping: - }, + uv.x = uv.x < 0 ? 0 : 1; + break; - makeRotationFromQuaternion: function ( q ) { + case MirroredRepeatWrapping: - var te = this.elements; + if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) { - 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; + uv.x = Math.ceil( uv.x ) - uv.x; - te[ 0 ] = 1 - ( yy + zz ); - te[ 4 ] = xy - wz; - te[ 8 ] = xz + wy; + } else { - te[ 1 ] = xy + wz; - te[ 5 ] = 1 - ( xx + zz ); - te[ 9 ] = yz - wx; + uv.x = uv.x - Math.floor( uv.x ); - te[ 2 ] = xz - wy; - te[ 6 ] = yz + wx; - te[ 10 ] = 1 - ( xx + yy ); + } + break; - // 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; + if ( uv.y < 0 || uv.y > 1 ) { - }, + switch ( this.wrapT ) { - lookAt: function () { + case RepeatWrapping: - var x, y, z; + uv.y = uv.y - Math.floor( uv.y ); + break; - return function lookAt( eye, target, up ) { + case ClampToEdgeWrapping: - if ( x === undefined ) { + uv.y = uv.y < 0 ? 0 : 1; + break; - x = new Vector3(); - y = new Vector3(); - z = new Vector3(); + case MirroredRepeatWrapping: - } + if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) { - var te = this.elements; + uv.y = Math.ceil( uv.y ) - uv.y; - z.subVectors( eye, target ).normalize(); + } else { - if ( z.lengthSq() === 0 ) { + uv.y = uv.y - Math.floor( uv.y ); - z.z = 1; + } + break; - } + } - x.crossVectors( up, z ).normalize(); + } - if ( x.lengthSq() === 0 ) { + if ( this.flipY ) { - z.z += 0.0001; - x.crossVectors( up, z ).normalize(); + uv.y = 1 - uv.y; - } + } - y.crossVectors( z, x ); + } + }; - 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; + Object.assign( Texture.prototype, EventDispatcher.prototype ); - return this; + var count = 0; + function TextureIdCount() { return count++; }; - }; + /** + * @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 + */ - }(), + function Matrix4() { - multiply: function ( m, n ) { + this.elements = new Float32Array( [ - if ( n !== undefined ) { + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 - console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' ); - return this.multiplyMatrices( m, n ); + ] ); - } + if ( arguments.length > 0 ) { - return this.multiplyMatrices( this, m ); + console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' ); - }, + } - premultiply: function ( m ) { + }; - return this.multiplyMatrices( m, this ); + Matrix4.prototype = { - }, + constructor: Matrix4, - multiplyMatrices: function ( a, b ) { + isMatrix4: true, - var ae = a.elements; - var be = b.elements; - var te = this.elements; + set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) { - 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 te = this.elements; - 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 ] = 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; - 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; + return this; - 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[ 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; + identity: function () { - 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; + this.set( - return this; + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 - }, + ); - multiplyToArray: function ( a, b, r ) { + return this; - var te = this.elements; + }, - this.multiplyMatrices( a, b ); + clone: function () { - 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 new Matrix4().fromArray( this.elements ); - return this; + }, - }, + copy: function ( m ) { - multiplyScalar: function ( s ) { + this.elements.set( m.elements ); - var te = this.elements; + return this; - 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; + copyPosition: function ( m ) { - }, + var te = this.elements; + var me = m.elements; - applyToVector3Array: function () { + te[ 12 ] = me[ 12 ]; + te[ 13 ] = me[ 13 ]; + te[ 14 ] = me[ 14 ]; - var v1; + return this; - return function applyToVector3Array( array, offset, length ) { + }, - if ( v1 === undefined ) v1 = new Vector3(); - if ( offset === undefined ) offset = 0; - if ( length === undefined ) length = array.length; + extractBasis: function ( xAxis, yAxis, zAxis ) { - for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) { + xAxis.setFromMatrixColumn( this, 0 ); + yAxis.setFromMatrixColumn( this, 1 ); + zAxis.setFromMatrixColumn( this, 2 ); - v1.fromArray( array, j ); - v1.applyMatrix4( this ); - v1.toArray( array, j ); + return this; - } + }, - return array; + 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 + ); - }(), + return this; - applyToBuffer: function () { + }, - var v1; + extractRotation: function () { - return function applyToBuffer( buffer, offset, length ) { + var v1; - if ( v1 === undefined ) v1 = new Vector3(); - if ( offset === undefined ) offset = 0; - if ( length === undefined ) length = buffer.length / buffer.itemSize; + return function extractRotation( m ) { - for ( var i = 0, j = offset; i < length; i ++, j ++ ) { + if ( v1 === undefined ) v1 = new Vector3(); - v1.x = buffer.getX( j ); - v1.y = buffer.getY( j ); - v1.z = buffer.getZ( j ); + var te = this.elements; + var me = m.elements; - v1.applyMatrix4( this ); + var scaleX = 1 / v1.setFromMatrixColumn( m, 0 ).length(); + var scaleY = 1 / v1.setFromMatrixColumn( m, 1 ).length(); + var scaleZ = 1 / v1.setFromMatrixColumn( m, 2 ).length(); - buffer.setXYZ( v1.x, v1.y, v1.z ); + te[ 0 ] = me[ 0 ] * scaleX; + te[ 1 ] = me[ 1 ] * scaleX; + te[ 2 ] = me[ 2 ] * scaleX; - } + te[ 4 ] = me[ 4 ] * scaleY; + te[ 5 ] = me[ 5 ] * scaleY; + te[ 6 ] = me[ 6 ] * scaleY; - return buffer; + te[ 8 ] = me[ 8 ] * scaleZ; + te[ 9 ] = me[ 9 ] * scaleZ; + te[ 10 ] = me[ 10 ] * scaleZ; - }; + return this; - }(), + }; - determinant: function () { + }(), - var te = this.elements; + makeRotationFromEuler: function ( euler ) { - 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 ]; + if ( (euler && euler.isEuler) === false ) { - //TODO: make this more efficient - //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm ) + console.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' ); - 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 - ) + } - ); + 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 ); - transpose: function () { + if ( euler.order === 'XYZ' ) { - var te = this.elements; - var tmp; + var ae = a * e, af = a * f, be = b * e, bf = b * f; - 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; + te[ 0 ] = c * e; + te[ 4 ] = - c * f; + te[ 8 ] = d; - 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; + te[ 1 ] = af + be * d; + te[ 5 ] = ae - bf * d; + te[ 9 ] = - b * c; - return this; + te[ 2 ] = bf - ae * d; + te[ 6 ] = be + af * d; + te[ 10 ] = a * c; - }, + } else if ( euler.order === 'YXZ' ) { - flattenToArrayOffset: function ( array, offset ) { + var ce = c * e, cf = c * f, de = d * e, df = d * f; - console.warn( "THREE.Matrix3: .flattenToArrayOffset is deprecated " + - "- just use .toArray instead." ); + te[ 0 ] = ce + df * b; + te[ 4 ] = de * b - cf; + te[ 8 ] = a * d; - return this.toArray( array, offset ); + 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; - getPosition: function () { + } else if ( euler.order === 'ZXY' ) { - var v1; + var ce = c * e, cf = c * f, de = d * e, df = d * f; - return function getPosition() { + te[ 0 ] = ce - df * b; + te[ 4 ] = - a * f; + te[ 8 ] = de + cf * b; - if ( v1 === undefined ) v1 = new Vector3(); - console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' ); + te[ 1 ] = cf + de * b; + te[ 5 ] = a * e; + te[ 9 ] = df - ce * b; - return v1.setFromMatrixColumn( this, 3 ); + te[ 2 ] = - a * d; + te[ 6 ] = b; + te[ 10 ] = a * c; - }; + } else if ( euler.order === 'ZYX' ) { - }(), + var ae = a * e, af = a * f, be = b * e, bf = b * f; - setPosition: function ( v ) { + te[ 0 ] = c * e; + te[ 4 ] = be * d - af; + te[ 8 ] = ae * d + bf; - var te = this.elements; + te[ 1 ] = c * f; + te[ 5 ] = bf * d + ae; + te[ 9 ] = af * d - be; - te[ 12 ] = v.x; - te[ 13 ] = v.y; - te[ 14 ] = v.z; + te[ 2 ] = - d; + te[ 6 ] = b * c; + te[ 10 ] = a * c; - return this; + } else if ( euler.order === 'YZX' ) { - }, + var ac = a * c, ad = a * d, bc = b * c, bd = b * d; - getInverse: function ( m, throwOnDegenerate ) { + te[ 0 ] = c * e; + te[ 4 ] = bd - ac * f; + te[ 8 ] = bc * f + ad; - // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm - var te = this.elements, - me = m.elements, + te[ 1 ] = f; + te[ 5 ] = a * e; + te[ 9 ] = - b * e; - 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 ], + te[ 2 ] = - d * e; + te[ 6 ] = ad * f + bc; + te[ 10 ] = ac - bd * f; - 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; + } else if ( euler.order === 'XZY' ) { - var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14; + var ac = a * c, ad = a * d, bc = b * c, bd = b * d; - if ( det === 0 ) { + te[ 0 ] = c * e; + te[ 4 ] = - f; + te[ 8 ] = d * e; - var msg = "THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0"; + te[ 1 ] = ac * f + bd; + te[ 5 ] = a * e; + te[ 9 ] = ad * f - bc; - if ( throwOnDegenerate || false ) {} else { + te[ 2 ] = bc * f - ad; + te[ 6 ] = b * e; + te[ 10 ] = bd * f + ac; - console.warn( msg ); + } - } + // last column + te[ 3 ] = 0; + te[ 7 ] = 0; + te[ 11 ] = 0; - return this.identity(); + // bottom row + te[ 12 ] = 0; + te[ 13 ] = 0; + te[ 14 ] = 0; + te[ 15 ] = 1; - } + 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; + makeRotationFromQuaternion: function ( q ) { - 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; - 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 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; - 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 ] = 1 - ( yy + zz ); + te[ 4 ] = xy - wz; + te[ 8 ] = xz + wy; - return this; + te[ 1 ] = xy + wz; + te[ 5 ] = 1 - ( xx + zz ); + te[ 9 ] = yz - wx; - }, + te[ 2 ] = xz - wy; + te[ 6 ] = yz + wx; + te[ 10 ] = 1 - ( xx + yy ); - scale: function ( v ) { + // last column + te[ 3 ] = 0; + te[ 7 ] = 0; + te[ 11 ] = 0; - var te = this.elements; - var x = v.x, y = v.y, z = v.z; + // bottom row + te[ 12 ] = 0; + te[ 13 ] = 0; + te[ 14 ] = 0; + te[ 15 ] = 1; - 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; - return this; + }, - }, + lookAt: function () { - getMaxScaleOnAxis: function () { + var x, y, z; - var te = this.elements; + return function lookAt( eye, target, up ) { - 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 ]; + if ( x === undefined ) { - return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) ); + x = new Vector3(); + y = new Vector3(); + z = new Vector3(); - }, + } - makeTranslation: function ( x, y, z ) { + var te = this.elements; - this.set( + z.subVectors( eye, target ).normalize(); - 1, 0, 0, x, - 0, 1, 0, y, - 0, 0, 1, z, - 0, 0, 0, 1 + if ( z.lengthSq() === 0 ) { - ); + z.z = 1; - return this; + } - }, + x.crossVectors( up, z ).normalize(); - makeRotationX: function ( theta ) { + if ( x.lengthSq() === 0 ) { - var c = Math.cos( theta ), s = Math.sin( theta ); + z.z += 0.0001; + x.crossVectors( up, z ).normalize(); - this.set( + } - 1, 0, 0, 0, - 0, c, - s, 0, - 0, s, c, 0, - 0, 0, 0, 1 + y.crossVectors( z, x ); - ); - 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; - makeRotationY: function ( theta ) { + }; - var c = Math.cos( theta ), s = Math.sin( theta ); + }(), - this.set( + multiply: function ( m, n ) { - c, 0, s, 0, - 0, 1, 0, 0, - - s, 0, c, 0, - 0, 0, 0, 1 + if ( n !== undefined ) { - ); + console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' ); + return this.multiplyMatrices( m, n ); - return this; + } - }, + return this.multiplyMatrices( this, m ); - makeRotationZ: function ( theta ) { + }, - var c = Math.cos( theta ), s = Math.sin( theta ); + premultiply: function ( m ) { - this.set( + return this.multiplyMatrices( m, this ); - c, - s, 0, 0, - s, c, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 + }, - ); + multiplyMatrices: function ( a, b ) { - return this; + 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 ]; - makeRotationAxis: function ( axis, angle ) { + 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 ]; - // Based on http://www.gamedev.net/reference/articles/article1199.asp + 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 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; + 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; - this.set( + 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; - 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 + 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; + }, - }, + multiplyToArray: function ( a, b, r ) { - makeScale: function ( x, y, z ) { + var te = this.elements; - this.set( + this.multiplyMatrices( a, b ); - x, 0, 0, 0, - 0, y, 0, 0, - 0, 0, z, 0, - 0, 0, 0, 1 + 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; - return this; + }, - }, + multiplyScalar: function ( s ) { - compose: function ( position, quaternion, scale ) { + var te = this.elements; - this.makeRotationFromQuaternion( quaternion ); - this.scale( scale ); - this.setPosition( position ); + 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; + return this; - }, + }, - decompose: function () { + applyToVector3Array: function () { - var vector, matrix; + var v1; - return function decompose( position, quaternion, scale ) { + return function applyToVector3Array( array, offset, length ) { - if ( vector === undefined ) { + if ( v1 === undefined ) v1 = new Vector3(); + if ( offset === undefined ) offset = 0; + if ( length === undefined ) length = array.length; - vector = new Vector3(); - matrix = new Matrix4(); + for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) { - } + v1.fromArray( array, j ); + v1.applyMatrix4( this ); + v1.toArray( array, j ); - 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(); + return array; - // if determine is negative, we need to invert one scale - var det = this.determinant(); - if ( det < 0 ) { + }; - sx = - sx; + }(), - } + applyToBuffer: function () { - position.x = te[ 12 ]; - position.y = te[ 13 ]; - position.z = te[ 14 ]; + var v1; - // scale the rotation part + return function applyToBuffer( buffer, offset, length ) { - matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy() + if ( v1 === undefined ) v1 = new Vector3(); + if ( offset === undefined ) offset = 0; + if ( length === undefined ) length = buffer.length / buffer.itemSize; - var invSX = 1 / sx; - var invSY = 1 / sy; - var invSZ = 1 / sz; + for ( var i = 0, j = offset; i < length; i ++, j ++ ) { - matrix.elements[ 0 ] *= invSX; - matrix.elements[ 1 ] *= invSX; - matrix.elements[ 2 ] *= invSX; + v1.x = buffer.getX( j ); + v1.y = buffer.getY( j ); + v1.z = buffer.getZ( j ); - matrix.elements[ 4 ] *= invSY; - matrix.elements[ 5 ] *= invSY; - matrix.elements[ 6 ] *= invSY; + v1.applyMatrix4( this ); - matrix.elements[ 8 ] *= invSZ; - matrix.elements[ 9 ] *= invSZ; - matrix.elements[ 10 ] *= invSZ; + buffer.setXYZ( v1.x, v1.y, v1.z ); - quaternion.setFromRotationMatrix( matrix ); + } - scale.x = sx; - scale.y = sy; - scale.z = sz; + return buffer; - return this; + }; - }; + }(), - }(), + determinant: function () { - makeFrustum: function ( left, right, bottom, top, near, far ) { + var te = this.elements; - var te = this.elements; - var x = 2 * near / ( right - left ); - var y = 2 * near / ( top - bottom ); + 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 ]; - 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 ); + //TODO: make this more efficient + //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm ) - 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 ( + 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 + ) - return this; + ); - }, + }, - makePerspective: function ( fov, aspect, near, far ) { + transpose: function () { - var ymax = near * Math.tan( exports.Math.DEG2RAD * fov * 0.5 ); - var ymin = - ymax; - var xmin = ymin * aspect; - var xmax = ymax * aspect; + var te = this.elements; + var tmp; - return this.makeFrustum( xmin, xmax, ymin, ymax, near, far ); + 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; - }, + 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; - makeOrthographic: function ( left, right, top, bottom, near, far ) { + return this; - var te = this.elements; - var w = 1.0 / ( right - left ); - var h = 1.0 / ( top - bottom ); - var p = 1.0 / ( far - near ); + }, - var x = ( right + left ) * w; - var y = ( top + bottom ) * h; - var z = ( far + near ) * p; + flattenToArrayOffset: function ( array, offset ) { - 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; + console.warn( "THREE.Matrix3: .flattenToArrayOffset is deprecated " + + "- just use .toArray instead." ); - return this; + return this.toArray( array, offset ); - }, + }, - equals: function ( matrix ) { + getPosition: function () { - var te = this.elements; - var me = matrix.elements; + var v1; - for ( var i = 0; i < 16; i ++ ) { + return function getPosition() { - if ( te[ i ] !== me[ i ] ) return false; + if ( v1 === undefined ) v1 = new Vector3(); + console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' ); - } + return v1.setFromMatrixColumn( this, 3 ); - return true; + }; - }, + }(), - fromArray: function ( array ) { + setPosition: function ( v ) { - this.elements.set( array ); + var te = this.elements; - return this; + te[ 12 ] = v.x; + te[ 13 ] = v.y; + te[ 14 ] = v.z; - }, + return this; - toArray: function ( array, offset ) { + }, - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + getInverse: function ( m, throwOnDegenerate ) { - var te = this.elements; + // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm + var te = this.elements, + me = m.elements, - array[ offset ] = te[ 0 ]; - array[ offset + 1 ] = te[ 1 ]; - array[ offset + 2 ] = te[ 2 ]; - array[ offset + 3 ] = te[ 3 ]; + 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 ], - array[ offset + 4 ] = te[ 4 ]; - array[ offset + 5 ] = te[ 5 ]; - array[ offset + 6 ] = te[ 6 ]; - array[ offset + 7 ] = te[ 7 ]; + 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; - array[ offset + 8 ] = te[ 8 ]; - array[ offset + 9 ] = te[ 9 ]; - array[ offset + 10 ] = te[ 10 ]; - array[ offset + 11 ] = te[ 11 ]; + var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14; - array[ offset + 12 ] = te[ 12 ]; - array[ offset + 13 ] = te[ 13 ]; - array[ offset + 14 ] = te[ 14 ]; - array[ offset + 15 ] = te[ 15 ]; + if ( det === 0 ) { - return array; + var msg = "THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0"; - } + if ( throwOnDegenerate || false ) {} else { - }; + console.warn( msg ); - /** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author WestLangley / http://github.com/WestLangley - * @author bhouston / http://clara.io - */ + } - function Quaternion( x, y, z, w ) { + return this.identity(); - this._x = x || 0; - this._y = y || 0; - this._z = z || 0; - this._w = ( w !== undefined ) ? w : 1; + } - }; + var detInv = 1 / det; - Quaternion.prototype = { + 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; - constructor: Quaternion, + 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; - get x () { + 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; - return this._x; + 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; - }, + return this; - set x ( value ) { + }, - this._x = value; - this.onChangeCallback(); + scale: function ( v ) { - }, + var te = this.elements; + var x = v.x, y = v.y, z = v.z; - get y () { + 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._y; + return this; - }, + }, - set y ( value ) { + getMaxScaleOnAxis: function () { - this._y = value; - this.onChangeCallback(); + var te = this.elements; - }, + 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 ]; - get z () { + return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) ); - return this._z; + }, - }, + makeTranslation: function ( x, y, z ) { - set z ( value ) { + this.set( - this._z = value; - this.onChangeCallback(); + 1, 0, 0, x, + 0, 1, 0, y, + 0, 0, 1, z, + 0, 0, 0, 1 - }, + ); - get w () { + return this; - return this._w; + }, - }, + makeRotationX: function ( theta ) { - set w ( value ) { + var c = Math.cos( theta ), s = Math.sin( theta ); - this._w = value; - this.onChangeCallback(); + this.set( - }, + 1, 0, 0, 0, + 0, c, - s, 0, + 0, s, c, 0, + 0, 0, 0, 1 - set: function ( x, y, z, w ) { + ); - this._x = x; - this._y = y; - this._z = z; - this._w = w; + return this; - this.onChangeCallback(); + }, - return this; + makeRotationY: function ( theta ) { - }, + var c = Math.cos( theta ), s = Math.sin( theta ); - clone: function () { + this.set( - return new this.constructor( this._x, this._y, this._z, this._w ); + c, 0, s, 0, + 0, 1, 0, 0, + - s, 0, c, 0, + 0, 0, 0, 1 - }, + ); - copy: function ( quaternion ) { + return this; - this._x = quaternion.x; - this._y = quaternion.y; - this._z = quaternion.z; - this._w = quaternion.w; + }, - this.onChangeCallback(); + makeRotationZ: function ( theta ) { - return this; + var c = Math.cos( theta ), s = Math.sin( theta ); - }, + this.set( - setFromEuler: function ( euler, update ) { + c, - s, 0, 0, + s, c, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 - if ( (euler && euler.isEuler) === false ) { + ); - throw new Error( 'THREE.Quaternion: .setFromEuler() now expects a Euler rotation rather than a Vector3 and order.' ); + return this; - } + }, - // http://www.mathworks.com/matlabcentral/fileexchange/ - // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/ - // content/SpinCalc.m + makeRotationAxis: function ( axis, angle ) { - 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 ); + // Based on http://www.gamedev.net/reference/articles/article1199.asp - var order = euler.order; + 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; - if ( order === 'XYZ' ) { + this.set( - 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; + 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 - } else if ( order === 'YXZ' ) { + ); - 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; + return this; - } else if ( order === 'ZXY' ) { + }, - 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; + makeScale: function ( x, y, z ) { - } else if ( order === 'ZYX' ) { + this.set( - 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; + x, 0, 0, 0, + 0, y, 0, 0, + 0, 0, z, 0, + 0, 0, 0, 1 - } 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; + return this; - } else if ( order === 'XZY' ) { + }, - 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; + compose: function ( position, quaternion, scale ) { - } + this.makeRotationFromQuaternion( quaternion ); + this.scale( scale ); + this.setPosition( position ); - if ( update !== false ) this.onChangeCallback(); + return this; - return this; + }, - }, + decompose: function () { - setFromAxisAngle: function ( axis, angle ) { + var vector, matrix; - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm + return function decompose( position, quaternion, scale ) { - // assumes axis is normalized + if ( vector === undefined ) { - var halfAngle = angle / 2, s = Math.sin( halfAngle ); + vector = new Vector3(); + matrix = new Matrix4(); - this._x = axis.x * s; - this._y = axis.y * s; - this._z = axis.z * s; - this._w = Math.cos( halfAngle ); + } - this.onChangeCallback(); + var te = this.elements; - return this; + 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(); - }, + // if determine is negative, we need to invert one scale + var det = this.determinant(); + if ( det < 0 ) { - setFromRotationMatrix: function ( m ) { + sx = - sx; - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm + } - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + position.x = te[ 12 ]; + position.y = te[ 13 ]; + position.z = te[ 14 ]; - var te = m.elements, + // scale the rotation part - 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 ], + matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy() - trace = m11 + m22 + m33, - s; + var invSX = 1 / sx; + var invSY = 1 / sy; + var invSZ = 1 / sz; - if ( trace > 0 ) { + matrix.elements[ 0 ] *= invSX; + matrix.elements[ 1 ] *= invSX; + matrix.elements[ 2 ] *= invSX; - s = 0.5 / Math.sqrt( trace + 1.0 ); + matrix.elements[ 4 ] *= invSY; + matrix.elements[ 5 ] *= invSY; + matrix.elements[ 6 ] *= invSY; - this._w = 0.25 / s; - this._x = ( m32 - m23 ) * s; - this._y = ( m13 - m31 ) * s; - this._z = ( m21 - m12 ) * s; + matrix.elements[ 8 ] *= invSZ; + matrix.elements[ 9 ] *= invSZ; + matrix.elements[ 10 ] *= invSZ; - } else if ( m11 > m22 && m11 > m33 ) { + quaternion.setFromRotationMatrix( matrix ); - s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 ); + scale.x = sx; + scale.y = sy; + scale.z = sz; - this._w = ( m32 - m23 ) / s; - this._x = 0.25 * s; - this._y = ( m12 + m21 ) / s; - this._z = ( m13 + m31 ) / s; + return this; - } else if ( m22 > m33 ) { + }; - s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 ); + }(), - this._w = ( m13 - m31 ) / s; - this._x = ( m12 + m21 ) / s; - this._y = 0.25 * s; - this._z = ( m23 + m32 ) / s; + makeFrustum: function ( left, right, bottom, top, near, far ) { - } else { + var te = this.elements; + var x = 2 * near / ( right - left ); + var y = 2 * near / ( top - bottom ); - s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 ); + 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 ); - this._w = ( m21 - m12 ) / s; - this._x = ( m13 + m31 ) / s; - this._y = ( m23 + m32 ) / s; - this._z = 0.25 * s; + 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; - this.onChangeCallback(); + }, - return this; + makePerspective: function ( fov, aspect, near, far ) { - }, + var ymax = near * Math.tan( exports.Math.DEG2RAD * fov * 0.5 ); + var ymin = - ymax; + var xmin = ymin * aspect; + var xmax = ymax * aspect; - setFromUnitVectors: function () { + return this.makeFrustum( xmin, xmax, ymin, ymax, near, far ); - // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final + }, - // assumes direction vectors vFrom and vTo are normalized + makeOrthographic: function ( left, right, top, bottom, near, far ) { - var v1, r; + var te = this.elements; + var w = 1.0 / ( right - left ); + var h = 1.0 / ( top - bottom ); + var p = 1.0 / ( far - near ); - var EPS = 0.000001; + var x = ( right + left ) * w; + var y = ( top + bottom ) * h; + var z = ( far + near ) * p; - return function setFromUnitVectors( vFrom, vTo ) { + 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; - if ( v1 === undefined ) v1 = new Vector3(); + return this; - r = vFrom.dot( vTo ) + 1; + }, - if ( r < EPS ) { + equals: function ( matrix ) { - r = 0; + var te = this.elements; + var me = matrix.elements; - if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) { + for ( var i = 0; i < 16; i ++ ) { - v1.set( - vFrom.y, vFrom.x, 0 ); + if ( te[ i ] !== me[ i ] ) return false; - } else { + } - v1.set( 0, - vFrom.z, vFrom.y ); + return true; - } + }, - } else { + fromArray: function ( array ) { - v1.crossVectors( vFrom, vTo ); + this.elements.set( array ); - } + return this; - this._x = v1.x; - this._y = v1.y; - this._z = v1.z; - this._w = r; + }, - return this.normalize(); + toArray: function ( array, offset ) { - }; + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - }(), + var te = this.elements; - inverse: function () { + array[ offset ] = te[ 0 ]; + array[ offset + 1 ] = te[ 1 ]; + array[ offset + 2 ] = te[ 2 ]; + array[ offset + 3 ] = te[ 3 ]; - return this.conjugate().normalize(); + array[ offset + 4 ] = te[ 4 ]; + array[ offset + 5 ] = te[ 5 ]; + array[ offset + 6 ] = te[ 6 ]; + array[ offset + 7 ] = te[ 7 ]; - }, + array[ offset + 8 ] = te[ 8 ]; + array[ offset + 9 ] = te[ 9 ]; + array[ offset + 10 ] = te[ 10 ]; + array[ offset + 11 ] = te[ 11 ]; - conjugate: function () { + array[ offset + 12 ] = te[ 12 ]; + array[ offset + 13 ] = te[ 13 ]; + array[ offset + 14 ] = te[ 14 ]; + array[ offset + 15 ] = te[ 15 ]; - this._x *= - 1; - this._y *= - 1; - this._z *= - 1; + return array; - this.onChangeCallback(); + } - return this; + }; - }, + /** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + * @author WestLangley / http://github.com/WestLangley + * @author bhouston / http://clara.io + */ - dot: function ( v ) { + function Quaternion( x, y, z, w ) { - return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w; + this._x = x || 0; + this._y = y || 0; + this._z = z || 0; + this._w = ( w !== undefined ) ? w : 1; - }, + }; - lengthSq: function () { + Quaternion.prototype = { - return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; + constructor: Quaternion, - }, + get x () { - length: function () { + return this._x; - return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w ); + }, - }, + set x ( value ) { - normalize: function () { + this._x = value; + this.onChangeCallback(); - var l = this.length(); + }, - if ( l === 0 ) { + get y () { - this._x = 0; - this._y = 0; - this._z = 0; - this._w = 1; + return this._y; - } else { + }, - l = 1 / l; + set y ( value ) { - this._x = this._x * l; - this._y = this._y * l; - this._z = this._z * l; - this._w = this._w * l; + this._y = value; + this.onChangeCallback(); - } + }, - this.onChangeCallback(); + get z () { - return this; + return this._z; - }, + }, - multiply: function ( q, p ) { + set z ( value ) { - if ( p !== undefined ) { + this._z = value; + this.onChangeCallback(); - console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' ); - return this.multiplyQuaternions( q, p ); + }, - } + get w () { - return this.multiplyQuaternions( this, q ); + return this._w; - }, + }, - premultiply: function ( q ) { + set w ( value ) { - return this.multiplyQuaternions( q, this ); + this._w = value; + this.onChangeCallback(); - }, + }, - multiplyQuaternions: function ( a, b ) { + set: function ( x, y, z, w ) { - // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm + this._x = x; + this._y = y; + this._z = z; + this._w = w; - 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.onChangeCallback(); - 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; + clone: function () { - }, + return new this.constructor( this._x, this._y, this._z, this._w ); - slerp: function ( qb, t ) { + }, - if ( t === 0 ) return this; - if ( t === 1 ) return this.copy( qb ); + copy: function ( quaternion ) { - var x = this._x, y = this._y, z = this._z, w = this._w; + this._x = quaternion.x; + this._y = quaternion.y; + this._z = quaternion.z; + this._w = quaternion.w; - // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/ + this.onChangeCallback(); - 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; + setFromEuler: function ( euler, update ) { - cosHalfTheta = - cosHalfTheta; + if ( (euler && euler.isEuler) === false ) { - } else { + throw new Error( 'THREE.Quaternion: .setFromEuler() now expects a Euler rotation rather than a Vector3 and order.' ); - this.copy( qb ); + } - } + // http://www.mathworks.com/matlabcentral/fileexchange/ + // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/ + // content/SpinCalc.m - if ( cosHalfTheta >= 1.0 ) { + 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 ); - this._w = w; - this._x = x; - this._y = y; - this._z = z; + var order = euler.order; - return this; + 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; - var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta ); + } else if ( order === 'YXZ' ) { - if ( Math.abs( sinHalfTheta ) < 0.001 ) { + 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._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 ); + } else if ( order === 'ZXY' ) { - 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 === 'ZYX' ) { - var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta ); - var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta, - ratioB = Math.sin( t * halfTheta ) / sinHalfTheta; + 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._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 ); + } else if ( order === 'YZX' ) { - this.onChangeCallback(); + 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; - return this; + } else if ( order === 'XZY' ) { - }, + 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 ( quaternion ) { + } - return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w ); + if ( update !== false ) this.onChangeCallback(); - }, + return this; - fromArray: function ( array, offset ) { + }, - if ( offset === undefined ) offset = 0; + setFromAxisAngle: function ( axis, angle ) { - this._x = array[ offset ]; - this._y = array[ offset + 1 ]; - this._z = array[ offset + 2 ]; - this._w = array[ offset + 3 ]; + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm - this.onChangeCallback(); + // assumes axis is normalized - return this; + var halfAngle = angle / 2, s = Math.sin( halfAngle ); - }, + this._x = axis.x * s; + this._y = axis.y * s; + this._z = axis.z * s; + this._w = Math.cos( halfAngle ); - toArray: function ( array, offset ) { + this.onChangeCallback(); - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + return this; - array[ offset ] = this._x; - array[ offset + 1 ] = this._y; - array[ offset + 2 ] = this._z; - array[ offset + 3 ] = this._w; + }, - return array; + setFromRotationMatrix: function ( m ) { - }, + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm - onChange: function ( callback ) { + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - this.onChangeCallback = callback; + var te = m.elements, - return this; + 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 ], - }, + trace = m11 + m22 + m33, + s; - onChangeCallback: function () {} + if ( trace > 0 ) { - }; + s = 0.5 / Math.sqrt( trace + 1.0 ); - Object.assign( Quaternion, { + this._w = 0.25 / s; + this._x = ( m32 - m23 ) * s; + this._y = ( m13 - m31 ) * s; + this._z = ( m21 - m12 ) * s; - slerp: function( qa, qb, qm, t ) { + } else if ( m11 > m22 && m11 > m33 ) { - return qm.copy( qa ).slerp( qb, t ); + s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 ); - }, + this._w = ( m32 - m23 ) / s; + this._x = 0.25 * s; + this._y = ( m12 + m21 ) / s; + this._z = ( m13 + m31 ) / s; - slerpFlat: function( - dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) { + } else if ( m22 > m33 ) { - // fuzz-free, array-based Quaternion SLERP operation + s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 ); - var x0 = src0[ srcOffset0 + 0 ], - y0 = src0[ srcOffset0 + 1 ], - z0 = src0[ srcOffset0 + 2 ], - w0 = src0[ srcOffset0 + 3 ], + this._w = ( m13 - m31 ) / s; + this._x = ( m12 + m21 ) / s; + this._y = 0.25 * s; + this._z = ( m23 + m32 ) / s; - x1 = src1[ srcOffset1 + 0 ], - y1 = src1[ srcOffset1 + 1 ], - z1 = src1[ srcOffset1 + 2 ], - w1 = src1[ srcOffset1 + 3 ]; + } else { - if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) { + s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 ); - var s = 1 - t, + this._w = ( m21 - m12 ) / s; + this._x = ( m13 + m31 ) / s; + this._y = ( m23 + m32 ) / s; + this._z = 0.25 * s; - cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1, + } - dir = ( cos >= 0 ? 1 : - 1 ), - sqrSin = 1 - cos * cos; + this.onChangeCallback(); - // Skip the Slerp for tiny steps to avoid numeric problems: - if ( sqrSin > Number.EPSILON ) { + return this; - var sin = Math.sqrt( sqrSin ), - len = Math.atan2( sin, cos * dir ); + }, - s = Math.sin( s * len ) / sin; - t = Math.sin( t * len ) / sin; + setFromUnitVectors: function () { - } + // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final - var tDir = t * dir; + // assumes direction vectors vFrom and vTo are normalized - x0 = x0 * s + x1 * tDir; - y0 = y0 * s + y1 * tDir; - z0 = z0 * s + z1 * tDir; - w0 = w0 * s + w1 * tDir; + var v1, r; - // Normalize in case we just did a lerp: - if ( s === 1 - t ) { + var EPS = 0.000001; - var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 ); + return function setFromUnitVectors( vFrom, vTo ) { - x0 *= f; - y0 *= f; - z0 *= f; - w0 *= f; + if ( v1 === undefined ) v1 = new Vector3(); - } + r = vFrom.dot( vTo ) + 1; - } + if ( r < EPS ) { - dst[ dstOffset ] = x0; - dst[ dstOffset + 1 ] = y0; - dst[ dstOffset + 2 ] = z0; - dst[ dstOffset + 3 ] = w0; + r = 0; - } + if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) { - } ); + v1.set( - vFrom.y, vFrom.x, 0 ); - /** - * @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 - */ + } else { - function Vector3( x, y, z ) { + v1.set( 0, - vFrom.z, vFrom.y ); - this.x = x || 0; - this.y = y || 0; - this.z = z || 0; + } - }; + } else { - Vector3.prototype = { + v1.crossVectors( vFrom, vTo ); - constructor: Vector3, + } - isVector3: true, + this._x = v1.x; + this._y = v1.y; + this._z = v1.z; + this._w = r; - set: function ( x, y, z ) { + return this.normalize(); - this.x = x; - this.y = y; - this.z = z; + }; - return this; + }(), - }, + inverse: function () { - setScalar: function ( scalar ) { + return this.conjugate().normalize(); - this.x = scalar; - this.y = scalar; - this.z = scalar; + }, - return this; + conjugate: function () { - }, + this._x *= - 1; + this._y *= - 1; + this._z *= - 1; - setX: function ( x ) { + this.onChangeCallback(); - this.x = x; + return this; - return this; + }, - }, + dot: function ( v ) { - setY: function ( y ) { + return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w; - this.y = y; + }, - return this; + lengthSq: function () { - }, + return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; - setZ: function ( z ) { + }, - this.z = z; + length: function () { - return this; + return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w ); - }, + }, - setComponent: function ( index, value ) { + normalize: function () { - switch ( index ) { + var l = this.length(); - 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 ); + if ( l === 0 ) { - } + this._x = 0; + this._y = 0; + this._z = 0; + this._w = 1; - }, + } else { - getComponent: function ( index ) { + l = 1 / l; - switch ( index ) { + this._x = this._x * l; + this._y = this._y * l; + this._z = this._z * l; + this._w = this._w * l; - 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 () { + }, - return new this.constructor( this.x, this.y, this.z ); + multiply: function ( q, p ) { - }, + if ( p !== undefined ) { - copy: function ( v ) { + console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' ); + return this.multiplyQuaternions( q, p ); - this.x = v.x; - this.y = v.y; - this.z = v.z; + } - return this; + return this.multiplyQuaternions( this, q ); - }, + }, - add: function ( v, w ) { + premultiply: function ( q ) { - if ( w !== undefined ) { + return this.multiplyQuaternions( q, this ); - console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); - return this.addVectors( v, w ); + }, - } + multiplyQuaternions: function ( a, b ) { - this.x += v.x; - this.y += v.y; - this.z += v.z; + // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm - return this; + 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 = 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; - addScalar: function ( s ) { + this.onChangeCallback(); - this.x += s; - this.y += s; - this.z += s; + return this; - return this; + }, - }, + slerp: function ( qb, t ) { - addVectors: function ( a, b ) { + if ( t === 0 ) return this; + if ( t === 1 ) return this.copy( qb ); - this.x = a.x + b.x; - this.y = a.y + b.y; - this.z = a.z + b.z; + var x = this._x, y = this._y, z = this._z, w = this._w; - return this; + // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/ - }, + var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z; - addScaledVector: function ( v, s ) { + if ( cosHalfTheta < 0 ) { - this.x += v.x * s; - this.y += v.y * s; - this.z += v.z * s; + this._w = - qb._w; + this._x = - qb._x; + this._y = - qb._y; + this._z = - qb._z; - return this; + cosHalfTheta = - cosHalfTheta; - }, + } else { - sub: function ( v, w ) { + this.copy( qb ); - if ( w !== undefined ) { + } - console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); - return this.subVectors( v, w ); + if ( cosHalfTheta >= 1.0 ) { - } + this._w = w; + this._x = x; + this._y = y; + this._z = z; - this.x -= v.x; - this.y -= v.y; - this.z -= v.z; + return this; - return this; + } - }, + var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta ); - subScalar: function ( s ) { + if ( Math.abs( sinHalfTheta ) < 0.001 ) { - this.x -= s; - this.y -= s; - this.z -= s; + 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; + return this; - }, + } - subVectors: function ( a, b ) { + var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta ); + var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta, + ratioB = Math.sin( t * halfTheta ) / sinHalfTheta; - this.x = a.x - b.x; - this.y = a.y - b.y; - this.z = a.z - b.z; + 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 ); - return this; + this.onChangeCallback(); - }, + return this; - multiply: function ( v, w ) { + }, - if ( w !== undefined ) { + equals: function ( quaternion ) { - console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' ); - return this.multiplyVectors( v, w ); + return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w ); - } + }, - this.x *= v.x; - this.y *= v.y; - this.z *= v.z; + fromArray: function ( array, offset ) { - return this; + if ( offset === undefined ) offset = 0; - }, + this._x = array[ offset ]; + this._y = array[ offset + 1 ]; + this._z = array[ offset + 2 ]; + this._w = array[ offset + 3 ]; - multiplyScalar: function ( scalar ) { + this.onChangeCallback(); - if ( isFinite( scalar ) ) { + return this; - this.x *= scalar; - this.y *= scalar; - this.z *= scalar; + }, - } else { + toArray: function ( array, offset ) { - this.x = 0; - this.y = 0; - this.z = 0; + 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._w; - return this; + return array; - }, + }, - multiplyVectors: function ( a, b ) { + onChange: function ( callback ) { - this.x = a.x * b.x; - this.y = a.y * b.y; - this.z = a.z * b.z; + this.onChangeCallback = callback; - return this; + return this; - }, + }, - applyEuler: function () { + onChangeCallback: function () {} - var quaternion; + }; - return function applyEuler( euler ) { + Object.assign( Quaternion, { - if ( (euler && euler.isEuler) === false ) { + slerp: function( qa, qb, qm, t ) { - console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' ); + return qm.copy( qa ).slerp( qb, t ); - } + }, - if ( quaternion === undefined ) quaternion = new Quaternion(); + slerpFlat: function( + dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) { - return this.applyQuaternion( quaternion.setFromEuler( euler ) ); + // fuzz-free, array-based Quaternion SLERP operation - }; + var x0 = src0[ srcOffset0 + 0 ], + y0 = src0[ srcOffset0 + 1 ], + z0 = src0[ srcOffset0 + 2 ], + w0 = src0[ srcOffset0 + 3 ], - }(), + x1 = src1[ srcOffset1 + 0 ], + y1 = src1[ srcOffset1 + 1 ], + z1 = src1[ srcOffset1 + 2 ], + w1 = src1[ srcOffset1 + 3 ]; - applyAxisAngle: function () { + if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) { - var quaternion; + var s = 1 - t, - return function applyAxisAngle( axis, angle ) { + cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1, - if ( quaternion === undefined ) quaternion = new Quaternion(); + dir = ( cos >= 0 ? 1 : - 1 ), + sqrSin = 1 - cos * cos; - return this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) ); + // Skip the Slerp for tiny steps to avoid numeric problems: + if ( sqrSin > Number.EPSILON ) { - }; + var sin = Math.sqrt( sqrSin ), + len = Math.atan2( sin, cos * dir ); - }(), + s = Math.sin( s * len ) / sin; + t = Math.sin( t * len ) / sin; - applyMatrix3: function ( m ) { + } - var x = this.x, y = this.y, z = this.z; - var e = m.elements; + var tDir = t * dir; - 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; + x0 = x0 * s + x1 * tDir; + y0 = y0 * s + y1 * tDir; + z0 = z0 * s + z1 * tDir; + w0 = w0 * s + w1 * tDir; - return this; + // 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 ); - applyMatrix4: function ( m ) { + x0 *= f; + y0 *= f; + z0 *= f; + w0 *= f; - // input: THREE.Matrix4 affine matrix + } - var x = this.x, y = this.y, z = this.z; - var e = m.elements; + } - 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 ]; + dst[ dstOffset ] = x0; + dst[ dstOffset + 1 ] = y0; + dst[ dstOffset + 2 ] = z0; + dst[ dstOffset + 3 ] = w0; - return this; + } - }, + } ); - applyProjection: function ( m ) { + /** + * @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 + */ - // input: THREE.Matrix4 projection matrix + function Vector3( x, y, 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 + this.x = x || 0; + this.y = y || 0; + this.z = z || 0; - 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; + Vector3.prototype = { - }, + constructor: Vector3, - applyQuaternion: function ( q ) { + isVector3: true, - var x = this.x, y = this.y, z = this.z; - var qx = q.x, qy = q.y, qz = q.z, qw = q.w; + set: function ( x, y, z ) { - // calculate quat * vector + this.x = x; + this.y = y; + this.z = 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; + return this; - // calculate result * inverse quat + }, - 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; + setScalar: function ( scalar ) { - return this; + this.x = scalar; + this.y = scalar; + this.z = scalar; - }, + return this; - project: function () { + }, - var matrix; + setX: function ( x ) { - return function project( camera ) { + this.x = x; - if ( matrix === undefined ) matrix = new Matrix4(); + return this; - matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) ); - return this.applyProjection( matrix ); + }, - }; + setY: function ( y ) { - }(), + this.y = y; - unproject: function () { + return this; - var matrix; + }, - return function unproject( camera ) { + setZ: function ( z ) { - if ( matrix === undefined ) matrix = new Matrix4(); + this.z = z; - matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) ); - return this.applyProjection( matrix ); + return this; - }; + }, - }(), + setComponent: function ( index, value ) { - transformDirection: function ( m ) { + switch ( index ) { - // input: THREE.Matrix4 affine matrix - // vector interpreted as a direction + 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 ); - var x = this.x, y = this.y, z = this.z; - var e = m.elements; + } - 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(); + getComponent: function ( index ) { - }, + switch ( index ) { - divide: function ( v ) { + 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.x /= v.x; - this.y /= v.y; - this.z /= v.z; + } - return this; + }, - }, + clone: function () { - divideScalar: function ( scalar ) { + return new this.constructor( this.x, this.y, this.z ); - return this.multiplyScalar( 1 / scalar ); + }, - }, + copy: function ( v ) { - min: function ( v ) { + this.x = v.x; + this.y = v.y; + this.z = v.z; - 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; - return this; + }, - }, + add: function ( v, w ) { - max: function ( v ) { + if ( w !== undefined ) { - this.x = Math.max( this.x, v.x ); - this.y = Math.max( this.y, v.y ); - this.z = Math.max( this.z, v.z ); + console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); + return this.addVectors( v, w ); - return this; + } - }, + this.x += v.x; + this.y += v.y; + this.z += v.z; - 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 ) ); + addScalar: function ( s ) { - return this; + this.x += s; + this.y += s; + this.z += s; - }, + return this; - clampScalar: function () { + }, - var min, max; + addVectors: function ( a, b ) { - return function clampScalar( minVal, maxVal ) { + this.x = a.x + b.x; + this.y = a.y + b.y; + this.z = a.z + b.z; - if ( min === undefined ) { + return this; - min = new Vector3(); - max = new Vector3(); + }, - } + addScaledVector: function ( v, s ) { - min.set( minVal, minVal, minVal ); - max.set( maxVal, maxVal, maxVal ); + this.x += v.x * s; + this.y += v.y * s; + this.z += v.z * s; - return this.clamp( min, max ); + return this; - }; + }, - }(), + sub: function ( v, w ) { - clampLength: function ( min, max ) { + if ( w !== undefined ) { - var length = this.length(); + console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); + return this.subVectors( v, w ); - return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length ); + } - }, + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; - floor: function () { + return this; - this.x = Math.floor( this.x ); - this.y = Math.floor( this.y ); - this.z = Math.floor( this.z ); + }, - return this; + subScalar: function ( s ) { - }, + this.x -= s; + this.y -= s; + this.z -= s; - ceil: function () { + return this; - this.x = Math.ceil( this.x ); - this.y = Math.ceil( this.y ); - this.z = Math.ceil( this.z ); + }, - return this; + subVectors: function ( a, b ) { - }, + this.x = a.x - b.x; + this.y = a.y - b.y; + this.z = a.z - b.z; - round: function () { + return this; - this.x = Math.round( this.x ); - this.y = Math.round( this.y ); - this.z = Math.round( this.z ); + }, - return this; + multiply: function ( v, w ) { - }, + if ( w !== undefined ) { - roundToZero: function () { + console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' ); + return this.multiplyVectors( v, w ); - 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; + this.x *= v.x; + this.y *= v.y; + this.z *= v.z; - }, + return this; - negate: function () { + }, - this.x = - this.x; - this.y = - this.y; - this.z = - this.z; + multiplyScalar: function ( scalar ) { - return this; + if ( isFinite( scalar ) ) { - }, + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; - dot: function ( v ) { + } else { - return this.x * v.x + this.y * v.y + this.z * v.z; + this.x = 0; + this.y = 0; + this.z = 0; - }, + } - lengthSq: function () { + return this; - return this.x * this.x + this.y * this.y + this.z * this.z; + }, - }, + multiplyVectors: function ( a, b ) { - length: function () { + this.x = a.x * b.x; + this.y = a.y * b.y; + this.z = a.z * b.z; - return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z ); + return this; - }, + }, - lengthManhattan: function () { + applyEuler: function () { - return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ); + var quaternion; - }, + return function applyEuler( euler ) { - normalize: function () { + if ( (euler && euler.isEuler) === false ) { - return this.divideScalar( this.length() ); + console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' ); - }, + } - setLength: function ( length ) { + if ( quaternion === undefined ) quaternion = new Quaternion(); - return this.multiplyScalar( length / this.length() ); + return this.applyQuaternion( quaternion.setFromEuler( euler ) ); - }, + }; - lerp: function ( v, alpha ) { + }(), - this.x += ( v.x - this.x ) * alpha; - this.y += ( v.y - this.y ) * alpha; - this.z += ( v.z - this.z ) * alpha; + applyAxisAngle: function () { - return this; + var quaternion; - }, + return function applyAxisAngle( axis, angle ) { - lerpVectors: function ( v1, v2, alpha ) { + if ( quaternion === undefined ) quaternion = new Quaternion(); - return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); + return this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) ); - }, + }; - cross: function ( v, w ) { + }(), - if ( w !== undefined ) { + applyMatrix3: function ( m ) { - console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' ); - return this.crossVectors( v, w ); + var x = this.x, y = this.y, z = this.z; + var e = m.elements; - } + 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; - var x = this.x, y = this.y, z = this.z; + return this; - this.x = y * v.z - z * v.y; - this.y = z * v.x - x * v.z; - this.z = x * v.y - y * v.x; + }, - return this; + applyMatrix4: function ( m ) { - }, + // input: THREE.Matrix4 affine matrix - crossVectors: function ( a, b ) { + var x = this.x, y = this.y, z = this.z; + var e = m.elements; - var ax = a.x, ay = a.y, az = a.z; - var bx = b.x, by = b.y, bz = b.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 ]; - this.x = ay * bz - az * by; - this.y = az * bx - ax * bz; - this.z = ax * by - ay * bx; + return this; - return this; + }, - }, + applyProjection: function ( m ) { - projectOnVector: function ( vector ) { + // input: THREE.Matrix4 projection matrix - var scalar = vector.dot( this ) / vector.lengthSq(); + 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.copy( vector ).multiplyScalar( scalar ); + 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; - projectOnPlane: function () { + }, - var v1; + applyQuaternion: function ( q ) { - return function projectOnPlane( planeNormal ) { + var x = this.x, y = this.y, z = this.z; + var qx = q.x, qy = q.y, qz = q.z, qw = q.w; - if ( v1 === undefined ) v1 = new Vector3(); + // calculate quat * vector - v1.copy( this ).projectOnVector( planeNormal ); + 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; - return this.sub( v1 ); + // calculate result * inverse quat - }; + 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; - reflect: function () { + }, - // reflect incident vector off plane orthogonal to normal - // normal is assumed to have unit length + project: function () { - var v1; + var matrix; - return function reflect( normal ) { + return function project( camera ) { - if ( v1 === undefined ) v1 = new Vector3(); + if ( matrix === undefined ) matrix = new Matrix4(); - return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) ); + matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) ); + return this.applyProjection( matrix ); - }; + }; - }(), + }(), - angleTo: function ( v ) { + unproject: function () { - var theta = this.dot( v ) / ( Math.sqrt( this.lengthSq() * v.lengthSq() ) ); + var matrix; - // clamp, to handle numerical problems + return function unproject( camera ) { - return Math.acos( exports.Math.clamp( theta, - 1, 1 ) ); + if ( matrix === undefined ) matrix = new Matrix4(); - }, + matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) ); + return this.applyProjection( matrix ); - distanceTo: function ( v ) { + }; - return Math.sqrt( this.distanceToSquared( v ) ); + }(), - }, + transformDirection: function ( m ) { - distanceToSquared: function ( v ) { + // input: THREE.Matrix4 affine matrix + // vector interpreted as a direction - var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z; + var x = this.x, y = this.y, z = this.z; + var e = m.elements; - return dx * dx + dy * dy + dz * dz; + 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(); - distanceToManhattan: function ( v ) { + }, - return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z ); + divide: function ( v ) { - }, + this.x /= v.x; + this.y /= v.y; + this.z /= v.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 ); + divideScalar: function ( scalar ) { - return this; + return this.multiplyScalar( 1 / scalar ); - }, + }, - setFromMatrixPosition: function ( m ) { + min: function ( v ) { - return this.setFromMatrixColumn( m, 3 ); + 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; - setFromMatrixScale: function ( m ) { + }, - var sx = this.setFromMatrixColumn( m, 0 ).length(); - var sy = this.setFromMatrixColumn( m, 1 ).length(); - var sz = this.setFromMatrixColumn( m, 2 ).length(); + max: function ( v ) { - this.x = sx; - this.y = sy; - this.z = sz; + this.x = Math.max( this.x, v.x ); + this.y = Math.max( this.y, v.y ); + this.z = Math.max( this.z, v.z ); - return this; + return this; - }, + }, - setFromMatrixColumn: function ( m, index ) { + clamp: function ( min, max ) { - if ( typeof m === 'number' ) { + // This function assumes min < max, if this assumption isn't true it will not operate correctly - console.warn( 'THREE.Vector3: setFromMatrixColumn now expects ( matrix, index ).' ); - var temp = m - m = index; - index = temp; + 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; - return this.fromArray( m.elements, index * 4 ); + }, - }, + clampScalar: function () { - equals: function ( v ) { + var min, max; - return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) ); + return function clampScalar( minVal, maxVal ) { - }, + if ( min === undefined ) { - fromArray: function ( array, offset ) { + min = new Vector3(); + max = new Vector3(); - if ( offset === undefined ) offset = 0; + } - this.x = array[ offset ]; - this.y = array[ offset + 1 ]; - this.z = array[ offset + 2 ]; + min.set( minVal, minVal, minVal ); + max.set( maxVal, maxVal, maxVal ); - return this; + return this.clamp( min, max ); - }, + }; - toArray: function ( array, offset ) { + }(), - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + clampLength: function ( min, max ) { - array[ offset ] = this.x; - array[ offset + 1 ] = this.y; - array[ offset + 2 ] = this.z; + var length = this.length(); - return array; + return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length ); - }, + }, - fromAttribute: function ( attribute, index, offset ) { + floor: function () { - if ( offset === undefined ) offset = 0; + this.x = Math.floor( this.x ); + this.y = Math.floor( this.y ); + this.z = Math.floor( this.z ); - index = index * attribute.itemSize + offset; + return this; - this.x = attribute.array[ index ]; - this.y = attribute.array[ index + 1 ]; - this.z = attribute.array[ index + 2 ]; + }, - return this; + ceil: function () { - } + this.x = Math.ceil( this.x ); + this.y = Math.ceil( this.y ); + this.z = Math.ceil( this.z ); - }; + return this; - /** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - */ + }, - function SpritePlugin( renderer, sprites ) { + round: function () { - var gl = renderer.context; - var state = renderer.state; + this.x = Math.round( this.x ); + this.y = Math.round( this.y ); + this.z = Math.round( this.z ); - var vertexBuffer, elementBuffer; - var program, attributes, uniforms; + return this; - var texture; + }, - // decompose matrixWorld + roundToZero: function () { - var spritePosition = new Vector3(); - var spriteRotation = new Quaternion(); - var spriteScale = new Vector3(); + 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 ); - 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 - ] ); + negate: function () { - vertexBuffer = gl.createBuffer(); - elementBuffer = gl.createBuffer(); + this.x = - this.x; + this.y = - this.y; + this.z = - this.z; - 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 ); + }, - program = createProgram(); + dot: function ( v ) { - attributes = { - position: gl.getAttribLocation ( program, 'position' ), - uv: gl.getAttribLocation ( program, 'uv' ) - }; + return this.x * v.x + this.y * v.y + this.z * v.z; - uniforms = { - uvOffset: gl.getUniformLocation( program, 'uvOffset' ), - uvScale: gl.getUniformLocation( program, 'uvScale' ), + }, - rotation: gl.getUniformLocation( program, 'rotation' ), - scale: gl.getUniformLocation( program, 'scale' ), + lengthSq: function () { - color: gl.getUniformLocation( program, 'color' ), - map: gl.getUniformLocation( program, 'map' ), - opacity: gl.getUniformLocation( program, 'opacity' ), + return this.x * this.x + this.y * this.y + this.z * this.z; - modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ), - projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ), + }, - 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' ), + length: function () { - alphaTest: gl.getUniformLocation( program, 'alphaTest' ) - }; + return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z ); - var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); - canvas.width = 8; - canvas.height = 8; + }, - var context = canvas.getContext( '2d' ); - context.fillStyle = 'white'; - context.fillRect( 0, 0, 8, 8 ); + lengthManhattan: function () { - texture = new Texture( canvas ); - texture.needsUpdate = true; + return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ); - } + }, - this.render = function ( scene, camera ) { + normalize: function () { - if ( sprites.length === 0 ) return; + return this.divideScalar( this.length() ); - // setup gl + }, - if ( program === undefined ) { + setLength: function ( length ) { - init(); + return this.multiplyScalar( length / this.length() ); - } + }, - gl.useProgram( program ); + lerp: function ( v, alpha ) { - state.initAttributes(); - state.enableAttribute( attributes.position ); - state.enableAttribute( attributes.uv ); - state.disableUnusedAttributes(); + this.x += ( v.x - this.x ) * alpha; + this.y += ( v.y - this.y ) * alpha; + this.z += ( v.z - this.z ) * alpha; - state.disable( gl.CULL_FACE ); - state.enable( gl.BLEND ); + return this; - 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 ); + }, - gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); + lerpVectors: function ( v1, v2, alpha ) { - gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements ); + return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); - state.activeTexture( gl.TEXTURE0 ); - gl.uniform1i( uniforms.map, 0 ); + }, - var oldFogType = 0; - var sceneFogType = 0; - var fog = scene.fog; + cross: function ( v, w ) { - if ( fog ) { + if ( w !== undefined ) { - gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b ); + console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' ); + return this.crossVectors( v, w ); - if ( (fog && fog.isFog) ) { + } - gl.uniform1f( uniforms.fogNear, fog.near ); - gl.uniform1f( uniforms.fogFar, fog.far ); + var x = this.x, y = this.y, z = this.z; - gl.uniform1i( uniforms.fogType, 1 ); - oldFogType = 1; - sceneFogType = 1; + this.x = y * v.z - z * v.y; + this.y = z * v.x - x * v.z; + this.z = x * v.y - y * v.x; - } else if ( (fog && fog.isFogExp2) ) { + return this; - gl.uniform1f( uniforms.fogDensity, fog.density ); + }, - gl.uniform1i( uniforms.fogType, 2 ); - oldFogType = 2; - sceneFogType = 2; + crossVectors: function ( a, b ) { - } + var ax = a.x, ay = a.y, az = a.z; + var bx = b.x, by = b.y, bz = b.z; - } else { + this.x = ay * bz - az * by; + this.y = az * bx - ax * bz; + this.z = ax * by - ay * bx; - gl.uniform1i( uniforms.fogType, 0 ); - oldFogType = 0; - sceneFogType = 0; + return this; - } + }, + projectOnVector: function ( vector ) { - // update positions and sort + var scalar = vector.dot( this ) / vector.lengthSq(); - for ( var i = 0, l = sprites.length; i < l; i ++ ) { + return this.copy( vector ).multiplyScalar( scalar ); - var sprite = sprites[ i ]; + }, - sprite.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld ); - sprite.z = - sprite.modelViewMatrix.elements[ 14 ]; + projectOnPlane: function () { - } + var v1; - sprites.sort( painterSortStable ); + return function projectOnPlane( planeNormal ) { - // render all sprites + if ( v1 === undefined ) v1 = new Vector3(); - var scale = []; + v1.copy( this ).projectOnVector( planeNormal ); - for ( var i = 0, l = sprites.length; i < l; i ++ ) { + return this.sub( v1 ); - var sprite = sprites[ i ]; - var material = sprite.material; + }; - if ( material.visible === false ) continue; + }(), - gl.uniform1f( uniforms.alphaTest, material.alphaTest ); - gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite.modelViewMatrix.elements ); + reflect: function () { - sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale ); + // reflect incident vector off plane orthogonal to normal + // normal is assumed to have unit length - scale[ 0 ] = spriteScale.x; - scale[ 1 ] = spriteScale.y; + var v1; - var fogType = 0; + return function reflect( normal ) { - if ( scene.fog && material.fog ) { + if ( v1 === undefined ) v1 = new Vector3(); - fogType = sceneFogType; + return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) ); - } + }; - if ( oldFogType !== fogType ) { + }(), - gl.uniform1i( uniforms.fogType, fogType ); - oldFogType = fogType; + angleTo: function ( v ) { - } + var theta = this.dot( v ) / ( Math.sqrt( this.lengthSq() * v.lengthSq() ) ); - if ( material.map !== null ) { + // clamp, to handle numerical problems - 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 Math.acos( exports.Math.clamp( theta, - 1, 1 ) ); - } else { + }, - gl.uniform2f( uniforms.uvOffset, 0, 0 ); - gl.uniform2f( uniforms.uvScale, 1, 1 ); + distanceTo: function ( v ) { - } + return Math.sqrt( this.distanceToSquared( v ) ); - gl.uniform1f( uniforms.opacity, material.opacity ); - gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b ); + }, - gl.uniform1f( uniforms.rotation, material.rotation ); - gl.uniform2fv( uniforms.scale, scale ); + distanceToSquared: function ( v ) { - state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst ); - state.setDepthTest( material.depthTest ); - state.setDepthWrite( material.depthWrite ); + var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z; - if ( material.map ) { + return dx * dx + dy * dy + dz * dz; - renderer.setTexture2D( material.map, 0 ); + }, - } else { + distanceToManhattan: function ( v ) { - renderer.setTexture2D( texture, 0 ); + return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z ); - } + }, - gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); + setFromSpherical: function( s ) { - } + var sinPhiRadius = Math.sin( s.phi ) * s.radius; - // restore gl + this.x = sinPhiRadius * Math.sin( s.theta ); + this.y = Math.cos( s.phi ) * s.radius; + this.z = sinPhiRadius * Math.cos( s.theta ); - state.enable( gl.CULL_FACE ); + return this; - renderer.resetGLState(); + }, - }; + setFromMatrixPosition: function ( m ) { - function createProgram() { + return this.setFromMatrixColumn( m, 3 ); - var program = gl.createProgram(); + }, - var vertexShader = gl.createShader( gl.VERTEX_SHADER ); - var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER ); + setFromMatrixScale: function ( m ) { - gl.shaderSource( vertexShader, [ + var sx = this.setFromMatrixColumn( m, 0 ).length(); + var sy = this.setFromMatrixColumn( m, 1 ).length(); + var sz = this.setFromMatrixColumn( m, 2 ).length(); - 'precision ' + renderer.getPrecision() + ' float;', + this.x = sx; + this.y = sy; + this.z = sz; - 'uniform mat4 modelViewMatrix;', - 'uniform mat4 projectionMatrix;', - 'uniform float rotation;', - 'uniform vec2 scale;', - 'uniform vec2 uvOffset;', - 'uniform vec2 uvScale;', + return this; - 'attribute vec2 position;', - 'attribute vec2 uv;', + }, - 'varying vec2 vUV;', + setFromMatrixColumn: function ( m, index ) { - 'void main() {', + if ( typeof m === 'number' ) { - 'vUV = uvOffset + uv * uvScale;', + console.warn( 'THREE.Vector3: setFromMatrixColumn now expects ( matrix, index ).' ); + var temp = m + m = index; + index = temp; - '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;', + return this.fromArray( m.elements, index * 4 ); - 'vec4 finalPosition;', + }, - 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );', - 'finalPosition.xy += rotatedPosition;', - 'finalPosition = projectionMatrix * finalPosition;', + equals: function ( v ) { - 'gl_Position = finalPosition;', + return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) ); - '}' + }, - ].join( '\n' ) ); + fromArray: function ( array, offset ) { - gl.shaderSource( fragmentShader, [ + if ( offset === undefined ) offset = 0; - 'precision ' + renderer.getPrecision() + ' float;', + this.x = array[ offset ]; + this.y = array[ offset + 1 ]; + this.z = array[ offset + 2 ]; - '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;', + toArray: function ( array, offset ) { - 'void main() {', + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - 'vec4 texture = texture2D( map, vUV );', + array[ offset ] = this.x; + array[ offset + 1 ] = this.y; + array[ offset + 2 ] = this.z; - 'if ( texture.a < alphaTest ) discard;', + return array; - 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );', + }, - 'if ( fogType > 0 ) {', + fromAttribute: function ( attribute, index, offset ) { - 'float depth = gl_FragCoord.z / gl_FragCoord.w;', - 'float fogFactor = 0.0;', + if ( offset === undefined ) offset = 0; - 'if ( fogType == 1 ) {', + index = index * attribute.itemSize + offset; - 'fogFactor = smoothstep( fogNear, fogFar, depth );', + this.x = attribute.array[ index ]; + this.y = attribute.array[ index + 1 ]; + this.z = attribute.array[ index + 2 ]; - '} else {', + return this; - '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 );', + /** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + */ - '}', + function SpritePlugin( renderer, sprites ) { - '}' + var gl = renderer.context; + var state = renderer.state; - ].join( '\n' ) ); + var vertexBuffer, elementBuffer; + var program, attributes, uniforms; - gl.compileShader( vertexShader ); - gl.compileShader( fragmentShader ); + var texture; - gl.attachShader( program, vertexShader ); - gl.attachShader( program, fragmentShader ); + // decompose matrixWorld - gl.linkProgram( program ); + var spritePosition = new Vector3(); + var spriteRotation = new Quaternion(); + var spriteScale = new Vector3(); - return program; + 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 painterSortStable( a, b ) { + var faces = new Uint16Array( [ + 0, 1, 2, + 0, 2, 3 + ] ); - if ( a.renderOrder !== b.renderOrder ) { + vertexBuffer = gl.createBuffer(); + elementBuffer = gl.createBuffer(); - return a.renderOrder - b.renderOrder; + gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer ); + gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW ); - } else if ( a.z !== b.z ) { + gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); + gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW ); - return b.z - a.z; + program = createProgram(); - } else { + attributes = { + position: gl.getAttribLocation ( program, 'position' ), + uv: gl.getAttribLocation ( program, 'uv' ) + }; - return b.id - a.id; + uniforms = { + uvOffset: gl.getUniformLocation( program, 'uvOffset' ), + uvScale: gl.getUniformLocation( program, 'uvScale' ), - } + rotation: gl.getUniformLocation( program, 'rotation' ), + scale: gl.getUniformLocation( program, 'scale' ), - } + color: gl.getUniformLocation( program, 'color' ), + map: gl.getUniformLocation( program, 'map' ), + opacity: gl.getUniformLocation( program, 'opacity' ), - }; + modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ), + projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ), - /** - * @author bhouston / http://clara.io - */ + 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' ), - function Box2( min, max ) { + alphaTest: gl.getUniformLocation( program, 'alphaTest' ) + }; - this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity ); - this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity ); + var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); + canvas.width = 8; + canvas.height = 8; - }; + var context = canvas.getContext( '2d' ); + context.fillStyle = 'white'; + context.fillRect( 0, 0, 8, 8 ); - Box2.prototype = { + texture = new Texture( canvas ); + texture.needsUpdate = true; - constructor: Box2, + } - set: function ( min, max ) { + this.render = function ( scene, camera ) { - this.min.copy( min ); - this.max.copy( max ); + if ( sprites.length === 0 ) return; - return this; + // setup gl - }, + if ( program === undefined ) { - setFromPoints: function ( points ) { + init(); - this.makeEmpty(); + } - for ( var i = 0, il = points.length; i < il; i ++ ) { + gl.useProgram( program ); - this.expandByPoint( points[ i ] ); + state.initAttributes(); + state.enableAttribute( attributes.position ); + state.enableAttribute( attributes.uv ); + state.disableUnusedAttributes(); - } + state.disable( gl.CULL_FACE ); + state.enable( gl.BLEND ); - return this; + 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 ); - }, + gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); - setFromCenterAndSize: function () { + gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements ); - var v1 = new Vector2(); + state.activeTexture( gl.TEXTURE0 ); + gl.uniform1i( uniforms.map, 0 ); - return function setFromCenterAndSize( center, size ) { + var oldFogType = 0; + var sceneFogType = 0; + var fog = scene.fog; - var halfSize = v1.copy( size ).multiplyScalar( 0.5 ); - this.min.copy( center ).sub( halfSize ); - this.max.copy( center ).add( halfSize ); + if ( fog ) { - return this; + gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b ); - }; + if ( (fog && fog.isFog) ) { - }(), + gl.uniform1f( uniforms.fogNear, fog.near ); + gl.uniform1f( uniforms.fogFar, fog.far ); - clone: function () { + gl.uniform1i( uniforms.fogType, 1 ); + oldFogType = 1; + sceneFogType = 1; - return new this.constructor().copy( this ); + } else if ( (fog && fog.isFogExp2) ) { - }, + gl.uniform1f( uniforms.fogDensity, fog.density ); - copy: function ( box ) { + gl.uniform1i( uniforms.fogType, 2 ); + oldFogType = 2; + sceneFogType = 2; - this.min.copy( box.min ); - this.max.copy( box.max ); + } - return this; + } else { - }, + gl.uniform1i( uniforms.fogType, 0 ); + oldFogType = 0; + sceneFogType = 0; - makeEmpty: function () { + } - this.min.x = this.min.y = + Infinity; - this.max.x = this.max.y = - Infinity; - return this; + // update positions and sort - }, + for ( var i = 0, l = sprites.length; i < l; i ++ ) { - isEmpty: function () { + var sprite = sprites[ i ]; - // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes + sprite.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld ); + sprite.z = - sprite.modelViewMatrix.elements[ 14 ]; - return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ); + } - }, + sprites.sort( painterSortStable ); - center: function ( optionalTarget ) { + // render all sprites - var result = optionalTarget || new Vector2(); - return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); + var scale = []; - }, + for ( var i = 0, l = sprites.length; i < l; i ++ ) { - size: function ( optionalTarget ) { + var sprite = sprites[ i ]; + var material = sprite.material; - var result = optionalTarget || new Vector2(); - return result.subVectors( this.max, this.min ); + if ( material.visible === false ) continue; - }, + gl.uniform1f( uniforms.alphaTest, material.alphaTest ); + gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite.modelViewMatrix.elements ); - expandByPoint: function ( point ) { + sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale ); - this.min.min( point ); - this.max.max( point ); + scale[ 0 ] = spriteScale.x; + scale[ 1 ] = spriteScale.y; - return this; + var fogType = 0; - }, + if ( scene.fog && material.fog ) { - expandByVector: function ( vector ) { + fogType = sceneFogType; - this.min.sub( vector ); - this.max.add( vector ); + } - return this; + if ( oldFogType !== fogType ) { - }, + gl.uniform1i( uniforms.fogType, fogType ); + oldFogType = fogType; - expandByScalar: function ( scalar ) { + } - this.min.addScalar( - scalar ); - this.max.addScalar( scalar ); + if ( material.map !== null ) { - return this; + 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 { - containsPoint: function ( point ) { + gl.uniform2f( uniforms.uvOffset, 0, 0 ); + gl.uniform2f( uniforms.uvScale, 1, 1 ); - if ( point.x < this.min.x || point.x > this.max.x || - point.y < this.min.y || point.y > this.max.y ) { + } - return false; + gl.uniform1f( uniforms.opacity, material.opacity ); + gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b ); - } + gl.uniform1f( uniforms.rotation, material.rotation ); + gl.uniform2fv( uniforms.scale, scale ); - return true; + state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst ); + state.setDepthTest( material.depthTest ); + state.setDepthWrite( material.depthWrite ); - }, + if ( material.map ) { - containsBox: function ( box ) { + renderer.setTexture2D( material.map, 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 ) ) { + } else { - return true; + renderer.setTexture2D( texture, 0 ); - } + } - return false; + gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); - }, + } - getParameter: function ( point, optionalTarget ) { + // restore gl - // This can potentially have a divide by zero if the box - // has a size dimension of 0. + state.enable( gl.CULL_FACE ); - var result = optionalTarget || new Vector2(); + renderer.resetGLState(); - 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 createProgram() { - intersectsBox: function ( box ) { + var program = gl.createProgram(); - // using 6 splitting planes to rule out intersections. + var vertexShader = gl.createShader( gl.VERTEX_SHADER ); + var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER ); - 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 ) { + gl.shaderSource( vertexShader, [ - return false; + 'precision ' + renderer.getPrecision() + ' float;', - } + 'uniform mat4 modelViewMatrix;', + 'uniform mat4 projectionMatrix;', + 'uniform float rotation;', + 'uniform vec2 scale;', + 'uniform vec2 uvOffset;', + 'uniform vec2 uvScale;', - return true; + 'attribute vec2 position;', + 'attribute vec2 uv;', - }, + 'varying vec2 vUV;', - clampPoint: function ( point, optionalTarget ) { + 'void main() {', - var result = optionalTarget || new Vector2(); - return result.copy( point ).clamp( this.min, this.max ); + 'vUV = uvOffset + uv * uvScale;', - }, + 'vec2 alignedPosition = position * scale;', - distanceToPoint: function () { + 'vec2 rotatedPosition;', + 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;', + 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;', - var v1 = new Vector2(); + 'vec4 finalPosition;', - return function distanceToPoint( point ) { + 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );', + 'finalPosition.xy += rotatedPosition;', + 'finalPosition = projectionMatrix * finalPosition;', - var clampedPoint = v1.copy( point ).clamp( this.min, this.max ); - return clampedPoint.sub( point ).length(); + 'gl_Position = finalPosition;', - }; + '}' - }(), + ].join( '\n' ) ); - intersect: function ( box ) { + gl.shaderSource( fragmentShader, [ - this.min.max( box.min ); - this.max.min( box.max ); + 'precision ' + renderer.getPrecision() + ' float;', - return this; + '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;', - union: function ( box ) { + 'varying vec2 vUV;', - this.min.min( box.min ); - this.max.max( box.max ); + 'void main() {', - return this; + 'vec4 texture = texture2D( map, vUV );', - }, + 'if ( texture.a < alphaTest ) discard;', - translate: function ( offset ) { + 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );', - this.min.add( offset ); - this.max.add( offset ); + 'if ( fogType > 0 ) {', - return this; + 'float depth = gl_FragCoord.z / gl_FragCoord.w;', + 'float fogFactor = 0.0;', - }, + 'if ( fogType == 1 ) {', - equals: function ( box ) { + 'fogFactor = smoothstep( fogNear, fogFar, depth );', - return box.min.equals( this.min ) && box.max.equals( this.max ); + '} else {', - } + 'const float LOG2 = 1.442695;', + 'fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );', + 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );', - }; + '}', - /** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - */ + 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );', - function LensFlarePlugin( renderer, flares ) { + '}', - var gl = renderer.context; - var state = renderer.state; + '}' - var vertexBuffer, elementBuffer; - var shader, program, attributes, uniforms; + ].join( '\n' ) ); - var tempTexture, occlusionTexture; + gl.compileShader( vertexShader ); + gl.compileShader( fragmentShader ); - function init() { + gl.attachShader( program, vertexShader ); + gl.attachShader( program, fragmentShader ); - var vertices = new Float32Array( [ - - 1, - 1, 0, 0, - 1, - 1, 1, 0, - 1, 1, 1, 1, - - 1, 1, 0, 1 - ] ); + gl.linkProgram( program ); - var faces = new Uint16Array( [ - 0, 1, 2, - 0, 2, 3 - ] ); + return program; - // buffers + } - vertexBuffer = gl.createBuffer(); - elementBuffer = gl.createBuffer(); + function painterSortStable( a, b ) { - gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer ); - gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW ); + if ( a.renderOrder !== b.renderOrder ) { - gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); - gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW ); + return a.renderOrder - b.renderOrder; - // textures + } else if ( a.z !== b.z ) { - tempTexture = gl.createTexture(); - occlusionTexture = gl.createTexture(); + return b.z - a.z; - 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 ); + } else { - 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 ); + return b.id - a.id; - shader = { + } - vertexShader: [ + } - "uniform lowp int renderType;", + }; - "uniform vec3 screenPosition;", - "uniform vec2 scale;", - "uniform float rotation;", + /** + * @author bhouston / http://clara.io + */ - "uniform sampler2D occlusionMap;", + function Box2( min, max ) { - "attribute vec2 position;", - "attribute vec2 uv;", + this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity ); + this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity ); - "varying vec2 vUV;", - "varying float vVisibility;", + }; - "void main() {", + Box2.prototype = { - "vUV = uv;", + constructor: Box2, - "vec2 pos = position;", + set: function ( min, max ) { - "if ( renderType == 2 ) {", + this.min.copy( min ); + this.max.copy( max ); - "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 ) );", + return this; - "vVisibility = visibility.r / 9.0;", - "vVisibility *= 1.0 - visibility.g / 9.0;", - "vVisibility *= visibility.b / 9.0;", - "vVisibility *= 1.0 - visibility.a / 9.0;", + }, - "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;", - "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;", + setFromPoints: function ( points ) { - "}", + this.makeEmpty(); - "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );", + for ( var i = 0, il = points.length; i < il; i ++ ) { - "}" + this.expandByPoint( points[ i ] ); - ].join( "\n" ), + } - fragmentShader: [ + return this; - "uniform lowp int renderType;", + }, - "uniform sampler2D map;", - "uniform float opacity;", - "uniform vec3 color;", + setFromCenterAndSize: function () { - "varying vec2 vUV;", - "varying float vVisibility;", + var v1 = new Vector2(); - "void main() {", + return function setFromCenterAndSize( center, size ) { - // pink square + var halfSize = v1.copy( size ).multiplyScalar( 0.5 ); + this.min.copy( center ).sub( halfSize ); + this.max.copy( center ).add( halfSize ); - "if ( renderType == 0 ) {", + return this; - "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );", + }; - // restore + }(), - "} else if ( renderType == 1 ) {", + clone: function () { - "gl_FragColor = texture2D( map, vUV );", + return new this.constructor().copy( this ); - // flare + }, - "} else {", + copy: function ( box ) { - "vec4 texture = texture2D( map, vUV );", - "texture.a *= opacity * vVisibility;", - "gl_FragColor = texture;", - "gl_FragColor.rgb *= color;", + this.min.copy( box.min ); + this.max.copy( box.max ); - "}", + return this; - "}" + }, - ].join( "\n" ) + makeEmpty: function () { - }; + this.min.x = this.min.y = + Infinity; + this.max.x = this.max.y = - Infinity; - program = createProgram( shader ); + return this; - attributes = { - vertex: gl.getAttribLocation ( program, "position" ), - uv: gl.getAttribLocation ( program, "uv" ) - }; + }, - 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" ) - }; + isEmpty: function () { - } + // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes - /* - * Render lens flares - * Method: renders 16x16 0xff00ff-colored points scattered over the light source area, - * reads these back and calculates occlusion. - */ + return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ); - this.render = function ( scene, camera, viewport ) { + }, - if ( flares.length === 0 ) return; + center: function ( optionalTarget ) { - var tempPosition = new Vector3(); + var result = optionalTarget || new Vector2(); + return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); - 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 ); + size: function ( optionalTarget ) { - var screenPosition = new Vector3( 1, 1, 0 ), - screenPositionPixels = new Vector2( 1, 1 ); + var result = optionalTarget || new Vector2(); + return result.subVectors( this.max, this.min ); - var validArea = new Box2(); + }, - validArea.min.set( 0, 0 ); - validArea.max.set( viewport.z - 16, viewport.w - 16 ); + expandByPoint: function ( point ) { - if ( program === undefined ) { + this.min.min( point ); + this.max.max( point ); - init(); + return this; - } + }, - gl.useProgram( program ); + expandByVector: function ( vector ) { - state.initAttributes(); - state.enableAttribute( attributes.vertex ); - state.enableAttribute( attributes.uv ); - state.disableUnusedAttributes(); + this.min.sub( vector ); + this.max.add( vector ); - // loop through all lens flares to update their occlusion and positions - // setup gl and common used attribs/uniforms + return this; - 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 ); + expandByScalar: function ( scalar ) { - gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); + this.min.addScalar( - scalar ); + this.max.addScalar( scalar ); - state.disable( gl.CULL_FACE ); - state.setDepthWrite( false ); + return this; - for ( var i = 0, l = flares.length; i < l; i ++ ) { + }, - size = 16 / viewport.w; - scale.set( size * invAspect, size ); + containsPoint: function ( point ) { - // calc object screen position + if ( point.x < this.min.x || point.x > this.max.x || + point.y < this.min.y || point.y > this.max.y ) { - var flare = flares[ i ]; + return false; - tempPosition.set( flare.matrixWorld.elements[ 12 ], flare.matrixWorld.elements[ 13 ], flare.matrixWorld.elements[ 14 ] ); + } - tempPosition.applyMatrix4( camera.matrixWorldInverse ); - tempPosition.applyProjection( camera.projectionMatrix ); + return true; - // setup arrays for gl programs + }, - screenPosition.copy( tempPosition ); + containsBox: function ( box ) { - // horizontal and vertical coordinate of the lower left corner of the pixels to copy + 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 ) ) { - screenPositionPixels.x = viewport.x + ( screenPosition.x * halfViewportWidth ) + halfViewportWidth - 8; - screenPositionPixels.y = viewport.y + ( screenPosition.y * halfViewportHeight ) + halfViewportHeight - 8; + return true; - // screen cull + } - if ( validArea.containsPoint( screenPositionPixels ) === true ) { + return false; - // save current RGB to temp texture + }, - 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 ); + getParameter: function ( point, optionalTarget ) { + // This can potentially have a divide by zero if the box + // has a size dimension of 0. - // render pink quad + var result = optionalTarget || new Vector2(); - gl.uniform1i( uniforms.renderType, 0 ); - gl.uniform2f( uniforms.scale, scale.x, scale.y ); - gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z ); + 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 ) + ); - state.disable( gl.BLEND ); - state.enable( gl.DEPTH_TEST ); + }, - gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); + intersectsBox: function ( box ) { + // using 6 splitting planes to rule out intersections. - // copy result to occlusionMap + 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 ) { - 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 false; + } - // restore graphics + return true; - gl.uniform1i( uniforms.renderType, 1 ); - state.disable( gl.DEPTH_TEST ); + }, - state.activeTexture( gl.TEXTURE1 ); - state.bindTexture( gl.TEXTURE_2D, tempTexture ); - gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); + clampPoint: function ( point, optionalTarget ) { + var result = optionalTarget || new Vector2(); + return result.copy( point ).clamp( this.min, this.max ); - // update object positions + }, - flare.positionScreen.copy( screenPosition ); + distanceToPoint: function () { - if ( flare.customUpdateCallback ) { + var v1 = new Vector2(); - flare.customUpdateCallback( flare ); + return function distanceToPoint( point ) { - } else { + var clampedPoint = v1.copy( point ).clamp( this.min, this.max ); + return clampedPoint.sub( point ).length(); - flare.updateLensFlares(); + }; - } + }(), - // render flares + intersect: function ( box ) { - gl.uniform1i( uniforms.renderType, 2 ); - state.enable( gl.BLEND ); + this.min.max( box.min ); + this.max.min( box.max ); - for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) { + return this; - var sprite = flare.lensFlares[ j ]; + }, - if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) { + union: function ( box ) { - screenPosition.x = sprite.x; - screenPosition.y = sprite.y; - screenPosition.z = sprite.z; + this.min.min( box.min ); + this.max.max( box.max ); - size = sprite.size * sprite.scale / viewport.w; + return this; - scale.x = size * invAspect; - scale.y = size; + }, - gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z ); - gl.uniform2f( uniforms.scale, scale.x, scale.y ); - gl.uniform1f( uniforms.rotation, sprite.rotation ); + translate: function ( offset ) { - gl.uniform1f( uniforms.opacity, sprite.opacity ); - gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b ); + this.min.add( offset ); + this.max.add( offset ); - state.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst ); - renderer.setTexture2D( sprite.texture, 1 ); + return this; - gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); + }, - } + equals: function ( box ) { - } + return box.min.equals( this.min ) && box.max.equals( this.max ); - } + } - } + }; - // restore gl + /** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + */ - state.enable( gl.CULL_FACE ); - state.enable( gl.DEPTH_TEST ); - state.setDepthWrite( true ); + function LensFlarePlugin( renderer, flares ) { - renderer.resetGLState(); + var gl = renderer.context; + var state = renderer.state; - }; + var vertexBuffer, elementBuffer; + var shader, program, attributes, uniforms; - function createProgram( shader ) { + var tempTexture, occlusionTexture; - var program = gl.createProgram(); + function init() { - var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER ); - var vertexShader = gl.createShader( gl.VERTEX_SHADER ); + var vertices = new Float32Array( [ + - 1, - 1, 0, 0, + 1, - 1, 1, 0, + 1, 1, 1, 1, + - 1, 1, 0, 1 + ] ); - var prefix = "precision " + renderer.getPrecision() + " float;\n"; + var faces = new Uint16Array( [ + 0, 1, 2, + 0, 2, 3 + ] ); - gl.shaderSource( fragmentShader, prefix + shader.fragmentShader ); - gl.shaderSource( vertexShader, prefix + shader.vertexShader ); + // buffers - gl.compileShader( fragmentShader ); - gl.compileShader( vertexShader ); + vertexBuffer = gl.createBuffer(); + elementBuffer = gl.createBuffer(); - gl.attachShader( program, fragmentShader ); - gl.attachShader( program, vertexShader ); + gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer ); + gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW ); - gl.linkProgram( program ); + gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); + gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW ); - return program; + // textures - } + 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 ); - /** - * @author mrdoob / http://mrdoob.com/ - */ + 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 ); - function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) { + shader = { - images = images !== undefined ? images : []; - mapping = mapping !== undefined ? mapping : CubeReflectionMapping; + vertexShader: [ - Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); + "uniform lowp int renderType;", - this.flipY = false; + "uniform vec3 screenPosition;", + "uniform vec2 scale;", + "uniform float rotation;", - }; + "uniform sampler2D occlusionMap;", - CubeTexture.prototype = Object.create( Texture.prototype ); - CubeTexture.prototype.constructor = CubeTexture; + "attribute vec2 position;", + "attribute vec2 uv;", - CubeTexture.prototype.isCubeTexture = true; + "varying vec2 vUV;", + "varying float vVisibility;", - Object.defineProperty( CubeTexture.prototype, 'images', { + "void main() {", - get: function () { + "vUV = uv;", - return this.image; + "vec2 pos = position;", - }, + "if ( renderType == 2 ) {", - set: function ( value ) { + "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.image = value; + "vVisibility = visibility.r / 9.0;", + "vVisibility *= 1.0 - visibility.g / 9.0;", + "vVisibility *= visibility.b / 9.0;", + "vVisibility *= 1.0 - visibility.a / 9.0;", - } + "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;", + "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;", - } ); + "}", - /** - * - * 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_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );", - exports.WebGLUniforms = ( function() { // scope + "}" - var emptyTexture = new Texture(); - var emptyCubeTexture = new CubeTexture(); + ].join( "\n" ), - // --- Base for inner nodes (including the root) --- + fragmentShader: [ - var UniformContainer = function() { + "uniform lowp int renderType;", - this.seq = []; - this.map = {}; + "uniform sampler2D map;", + "uniform float opacity;", + "uniform vec3 color;", - }, + "varying vec2 vUV;", + "varying float vVisibility;", - // --- Utilities --- + "void main() {", - // Array Caches (provide typed arrays for temporary by size) + // pink square - arrayCacheF32 = [], - arrayCacheI32 = [], + "if ( renderType == 0 ) {", - // Flattening for arrays of vectors and matrices + "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );", - flatten = function( array, nBlocks, blockSize ) { + // restore - var firstElem = array[ 0 ]; + "} else if ( renderType == 1 ) {", - if ( firstElem <= 0 || firstElem > 0 ) return array; - // unoptimized: ! isNaN( firstElem ) - // see http://jacksondunstan.com/articles/983 + "gl_FragColor = texture2D( map, vUV );", - var n = nBlocks * blockSize, - r = arrayCacheF32[ n ]; + // flare - if ( r === undefined ) { + "} else {", - r = new Float32Array( n ); - arrayCacheF32[ n ] = r; + "vec4 texture = texture2D( map, vUV );", + "texture.a *= opacity * vVisibility;", + "gl_FragColor = texture;", + "gl_FragColor.rgb *= color;", - } + "}", - if ( nBlocks !== 0 ) { + "}" - firstElem.toArray( r, 0 ); + ].join( "\n" ) - for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) { + }; - offset += blockSize; - array[ i ].toArray( r, offset ); + program = createProgram( shader ); - } + attributes = { + vertex: gl.getAttribLocation ( program, "position" ), + uv: gl.getAttribLocation ( program, "uv" ) + }; - } + 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 r; + } - }, + /* + * Render lens flares + * Method: renders 16x16 0xff00ff-colored points scattered over the light source area, + * reads these back and calculates occlusion. + */ - // Texture unit allocation + this.render = function ( scene, camera, viewport ) { - allocTexUnits = function( renderer, n ) { + if ( flares.length === 0 ) return; - var r = arrayCacheI32[ n ]; + var tempPosition = new Vector3(); - if ( r === undefined ) { + var invAspect = viewport.w / viewport.z, + halfViewportWidth = viewport.z * 0.5, + halfViewportHeight = viewport.w * 0.5; - r = new Int32Array( n ); - arrayCacheI32[ n ] = r; + var size = 16 / viewport.w, + scale = new Vector2( size * invAspect, size ); - } + var screenPosition = new Vector3( 1, 1, 0 ), + screenPositionPixels = new Vector2( 1, 1 ); - for ( var i = 0; i !== n; ++ i ) - r[ i ] = renderer.allocTextureUnit(); + var validArea = new Box2(); - return r; + validArea.min.set( 0, 0 ); + validArea.max.set( viewport.z - 16, viewport.w - 16 ); - }, + if ( program === undefined ) { - // --- Setters --- + init(); - // Note: Defining these methods externally, because they come in a bunch - // and this way their names minify. + } - // Single scalar + gl.useProgram( program ); - setValue1f = function( gl, v ) { gl.uniform1f( this.addr, v ); }, - setValue1i = function( gl, v ) { gl.uniform1i( this.addr, v ); }, + state.initAttributes(); + state.enableAttribute( attributes.vertex ); + state.enableAttribute( attributes.uv ); + state.disableUnusedAttributes(); - // Single float vector (from flat array or THREE.VectorN) + // loop through all lens flares to update their occlusion and positions + // setup gl and common used attribs/uniforms - setValue2fv = function( gl, v ) { + gl.uniform1i( uniforms.occlusionMap, 0 ); + gl.uniform1i( uniforms.map, 1 ); - if ( v.x === undefined ) gl.uniform2fv( this.addr, v ); - else gl.uniform2f( this.addr, v.x, v.y ); + 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 ); - }, + gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); - setValue3fv = function( gl, v ) { + state.disable( gl.CULL_FACE ); + state.setDepthWrite( false ); - 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 ); + for ( var i = 0, l = flares.length; i < l; i ++ ) { - }, + size = 16 / viewport.w; + scale.set( size * invAspect, size ); - setValue4fv = function( gl, v ) { + // calc object screen position - if ( v.x === undefined ) gl.uniform4fv( this.addr, v ); - else gl.uniform4f( this.addr, v.x, v.y, v.z, v.w ); + var flare = flares[ i ]; - }, + tempPosition.set( flare.matrixWorld.elements[ 12 ], flare.matrixWorld.elements[ 13 ], flare.matrixWorld.elements[ 14 ] ); - // Single matrix (from flat array or MatrixN) + tempPosition.applyMatrix4( camera.matrixWorldInverse ); + tempPosition.applyProjection( camera.projectionMatrix ); - setValue2fm = function( gl, v ) { + // setup arrays for gl programs - gl.uniformMatrix2fv( this.addr, false, v.elements || v ); + screenPosition.copy( tempPosition ); - }, + // horizontal and vertical coordinate of the lower left corner of the pixels to copy - setValue3fm = function( gl, v ) { + screenPositionPixels.x = viewport.x + ( screenPosition.x * halfViewportWidth ) + halfViewportWidth - 8; + screenPositionPixels.y = viewport.y + ( screenPosition.y * halfViewportHeight ) + halfViewportHeight - 8; - gl.uniformMatrix3fv( this.addr, false, v.elements || v ); + // screen cull - }, + if ( validArea.containsPoint( screenPositionPixels ) === true ) { - setValue4fm = function( gl, v ) { + // save current RGB to temp texture - gl.uniformMatrix4fv( this.addr, false, v.elements || v ); + 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 ); - }, - // Single texture (2D / Cube) + // render pink quad - setValueT1 = function( gl, v, renderer ) { + gl.uniform1i( uniforms.renderType, 0 ); + gl.uniform2f( uniforms.scale, scale.x, scale.y ); + gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z ); - var unit = renderer.allocTextureUnit(); - gl.uniform1i( this.addr, unit ); - renderer.setTexture2D( v || emptyTexture, unit ); + state.disable( gl.BLEND ); + state.enable( gl.DEPTH_TEST ); - }, + gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); - setValueT6 = function( gl, v, renderer ) { - var unit = renderer.allocTextureUnit(); - gl.uniform1i( this.addr, unit ); - renderer.setTextureCube( v || emptyCubeTexture, unit ); + // 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 ); - // 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 ); }, + // restore graphics - // Helper to pick the right setter for the singular case + gl.uniform1i( uniforms.renderType, 1 ); + state.disable( gl.DEPTH_TEST ); - getSingularSetter = function( type ) { + state.activeTexture( gl.TEXTURE1 ); + state.bindTexture( gl.TEXTURE_2D, tempTexture ); + gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); - switch ( type ) { - case 0x1406: return setValue1f; // FLOAT - case 0x8b50: return setValue2fv; // _VEC2 - case 0x8b51: return setValue3fv; // _VEC3 - case 0x8b52: return setValue4fv; // _VEC4 + // update object positions - case 0x8b5a: return setValue2fm; // _MAT2 - case 0x8b5b: return setValue3fm; // _MAT3 - case 0x8b5c: return setValue4fm; // _MAT4 + flare.positionScreen.copy( screenPosition ); - case 0x8b5e: return setValueT1; // SAMPLER_2D - case 0x8b60: return setValueT6; // SAMPLER_CUBE + if ( flare.customUpdateCallback ) { - 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 + flare.customUpdateCallback( flare ); - } + } else { - }, + flare.updateLensFlares(); - // Array of scalars + } - setValue1fv = function( gl, v ) { gl.uniform1fv( this.addr, v ); }, - setValue1iv = function( gl, v ) { gl.uniform1iv( this.addr, v ); }, + // render flares - // Array of vectors (flat or from THREE classes) + gl.uniform1i( uniforms.renderType, 2 ); + state.enable( gl.BLEND ); - setValueV2a = function( gl, v ) { + for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) { - gl.uniform2fv( this.addr, flatten( v, this.size, 2 ) ); + var sprite = flare.lensFlares[ j ]; - }, + if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) { - setValueV3a = function( gl, v ) { + screenPosition.x = sprite.x; + screenPosition.y = sprite.y; + screenPosition.z = sprite.z; - gl.uniform3fv( this.addr, flatten( v, this.size, 3 ) ); + size = sprite.size * sprite.scale / viewport.w; - }, + scale.x = size * invAspect; + scale.y = size; - setValueV4a = function( gl, 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.uniform4fv( this.addr, flatten( v, this.size, 4 ) ); + gl.uniform1f( uniforms.opacity, sprite.opacity ); + gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b ); - }, + state.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst ); + renderer.setTexture2D( sprite.texture, 1 ); - // Array of matrices (flat or from THREE clases) + gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); - setValueM2a = function( gl, v ) { + } - gl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) ); + } - }, + } - setValueM3a = function( gl, v ) { + } - gl.uniformMatrix3fv( this.addr, false, flatten( v, this.size, 9 ) ); + // restore gl - }, + state.enable( gl.CULL_FACE ); + state.enable( gl.DEPTH_TEST ); + state.setDepthWrite( true ); - setValueM4a = function( gl, v ) { + renderer.resetGLState(); - gl.uniformMatrix4fv( this.addr, false, flatten( v, this.size, 16 ) ); + }; - }, + function createProgram( shader ) { - // Array of textures (2D / Cube) + var program = gl.createProgram(); - setValueT1a = function( gl, v, renderer ) { + var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER ); + var vertexShader = gl.createShader( gl.VERTEX_SHADER ); - var n = v.length, - units = allocTexUnits( renderer, n ); + var prefix = "precision " + renderer.getPrecision() + " float;\n"; - gl.uniform1iv( this.addr, units ); + gl.shaderSource( fragmentShader, prefix + shader.fragmentShader ); + gl.shaderSource( vertexShader, prefix + shader.vertexShader ); - for ( var i = 0; i !== n; ++ i ) { + gl.compileShader( fragmentShader ); + gl.compileShader( vertexShader ); - renderer.setTexture2D( v[ i ] || emptyTexture, units[ i ] ); + gl.attachShader( program, fragmentShader ); + gl.attachShader( program, vertexShader ); - } + gl.linkProgram( program ); - }, + return program; - setValueT6a = function( gl, v, renderer ) { + } - var n = v.length, - units = allocTexUnits( renderer, n ); + }; - gl.uniform1iv( this.addr, units ); + /** + * @author mrdoob / http://mrdoob.com/ + */ - for ( var i = 0; i !== n; ++ i ) { + function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) { - renderer.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] ); + images = images !== undefined ? images : []; + mapping = mapping !== undefined ? mapping : CubeReflectionMapping; - } + Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); - }, + this.flipY = false; + }; - // Helper to pick the right setter for a pure (bottom-level) array + CubeTexture.prototype = Object.create( Texture.prototype ); + CubeTexture.prototype.constructor = CubeTexture; - getPureArraySetter = function( type ) { + CubeTexture.prototype.isCubeTexture = true; - switch ( type ) { + Object.defineProperty( CubeTexture.prototype, 'images', { - case 0x1406: return setValue1fv; // FLOAT - case 0x8b50: return setValueV2a; // _VEC2 - case 0x8b51: return setValueV3a; // _VEC3 - case 0x8b52: return setValueV4a; // _VEC4 + get: function () { - case 0x8b5a: return setValueM2a; // _MAT2 - case 0x8b5b: return setValueM3a; // _MAT3 - case 0x8b5c: return setValueM4a; // _MAT4 + return this.image; - case 0x8b5e: return setValueT1a; // SAMPLER_2D - case 0x8b60: return setValueT6a; // SAMPLER_CUBE + }, - 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 + set: function ( value ) { - } + this.image = value; - }, + } - // --- Uniform Classes --- + } ); + + /** + * + * 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 + * + */ - SingleUniform = function SingleUniform( id, activeInfo, addr ) { + exports.WebGLUniforms = ( function() { // scope - this.id = id; - this.addr = addr; - this.setValue = getSingularSetter( activeInfo.type ); + var emptyTexture = new Texture(); + var emptyCubeTexture = new CubeTexture(); - // this.path = activeInfo.name; // DEBUG + // --- Base for inner nodes (including the root) --- - }, + var UniformContainer = function() { - PureArrayUniform = function( id, activeInfo, addr ) { + this.seq = []; + this.map = {}; - this.id = id; - this.addr = addr; - this.size = activeInfo.size; - this.setValue = getPureArraySetter( activeInfo.type ); + }, - // this.path = activeInfo.name; // DEBUG + // --- Utilities --- - }, + // Array Caches (provide typed arrays for temporary by size) - StructuredUniform = function( id ) { + arrayCacheF32 = [], + arrayCacheI32 = [], - this.id = id; + // Flattening for arrays of vectors and matrices - UniformContainer.call( this ); // mix-in + flatten = function( array, nBlocks, blockSize ) { - }; + var firstElem = array[ 0 ]; - StructuredUniform.prototype.setValue = function( gl, value ) { + if ( firstElem <= 0 || firstElem > 0 ) return array; + // unoptimized: ! isNaN( firstElem ) + // see http://jacksondunstan.com/articles/983 - // Note: Don't need an extra 'renderer' parameter, since samplers - // are not allowed in structured uniforms. + var n = nBlocks * blockSize, + r = arrayCacheF32[ n ]; - var seq = this.seq; + if ( r === undefined ) { - for ( var i = 0, n = seq.length; i !== n; ++ i ) { + r = new Float32Array( n ); + arrayCacheF32[ n ] = r; - var u = seq[ i ]; - u.setValue( gl, value[ u.id ] ); + } - } + if ( nBlocks !== 0 ) { - }; + firstElem.toArray( r, 0 ); - // --- Top-level --- + for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) { - // Parser - builds up the property tree from the path strings + offset += blockSize; + array[ i ].toArray( r, offset ); - 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 ) { + } - container.seq.push( uniformObject ); - container.map[ uniformObject.id ] = uniformObject; + return r; - }, + }, - parseUniform = function( activeInfo, addr, container ) { + // Texture unit allocation - var path = activeInfo.name, - pathLength = path.length; + allocTexUnits = function( renderer, n ) { - // reset RegExp object, because of the early exit of a previous run - RePathPart.lastIndex = 0; + var r = arrayCacheI32[ n ]; - for (; ;) { + if ( r === undefined ) { - var match = RePathPart.exec( path ), - matchEnd = RePathPart.lastIndex, + r = new Int32Array( n ); + arrayCacheI32[ n ] = r; - id = match[ 1 ], - idIsIndex = match[ 2 ] === ']', - subscript = match[ 3 ]; + } - if ( idIsIndex ) id = id | 0; // convert to integer + for ( var i = 0; i !== n; ++ i ) + r[ i ] = renderer.allocTextureUnit(); - if ( subscript === undefined || - subscript === '[' && matchEnd + 2 === pathLength ) { - // bare name or "pure" bottom-level array "[0]" suffix + return r; - addUniform( container, subscript === undefined ? - new SingleUniform( id, activeInfo, addr ) : - new PureArrayUniform( id, activeInfo, addr ) ); + }, - break; + // --- Setters --- - } else { - // step into inner node / create it in case it doesn't exist + // Note: Defining these methods externally, because they come in a bunch + // and this way their names minify. - var map = container.map, - next = map[ id ]; + // Single scalar - if ( next === undefined ) { + setValue1f = function( gl, v ) { gl.uniform1f( this.addr, v ); }, + setValue1i = function( gl, v ) { gl.uniform1i( this.addr, v ); }, - next = new StructuredUniform( id ); - addUniform( container, next ); + // Single float vector (from flat array or THREE.VectorN) - } + setValue2fv = function( gl, v ) { - container = next; + if ( v.x === undefined ) gl.uniform2fv( this.addr, v ); + else gl.uniform2f( this.addr, v.x, v.y ); - } + }, - } + setValue3fv = function( gl, v ) { - }, + 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 ); - // Root Container + }, - WebGLUniforms = function WebGLUniforms( gl, program, renderer ) { + setValue4fv = function( gl, v ) { - UniformContainer.call( this ); + if ( v.x === undefined ) gl.uniform4fv( this.addr, v ); + else gl.uniform4f( this.addr, v.x, v.y, v.z, v.w ); - this.renderer = renderer; + }, - var n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS ); + // Single matrix (from flat array or MatrixN) - for ( var i = 0; i !== n; ++ i ) { + setValue2fm = function( gl, v ) { - var info = gl.getActiveUniform( program, i ), - path = info.name, - addr = gl.getUniformLocation( program, path ); + gl.uniformMatrix2fv( this.addr, false, v.elements || v ); - parseUniform( info, addr, this ); + }, - } + setValue3fm = function( gl, v ) { - }; + gl.uniformMatrix3fv( this.addr, false, v.elements || v ); + }, - WebGLUniforms.prototype.setValue = function( gl, name, value ) { + setValue4fm = function( gl, v ) { - var u = this.map[ name ]; + gl.uniformMatrix4fv( this.addr, false, v.elements || v ); - if ( u !== undefined ) u.setValue( gl, value, this.renderer ); + }, - }; + // Single texture (2D / Cube) - WebGLUniforms.prototype.set = function( gl, object, name ) { + setValueT1 = function( gl, v, renderer ) { - var u = this.map[ name ]; + var unit = renderer.allocTextureUnit(); + gl.uniform1i( this.addr, unit ); + renderer.setTexture2D( v || emptyTexture, unit ); - if ( u !== undefined ) u.setValue( gl, object[ name ], this.renderer ); + }, - }; + setValueT6 = function( gl, v, renderer ) { - WebGLUniforms.prototype.setOptional = function( gl, object, name ) { + var unit = renderer.allocTextureUnit(); + gl.uniform1i( this.addr, unit ); + renderer.setTextureCube( v || emptyCubeTexture, unit ); - var v = object[ name ]; + }, - if ( v !== undefined ) this.setValue( gl, name, v ); + // 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 ); }, + // Helper to pick the right setter for the singular case - // Static interface + getSingularSetter = function( type ) { - WebGLUniforms.upload = function( gl, seq, values, renderer ) { + switch ( type ) { - for ( var i = 0, n = seq.length; i !== n; ++ i ) { + case 0x1406: return setValue1f; // FLOAT + case 0x8b50: return setValue2fv; // _VEC2 + case 0x8b51: return setValue3fv; // _VEC3 + case 0x8b52: return setValue4fv; // _VEC4 - var u = seq[ i ], - v = values[ u.id ]; + case 0x8b5a: return setValue2fm; // _MAT2 + case 0x8b5b: return setValue3fm; // _MAT3 + case 0x8b5c: return setValue4fm; // _MAT4 - if ( v.needsUpdate !== false ) { - // note: always updating when .needsUpdate is undefined + case 0x8b5e: return setValueT1; // SAMPLER_2D + case 0x8b60: return setValueT6; // SAMPLER_CUBE - u.setValue( gl, v.value, renderer ); + 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 - } + } - } + }, - }; + // Array of scalars - WebGLUniforms.seqWithValue = function( seq, values ) { + setValue1fv = function( gl, v ) { gl.uniform1fv( this.addr, v ); }, + setValue1iv = function( gl, v ) { gl.uniform1iv( this.addr, v ); }, - var r = []; + // Array of vectors (flat or from THREE classes) - for ( var i = 0, n = seq.length; i !== n; ++ i ) { + setValueV2a = function( gl, v ) { - var u = seq[ i ]; - if ( u.id in values ) r.push( u ); + gl.uniform2fv( this.addr, flatten( v, this.size, 2 ) ); - } + }, - return r; + setValueV3a = function( gl, v ) { - }; + gl.uniform3fv( this.addr, flatten( v, this.size, 3 ) ); - WebGLUniforms.splitDynamic = function( seq, values ) { + }, - var r = null, - n = seq.length, - w = 0; + setValueV4a = function( gl, v ) { - for ( var i = 0; i !== n; ++ i ) { + gl.uniform4fv( this.addr, flatten( v, this.size, 4 ) ); - var u = seq[ i ], - v = values[ u.id ]; + }, - if ( v && v.dynamic === true ) { + // Array of matrices (flat or from THREE clases) - if ( r === null ) r = []; - r.push( u ); + setValueM2a = function( gl, v ) { - } else { + gl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) ); - // in-place compact 'seq', removing the matches - if ( w < i ) seq[ w ] = u; - ++ w; + }, - } + setValueM3a = function( gl, v ) { - } + gl.uniformMatrix3fv( this.addr, false, flatten( v, this.size, 9 ) ); - if ( w < n ) seq.length = w; + }, - return r; + setValueM4a = function( gl, v ) { - }; + gl.uniformMatrix4fv( this.addr, false, flatten( v, this.size, 16 ) ); - WebGLUniforms.evalDynamic = function( seq, values, object, camera ) { + }, - for ( var i = 0, n = seq.length; i !== n; ++ i ) { + // Array of textures (2D / Cube) - var v = values[ seq[ i ].id ], - f = v.onUpdateCallback; + setValueT1a = function( gl, v, renderer ) { - if ( f !== undefined ) f.call( v, object, camera ); + var n = v.length, + units = allocTexUnits( renderer, n ); - } + gl.uniform1iv( this.addr, units ); - }; + for ( var i = 0; i !== n; ++ i ) { - return WebGLUniforms; + renderer.setTexture2D( v[ i ] || emptyTexture, units[ i ] ); - } )(); + } - /** - * @author mrdoob / http://mrdoob.com/ - */ + }, - function WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, info ) { + setValueT6a = function( gl, v, renderer ) { - var _infoMemory = info.memory; - var _isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && _gl instanceof WebGL2RenderingContext ); + var n = v.length, + units = allocTexUnits( renderer, n ); - // + gl.uniform1iv( this.addr, units ); - function clampToMaxSize( image, maxSize ) { + for ( var i = 0; i !== n; ++ i ) { - if ( image.width > maxSize || image.height > maxSize ) { + renderer.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] ); - // Warning: Scaling through the canvas will only work with images that use - // premultiplied alpha. + } - var scale = maxSize / Math.max( image.width, image.height ); + }, - 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 ); - var context = canvas.getContext( '2d' ); - context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height ); + // Helper to pick the right setter for a pure (bottom-level) array - console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image ); + getPureArraySetter = function( type ) { - return canvas; + switch ( type ) { - } + case 0x1406: return setValue1fv; // FLOAT + case 0x8b50: return setValueV2a; // _VEC2 + case 0x8b51: return setValueV3a; // _VEC3 + case 0x8b52: return setValueV4a; // _VEC4 - return image; + case 0x8b5a: return setValueM2a; // _MAT2 + case 0x8b5b: return setValueM3a; // _MAT3 + case 0x8b5c: return setValueM4a; // _MAT4 - } + case 0x8b5e: return setValueT1a; // SAMPLER_2D + case 0x8b60: return setValueT6a; // SAMPLER_CUBE - function isPowerOfTwo( image ) { + 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 - return exports.Math.isPowerOfTwo( image.width ) && exports.Math.isPowerOfTwo( image.height ); + } - } + }, - function makePowerOfTwo( image ) { + // --- Uniform Classes --- - if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement ) { + SingleUniform = function SingleUniform( id, activeInfo, addr ) { - 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 ); + this.id = id; + this.addr = addr; + this.setValue = getSingularSetter( activeInfo.type ); - var context = canvas.getContext( '2d' ); - context.drawImage( image, 0, 0, canvas.width, canvas.height ); + // this.path = activeInfo.name; // DEBUG - console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image ); + }, - return canvas; + PureArrayUniform = function( id, activeInfo, addr ) { - } + this.id = id; + this.addr = addr; + this.size = activeInfo.size; + this.setValue = getPureArraySetter( activeInfo.type ); - return image; + // this.path = activeInfo.name; // DEBUG - } + }, - function textureNeedsPowerOfTwo( texture ) { + StructuredUniform = function( id ) { - if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) return true; - if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) return true; + this.id = id; - return false; + UniformContainer.call( this ); // mix-in - } + }; - // Fallback filters for non-power-of-2 textures + StructuredUniform.prototype.setValue = function( gl, value ) { - function filterFallback( f ) { + // Note: Don't need an extra 'renderer' parameter, since samplers + // are not allowed in structured uniforms. - if ( f === NearestFilter || f === NearestMipMapNearestFilter || f === NearestMipMapLinearFilter ) { + var seq = this.seq; - return _gl.NEAREST; + for ( var i = 0, n = seq.length; i !== n; ++ i ) { - } + var u = seq[ i ]; + u.setValue( gl, value[ u.id ] ); - return _gl.LINEAR; + } - } + }; - // + // --- Top-level --- - function onTextureDispose( event ) { + // Parser - builds up the property tree from the path strings - var texture = event.target; + 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. - texture.removeEventListener( 'dispose', onTextureDispose ); + addUniform = function( container, uniformObject ) { - deallocateTexture( texture ); + container.seq.push( uniformObject ); + container.map[ uniformObject.id ] = uniformObject; - _infoMemory.textures --; + }, + parseUniform = function( activeInfo, addr, container ) { - } + var path = activeInfo.name, + pathLength = path.length; - function onRenderTargetDispose( event ) { + // reset RegExp object, because of the early exit of a previous run + RePathPart.lastIndex = 0; - var renderTarget = event.target; + for (; ;) { - renderTarget.removeEventListener( 'dispose', onRenderTargetDispose ); + var match = RePathPart.exec( path ), + matchEnd = RePathPart.lastIndex, - deallocateRenderTarget( renderTarget ); + id = match[ 1 ], + idIsIndex = match[ 2 ] === ']', + subscript = match[ 3 ]; - _infoMemory.textures --; + if ( idIsIndex ) id = id | 0; // convert to integer - } + 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 ) ); - function deallocateTexture( texture ) { + break; - var textureProperties = properties.get( texture ); + } else { + // step into inner node / create it in case it doesn't exist - if ( texture.image && textureProperties.__image__webglTextureCube ) { + var map = container.map, + next = map[ id ]; - // cube texture + if ( next === undefined ) { - _gl.deleteTexture( textureProperties.__image__webglTextureCube ); + next = new StructuredUniform( id ); + addUniform( container, next ); - } else { + } - // 2D texture + container = next; - if ( textureProperties.__webglInit === undefined ) return; + } - _gl.deleteTexture( textureProperties.__webglTexture ); + } - } + }, - // remove all webgl properties - properties.delete( texture ); + // Root Container - } + WebGLUniforms = function WebGLUniforms( gl, program, renderer ) { - function deallocateRenderTarget( renderTarget ) { + UniformContainer.call( this ); - var renderTargetProperties = properties.get( renderTarget ); - var textureProperties = properties.get( renderTarget.texture ); + this.renderer = renderer; - if ( ! renderTarget ) return; + var n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS ); - if ( textureProperties.__webglTexture !== undefined ) { + for ( var i = 0; i !== n; ++ i ) { - _gl.deleteTexture( textureProperties.__webglTexture ); + var info = gl.getActiveUniform( program, i ), + path = info.name, + addr = gl.getUniformLocation( program, path ); - } + parseUniform( info, addr, this ); - if ( renderTarget.depthTexture ) { + } - renderTarget.depthTexture.dispose(); + }; - } - if ( (renderTarget && renderTarget.isWebGLRenderTargetCube) ) { + WebGLUniforms.prototype.setValue = function( gl, name, value ) { - for ( var i = 0; i < 6; i ++ ) { + var u = this.map[ name ]; - _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] ); - if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] ); + if ( u !== undefined ) u.setValue( gl, value, this.renderer ); - } + }; - } else { + WebGLUniforms.prototype.set = function( gl, object, name ) { - _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer ); - if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer ); + var u = this.map[ name ]; - } + if ( u !== undefined ) u.setValue( gl, object[ name ], this.renderer ); - properties.delete( renderTarget.texture ); - properties.delete( renderTarget ); + }; - } + WebGLUniforms.prototype.setOptional = function( gl, object, name ) { - // + var v = object[ name ]; + if ( v !== undefined ) this.setValue( gl, name, v ); + }; - function setTexture2D( texture, slot ) { - var textureProperties = properties.get( texture ); + // Static interface - if ( texture.version > 0 && textureProperties.__version !== texture.version ) { + WebGLUniforms.upload = function( gl, seq, values, renderer ) { - var image = texture.image; + for ( var i = 0, n = seq.length; i !== n; ++ i ) { - if ( image === undefined ) { + var u = seq[ i ], + v = values[ u.id ]; - console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture ); + if ( v.needsUpdate !== false ) { + // note: always updating when .needsUpdate is undefined - } else if ( image.complete === false ) { + u.setValue( gl, v.value, renderer ); - console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture ); + } - } else { + } - uploadTexture( textureProperties, texture, slot ); - return; + }; - } + WebGLUniforms.seqWithValue = function( seq, values ) { - } + var r = []; - state.activeTexture( _gl.TEXTURE0 + slot ); - state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture ); + for ( var i = 0, n = seq.length; i !== n; ++ i ) { - } + var u = seq[ i ]; + if ( u.id in values ) r.push( u ); - function setTextureCube( texture, slot ) { + } - var textureProperties = properties.get( texture ); + return r; - if ( texture.image.length === 6 ) { + }; - if ( texture.version > 0 && textureProperties.__version !== texture.version ) { + WebGLUniforms.splitDynamic = function( seq, values ) { - if ( ! textureProperties.__image__webglTextureCube ) { + var r = null, + n = seq.length, + w = 0; - texture.addEventListener( 'dispose', onTextureDispose ); + for ( var i = 0; i !== n; ++ i ) { - textureProperties.__image__webglTextureCube = _gl.createTexture(); + var u = seq[ i ], + v = values[ u.id ]; - _infoMemory.textures ++; + if ( v && v.dynamic === true ) { - } + if ( r === null ) r = []; + r.push( u ); - state.activeTexture( _gl.TEXTURE0 + slot ); - state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube ); + } else { - _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY ); + // in-place compact 'seq', removing the matches + if ( w < i ) seq[ w ] = u; + ++ w; - var isCompressed = (texture && texture.isCompressedTexture); - var isDataTexture = (texture.image[ 0 ] && texture.image[ 0 ].isDataTexture); + } - var cubeImage = []; + } - for ( var i = 0; i < 6; i ++ ) { + if ( w < n ) seq.length = w; - if ( ! isCompressed && ! isDataTexture ) { + return r; - cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize ); + }; - } else { + WebGLUniforms.evalDynamic = function( seq, values, object, camera ) { - cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ]; + for ( var i = 0, n = seq.length; i !== n; ++ i ) { - } + var v = values[ seq[ i ].id ], + f = v.onUpdateCallback; - } + if ( f !== undefined ) f.call( v, object, camera ); - var image = cubeImage[ 0 ], - isPowerOfTwoImage = isPowerOfTwo( image ), - glFormat = paramThreeToGL( texture.format ), - glType = paramThreeToGL( texture.type ); + } - setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isPowerOfTwoImage ); + }; - for ( var i = 0; i < 6; i ++ ) { + return WebGLUniforms; - if ( ! isCompressed ) { + } )(); - if ( isDataTexture ) { + /** + * @author mrdoob / http://mrdoob.com/ + */ - state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data ); + function WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, info ) { - } else { + var _infoMemory = info.memory; + var _isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && _gl instanceof WebGL2RenderingContext ); - state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] ); + // - } + function clampToMaxSize( image, maxSize ) { - } else { + if ( image.width > maxSize || image.height > maxSize ) { - var mipmap, mipmaps = cubeImage[ i ].mipmaps; + // Warning: Scaling through the canvas will only work with images that use + // premultiplied alpha. - for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) { + var scale = maxSize / Math.max( image.width, image.height ); - mipmap = mipmaps[ j ]; + 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 ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) { + var context = canvas.getContext( '2d' ); + context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height ); - if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) { + console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image ); - state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data ); + return canvas; - } else { + } - console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()" ); + return image; - } + } - } else { + function isPowerOfTwo( image ) { - state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + return exports.Math.isPowerOfTwo( image.width ) && exports.Math.isPowerOfTwo( image.height ); - } + } - } + 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 ); - if ( texture.generateMipmaps && isPowerOfTwoImage ) { + var context = canvas.getContext( '2d' ); + context.drawImage( image, 0, 0, canvas.width, canvas.height ); - _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP ); + console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image ); - } + return canvas; - textureProperties.__version = texture.version; + } - if ( texture.onUpdate ) texture.onUpdate( texture ); + return image; - } else { + } - state.activeTexture( _gl.TEXTURE0 + slot ); - state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube ); + function textureNeedsPowerOfTwo( texture ) { - } + if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) return true; + if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) return true; - } + return false; - } + } - function setTextureCubeDynamic( texture, slot ) { + // Fallback filters for non-power-of-2 textures - state.activeTexture( _gl.TEXTURE0 + slot ); - state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture ); + function filterFallback( f ) { - } + if ( f === NearestFilter || f === NearestMipMapNearestFilter || f === NearestMipMapLinearFilter ) { - function setTextureParameters( textureType, texture, isPowerOfTwoImage ) { + return _gl.NEAREST; - var extension; + } - if ( isPowerOfTwoImage ) { + return _gl.LINEAR; - _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) ); - _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) ); + } - _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) ); - _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) ); + // - } else { + function onTextureDispose( event ) { - _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE ); - _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE ); + var texture = event.target; - if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) { + texture.removeEventListener( 'dispose', onTextureDispose ); - console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture ); + deallocateTexture( texture ); - } + _infoMemory.textures --; - _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 ) { + } - console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture ); + function onRenderTargetDispose( event ) { - } + var renderTarget = event.target; - } + renderTarget.removeEventListener( 'dispose', onRenderTargetDispose ); - extension = extensions.get( 'EXT_texture_filter_anisotropic' ); + deallocateRenderTarget( renderTarget ); - if ( extension ) { + _infoMemory.textures --; - 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; + } - if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) { + // - _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) ); - properties.get( texture ).__currentAnisotropy = texture.anisotropy; + function deallocateTexture( texture ) { - } + var textureProperties = properties.get( texture ); - } + if ( texture.image && textureProperties.__image__webglTextureCube ) { - } + // cube texture - function uploadTexture( textureProperties, texture, slot ) { + _gl.deleteTexture( textureProperties.__image__webglTextureCube ); - if ( textureProperties.__webglInit === undefined ) { + } else { - textureProperties.__webglInit = true; + // 2D texture - texture.addEventListener( 'dispose', onTextureDispose ); + if ( textureProperties.__webglInit === undefined ) return; - textureProperties.__webglTexture = _gl.createTexture(); + _gl.deleteTexture( textureProperties.__webglTexture ); - _infoMemory.textures ++; + } - } + // remove all webgl properties + properties.delete( texture ); - state.activeTexture( _gl.TEXTURE0 + slot ); - state.bindTexture( _gl.TEXTURE_2D, textureProperties.__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 ); + function deallocateRenderTarget( renderTarget ) { - var image = clampToMaxSize( texture.image, capabilities.maxTextureSize ); + var renderTargetProperties = properties.get( renderTarget ); + var textureProperties = properties.get( renderTarget.texture ); - if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( image ) === false ) { + if ( ! renderTarget ) return; - image = makePowerOfTwo( image ); + if ( textureProperties.__webglTexture !== undefined ) { - } + _gl.deleteTexture( textureProperties.__webglTexture ); - var isPowerOfTwoImage = isPowerOfTwo( image ), - glFormat = paramThreeToGL( texture.format ), - glType = paramThreeToGL( texture.type ); + } - setTextureParameters( _gl.TEXTURE_2D, texture, isPowerOfTwoImage ); + if ( renderTarget.depthTexture ) { - var mipmap, mipmaps = texture.mipmaps; + renderTarget.depthTexture.dispose(); - if ( (texture && texture.isDepthTexture) ) { + } - // populate depth texture with dummy data + if ( (renderTarget && renderTarget.isWebGLRenderTargetCube) ) { - var internalFormat = _gl.DEPTH_COMPONENT; + for ( var i = 0; i < 6; i ++ ) { - if ( texture.type === FloatType ) { + _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] ); + if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] ); - if ( !_isWebGL2 ) throw new Error('Float Depth Texture only supported in WebGL2.0'); - internalFormat = _gl.DEPTH_COMPONENT32F; + } - } else if ( _isWebGL2 ) { + } else { - // WebGL 2.0 requires signed internalformat for glTexImage2D - internalFormat = _gl.DEPTH_COMPONENT16; + _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer ); + if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer ); - } + } - // Depth stencil textures need the DEPTH_STENCIL internal format - // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) - if ( texture.format === DepthStencilFormat ) { + properties.delete( renderTarget.texture ); + properties.delete( renderTarget ); - internalFormat = _gl.DEPTH_STENCIL; + } - } + // - state.texImage2D( _gl.TEXTURE_2D, 0, internalFormat, image.width, image.height, 0, glFormat, glType, null ); - } else if ( (texture && texture.isDataTexture) ) { - // 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 + function setTexture2D( texture, slot ) { - if ( mipmaps.length > 0 && isPowerOfTwoImage ) { + var textureProperties = properties.get( texture ); - for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { + if ( texture.version > 0 && textureProperties.__version !== texture.version ) { - mipmap = mipmaps[ i ]; - state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + var image = texture.image; - } + if ( image === undefined ) { - texture.generateMipmaps = false; + console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture ); - } else { + } else if ( image.complete === false ) { - state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data ); + console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture ); - } + } else { - } else if ( (texture && texture.isCompressedTexture) ) { + uploadTexture( textureProperties, texture, slot ); + return; - for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { + } - mipmap = mipmaps[ i ]; + } - if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) { + state.activeTexture( _gl.TEXTURE0 + slot ); + state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture ); - if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) { + } - state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data ); + function setTextureCube( texture, slot ) { - } else { + var textureProperties = properties.get( texture ); - console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" ); + if ( texture.image.length === 6 ) { - } + if ( texture.version > 0 && textureProperties.__version !== texture.version ) { - } else { + if ( ! textureProperties.__image__webglTextureCube ) { - state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + texture.addEventListener( 'dispose', onTextureDispose ); - } + textureProperties.__image__webglTextureCube = _gl.createTexture(); - } + _infoMemory.textures ++; - } 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 + _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY ); - if ( mipmaps.length > 0 && isPowerOfTwoImage ) { + var isCompressed = (texture && texture.isCompressedTexture); + var isDataTexture = (texture.image[ 0 ] && texture.image[ 0 ].isDataTexture); - for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { + var cubeImage = []; - mipmap = mipmaps[ i ]; - state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap ); + for ( var i = 0; i < 6; i ++ ) { - } + if ( ! isCompressed && ! isDataTexture ) { - texture.generateMipmaps = false; + cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize ); - } else { + } else { - state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, image ); + cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ]; - } + } - } + } - if ( texture.generateMipmaps && isPowerOfTwoImage ) _gl.generateMipmap( _gl.TEXTURE_2D ); + var image = cubeImage[ 0 ], + isPowerOfTwoImage = isPowerOfTwo( image ), + glFormat = paramThreeToGL( texture.format ), + glType = paramThreeToGL( texture.type ); - textureProperties.__version = texture.version; + setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isPowerOfTwoImage ); - if ( texture.onUpdate ) texture.onUpdate( texture ); + for ( var i = 0; i < 6; i ++ ) { - } + if ( ! isCompressed ) { - // Render targets + if ( isDataTexture ) { - // Setup storage for target texture and bind it to correct framebuffer - function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) { + state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data ); - 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 ); + } else { - } + state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] ); - // Setup storage for internal depth/stencil buffers and bind to correct framebuffer - function setupRenderBufferStorage( renderbuffer, renderTarget ) { + } - _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer ); + } else { - if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) { + var mipmap, mipmaps = cubeImage[ i ].mipmaps; - _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height ); - _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); + for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) { - } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) { + mipmap = mipmaps[ j ]; - _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height ); - _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); + if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) { - } else { + if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) { - // FIXME: We don't support !depth !stencil - _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height ); + state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data ); - } + } else { - _gl.bindRenderbuffer( _gl.RENDERBUFFER, null ); + console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()" ); - } + } - // Setup resources for a Depth Texture for a FBO (needs an extension) - function setupDepthTexture( framebuffer, renderTarget ) { + } else { - var isCube = ( (renderTarget && renderTarget.isWebGLRenderTargetCube) ); - if ( isCube ) throw new Error('Depth Texture with cube render targets is not supported!'); + state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); - _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + } - if ( !( (renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture) ) ) { + } - throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture'); + } - } + } - // 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; - } + if ( texture.generateMipmaps && isPowerOfTwoImage ) { - setTexture2D( renderTarget.depthTexture, 0 ); + _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP ); - var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture; + } - if ( renderTarget.depthTexture.format === DepthFormat ) { + textureProperties.__version = texture.version; - _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 ); + if ( texture.onUpdate ) texture.onUpdate( texture ); - } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) { + } else { - _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 ); + state.activeTexture( _gl.TEXTURE0 + slot ); + state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube ); - } else { + } - throw new Error('Unknown depthTexture format') + } - } + } - } + function setTextureCubeDynamic( texture, slot ) { - // Setup GL resources for a non-texture depth buffer - function setupDepthRenderbuffer( renderTarget ) { + state.activeTexture( _gl.TEXTURE0 + slot ); + state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture ); - var renderTargetProperties = properties.get( renderTarget ); + } - var isCube = ( (renderTarget && renderTarget.isWebGLRenderTargetCube) ); + function setTextureParameters( textureType, texture, isPowerOfTwoImage ) { - if ( renderTarget.depthTexture ) { + var extension; - if ( isCube ) throw new Error('target.depthTexture not supported in Cube render targets'); + if ( isPowerOfTwoImage ) { - setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget ); + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) ); + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) ); - } else { + _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) ); + _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) ); - if ( isCube ) { + } else { - renderTargetProperties.__webglDepthbuffer = []; + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE ); + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE ); - for ( var i = 0; i < 6; i ++ ) { + if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) { - _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] ); - renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer(); - setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget ); + console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture ); - } + } - } else { + _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) ); + _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) ); - _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer ); - renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer(); - setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget ); + if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) { - } + console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture ); - } + } - _gl.bindFramebuffer( _gl.FRAMEBUFFER, null ); + } - } + extension = extensions.get( 'EXT_texture_filter_anisotropic' ); - // Set up GL resources for the render target - function setupRenderTarget( renderTarget ) { + if ( extension ) { - var renderTargetProperties = properties.get( renderTarget ); - var textureProperties = properties.get( renderTarget.texture ); + 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; - renderTarget.addEventListener( 'dispose', onRenderTargetDispose ); + if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) { - textureProperties.__webglTexture = _gl.createTexture(); + _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) ); + properties.get( texture ).__currentAnisotropy = texture.anisotropy; - _infoMemory.textures ++; + } - var isCube = ( (renderTarget && renderTarget.isWebGLRenderTargetCube) ); - var isTargetPowerOfTwo = isPowerOfTwo( renderTarget ); + } - // Setup framebuffer + } - if ( isCube ) { + function uploadTexture( textureProperties, texture, slot ) { - renderTargetProperties.__webglFramebuffer = []; + if ( textureProperties.__webglInit === undefined ) { - for ( var i = 0; i < 6; i ++ ) { + textureProperties.__webglInit = true; - renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer(); + texture.addEventListener( 'dispose', onTextureDispose ); - } + textureProperties.__webglTexture = _gl.createTexture(); - } else { + _infoMemory.textures ++; - renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer(); + } - } + state.activeTexture( _gl.TEXTURE0 + slot ); + state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture ); - // Setup color buffer + _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 ( isCube ) { + var image = clampToMaxSize( texture.image, capabilities.maxTextureSize ); - state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture ); - setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo ); + if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( image ) === false ) { - for ( var i = 0; i < 6; i ++ ) { + image = makePowerOfTwo( image ); - setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i ); + } - } + var isPowerOfTwoImage = isPowerOfTwo( image ), + glFormat = paramThreeToGL( texture.format ), + glType = paramThreeToGL( texture.type ); - if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP ); - state.bindTexture( _gl.TEXTURE_CUBE_MAP, null ); + setTextureParameters( _gl.TEXTURE_2D, texture, isPowerOfTwoImage ); - } else { + var mipmap, mipmaps = texture.mipmaps; - 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 ( (texture && texture.isDepthTexture) ) { - if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D ); - state.bindTexture( _gl.TEXTURE_2D, null ); + // populate depth texture with dummy data - } + var internalFormat = _gl.DEPTH_COMPONENT; - // Setup depth and stencil buffers + if ( texture.type === FloatType ) { - if ( renderTarget.depthBuffer ) { + if ( !_isWebGL2 ) throw new Error('Float Depth Texture only supported in WebGL2.0'); + internalFormat = _gl.DEPTH_COMPONENT32F; - setupDepthRenderbuffer( renderTarget ); + } else if ( _isWebGL2 ) { - } + // WebGL 2.0 requires signed internalformat for glTexImage2D + internalFormat = _gl.DEPTH_COMPONENT16; - } + } - function updateRenderTargetMipmap( renderTarget ) { + // Depth stencil textures need the DEPTH_STENCIL internal format + // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) + if ( texture.format === DepthStencilFormat ) { - var texture = renderTarget.texture; + internalFormat = _gl.DEPTH_STENCIL; - if ( texture.generateMipmaps && isPowerOfTwo( renderTarget ) && - texture.minFilter !== NearestFilter && - texture.minFilter !== LinearFilter ) { + } - var target = (renderTarget && renderTarget.isWebGLRenderTargetCube) ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D; - var webglTexture = properties.get( texture ).__webglTexture; + state.texImage2D( _gl.TEXTURE_2D, 0, internalFormat, image.width, image.height, 0, glFormat, glType, null ); - state.bindTexture( target, webglTexture ); - _gl.generateMipmap( target ); - state.bindTexture( target, null ); + } else if ( (texture && texture.isDataTexture) ) { - } + // 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 ) { - this.setTexture2D = setTexture2D; - this.setTextureCube = setTextureCube; - this.setTextureCubeDynamic = setTextureCubeDynamic; - this.setupRenderTarget = setupRenderTarget; - this.updateRenderTargetMipmap = updateRenderTargetMipmap; + 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 ); - /** - * @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 - */ + } - function Vector4( x, y, z, w ) { + texture.generateMipmaps = false; - this.x = x || 0; - this.y = y || 0; - this.z = z || 0; - this.w = ( w !== undefined ) ? w : 1; + } else { - }; + state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data ); - Vector4.prototype = { + } - constructor: Vector4, + } else if ( (texture && texture.isCompressedTexture) ) { - isVector4: true, + for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { - set: function ( x, y, z, w ) { + mipmap = mipmaps[ i ]; - this.x = x; - this.y = y; - this.z = z; - this.w = w; + if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) { - return this; + if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) { - }, + state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data ); - setScalar: function ( scalar ) { + } else { - this.x = scalar; - this.y = scalar; - this.z = scalar; - this.w = scalar; + console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" ); - return this; + } - }, + } else { - setX: function ( x ) { + state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); - this.x = x; + } - return this; + } - }, + } else { - setY: function ( y ) { + // regular Texture (image, video, canvas) - this.y = y; + // 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 - return this; + if ( mipmaps.length > 0 && isPowerOfTwoImage ) { - }, + for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { - setZ: function ( z ) { + mipmap = mipmaps[ i ]; + state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap ); - this.z = z; + } - return this; + texture.generateMipmaps = false; - }, + } else { - setW: function ( w ) { + state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, image ); - this.w = w; + } - return this; + } - }, + if ( texture.generateMipmaps && isPowerOfTwoImage ) _gl.generateMipmap( _gl.TEXTURE_2D ); - setComponent: function ( index, value ) { + textureProperties.__version = texture.version; - switch ( index ) { + if ( texture.onUpdate ) texture.onUpdate( texture ); - 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 ); + } - } + // Render targets - }, + // Setup storage for target texture and bind it to correct framebuffer + function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) { - getComponent: function ( index ) { + 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 ); - switch ( index ) { + } - 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 ); + // Setup storage for internal depth/stencil buffers and bind to correct framebuffer + function setupRenderBufferStorage( renderbuffer, renderTarget ) { - } + _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer ); - }, + if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) { - clone: function () { + _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height ); + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); - return new this.constructor( this.x, this.y, this.z, this.w ); + } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) { - }, + _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height ); + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); - copy: function ( v ) { + } else { - this.x = v.x; - this.y = v.y; - this.z = v.z; - this.w = ( v.w !== undefined ) ? v.w : 1; + // FIXME: We don't support !depth !stencil + _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height ); - return this; + } - }, + _gl.bindRenderbuffer( _gl.RENDERBUFFER, null ); - add: function ( v, w ) { + } - if ( w !== undefined ) { + // Setup resources for a Depth Texture for a FBO (needs an extension) + function setupDepthTexture( framebuffer, renderTarget ) { - console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); - return this.addVectors( v, w ); + var isCube = ( (renderTarget && renderTarget.isWebGLRenderTargetCube) ); + if ( isCube ) throw new Error('Depth Texture with cube render targets is not supported!'); - } + _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); - this.x += v.x; - this.y += v.y; - this.z += v.z; - this.w += v.w; + if ( !( (renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture) ) ) { - return this; + throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture'); - }, + } - addScalar: function ( s ) { + // 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; + } - this.x += s; - this.y += s; - this.z += s; - this.w += s; + setTexture2D( renderTarget.depthTexture, 0 ); - return this; + var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture; - }, + if ( renderTarget.depthTexture.format === DepthFormat ) { - addVectors: function ( a, b ) { + _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 ); - this.x = a.x + b.x; - this.y = a.y + b.y; - this.z = a.z + b.z; - this.w = a.w + b.w; + } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) { - return this; + _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 ); - }, + } else { - addScaledVector: function ( v, s ) { + throw new Error('Unknown depthTexture format') - this.x += v.x * s; - this.y += v.y * s; - this.z += v.z * s; - this.w += v.w * s; + } - return this; + } - }, + // Setup GL resources for a non-texture depth buffer + function setupDepthRenderbuffer( renderTarget ) { - sub: function ( v, w ) { + var renderTargetProperties = properties.get( renderTarget ); - if ( w !== undefined ) { + var isCube = ( (renderTarget && renderTarget.isWebGLRenderTargetCube) ); - console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); - return this.subVectors( v, w ); + if ( renderTarget.depthTexture ) { - } + if ( isCube ) throw new Error('target.depthTexture not supported in Cube render targets'); - this.x -= v.x; - this.y -= v.y; - this.z -= v.z; - this.w -= v.w; + setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget ); - return this; + } else { - }, + if ( isCube ) { - subScalar: function ( s ) { + renderTargetProperties.__webglDepthbuffer = []; - this.x -= s; - this.y -= s; - this.z -= s; - this.w -= s; + for ( var i = 0; i < 6; i ++ ) { - return this; + _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] ); + renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer(); + setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget ); - }, + } - subVectors: function ( a, b ) { + } else { - this.x = a.x - b.x; - this.y = a.y - b.y; - this.z = a.z - b.z; - this.w = a.w - b.w; + _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer ); + renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer(); + setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget ); - return this; + } - }, + } - multiplyScalar: function ( scalar ) { + _gl.bindFramebuffer( _gl.FRAMEBUFFER, null ); - if ( isFinite( scalar ) ) { + } - this.x *= scalar; - this.y *= scalar; - this.z *= scalar; - this.w *= scalar; + // Set up GL resources for the render target + function setupRenderTarget( renderTarget ) { - } else { + var renderTargetProperties = properties.get( renderTarget ); + var textureProperties = properties.get( renderTarget.texture ); - this.x = 0; - this.y = 0; - this.z = 0; - this.w = 0; + renderTarget.addEventListener( 'dispose', onRenderTargetDispose ); - } + textureProperties.__webglTexture = _gl.createTexture(); - return this; + _infoMemory.textures ++; - }, + var isCube = ( (renderTarget && renderTarget.isWebGLRenderTargetCube) ); + var isTargetPowerOfTwo = isPowerOfTwo( renderTarget ); - applyMatrix4: function ( m ) { + // Setup framebuffer - var x = this.x, y = this.y, z = this.z, w = this.w; - var e = m.elements; + if ( isCube ) { - 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; + renderTargetProperties.__webglFramebuffer = []; - return this; + for ( var i = 0; i < 6; i ++ ) { - }, + renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer(); - divideScalar: function ( scalar ) { + } - return this.multiplyScalar( 1 / scalar ); + } else { - }, + renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer(); - setAxisAngleFromQuaternion: function ( q ) { + } - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm + // Setup color buffer - // q is assumed to be normalized + if ( isCube ) { - this.w = 2 * Math.acos( q.w ); + state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture ); + setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo ); - var s = Math.sqrt( 1 - q.w * q.w ); + for ( var i = 0; i < 6; i ++ ) { - if ( s < 0.0001 ) { + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i ); - this.x = 1; - this.y = 0; - this.z = 0; + } - } else { + if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP ); + state.bindTexture( _gl.TEXTURE_CUBE_MAP, null ); - this.x = q.x / s; - this.y = q.y / s; - this.z = q.z / s; + } 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 ); - return this; + if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D ); + state.bindTexture( _gl.TEXTURE_2D, null ); - }, + } - setAxisAngleFromRotationMatrix: function ( m ) { + // Setup depth and stencil buffers - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm + if ( renderTarget.depthBuffer ) { - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + setupDepthRenderbuffer( renderTarget ); - 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, + } - 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 ]; + function updateRenderTargetMipmap( renderTarget ) { - if ( ( Math.abs( m12 - m21 ) < epsilon ) && - ( Math.abs( m13 - m31 ) < epsilon ) && - ( Math.abs( m23 - m32 ) < epsilon ) ) { + var texture = renderTarget.texture; - // singularity found - // first check for identity matrix which must have +1 for all terms - // in leading diagonal and zero in other terms + if ( texture.generateMipmaps && isPowerOfTwo( renderTarget ) && + texture.minFilter !== NearestFilter && + texture.minFilter !== LinearFilter ) { - if ( ( Math.abs( m12 + m21 ) < epsilon2 ) && - ( Math.abs( m13 + m31 ) < epsilon2 ) && - ( Math.abs( m23 + m32 ) < epsilon2 ) && - ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) { + var target = (renderTarget && renderTarget.isWebGLRenderTargetCube) ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D; + var webglTexture = properties.get( texture ).__webglTexture; - // this singularity is identity matrix so angle = 0 + state.bindTexture( target, webglTexture ); + _gl.generateMipmap( target ); + state.bindTexture( target, null ); - this.set( 1, 0, 0, 0 ); + } - return this; // zero angle, arbitrary axis + } - } + this.setTexture2D = setTexture2D; + this.setTextureCube = setTextureCube; + this.setTextureCubeDynamic = setTextureCubeDynamic; + this.setupRenderTarget = setupRenderTarget; + this.updateRenderTargetMipmap = updateRenderTargetMipmap; - // otherwise this singularity is angle = 180 + }; - angle = Math.PI; + /** + * @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 + */ - 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; + function Vector4( x, y, z, w ) { - if ( ( xx > yy ) && ( xx > zz ) ) { + this.x = x || 0; + this.y = y || 0; + this.z = z || 0; + this.w = ( w !== undefined ) ? w : 1; - // m11 is the largest diagonal term + }; - if ( xx < epsilon ) { + Vector4.prototype = { - x = 0; - y = 0.707106781; - z = 0.707106781; + constructor: Vector4, - } else { + isVector4: true, - x = Math.sqrt( xx ); - y = xy / x; - z = xz / x; + set: function ( x, y, z, w ) { - } + this.x = x; + this.y = y; + this.z = z; + this.w = w; - } else if ( yy > zz ) { + return this; - // m22 is the largest diagonal term + }, - if ( yy < epsilon ) { + setScalar: function ( scalar ) { - x = 0.707106781; - y = 0; - z = 0.707106781; + this.x = scalar; + this.y = scalar; + this.z = scalar; + this.w = scalar; - } else { + return this; - y = Math.sqrt( yy ); - x = xy / y; - z = yz / y; + }, - } + setX: function ( x ) { - } else { + this.x = x; - // m33 is the largest diagonal term so base result on this + return this; - if ( zz < epsilon ) { + }, - x = 0.707106781; - y = 0.707106781; - z = 0; + setY: function ( y ) { - } else { + this.y = y; - z = Math.sqrt( zz ); - x = xz / z; - y = yz / z; + return this; - } + }, - } + setZ: function ( z ) { - this.set( x, y, z, angle ); + this.z = z; - return this; // return 180 deg rotation + return this; - } + }, - // as we have reached here there are no singularities so we can handle normally + setW: function ( w ) { - var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) + - ( m13 - m31 ) * ( m13 - m31 ) + - ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize + this.w = w; - if ( Math.abs( s ) < 0.001 ) s = 1; + return this; - // 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 + }, - this.x = ( m32 - m23 ) / s; - this.y = ( m13 - m31 ) / s; - this.z = ( m21 - m12 ) / s; - this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 ); + setComponent: function ( index, value ) { - return this; + switch ( index ) { - }, + 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 ); - 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 ); - this.w = Math.min( this.w, v.w ); + }, - return this; + getComponent: function ( index ) { - }, + switch ( index ) { - max: function ( v ) { + 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 ); - 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; + }, - }, + clone: function () { - clamp: function ( min, max ) { + return new this.constructor( this.x, this.y, this.z, this.w ); - // 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 ) ); - this.w = Math.max( min.w, Math.min( max.w, this.w ) ); + copy: function ( v ) { - return this; + this.x = v.x; + this.y = v.y; + this.z = v.z; + this.w = ( v.w !== undefined ) ? v.w : 1; - }, + return this; - clampScalar: function () { + }, - var min, max; + add: function ( v, w ) { - return function clampScalar( minVal, maxVal ) { + if ( w !== undefined ) { - if ( min === undefined ) { + console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); + return this.addVectors( v, w ); - min = new Vector4(); - max = new Vector4(); + } - } + this.x += v.x; + this.y += v.y; + this.z += v.z; + this.w += v.w; - min.set( minVal, minVal, minVal, minVal ); - max.set( maxVal, maxVal, maxVal, maxVal ); + return this; - return this.clamp( min, max ); + }, - }; + addScalar: function ( s ) { - }(), + this.x += s; + this.y += s; + this.z += s; + this.w += s; - floor: function () { + return this; - this.x = Math.floor( this.x ); - this.y = Math.floor( this.y ); - this.z = Math.floor( this.z ); - this.w = Math.floor( this.w ); + }, - return this; + addVectors: 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; - ceil: function () { + return this; - this.x = Math.ceil( this.x ); - this.y = Math.ceil( this.y ); - this.z = Math.ceil( this.z ); - this.w = Math.ceil( this.w ); + }, - return this; + addScaledVector: function ( v, s ) { - }, + this.x += v.x * s; + this.y += v.y * s; + this.z += v.z * s; + this.w += v.w * s; - round: function () { + return this; - 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; + sub: function ( v, w ) { - }, + if ( w !== undefined ) { - roundToZero: function () { + console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); + return this.subVectors( v, w ); - 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 ); + } - return this; + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; + this.w -= v.w; - }, + return this; - negate: function () { + }, - this.x = - this.x; - this.y = - this.y; - this.z = - this.z; - this.w = - this.w; + subScalar: function ( s ) { - return this; + this.x -= s; + this.y -= s; + this.z -= s; + this.w -= s; - }, + return this; - dot: function ( v ) { + }, - return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; + 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; - lengthSq: function () { + return this; - return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; + }, - }, + multiplyScalar: function ( scalar ) { - length: function () { + if ( isFinite( scalar ) ) { - return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w ); + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; + this.w *= scalar; - }, + } else { - lengthManhattan: function () { + this.x = 0; + this.y = 0; + this.z = 0; + this.w = 0; - return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w ); + } - }, + return this; - normalize: function () { + }, - return this.divideScalar( this.length() ); + applyMatrix4: function ( m ) { - }, + var x = this.x, y = this.y, z = this.z, w = this.w; + var e = m.elements; - setLength: function ( length ) { + 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.multiplyScalar( length / this.length() ); + return this; - }, + }, - lerp: function ( v, alpha ) { + divideScalar: function ( scalar ) { - 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; + return this.multiplyScalar( 1 / scalar ); - return this; + }, - }, + setAxisAngleFromQuaternion: function ( q ) { - lerpVectors: function ( v1, v2, alpha ) { + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm - return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); + // q is assumed to be normalized - }, + this.w = 2 * Math.acos( q.w ); - equals: function ( v ) { + var s = Math.sqrt( 1 - q.w * q.w ); - return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) ); + if ( s < 0.0001 ) { - }, + this.x = 1; + this.y = 0; + this.z = 0; - fromArray: function ( array, offset ) { + } else { - if ( offset === undefined ) offset = 0; + this.x = q.x / s; + this.y = q.y / s; + this.z = q.z / s; - this.x = array[ offset ]; - this.y = array[ offset + 1 ]; - this.z = array[ offset + 2 ]; - this.w = array[ offset + 3 ]; + } - return this; + return this; - }, + }, - toArray: function ( array, offset ) { + setAxisAngleFromRotationMatrix: function ( m ) { - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm - array[ offset ] = this.x; - array[ offset + 1 ] = this.y; - array[ offset + 2 ] = this.z; - array[ offset + 3 ] = this.w; + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - return array; + 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, - fromAttribute: function ( attribute, index, offset ) { + 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 ]; - if ( offset === undefined ) offset = 0; + if ( ( Math.abs( m12 - m21 ) < epsilon ) && + ( Math.abs( m13 - m31 ) < epsilon ) && + ( Math.abs( m23 - m32 ) < epsilon ) ) { - index = index * attribute.itemSize + offset; + // singularity found + // first check for identity matrix which must have +1 for all terms + // in leading diagonal and zero in other terms - this.x = attribute.array[ index ]; - this.y = attribute.array[ index + 1 ]; - this.z = attribute.array[ index + 2 ]; - this.w = attribute.array[ index + 3 ]; + if ( ( Math.abs( m12 + m21 ) < epsilon2 ) && + ( Math.abs( m13 + m31 ) < epsilon2 ) && + ( Math.abs( m23 + m32 ) < epsilon2 ) && + ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) { - return this; + // this singularity is identity matrix so angle = 0 - } + this.set( 1, 0, 0, 0 ); - }; + return this; // zero angle, arbitrary axis - /** - * @author mrdoob / http://mrdoob.com/ - */ + } - function WebGLState( gl, extensions, paramThreeToGL ) { + // otherwise this singularity is angle = 180 - var _this = this; + angle = Math.PI; - this.buffers = { - color: new WebGLColorBuffer( gl, this ), - depth: new WebGLDepthBuffer( gl, this ), - stencil: new WebGLStencilBuffer( gl, this ) - }; + 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; - var maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS ); - var newAttributes = new Uint8Array( maxVertexAttributes ); - var enabledAttributes = new Uint8Array( maxVertexAttributes ); - var attributeDivisors = new Uint8Array( maxVertexAttributes ); + if ( ( xx > yy ) && ( xx > zz ) ) { - var capabilities = {}; + // m11 is the largest diagonal term - var compressedTextureFormats = null; + if ( xx < epsilon ) { - var currentBlending = null; - var currentBlendEquation = null; - var currentBlendSrc = null; - var currentBlendDst = null; - var currentBlendEquationAlpha = null; - var currentBlendSrcAlpha = null; - var currentBlendDstAlpha = null; - var currentPremultipledAlpha = false; + x = 0; + y = 0.707106781; + z = 0.707106781; - var currentFlipSided = null; - var currentCullFace = null; + } else { - var currentLineWidth = null; + x = Math.sqrt( xx ); + y = xy / x; + z = xz / x; - var currentPolygonOffsetFactor = null; - var currentPolygonOffsetUnits = null; + } - var currentScissorTest = null; + } else if ( yy > zz ) { - var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS ); + // m22 is the largest diagonal term - var currentTextureSlot = null; - var currentBoundTextures = {}; + if ( yy < epsilon ) { - var currentScissor = new Vector4(); - var currentViewport = new Vector4(); + x = 0.707106781; + y = 0; + z = 0.707106781; - function createTexture( type, target, count ) { + } else { - var data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4. - var texture = gl.createTexture(); + y = Math.sqrt( yy ); + x = xy / y; + z = yz / y; - gl.bindTexture( type, texture ); - gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST ); - gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST ); + } - for ( var i = 0; i < count; i ++ ) { + } else { - gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data ); + // m33 is the largest diagonal term so base result on this - } + if ( zz < epsilon ) { - return texture; + x = 0.707106781; + y = 0.707106781; + z = 0; - } + } else { - 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 ); + z = Math.sqrt( zz ); + x = xz / z; + y = yz / z; - // + } - this.init = function () { + } - this.clearColor( 0, 0, 0, 1 ); - this.clearDepth( 1 ); - this.clearStencil( 0 ); + this.set( x, y, z, angle ); - this.enable( gl.DEPTH_TEST ); - this.setDepthFunc( LessEqualDepth ); + return this; // return 180 deg rotation - this.setFlipSided( false ); - this.setCullFace( CullFaceBack ); - this.enable( gl.CULL_FACE ); + } - this.enable( gl.BLEND ); - this.setBlending( NormalBlending ); + // as we have reached here there are no singularities so we can handle normally - }; + var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) + + ( m13 - m31 ) * ( m13 - m31 ) + + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize - this.initAttributes = function () { + if ( Math.abs( s ) < 0.001 ) s = 1; - for ( var i = 0, l = newAttributes.length; i < l; i ++ ) { + // 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 - newAttributes[ i ] = 0; + 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; - }; + }, - this.enableAttribute = function ( attribute ) { + min: function ( v ) { - newAttributes[ attribute ] = 1; + 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 ); - if ( enabledAttributes[ attribute ] === 0 ) { + return this; - gl.enableVertexAttribArray( attribute ); - enabledAttributes[ attribute ] = 1; + }, - } + max: function ( v ) { - if ( attributeDivisors[ attribute ] !== 0 ) { + 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 ); - var extension = extensions.get( 'ANGLE_instanced_arrays' ); + return this; - extension.vertexAttribDivisorANGLE( attribute, 0 ); - attributeDivisors[ attribute ] = 0; + }, - } + clamp: function ( min, max ) { - }; + // This function assumes min < max, if this assumption isn't true it will not operate correctly - this.enableAttributeAndDivisor = function ( attribute, meshPerAttribute, extension ) { + 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 ) ); - newAttributes[ attribute ] = 1; + return this; - if ( enabledAttributes[ attribute ] === 0 ) { + }, - gl.enableVertexAttribArray( attribute ); - enabledAttributes[ attribute ] = 1; + clampScalar: function () { - } + var min, max; - if ( attributeDivisors[ attribute ] !== meshPerAttribute ) { + return function clampScalar( minVal, maxVal ) { - extension.vertexAttribDivisorANGLE( attribute, meshPerAttribute ); - attributeDivisors[ attribute ] = meshPerAttribute; + if ( min === undefined ) { - } + min = new Vector4(); + max = new Vector4(); - }; + } - this.disableUnusedAttributes = function () { + min.set( minVal, minVal, minVal, minVal ); + max.set( maxVal, maxVal, maxVal, maxVal ); - for ( var i = 0, l = enabledAttributes.length; i !== l; ++ i ) { + return this.clamp( min, max ); - if ( enabledAttributes[ i ] !== newAttributes[ i ] ) { + }; - gl.disableVertexAttribArray( i ); - enabledAttributes[ i ] = 0; + }(), - } + floor: function () { - } + this.x = Math.floor( this.x ); + this.y = Math.floor( this.y ); + this.z = Math.floor( this.z ); + this.w = Math.floor( this.w ); - }; + return this; - this.enable = function ( id ) { + }, - if ( capabilities[ id ] !== true ) { + ceil: function () { - gl.enable( id ); - capabilities[ id ] = true; + this.x = Math.ceil( this.x ); + this.y = Math.ceil( this.y ); + this.z = Math.ceil( this.z ); + this.w = Math.ceil( this.w ); - } + return this; - }; + }, - this.disable = function ( id ) { + round: function () { - if ( capabilities[ id ] !== false ) { + this.x = Math.round( this.x ); + this.y = Math.round( this.y ); + this.z = Math.round( this.z ); + this.w = Math.round( this.w ); - gl.disable( id ); - capabilities[ id ] = false; + return this; - } + }, - }; + roundToZero: function () { - this.getCompressedTextureFormats = 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 ); - if ( compressedTextureFormats === null ) { + return this; - compressedTextureFormats = []; + }, - if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) || - extensions.get( 'WEBGL_compressed_texture_s3tc' ) || - extensions.get( 'WEBGL_compressed_texture_etc1' ) ) { + negate: function () { - var formats = gl.getParameter( gl.COMPRESSED_TEXTURE_FORMATS ); + this.x = - this.x; + this.y = - this.y; + this.z = - this.z; + this.w = - this.w; - for ( var i = 0; i < formats.length; i ++ ) { + return this; - compressedTextureFormats.push( formats[ i ] ); + }, - } + dot: function ( v ) { - } + return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; - } + }, - return compressedTextureFormats; + lengthSq: function () { - }; + return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; - this.setBlending = function ( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) { + }, - if ( blending !== NoBlending ) { + length: function () { - this.enable( gl.BLEND ); + return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w ); - } else { + }, - this.disable( gl.BLEND ); - currentBlending = blending; // no blending, that is - return; + lengthManhattan: function () { - } + return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w ); - if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) { + }, - if ( blending === AdditiveBlending ) { + normalize: function () { - if ( premultipliedAlpha ) { + return this.divideScalar( this.length() ); - gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); - gl.blendFuncSeparate( gl.ONE, gl.ONE, gl.ONE, gl.ONE ); + }, - } else { + setLength: function ( length ) { - gl.blendEquation( gl.FUNC_ADD ); - gl.blendFunc( gl.SRC_ALPHA, gl.ONE ); + return this.multiplyScalar( length / this.length() ); - } + }, - } else if ( blending === SubtractiveBlending ) { + lerp: function ( v, alpha ) { - if ( premultipliedAlpha ) { + 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; - gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); - gl.blendFuncSeparate( gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA ); + return this; - } else { + }, - gl.blendEquation( gl.FUNC_ADD ); - gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR ); + lerpVectors: function ( v1, v2, alpha ) { - } + return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); - } else if ( blending === MultiplyBlending ) { + }, - if ( premultipliedAlpha ) { + equals: function ( v ) { - gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); - gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA ); + return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) ); - } else { + }, - gl.blendEquation( gl.FUNC_ADD ); - gl.blendFunc( gl.ZERO, gl.SRC_COLOR ); + fromArray: function ( array, offset ) { - } + 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 ]; - if ( premultipliedAlpha ) { + return this; - gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); - gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA ); + }, - } else { + toArray: function ( array, offset ) { - 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 ); + 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.w; - } + return array; - currentBlending = blending; - currentPremultipledAlpha = premultipliedAlpha; + }, - } + fromAttribute: function ( attribute, index, offset ) { - if ( blending === CustomBlending ) { + if ( offset === undefined ) offset = 0; - blendEquationAlpha = blendEquationAlpha || blendEquation; - blendSrcAlpha = blendSrcAlpha || blendSrc; - blendDstAlpha = blendDstAlpha || blendDst; + index = index * attribute.itemSize + offset; - if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) { + this.x = attribute.array[ index ]; + this.y = attribute.array[ index + 1 ]; + this.z = attribute.array[ index + 2 ]; + this.w = attribute.array[ index + 3 ]; - gl.blendEquationSeparate( paramThreeToGL( blendEquation ), paramThreeToGL( blendEquationAlpha ) ); + return this; - currentBlendEquation = blendEquation; - currentBlendEquationAlpha = blendEquationAlpha; + } - } + }; - if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) { + /** + * @author mrdoob / http://mrdoob.com/ + */ - gl.blendFuncSeparate( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ), paramThreeToGL( blendSrcAlpha ), paramThreeToGL( blendDstAlpha ) ); + function WebGLState( gl, extensions, paramThreeToGL ) { - currentBlendSrc = blendSrc; - currentBlendDst = blendDst; - currentBlendSrcAlpha = blendSrcAlpha; - currentBlendDstAlpha = blendDstAlpha; + var _this = this; - } + this.buffers = { + color: new WebGLColorBuffer( gl, this ), + depth: new WebGLDepthBuffer( gl, this ), + stencil: new WebGLStencilBuffer( gl, this ) + }; - } else { + var maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS ); + var newAttributes = new Uint8Array( maxVertexAttributes ); + var enabledAttributes = new Uint8Array( maxVertexAttributes ); + var attributeDivisors = new Uint8Array( maxVertexAttributes ); - currentBlendEquation = null; - currentBlendSrc = null; - currentBlendDst = null; - currentBlendEquationAlpha = null; - currentBlendSrcAlpha = null; - currentBlendDstAlpha = null; + var capabilities = {}; - } + 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; - // TODO Deprecate + var currentFlipSided = null; + var currentCullFace = null; - this.setColorWrite = function ( colorWrite ) { + var currentLineWidth = null; - this.buffers.color.setMask( colorWrite ); + var currentPolygonOffsetFactor = null; + var currentPolygonOffsetUnits = null; - }; + var currentScissorTest = null; - this.setDepthTest = function ( depthTest ) { + var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS ); - this.buffers.depth.setTest( depthTest ); + var currentTextureSlot = null; + var currentBoundTextures = {}; - }; + var currentScissor = new Vector4(); + var currentViewport = new Vector4(); - this.setDepthWrite = function ( depthWrite ) { + function createTexture( type, target, count ) { - this.buffers.depth.setMask( depthWrite ); + 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 ); - this.setDepthFunc = function ( depthFunc ) { + for ( var i = 0; i < count; i ++ ) { - this.buffers.depth.setFunc( depthFunc ); + gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data ); - }; + } - this.setStencilTest = function ( stencilTest ) { + return texture; - this.buffers.stencil.setTest( stencilTest ); + } - }; + 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 ); - this.setStencilWrite = function ( stencilWrite ) { + // - this.buffers.stencil.setMask( stencilWrite ); + this.init = function () { - }; + this.clearColor( 0, 0, 0, 1 ); + this.clearDepth( 1 ); + this.clearStencil( 0 ); - this.setStencilFunc = function ( stencilFunc, stencilRef, stencilMask ) { + this.enable( gl.DEPTH_TEST ); + this.setDepthFunc( LessEqualDepth ); - this.buffers.stencil.setFunc( stencilFunc, stencilRef, stencilMask ); + this.setFlipSided( false ); + this.setCullFace( CullFaceBack ); + this.enable( gl.CULL_FACE ); - }; + this.enable( gl.BLEND ); + this.setBlending( NormalBlending ); - this.setStencilOp = function ( stencilFail, stencilZFail, stencilZPass ) { + }; - this.buffers.stencil.setOp( stencilFail, stencilZFail, stencilZPass ); + this.initAttributes = function () { - }; + for ( var i = 0, l = newAttributes.length; i < l; i ++ ) { - // + newAttributes[ i ] = 0; - this.setFlipSided = function ( flipSided ) { + } - if ( currentFlipSided !== flipSided ) { + }; - if ( flipSided ) { + this.enableAttribute = function ( attribute ) { - gl.frontFace( gl.CW ); + newAttributes[ attribute ] = 1; - } else { + if ( enabledAttributes[ attribute ] === 0 ) { - gl.frontFace( gl.CCW ); + gl.enableVertexAttribArray( attribute ); + enabledAttributes[ attribute ] = 1; - } + } - currentFlipSided = flipSided; + if ( attributeDivisors[ attribute ] !== 0 ) { - } + var extension = extensions.get( 'ANGLE_instanced_arrays' ); - }; + extension.vertexAttribDivisorANGLE( attribute, 0 ); + attributeDivisors[ attribute ] = 0; - this.setCullFace = function ( cullFace ) { + } - if ( cullFace !== CullFaceNone ) { + }; - this.enable( gl.CULL_FACE ); + this.enableAttributeAndDivisor = function ( attribute, meshPerAttribute, extension ) { - if ( cullFace !== currentCullFace ) { + newAttributes[ attribute ] = 1; - if ( cullFace === CullFaceBack ) { + if ( enabledAttributes[ attribute ] === 0 ) { - gl.cullFace( gl.BACK ); + gl.enableVertexAttribArray( attribute ); + enabledAttributes[ attribute ] = 1; - } else if ( cullFace === CullFaceFront ) { + } - gl.cullFace( gl.FRONT ); + if ( attributeDivisors[ attribute ] !== meshPerAttribute ) { - } else { + extension.vertexAttribDivisorANGLE( attribute, meshPerAttribute ); + attributeDivisors[ attribute ] = meshPerAttribute; - gl.cullFace( gl.FRONT_AND_BACK ); + } - } + }; - } + this.disableUnusedAttributes = function () { - } else { + for ( var i = 0, l = enabledAttributes.length; i !== l; ++ i ) { - this.disable( gl.CULL_FACE ); + if ( enabledAttributes[ i ] !== newAttributes[ i ] ) { - } + gl.disableVertexAttribArray( i ); + enabledAttributes[ i ] = 0; - currentCullFace = cullFace; + } - }; + } - this.setLineWidth = function ( width ) { + }; - if ( width !== currentLineWidth ) { + this.enable = function ( id ) { - gl.lineWidth( width ); + if ( capabilities[ id ] !== true ) { - currentLineWidth = width; + gl.enable( id ); + capabilities[ id ] = true; - } + } - }; + }; - this.setPolygonOffset = function ( polygonOffset, factor, units ) { + this.disable = function ( id ) { - if ( polygonOffset ) { + if ( capabilities[ id ] !== false ) { - this.enable( gl.POLYGON_OFFSET_FILL ); + gl.disable( id ); + capabilities[ id ] = false; - if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) { + } - gl.polygonOffset( factor, units ); + }; - currentPolygonOffsetFactor = factor; - currentPolygonOffsetUnits = units; + this.getCompressedTextureFormats = function () { - } + if ( compressedTextureFormats === null ) { - } else { + compressedTextureFormats = []; - this.disable( gl.POLYGON_OFFSET_FILL ); + if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) || + extensions.get( 'WEBGL_compressed_texture_s3tc' ) || + extensions.get( 'WEBGL_compressed_texture_etc1' ) ) { - } + var formats = gl.getParameter( gl.COMPRESSED_TEXTURE_FORMATS ); - }; + for ( var i = 0; i < formats.length; i ++ ) { - this.getScissorTest = function () { + compressedTextureFormats.push( formats[ i ] ); - return currentScissorTest; + } - }; + } - this.setScissorTest = function ( scissorTest ) { + } - currentScissorTest = scissorTest; + return compressedTextureFormats; - if ( scissorTest ) { + }; - this.enable( gl.SCISSOR_TEST ); + this.setBlending = function ( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) { - } else { + if ( blending !== NoBlending ) { - this.disable( gl.SCISSOR_TEST ); + this.enable( gl.BLEND ); - } + } else { - }; + this.disable( gl.BLEND ); + currentBlending = blending; // no blending, that is + return; - // texture + } - this.activeTexture = function ( webglSlot ) { + if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) { - if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1; + if ( blending === AdditiveBlending ) { - if ( currentTextureSlot !== webglSlot ) { + if ( premultipliedAlpha ) { - gl.activeTexture( webglSlot ); - currentTextureSlot = webglSlot; + gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); + gl.blendFuncSeparate( gl.ONE, gl.ONE, gl.ONE, gl.ONE ); - } + } else { - }; + gl.blendEquation( gl.FUNC_ADD ); + gl.blendFunc( gl.SRC_ALPHA, gl.ONE ); - this.bindTexture = function ( webglType, webglTexture ) { + } - if ( currentTextureSlot === null ) { + } else if ( blending === SubtractiveBlending ) { - _this.activeTexture(); + if ( premultipliedAlpha ) { - } + gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); + gl.blendFuncSeparate( gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA ); - var boundTexture = currentBoundTextures[ currentTextureSlot ]; + } else { - if ( boundTexture === undefined ) { + gl.blendEquation( gl.FUNC_ADD ); + gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR ); - boundTexture = { type: undefined, texture: undefined }; - currentBoundTextures[ currentTextureSlot ] = boundTexture; + } - } + } else if ( blending === MultiplyBlending ) { - if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) { + if ( premultipliedAlpha ) { - gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] ); + gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); + gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA ); - boundTexture.type = webglType; - boundTexture.texture = webglTexture; + } else { - } + gl.blendEquation( gl.FUNC_ADD ); + gl.blendFunc( gl.ZERO, gl.SRC_COLOR ); - }; + } - this.compressedTexImage2D = function () { + } else { - try { + if ( premultipliedAlpha ) { - gl.compressedTexImage2D.apply( gl, arguments ); + gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); + gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA ); - } catch ( error ) { + } else { - console.error( error ); + 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.texImage2D = function () { + currentBlending = blending; + currentPremultipledAlpha = premultipliedAlpha; - try { + } - gl.texImage2D.apply( gl, arguments ); + if ( blending === CustomBlending ) { - } catch ( error ) { + blendEquationAlpha = blendEquationAlpha || blendEquation; + blendSrcAlpha = blendSrcAlpha || blendSrc; + blendDstAlpha = blendDstAlpha || blendDst; - console.error( error ); + if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) { - } + gl.blendEquationSeparate( paramThreeToGL( blendEquation ), paramThreeToGL( blendEquationAlpha ) ); - }; + currentBlendEquation = blendEquation; + currentBlendEquationAlpha = blendEquationAlpha; - // TODO Deprecate + } - this.clearColor = function ( r, g, b, a ) { + if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) { - this.buffers.color.setClear( r, g, b, a ); + gl.blendFuncSeparate( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ), paramThreeToGL( blendSrcAlpha ), paramThreeToGL( blendDstAlpha ) ); - }; + currentBlendSrc = blendSrc; + currentBlendDst = blendDst; + currentBlendSrcAlpha = blendSrcAlpha; + currentBlendDstAlpha = blendDstAlpha; - this.clearDepth = function ( depth ) { + } - this.buffers.depth.setClear( depth ); + } else { - }; + currentBlendEquation = null; + currentBlendSrc = null; + currentBlendDst = null; + currentBlendEquationAlpha = null; + currentBlendSrcAlpha = null; + currentBlendDstAlpha = null; - this.clearStencil = function ( stencil ) { + } - this.buffers.stencil.setClear( stencil ); + }; - }; + // TODO Deprecate - // + this.setColorWrite = function ( colorWrite ) { - this.scissor = function ( scissor ) { + this.buffers.color.setMask( colorWrite ); - if ( currentScissor.equals( scissor ) === false ) { + }; - gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w ); - currentScissor.copy( scissor ); + this.setDepthTest = function ( depthTest ) { - } + this.buffers.depth.setTest( depthTest ); - }; + }; - this.viewport = function ( viewport ) { + this.setDepthWrite = function ( depthWrite ) { - if ( currentViewport.equals( viewport ) === false ) { + this.buffers.depth.setMask( depthWrite ); - gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w ); - currentViewport.copy( viewport ); + }; - } + this.setDepthFunc = function ( depthFunc ) { - }; + this.buffers.depth.setFunc( depthFunc ); - // + }; - this.reset = function () { + this.setStencilTest = function ( stencilTest ) { - for ( var i = 0; i < enabledAttributes.length; i ++ ) { + this.buffers.stencil.setTest( stencilTest ); - if ( enabledAttributes[ i ] === 1 ) { + }; - gl.disableVertexAttribArray( i ); - enabledAttributes[ i ] = 0; + this.setStencilWrite = function ( stencilWrite ) { - } + this.buffers.stencil.setMask( stencilWrite ); - } + }; - capabilities = {}; + this.setStencilFunc = function ( stencilFunc, stencilRef, stencilMask ) { - compressedTextureFormats = null; + this.buffers.stencil.setFunc( stencilFunc, stencilRef, stencilMask ); - currentTextureSlot = null; - currentBoundTextures = {}; + }; - currentBlending = null; + this.setStencilOp = function ( stencilFail, stencilZFail, stencilZPass ) { - currentFlipSided = null; - currentCullFace = null; + this.buffers.stencil.setOp( stencilFail, stencilZFail, stencilZPass ); - this.buffers.color.reset(); - this.buffers.depth.reset(); - this.buffers.stencil.reset(); + }; - }; + // - }; + this.setFlipSided = function ( flipSided ) { - function WebGLColorBuffer( gl, state ) { + if ( currentFlipSided !== flipSided ) { - var locked = false; + if ( flipSided ) { - var color = new Vector4(); - var currentColorMask = null; - var currentColorClear = new Vector4(); + gl.frontFace( gl.CW ); - this.setMask = function ( colorMask ) { + } else { - if ( currentColorMask !== colorMask && ! locked ) { + gl.frontFace( gl.CCW ); - gl.colorMask( colorMask, colorMask, colorMask, colorMask ); - currentColorMask = colorMask; + } - } + currentFlipSided = flipSided; - }; + } - this.setLocked = function ( lock ) { + }; - locked = lock; + this.setCullFace = function ( cullFace ) { - }; + if ( cullFace !== CullFaceNone ) { - this.setClear = function ( r, g, b, a ) { + this.enable( gl.CULL_FACE ); - color.set( r, g, b, a ); + if ( cullFace !== currentCullFace ) { - if ( currentColorClear.equals( color ) === false ) { + if ( cullFace === CullFaceBack ) { - gl.clearColor( r, g, b, a ); - currentColorClear.copy( color ); + gl.cullFace( gl.BACK ); - } + } else if ( cullFace === CullFaceFront ) { - }; + gl.cullFace( gl.FRONT ); - this.reset = function () { + } else { - locked = false; + gl.cullFace( gl.FRONT_AND_BACK ); - currentColorMask = null; - currentColorClear = new Vector4(); + } - }; + } - }; + } else { - function WebGLDepthBuffer( gl, state ) { + this.disable( gl.CULL_FACE ); - var locked = false; + } - var currentDepthMask = null; - var currentDepthFunc = null; - var currentDepthClear = null; + currentCullFace = cullFace; - this.setTest = function ( depthTest ) { + }; - if ( depthTest ) { + this.setLineWidth = function ( width ) { - state.enable( gl.DEPTH_TEST ); + if ( width !== currentLineWidth ) { - } else { + gl.lineWidth( width ); - state.disable( gl.DEPTH_TEST ); + currentLineWidth = width; - } + } - }; + }; - this.setMask = function( depthMask ){ + this.setPolygonOffset = function ( polygonOffset, factor, units ) { - if ( currentDepthMask !== depthMask && ! locked ) { + if ( polygonOffset ) { - gl.depthMask( depthMask ); - currentDepthMask = depthMask; + this.enable( gl.POLYGON_OFFSET_FILL ); - } + if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) { - }; + gl.polygonOffset( factor, units ); - this.setFunc = function ( depthFunc ) { + currentPolygonOffsetFactor = factor; + currentPolygonOffsetUnits = units; - if ( currentDepthFunc !== depthFunc ) { + } - if ( depthFunc ) { + } else { - switch ( depthFunc ) { + this.disable( gl.POLYGON_OFFSET_FILL ); - case NeverDepth: + } - gl.depthFunc( gl.NEVER ); - break; + }; - case AlwaysDepth: + this.getScissorTest = function () { - gl.depthFunc( gl.ALWAYS ); - break; + return currentScissorTest; - case LessDepth: + }; - gl.depthFunc( gl.LESS ); - break; + this.setScissorTest = function ( scissorTest ) { - case LessEqualDepth: + currentScissorTest = scissorTest; - gl.depthFunc( gl.LEQUAL ); - break; + if ( scissorTest ) { - case EqualDepth: + this.enable( gl.SCISSOR_TEST ); - gl.depthFunc( gl.EQUAL ); - break; + } else { - case GreaterEqualDepth: + this.disable( gl.SCISSOR_TEST ); - gl.depthFunc( gl.GEQUAL ); - break; + } - case GreaterDepth: + }; - gl.depthFunc( gl.GREATER ); - break; + // texture - case NotEqualDepth: + this.activeTexture = function ( webglSlot ) { - gl.depthFunc( gl.NOTEQUAL ); - break; + if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1; - default: + if ( currentTextureSlot !== webglSlot ) { - gl.depthFunc( gl.LEQUAL ); + gl.activeTexture( webglSlot ); + currentTextureSlot = webglSlot; - } + } - } else { + }; - gl.depthFunc( gl.LEQUAL ); + this.bindTexture = function ( webglType, webglTexture ) { - } + if ( currentTextureSlot === null ) { - currentDepthFunc = depthFunc; + _this.activeTexture(); - } + } - }; + var boundTexture = currentBoundTextures[ currentTextureSlot ]; - this.setLocked = function ( lock ) { + if ( boundTexture === undefined ) { - locked = lock; + boundTexture = { type: undefined, texture: undefined }; + currentBoundTextures[ currentTextureSlot ] = boundTexture; - }; + } - this.setClear = function ( depth ) { + if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) { - if ( currentDepthClear !== depth ) { + gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] ); - gl.clearDepth( depth ); - currentDepthClear = depth; + boundTexture.type = webglType; + boundTexture.texture = webglTexture; - } + } - }; + }; - this.reset = function () { + this.compressedTexImage2D = function () { - locked = false; + try { - currentDepthMask = null; - currentDepthFunc = null; - currentDepthClear = null; + gl.compressedTexImage2D.apply( gl, arguments ); - }; + } catch ( error ) { - }; + console.error( error ); - function WebGLStencilBuffer( gl, state ) { + } - 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.texImage2D = function () { - this.setTest = function ( stencilTest ) { + try { - if ( stencilTest ) { + gl.texImage2D.apply( gl, arguments ); - state.enable( gl.STENCIL_TEST ); + } catch ( error ) { - } else { + console.error( error ); - state.disable( gl.STENCIL_TEST ); + } - } + }; - }; + // TODO Deprecate - this.setMask = function ( stencilMask ) { + this.clearColor = function ( r, g, b, a ) { - if ( currentStencilMask !== stencilMask && ! locked ) { + this.buffers.color.setClear( r, g, b, a ); - gl.stencilMask( stencilMask ); - currentStencilMask = stencilMask; + }; - } + this.clearDepth = function ( depth ) { - }; + this.buffers.depth.setClear( depth ); - this.setFunc = function ( stencilFunc, stencilRef, stencilMask ) { + }; - if ( currentStencilFunc !== stencilFunc || - currentStencilRef !== stencilRef || - currentStencilFuncMask !== stencilMask ) { + this.clearStencil = function ( stencil ) { - gl.stencilFunc( stencilFunc, stencilRef, stencilMask ); + this.buffers.stencil.setClear( stencil ); - currentStencilFunc = stencilFunc; - currentStencilRef = stencilRef; - currentStencilFuncMask = stencilMask; + }; - } + // - }; + this.scissor = function ( scissor ) { - this.setOp = function ( stencilFail, stencilZFail, stencilZPass ) { + if ( currentScissor.equals( scissor ) === false ) { - if ( currentStencilFail !== stencilFail || - currentStencilZFail !== stencilZFail || - currentStencilZPass !== stencilZPass ) { + gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w ); + currentScissor.copy( scissor ); - gl.stencilOp( stencilFail, stencilZFail, stencilZPass ); + } - currentStencilFail = stencilFail; - currentStencilZFail = stencilZFail; - currentStencilZPass = stencilZPass; + }; - } + this.viewport = function ( viewport ) { - }; + if ( currentViewport.equals( viewport ) === false ) { - this.setLocked = function ( lock ) { + gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w ); + currentViewport.copy( viewport ); - locked = lock; + } - }; + }; - this.setClear = function ( stencil ) { + // - if ( currentStencilClear !== stencil ) { + this.reset = function () { - gl.clearStencil( stencil ); - currentStencilClear = stencil; + for ( var i = 0; i < enabledAttributes.length; i ++ ) { - } + if ( enabledAttributes[ i ] === 1 ) { - }; + gl.disableVertexAttribArray( i ); + enabledAttributes[ i ] = 0; - this.reset = function () { + } - locked = false; + } - currentStencilMask = null; - currentStencilFunc = null; - currentStencilRef = null; - currentStencilFuncMask = null; - currentStencilFail = null; - currentStencilZFail = null; - currentStencilZPass = null; - currentStencilClear = null; + capabilities = {}; - }; + compressedTextureFormats = null; - }; + currentTextureSlot = null; + currentBoundTextures = {}; - /** - * @author szimek / https://github.com/szimek/ - * @author alteredq / http://alteredqualia.com/ - * @author Marius Kintel / https://github.com/kintel - */ + currentBlending = null; - /* - 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 ) { + currentFlipSided = null; + currentCullFace = null; - this.uuid = exports.Math.generateUUID(); + this.buffers.color.reset(); + this.buffers.depth.reset(); + this.buffers.stencil.reset(); - this.width = width; - this.height = height; + }; - this.scissor = new Vector4( 0, 0, width, height ); - this.scissorTest = false; + }; - this.viewport = new Vector4( 0, 0, width, height ); + function WebGLColorBuffer( gl, state ) { - options = options || {}; + var locked = false; - if ( options.minFilter === undefined ) options.minFilter = LinearFilter; + var color = new Vector4(); + var currentColorMask = null; + var currentColorClear = new Vector4(); - this.texture = new Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding ); + this.setMask = function ( colorMask ) { - 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 ( currentColorMask !== colorMask && ! locked ) { - }; + gl.colorMask( colorMask, colorMask, colorMask, colorMask ); + currentColorMask = colorMask; - Object.assign( WebGLRenderTarget.prototype, EventDispatcher.prototype, { + } - isWebGLRenderTarget: true, + }; - setSize: function ( width, height ) { + this.setLocked = function ( lock ) { - if ( this.width !== width || this.height !== height ) { + locked = lock; - this.width = width; - this.height = height; + }; - this.dispose(); + this.setClear = function ( r, g, b, a ) { - } + color.set( r, g, b, a ); - this.viewport.set( 0, 0, width, height ); - this.scissor.set( 0, 0, width, height ); + if ( currentColorClear.equals( color ) === false ) { - }, + gl.clearColor( r, g, b, a ); + currentColorClear.copy( color ); - clone: function () { + } - return new this.constructor().copy( this ); + }; - }, + this.reset = function () { - copy: function ( source ) { + locked = false; - this.width = source.width; - this.height = source.height; + currentColorMask = null; + currentColorClear = new Vector4(); - this.viewport.copy( source.viewport ); + }; - this.texture = source.texture.clone(); + }; - this.depthBuffer = source.depthBuffer; - this.stencilBuffer = source.stencilBuffer; - this.depthTexture = source.depthTexture; + function WebGLDepthBuffer( gl, state ) { - return this; + var locked = false; - }, + var currentDepthMask = null; + var currentDepthFunc = null; + var currentDepthClear = null; - dispose: function () { + this.setTest = function ( depthTest ) { - this.dispatchEvent( { type: 'dispose' } ); + if ( depthTest ) { - } + state.enable( gl.DEPTH_TEST ); - } ); + } else { - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + state.disable( gl.DEPTH_TEST ); - function Material() { + } - Object.defineProperty( this, 'id', { value: MaterialIdCount() } ); + }; - this.uuid = exports.Math.generateUUID(); + this.setMask = function( depthMask ){ - this.name = ''; - this.type = 'Material'; + if ( currentDepthMask !== depthMask && ! locked ) { - this.fog = true; - this.lights = true; + gl.depthMask( depthMask ); + currentDepthMask = depthMask; - 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; + this.setFunc = function ( depthFunc ) { - this.depthFunc = LessEqualDepth; - this.depthTest = true; - this.depthWrite = true; + if ( currentDepthFunc !== depthFunc ) { - this.clippingPlanes = null; - this.clipShadows = false; + if ( depthFunc ) { - this.colorWrite = true; + switch ( depthFunc ) { - this.precision = null; // override the renderer's default precision for this material + case NeverDepth: - this.polygonOffset = false; - this.polygonOffsetFactor = 0; - this.polygonOffsetUnits = 0; + gl.depthFunc( gl.NEVER ); + break; - this.alphaTest = 0; - this.premultipliedAlpha = false; + case AlwaysDepth: - this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer + gl.depthFunc( gl.ALWAYS ); + break; - this.visible = true; + case LessDepth: - this._needsUpdate = true; + gl.depthFunc( gl.LESS ); + break; - }; + case LessEqualDepth: - Material.prototype = { + gl.depthFunc( gl.LEQUAL ); + break; - constructor: Material, + case EqualDepth: - isMaterial: true, + gl.depthFunc( gl.EQUAL ); + break; - get needsUpdate() { + case GreaterEqualDepth: - return this._needsUpdate; + gl.depthFunc( gl.GEQUAL ); + break; - }, + case GreaterDepth: - set needsUpdate( value ) { + gl.depthFunc( gl.GREATER ); + break; - if ( value === true ) this.update(); - this._needsUpdate = value; + case NotEqualDepth: - }, + gl.depthFunc( gl.NOTEQUAL ); + break; - setValues: function ( values ) { + default: - if ( values === undefined ) return; + gl.depthFunc( gl.LEQUAL ); - for ( var key in values ) { + } - var newValue = values[ key ]; + } else { - if ( newValue === undefined ) { + gl.depthFunc( gl.LEQUAL ); - console.warn( "THREE.Material: '" + key + "' parameter is undefined." ); - continue; + } - } + currentDepthFunc = depthFunc; - var currentValue = this[ key ]; + } - if ( currentValue === undefined ) { + }; - console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." ); - continue; + this.setLocked = function ( lock ) { - } + locked = lock; - if ( (currentValue && currentValue.isColor) ) { + }; - currentValue.set( newValue ); + this.setClear = function ( depth ) { - } else if ( (currentValue && currentValue.isVector3) && (newValue && newValue.isVector3) ) { + if ( currentDepthClear !== depth ) { - currentValue.copy( newValue ); + gl.clearDepth( depth ); + currentDepthClear = depth; - } else if ( key === 'overdraw' ) { + } - // ensure overdraw is backwards-compatible with legacy boolean type - this[ key ] = Number( newValue ); + }; - } else { + this.reset = function () { - this[ key ] = newValue; + locked = false; - } + currentDepthMask = null; + currentDepthFunc = null; + currentDepthClear = null; - } + }; - }, + }; - toJSON: function ( meta ) { + function WebGLStencilBuffer( gl, state ) { - var isRoot = meta === undefined; + var locked = false; - if ( isRoot ) { + var currentStencilMask = null; + var currentStencilFunc = null; + var currentStencilRef = null; + var currentStencilFuncMask = null; + var currentStencilFail = null; + var currentStencilZFail = null; + var currentStencilZPass = null; + var currentStencilClear = null; - meta = { - textures: {}, - images: {} - }; + this.setTest = function ( stencilTest ) { - } + if ( stencilTest ) { - var data = { - metadata: { - version: 4.4, - type: 'Material', - generator: 'Material.toJSON' - } - }; + state.enable( gl.STENCIL_TEST ); - // standard Material serialization - data.uuid = this.uuid; - data.type = this.type; + } else { - if ( this.name !== '' ) data.name = this.name; + state.disable( gl.STENCIL_TEST ); - 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; + }; - 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; + this.setMask = function ( stencilMask ) { - 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) ) { + if ( currentStencilMask !== stencilMask && ! locked ) { - data.bumpMap = this.bumpMap.toJSON( meta ).uuid; - data.bumpScale = this.bumpScale; + gl.stencilMask( stencilMask ); + currentStencilMask = stencilMask; - } - if ( (this.normalMap && this.normalMap.isTexture) ) { + } - data.normalMap = this.normalMap.toJSON( meta ).uuid; - data.normalScale = this.normalScale.toArray(); + }; - } - if ( (this.displacementMap && this.displacementMap.isTexture) ) { + this.setFunc = function ( stencilFunc, stencilRef, stencilMask ) { - data.displacementMap = this.displacementMap.toJSON( meta ).uuid; - data.displacementScale = this.displacementScale; - data.displacementBias = this.displacementBias; + if ( currentStencilFunc !== stencilFunc || + currentStencilRef !== stencilRef || + currentStencilFuncMask !== stencilMask ) { - } - 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; + gl.stencilFunc( stencilFunc, stencilRef, stencilMask ); - 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; + currentStencilFunc = stencilFunc; + currentStencilRef = stencilRef; + currentStencilFuncMask = stencilMask; - if ( (this.envMap && this.envMap.isTexture) ) { + } - data.envMap = this.envMap.toJSON( meta ).uuid; - data.reflectivity = this.reflectivity; // Scale behind envMap + }; - } + this.setOp = function ( stencilFail, stencilZFail, stencilZPass ) { - if ( this.size !== undefined ) data.size = this.size; - if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation; + if ( currentStencilFail !== stencilFail || + currentStencilZFail !== stencilZFail || + currentStencilZPass !== stencilZPass ) { - 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; + gl.stencilOp( stencilFail, stencilZFail, stencilZPass ); - 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; + currentStencilFail = stencilFail; + currentStencilZFail = stencilZFail; + currentStencilZPass = stencilZPass; - // TODO: Copied from Object3D.toJSON + } - function extractFromCache( cache ) { + }; - var values = []; + this.setLocked = function ( lock ) { - for ( var key in cache ) { + locked = lock; - var data = cache[ key ]; - delete data.metadata; - values.push( data ); + }; - } + this.setClear = function ( stencil ) { - return values; + if ( currentStencilClear !== stencil ) { - } + gl.clearStencil( stencil ); + currentStencilClear = stencil; - if ( isRoot ) { + } - var textures = extractFromCache( meta.textures ); - var images = extractFromCache( meta.images ); + }; - if ( textures.length > 0 ) data.textures = textures; - if ( images.length > 0 ) data.images = images; + this.reset = function () { - } + locked = false; - return data; + currentStencilMask = null; + currentStencilFunc = null; + currentStencilRef = null; + currentStencilFuncMask = null; + currentStencilFail = null; + currentStencilZFail = null; + currentStencilZPass = null; + currentStencilClear = null; - }, + }; - clone: function () { + }; - return new this.constructor().copy( this ); + /** + * @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 ) { - copy: function ( source ) { + this.uuid = exports.Math.generateUUID(); - this.name = source.name; + this.width = width; + this.height = height; - this.fog = source.fog; - this.lights = source.lights; + this.scissor = new Vector4( 0, 0, width, height ); + this.scissorTest = false; - this.blending = source.blending; - this.side = source.side; - this.shading = source.shading; - this.vertexColors = source.vertexColors; + this.viewport = new Vector4( 0, 0, width, height ); - this.opacity = source.opacity; - this.transparent = source.transparent; + options = options || {}; - this.blendSrc = source.blendSrc; - this.blendDst = source.blendDst; - this.blendEquation = source.blendEquation; - this.blendSrcAlpha = source.blendSrcAlpha; - this.blendDstAlpha = source.blendDstAlpha; - this.blendEquationAlpha = source.blendEquationAlpha; + if ( options.minFilter === undefined ) options.minFilter = LinearFilter; - this.depthFunc = source.depthFunc; - this.depthTest = source.depthTest; - this.depthWrite = source.depthWrite; + this.texture = new Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding ); - this.colorWrite = source.colorWrite; + this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true; + this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true; + this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null; - this.precision = source.precision; + }; - this.polygonOffset = source.polygonOffset; - this.polygonOffsetFactor = source.polygonOffsetFactor; - this.polygonOffsetUnits = source.polygonOffsetUnits; + Object.assign( WebGLRenderTarget.prototype, EventDispatcher.prototype, { - this.alphaTest = source.alphaTest; + isWebGLRenderTarget: true, - this.premultipliedAlpha = source.premultipliedAlpha; + setSize: function ( width, height ) { - this.overdraw = source.overdraw; + if ( this.width !== width || this.height !== height ) { - this.visible = source.visible; - this.clipShadows = source.clipShadows; + this.width = width; + this.height = height; - var srcPlanes = source.clippingPlanes, - dstPlanes = null; + this.dispose(); - if ( srcPlanes !== null ) { + } - var n = srcPlanes.length; - dstPlanes = new Array( n ); + this.viewport.set( 0, 0, width, height ); + this.scissor.set( 0, 0, width, height ); - for ( var i = 0; i !== n; ++ i ) - dstPlanes[ i ] = srcPlanes[ i ].clone(); + }, - } + clone: function () { - this.clippingPlanes = dstPlanes; + return new this.constructor().copy( this ); - return this; + }, - }, + copy: function ( source ) { - update: function () { + this.width = source.width; + this.height = source.height; - this.dispatchEvent( { type: 'update' } ); + this.viewport.copy( source.viewport ); - }, + this.texture = source.texture.clone(); - dispose: function () { + this.depthBuffer = source.depthBuffer; + this.stencilBuffer = source.stencilBuffer; + this.depthTexture = source.depthTexture; - this.dispatchEvent( { type: 'dispose' } ); + return this; - } + }, - }; + dispose: function () { - Object.assign( Material.prototype, EventDispatcher.prototype ); + this.dispatchEvent( { type: 'dispose' } ); - var count$1 = 0; - function MaterialIdCount() { return count$1++; }; + } - /** - * Uniform Utilities - */ + } ); - exports.UniformsUtils = { + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - merge: function ( uniforms ) { + function Material() { - var merged = {}; + Object.defineProperty( this, 'id', { value: MaterialIdCount() } ); - for ( var u = 0; u < uniforms.length; u ++ ) { + this.uuid = exports.Math.generateUUID(); - var tmp = this.clone( uniforms[ u ] ); + this.name = ''; + this.type = 'Material'; - for ( var p in tmp ) { + this.fog = true; + this.lights = true; - merged[ p ] = tmp[ p ]; + 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; - return merged; + this.depthFunc = LessEqualDepth; + this.depthTest = true; + this.depthWrite = true; - }, + this.clippingPlanes = null; + this.clipShadows = false; - clone: function ( uniforms_src ) { + this.colorWrite = true; - var uniforms_dst = {}; + this.precision = null; // override the renderer's default precision for this material - for ( var u in uniforms_src ) { + this.polygonOffset = false; + this.polygonOffsetFactor = 0; + this.polygonOffsetUnits = 0; - uniforms_dst[ u ] = {}; + this.alphaTest = 0; + this.premultipliedAlpha = false; - for ( var p in uniforms_src[ u ] ) { + this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer - var parameter_src = uniforms_src[ u ][ p ]; + this.visible = true; - 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) ) { + this._needsUpdate = true; - uniforms_dst[ u ][ p ] = parameter_src.clone(); + }; - } else if ( Array.isArray( parameter_src ) ) { + Material.prototype = { - uniforms_dst[ u ][ p ] = parameter_src.slice(); + constructor: Material, - } else { + isMaterial: true, - uniforms_dst[ u ][ p ] = parameter_src; + get needsUpdate() { - } + return this._needsUpdate; - } + }, - } + set needsUpdate( value ) { - return uniforms_dst; + if ( value === true ) this.update(); + this._needsUpdate = value; - } + }, - }; + setValues: function ( values ) { - /** - * @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: - * } - */ + if ( values === undefined ) return; - function ShaderMaterial( parameters ) { + for ( var key in values ) { - Material.call( this ); + var newValue = values[ key ]; - this.type = 'ShaderMaterial'; + if ( newValue === undefined ) { - this.defines = {}; - this.uniforms = {}; + console.warn( "THREE.Material: '" + key + "' parameter is undefined." ); + continue; - 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}'; + } - this.linewidth = 1; + var currentValue = this[ key ]; - this.wireframe = false; - this.wireframeLinewidth = 1; + if ( currentValue === undefined ) { - 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 + console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." ); + continue; - 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 + } - 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 - }; + if ( (currentValue && currentValue.isColor) ) { - // 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 ] - }; + currentValue.set( newValue ); - this.index0AttributeName = undefined; + } else if ( (currentValue && currentValue.isVector3) && (newValue && newValue.isVector3) ) { - if ( parameters !== undefined ) { + currentValue.copy( newValue ); - if ( parameters.attributes !== undefined ) { + } else if ( key === 'overdraw' ) { - console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' ); + // ensure overdraw is backwards-compatible with legacy boolean type + this[ key ] = Number( newValue ); - } + } else { - this.setValues( parameters ); + this[ key ] = newValue; - } + } - }; + } - ShaderMaterial.prototype = Object.create( Material.prototype ); - ShaderMaterial.prototype.constructor = ShaderMaterial; + }, - ShaderMaterial.prototype.isShaderMaterial = true; + toJSON: function ( meta ) { - ShaderMaterial.prototype.copy = function ( source ) { + var isRoot = meta === undefined; - Material.prototype.copy.call( this, source ); + if ( isRoot ) { - this.fragmentShader = source.fragmentShader; - this.vertexShader = source.vertexShader; + meta = { + textures: {}, + images: {} + }; - this.uniforms = exports.UniformsUtils.clone( source.uniforms ); + } - this.defines = source.defines; + var data = { + metadata: { + version: 4.4, + type: 'Material', + generator: 'Material.toJSON' + } + }; - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; + // standard Material serialization + data.uuid = this.uuid; + data.type = this.type; - this.lights = source.lights; - this.clipping = source.clipping; + if ( this.name !== '' ) data.name = this.name; - this.skinning = source.skinning; + if ( (this.color && this.color.isColor) ) data.color = this.color.getHex(); - this.morphTargets = source.morphTargets; - this.morphNormals = source.morphNormals; + if ( this.roughness !== undefined ) data.roughness = this.roughness; + if ( this.metalness !== undefined ) data.metalness = this.metalness; - this.extensions = source.extensions; + 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; - return this; + 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) ) { - }; + data.bumpMap = this.bumpMap.toJSON( meta ).uuid; + data.bumpScale = this.bumpScale; - ShaderMaterial.prototype.toJSON = function ( meta ) { + } + if ( (this.normalMap && this.normalMap.isTexture) ) { - var data = Material.prototype.toJSON.call( this, meta ); + data.normalMap = this.normalMap.toJSON( meta ).uuid; + data.normalScale = this.normalScale.toArray(); - data.uniforms = this.uniforms; - data.vertexShader = this.vertexShader; - data.fragmentShader = this.fragmentShader; + } + if ( (this.displacementMap && this.displacementMap.isTexture) ) { - return data; + 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; - var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n"; + 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; - var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif\n"; + if ( (this.envMap && this.envMap.isTexture) ) { - var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif\n"; + data.envMap = this.envMap.toJSON( meta ).uuid; + data.reflectivity = this.reflectivity; // Scale behind envMap - 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"; + if ( this.size !== undefined ) data.size = this.size; + if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation; - var begin_vertex = "\nvec3 transformed = vec3( position );\n"; + 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; - var beginnormal_vertex = "\nvec3 objectNormal = vec3( normal );\n"; + 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; - 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"; + // TODO: Copied from Object3D.toJSON - 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"; + function extractFromCache( cache ) { - 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 values = []; - 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"; + for ( var key in cache ) { - var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvarying vec3 vViewPosition;\n#endif\n"; + var data = cache[ key ]; + delete data.metadata; + values.push( data ); - 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"; + return values; - var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif\n"; + } - var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif"; + if ( isRoot ) { - var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif"; + var textures = extractFromCache( meta.textures ); + var images = extractFromCache( meta.images ); - 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"; + if ( textures.length > 0 ) data.textures = textures; + if ( images.length > 0 ) data.images = images; - 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 defaultnormal_vertex = "#ifdef FLIP_SIDED\n\tobjectNormal = -objectNormal;\n#endif\nvec3 transformedNormal = normalMatrix * objectNormal;\n"; + return data; - var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif\n"; + }, - var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normal * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n"; + clone: function () { - 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"; + return new this.constructor().copy( this ); - var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif\n"; + }, - var encodings_fragment = " gl_FragColor = linearToOutputTexel( gl_FragColor );\n"; + copy: function ( source ) { - 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"; + this.name = source.name; - 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.fog = source.fog; + this.lights = source.lights; - 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"; + this.blending = source.blending; + this.side = source.side; + this.shading = source.shading; + this.vertexColors = source.vertexColors; - 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.opacity = source.opacity; + this.transparent = source.transparent; - 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"; + this.blendSrc = source.blendSrc; + this.blendDst = source.blendDst; + this.blendEquation = source.blendEquation; + this.blendSrcAlpha = source.blendSrcAlpha; + this.blendDstAlpha = source.blendDstAlpha; + this.blendEquationAlpha = source.blendEquationAlpha; - 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.depthFunc = source.depthFunc; + this.depthTest = source.depthTest; + this.depthWrite = source.depthWrite; - 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"; + this.colorWrite = source.colorWrite; - var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif\n"; + this.precision = source.precision; - var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif"; + this.polygonOffset = source.polygonOffset; + this.polygonOffsetFactor = source.polygonOffsetFactor; + this.polygonOffsetUnits = source.polygonOffsetUnits; - 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"; + this.alphaTest = source.alphaTest; - 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.premultipliedAlpha = source.premultipliedAlpha; - var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n"; + this.overdraw = source.overdraw; - 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"; + this.visible = source.visible; + this.clipShadows = source.clipShadows; - 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"; + var srcPlanes = source.clippingPlanes, + dstPlanes = null; - 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"; + if ( srcPlanes !== null ) { - 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 n = srcPlanes.length; + dstPlanes = new Array( n ); - var logdepthbuf_fragment = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\tgl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n#endif"; + for ( var i = 0; i !== n; ++ i ) + dstPlanes[ i ] = srcPlanes[ i ].clone(); - 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"; + this.clippingPlanes = dstPlanes; - 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"; + update: 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"; + this.dispatchEvent( { type: 'update' } ); - var map_particle_pars_fragment = "#ifdef USE_MAP\n\tuniform vec4 offsetRepeat;\n\tuniform sampler2D map;\n#endif\n"; + }, - var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.r;\n#endif\n"; + dispose: function () { - var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif"; + this.dispatchEvent( { type: 'dispose' } ); - 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"; + } - 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"; + }; - 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"; + Object.assign( Material.prototype, EventDispatcher.prototype ); - 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"; + var count$1 = 0; + function MaterialIdCount() { return count$1++; }; - 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"; + /** + * Uniform Utilities + */ - 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"; + exports.UniformsUtils = { - 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"; + merge: function ( uniforms ) { - var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif\n"; + var merged = {}; - 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"; + for ( var u = 0; u < uniforms.length; u ++ ) { - var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.r;\n#endif\n"; + var tmp = this.clone( uniforms[ u ] ); - var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif"; + for ( var p in tmp ) { - 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"; + merged[ p ] = tmp[ p ]; - 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"; + } - 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"; + return merged; - 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"; + clone: function ( uniforms_src ) { - 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 uniforms_dst = {}; - 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"; + for ( var u in uniforms_src ) { - 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"; + uniforms_dst[ u ] = {}; - var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif"; + for ( var p in uniforms_src[ u ] ) { - var tonemapping_fragment = "#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif\n"; + var parameter_src = uniforms_src[ u ][ p ]; - 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"; + 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 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"; + uniforms_dst[ u ][ p ] = parameter_src.clone(); - 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"; + } else if ( Array.isArray( parameter_src ) ) { - 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"; + uniforms_dst[ u ][ p ] = parameter_src.slice(); - var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif"; + } else { - var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif"; + uniforms_dst[ u ][ p ] = parameter_src; - 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"; + } - 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 cube_vert = "varying vec3 vWorldPosition;\n#include \nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}\n"; + return uniforms_dst; - 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"; + } - 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"; + /** + * @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 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"; + function ShaderMaterial( parameters ) { - 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"; + Material.call( this ); - var equirect_vert = "varying vec3 vWorldPosition;\n#include \nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}\n"; + this.type = 'ShaderMaterial'; - 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"; + this.defines = {}; + this.uniforms = {}; - 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"; + 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 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"; + this.linewidth = 1; - 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"; + this.wireframe = false; + this.wireframeLinewidth = 1; - 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"; + 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 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"; + 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 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"; + 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 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"; + // 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 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"; + this.index0AttributeName = undefined; - 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"; + if ( parameters !== undefined ) { - 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"; + if ( parameters.attributes !== undefined ) { - 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"; + console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' ); - 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 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"; + this.setValues( parameters ); - 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 - }; - - /** - * @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 ); - - }; + ShaderMaterial.prototype = Object.create( Material.prototype ); + ShaderMaterial.prototype.constructor = ShaderMaterial; - Color.prototype = { + ShaderMaterial.prototype.isShaderMaterial = true; - constructor: Color, + ShaderMaterial.prototype.copy = function ( source ) { - isColor: true, + Material.prototype.copy.call( this, source ); - r: 1, g: 1, b: 1, + this.fragmentShader = source.fragmentShader; + this.vertexShader = source.vertexShader; - set: function ( value ) { + this.uniforms = exports.UniformsUtils.clone( source.uniforms ); - if ( (value && value.isColor) ) { + this.defines = source.defines; - this.copy( value ); + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; - } else if ( typeof value === 'number' ) { + this.lights = source.lights; + this.clipping = source.clipping; - this.setHex( value ); + this.skinning = source.skinning; - } else if ( typeof value === 'string' ) { + this.morphTargets = source.morphTargets; + this.morphNormals = source.morphNormals; - this.setStyle( value ); + this.extensions = source.extensions; - } + return this; - return this; + }; - }, + ShaderMaterial.prototype.toJSON = function ( meta ) { - setScalar: function ( scalar ) { + var data = Material.prototype.toJSON.call( this, meta ); - this.r = scalar; - this.g = scalar; - this.b = scalar; + data.uniforms = this.uniforms; + data.vertexShader = this.vertexShader; + data.fragmentShader = this.fragmentShader; - }, + return data; - setHex: function ( hex ) { + }; - hex = Math.floor( hex ); + var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n"; - this.r = ( hex >> 16 & 255 ) / 255; - this.g = ( hex >> 8 & 255 ) / 255; - this.b = ( hex & 255 ) / 255; + var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif\n"; - return this; + var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif\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"; - setRGB: function ( r, g, b ) { + var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif"; - this.r = r; - this.g = g; - this.b = b; + 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"; - setHSL: 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"; - function hue2rgb( p, q, t ) { + 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"; - 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 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 clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvarying vec3 vViewPosition;\n#endif\n"; - return function setHSL( h, s, l ) { + var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvViewPosition = - mvPosition.xyz;\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 color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif"; - if ( s === 0 ) { + var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif\n"; - this.r = this.g = this.b = l; + var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif"; - } else { + var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif"; - var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s ); - var q = ( 2 * l ) - p; + 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"; - this.r = hue2rgb( q, p, h + 1 / 3 ); - this.g = hue2rgb( q, p, h ); - this.b = hue2rgb( q, p, h - 1 / 3 ); + 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 defaultnormal_vertex = "#ifdef FLIP_SIDED\n\tobjectNormal = -objectNormal;\n#endif\nvec3 transformedNormal = normalMatrix * objectNormal;\n"; - return this; + var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif\n"; - }; + var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normal * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n"; - }(), + 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"; - setStyle: function ( style ) { + var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif\n"; - function handleAlpha( string ) { + var encodings_fragment = " gl_FragColor = linearToOutputTexel( gl_FragColor );\n"; - if ( string === undefined ) return; + 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 ( parseFloat( string ) < 1 ) { + 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"; - console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' ); + 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"; - } + 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 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"; - var m; + 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"; - if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) { + var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif\n"; - // rgb / hsl + var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif"; - var color; - var name = m[ 1 ]; - var components = m[ 2 ]; + 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"; - switch ( name ) { + 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"; - case 'rgb': - case 'rgba': + var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n"; - if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) { + 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"; - // 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 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"; - handleAlpha( color[ 5 ] ); + 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"; - return this; + 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"; - if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) { + 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"; - // 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 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"; - handleAlpha( color[ 5 ] ); + 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"; - break; + 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"; - case 'hsl': - case 'hsla': + var map_particle_pars_fragment = "#ifdef USE_MAP\n\tuniform vec4 offsetRepeat;\n\tuniform sampler2D map;\n#endif\n"; - if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) { + var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.r;\n#endif\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 metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif"; - handleAlpha( color[ 5 ] ); + 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"; - return this.setHSL( h, s, l ); + 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"; - } + 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"; - break; + 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"; - } + 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"; - } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) { + 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"; - // hex color + 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 hex = m[ 1 ]; - var size = hex.length; + var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif\n"; - if ( size === 3 ) { + 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"; - // #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 roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.r;\n#endif\n"; - return this; + var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif"; - } else if ( size === 6 ) { + 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"; - // #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 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"; - return this; + 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"; - if ( style && style.length > 0 ) { + 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"; - // color keywords - var hex = exports.ColorKeywords[ style ]; + 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"; - if ( hex !== undefined ) { + 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"; - // red - this.setHex( hex ); + 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"; - } else { + var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif"; - // unknown color - console.warn( 'THREE.Color: Unknown color ' + style ); + var tonemapping_fragment = "#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif\n"; - } + 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"; - } + 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"; - return this; + 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"; - }, + 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"; - clone: function () { + var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif"; - return new this.constructor( this.r, this.g, this.b ); + var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif"; - }, + var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif"; - copy: function ( color ) { + 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"; - this.r = color.r; - this.g = color.g; - this.b = color.b; + 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"; - return this; + var cube_vert = "varying vec3 vWorldPosition;\n#include \nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}\n"; - }, + 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"; - copyGammaToLinear: function ( color, gammaFactor ) { + 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"; - if ( gammaFactor === undefined ) gammaFactor = 2.0; + 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"; - this.r = Math.pow( color.r, gammaFactor ); - this.g = Math.pow( color.g, gammaFactor ); - this.b = Math.pow( color.b, gammaFactor ); + 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"; - return this; + 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 equirect_vert = "varying vec3 vWorldPosition;\n#include \nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}\n"; - copyLinearToGamma: function ( color, gammaFactor ) { + 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"; - if ( gammaFactor === undefined ) gammaFactor = 2.0; + 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 safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0; + 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"; - this.r = Math.pow( color.r, safeInverse ); - this.g = Math.pow( color.g, safeInverse ); - this.b = Math.pow( color.b, safeInverse ); + 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"; - return this; + 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"; - convertGammaToLinear: function () { + 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 r = this.r, g = this.g, b = this.b; + 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"; - this.r = r * r; - this.g = g * g; - this.b = b * b; + 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"; - return this; + 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 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"; - convertLinearToGamma: function () { + 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"; - this.r = Math.sqrt( this.r ); - this.g = Math.sqrt( this.g ); - this.b = Math.sqrt( this.b ); + 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"; - return this; + 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 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"; - getHex: function () { + var shadow_vert = "#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; - return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0; + 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/ + */ - getHexString: function () { + function Color( r, g, b ) { - return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 ); + if ( g === undefined && b === undefined ) { - }, + // r is THREE.Color, hex or string + return this.set( r ); - getHSL: function ( optionalTarget ) { + } - // h,s,l ranges are in 0.0 - 1.0 + return this.setRGB( r, g, b ); - var hsl = optionalTarget || { h: 0, s: 0, l: 0 }; + }; - var r = this.r, g = this.g, b = this.b; + Color.prototype = { - var max = Math.max( r, g, b ); - var min = Math.min( r, g, b ); + constructor: Color, - var hue, saturation; - var lightness = ( min + max ) / 2.0; + isColor: true, - if ( min === max ) { + r: 1, g: 1, b: 1, - hue = 0; - saturation = 0; + set: function ( value ) { - } else { + if ( (value && value.isColor) ) { - var delta = max - min; + this.copy( value ); - saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min ); + } else if ( typeof value === 'number' ) { - switch ( max ) { + this.setHex( value ); - 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; + } else if ( typeof value === 'string' ) { - } + this.setStyle( value ); - hue /= 6; + } - } + return this; - hsl.h = hue; - hsl.s = saturation; - hsl.l = lightness; + }, - return hsl; + setScalar: function ( scalar ) { - }, + this.r = scalar; + this.g = scalar; + this.b = scalar; - getStyle: function () { + }, - return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')'; + setHex: function ( hex ) { - }, + hex = Math.floor( hex ); - offsetHSL: function ( h, s, l ) { + this.r = ( hex >> 16 & 255 ) / 255; + this.g = ( hex >> 8 & 255 ) / 255; + this.b = ( hex & 255 ) / 255; - var hsl = this.getHSL(); + return this; - hsl.h += h; hsl.s += s; hsl.l += l; + }, - this.setHSL( hsl.h, hsl.s, hsl.l ); + setRGB: function ( r, g, b ) { - return this; + this.r = r; + this.g = g; + this.b = b; - }, + return this; - add: function ( color ) { + }, - this.r += color.r; - this.g += color.g; - this.b += color.b; + setHSL: function () { - return this; + function hue2rgb( p, q, t ) { - }, + 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; - addColors: function ( color1, color2 ) { + } - this.r = color1.r + color2.r; - this.g = color1.g + color2.g; - this.b = color1.b + color2.b; + return function setHSL( h, s, l ) { - return this; + // 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 ) { - addScalar: function ( s ) { + this.r = this.g = this.b = l; - this.r += s; - this.g += s; - this.b += s; + } else { - return this; + var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s ); + var q = ( 2 * l ) - p; - }, + this.r = hue2rgb( q, p, h + 1 / 3 ); + this.g = hue2rgb( q, p, h ); + this.b = hue2rgb( q, p, h - 1 / 3 ); - sub: function( color ) { + } - 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 ); + return this; - return this; + }; - }, + }(), - multiply: function ( color ) { + setStyle: function ( style ) { - this.r *= color.r; - this.g *= color.g; - this.b *= color.b; + function handleAlpha( string ) { - return this; + if ( string === undefined ) return; - }, + if ( parseFloat( string ) < 1 ) { - multiplyScalar: function ( s ) { + console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' ); - this.r *= s; - this.g *= s; - this.b *= s; + } - return this; + } - }, - lerp: function ( color, alpha ) { + var m; - this.r += ( color.r - this.r ) * alpha; - this.g += ( color.g - this.g ) * alpha; - this.b += ( color.b - this.b ) * alpha; + if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) { - return this; + // rgb / hsl - }, + var color; + var name = m[ 1 ]; + var components = m[ 2 ]; - equals: function ( c ) { + switch ( name ) { - return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b ); + case 'rgb': + case 'rgba': - }, + if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) { - fromArray: function ( array, offset ) { + // 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; - if ( offset === undefined ) offset = 0; + handleAlpha( color[ 5 ] ); - this.r = array[ offset ]; - this.g = array[ offset + 1 ]; - this.b = array[ offset + 2 ]; + return this; - return this; + } - }, + if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) { - toArray: function ( array, offset ) { + // 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; - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + handleAlpha( color[ 5 ] ); - array[ offset ] = this.r; - array[ offset + 1 ] = this.g; - array[ offset + 2 ] = this.b; + return this; - return array; + } - } + break; - }; + case 'hsl': + case 'hsla': - 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 }; + if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) { - /** - * Uniforms library for shared webgl shaders - */ + // 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; - exports.UniformsLib = { + handleAlpha( color[ 5 ] ); - common: { + return this.setHSL( h, s, l ); - "diffuse": { value: new Color( 0xeeeeee ) }, - "opacity": { value: 1.0 }, + } - "map": { value: null }, - "offsetRepeat": { value: new Vector4( 0, 0, 1, 1 ) }, + break; - "specularMap": { value: null }, - "alphaMap": { value: null }, + } - "envMap": { value: null }, - "flipEnvMap": { value: - 1 }, - "reflectivity": { value: 1.0 }, - "refractionRatio": { value: 0.98 } + } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) { - }, + // hex color - aomap: { + var hex = m[ 1 ]; + var size = hex.length; - "aoMap": { value: null }, - "aoMapIntensity": { value: 1 } + if ( size === 3 ) { - }, + // #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; - lightmap: { + return this; - "lightMap": { value: null }, - "lightMapIntensity": { value: 1 } + } else if ( size === 6 ) { - }, + // #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; - emissivemap: { + return this; - "emissiveMap": { value: null } + } - }, + } - bumpmap: { + if ( style && style.length > 0 ) { - "bumpMap": { value: null }, - "bumpScale": { value: 1 } + // color keywords + var hex = exports.ColorKeywords[ style ]; - }, + if ( hex !== undefined ) { - normalmap: { + // red + this.setHex( hex ); - "normalMap": { value: null }, - "normalScale": { value: new Vector2( 1, 1 ) } + } else { - }, + // unknown color + console.warn( 'THREE.Color: Unknown color ' + style ); - displacementmap: { + } - "displacementMap": { value: null }, - "displacementScale": { value: 1 }, - "displacementBias": { value: 0 } + } - }, + return this; - roughnessmap: { + }, - "roughnessMap": { value: null } + clone: function () { - }, + return new this.constructor( this.r, this.g, this.b ); - metalnessmap: { + }, - "metalnessMap": { value: null } + copy: function ( color ) { - }, + this.r = color.r; + this.g = color.g; + this.b = color.b; - fog: { + return this; - "fogDensity": { value: 0.00025 }, - "fogNear": { value: 1 }, - "fogFar": { value: 2000 }, - "fogColor": { value: new Color( 0xffffff ) } + }, - }, + copyGammaToLinear: function ( color, gammaFactor ) { - lights: { + if ( gammaFactor === undefined ) gammaFactor = 2.0; - "ambientLightColor": { value: [] }, + this.r = Math.pow( color.r, gammaFactor ); + this.g = Math.pow( color.g, gammaFactor ); + this.b = Math.pow( color.b, gammaFactor ); - "directionalLights": { value: [], properties: { - "direction": {}, - "color": {}, + return this; - "shadow": {}, - "shadowBias": {}, - "shadowRadius": {}, - "shadowMapSize": {} - } }, + }, - "directionalShadowMap": { value: [] }, - "directionalShadowMatrix": { value: [] }, + copyLinearToGamma: function ( color, gammaFactor ) { - "spotLights": { value: [], properties: { - "color": {}, - "position": {}, - "direction": {}, - "distance": {}, - "coneCos": {}, - "penumbraCos": {}, - "decay": {}, + if ( gammaFactor === undefined ) gammaFactor = 2.0; - "shadow": {}, - "shadowBias": {}, - "shadowRadius": {}, - "shadowMapSize": {} - } }, + var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0; - "spotShadowMap": { value: [] }, - "spotShadowMatrix": { value: [] }, + this.r = Math.pow( color.r, safeInverse ); + this.g = Math.pow( color.g, safeInverse ); + this.b = Math.pow( color.b, safeInverse ); - "pointLights": { value: [], properties: { - "color": {}, - "position": {}, - "decay": {}, - "distance": {}, + return this; - "shadow": {}, - "shadowBias": {}, - "shadowRadius": {}, - "shadowMapSize": {} - } }, + }, - "pointShadowMap": { value: [] }, - "pointShadowMatrix": { value: [] }, + convertGammaToLinear: function () { - "hemisphereLights": { value: [], properties: { - "direction": {}, - "skyColor": {}, - "groundColor": {} - } } + var r = this.r, g = this.g, b = this.b; - }, + this.r = r * r; + this.g = g * g; + this.b = b * b; - points: { + return this; - "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 ) } + }, - } + convertLinearToGamma: function () { - }; + this.r = Math.sqrt( this.r ); + this.g = Math.sqrt( this.g ); + this.b = Math.sqrt( this.b ); - /** - * Webgl Shader Library for three.js - * - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - * @author mikael emtinger / http://gomo.se/ - */ + return this; + }, - exports.ShaderLib = { + getHex: function () { - 'basic': { + return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0; - uniforms: exports.UniformsUtils.merge( [ + }, - exports.UniformsLib[ 'common' ], - exports.UniformsLib[ 'aomap' ], - exports.UniformsLib[ 'fog' ] + getHexString: function () { - ] ), + return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 ); - vertexShader: ShaderChunk[ 'meshbasic_vert' ], - fragmentShader: ShaderChunk[ 'meshbasic_frag' ] + }, - }, + getHSL: function ( optionalTarget ) { - 'lambert': { + // h,s,l ranges are in 0.0 - 1.0 - uniforms: exports.UniformsUtils.merge( [ + var hsl = optionalTarget || { h: 0, s: 0, l: 0 }; - exports.UniformsLib[ 'common' ], - exports.UniformsLib[ 'aomap' ], - exports.UniformsLib[ 'lightmap' ], - exports.UniformsLib[ 'emissivemap' ], - exports.UniformsLib[ 'fog' ], - exports.UniformsLib[ 'lights' ], + var r = this.r, g = this.g, b = this.b; - { - "emissive" : { value: new Color( 0x000000 ) } - } + var max = Math.max( r, g, b ); + var min = Math.min( r, g, b ); - ] ), + var hue, saturation; + var lightness = ( min + max ) / 2.0; - vertexShader: ShaderChunk[ 'meshlambert_vert' ], - fragmentShader: ShaderChunk[ 'meshlambert_frag' ] + if ( min === max ) { - }, + hue = 0; + saturation = 0; - 'phong': { + } else { - uniforms: exports.UniformsUtils.merge( [ + var delta = max - min; - 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' ], + saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min ); - { - "emissive" : { value: new Color( 0x000000 ) }, - "specular" : { value: new Color( 0x111111 ) }, - "shininess": { value: 30 } - } + 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; - vertexShader: ShaderChunk[ 'meshphong_vert' ], - fragmentShader: ShaderChunk[ 'meshphong_frag' ] + } - }, + hue /= 6; - 'standard': { + } - uniforms: exports.UniformsUtils.merge( [ + hsl.h = hue; + hsl.s = saturation; + hsl.l = lightness; - 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' ], + return hsl; - { - "emissive" : { value: new Color( 0x000000 ) }, - "roughness": { value: 0.5 }, - "metalness": { value: 0 }, - "envMapIntensity" : { value: 1 }, // temporary - } + }, - ] ), + getStyle: function () { - vertexShader: ShaderChunk[ 'meshphysical_vert' ], - fragmentShader: ShaderChunk[ 'meshphysical_frag' ] + return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')'; - }, + }, - 'points': { + offsetHSL: function ( h, s, l ) { - uniforms: exports.UniformsUtils.merge( [ + var hsl = this.getHSL(); - exports.UniformsLib[ 'points' ], - exports.UniformsLib[ 'fog' ] + hsl.h += h; hsl.s += s; hsl.l += l; - ] ), + this.setHSL( hsl.h, hsl.s, hsl.l ); - vertexShader: ShaderChunk[ 'points_vert' ], - fragmentShader: ShaderChunk[ 'points_frag' ] + return this; - }, + }, - 'dashed': { + add: function ( color ) { - uniforms: exports.UniformsUtils.merge( [ + this.r += color.r; + this.g += color.g; + this.b += color.b; - exports.UniformsLib[ 'common' ], - exports.UniformsLib[ 'fog' ], + return this; - { - "scale" : { value: 1 }, - "dashSize" : { value: 1 }, - "totalSize": { value: 2 } - } + }, - ] ), + addColors: function ( color1, color2 ) { - vertexShader: ShaderChunk[ 'linedashed_vert' ], - fragmentShader: ShaderChunk[ 'linedashed_frag' ] + this.r = color1.r + color2.r; + this.g = color1.g + color2.g; + this.b = color1.b + color2.b; - }, + return this; - 'depth': { + }, - uniforms: exports.UniformsUtils.merge( [ + addScalar: function ( s ) { - exports.UniformsLib[ 'common' ], - exports.UniformsLib[ 'displacementmap' ] + this.r += s; + this.g += s; + this.b += s; - ] ), + return this; - vertexShader: ShaderChunk[ 'depth_vert' ], - fragmentShader: ShaderChunk[ 'depth_frag' ] + }, - }, + sub: function( color ) { - 'normal': { + 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 ); - uniforms: { + return this; - "opacity" : { value: 1.0 } + }, - }, + multiply: function ( color ) { - vertexShader: ShaderChunk[ 'normal_vert' ], - fragmentShader: ShaderChunk[ 'normal_frag' ] + this.r *= color.r; + this.g *= color.g; + this.b *= color.b; - }, + return this; - /* ------------------------------------------------------------------------- - // Cube map shader - ------------------------------------------------------------------------- */ + }, - 'cube': { + multiplyScalar: function ( s ) { - uniforms: { - "tCube": { value: null }, - "tFlip": { value: - 1 }, - "opacity": { value: 1.0 } - }, + this.r *= s; + this.g *= s; + this.b *= s; - vertexShader: ShaderChunk[ 'cube_vert' ], - fragmentShader: ShaderChunk[ 'cube_frag' ] + return this; - }, + }, - /* ------------------------------------------------------------------------- - // Cube map shader - ------------------------------------------------------------------------- */ + lerp: function ( color, alpha ) { - 'equirect': { + this.r += ( color.r - this.r ) * alpha; + this.g += ( color.g - this.g ) * alpha; + this.b += ( color.b - this.b ) * alpha; - uniforms: { - "tEquirect": { value: null }, - "tFlip": { value: - 1 } - }, + return this; - vertexShader: ShaderChunk[ 'equirect_vert' ], - fragmentShader: ShaderChunk[ 'equirect_frag' ] + }, - }, + equals: function ( c ) { - 'distanceRGBA': { + return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b ); - uniforms: { + }, - "lightPos": { value: new Vector3() } + fromArray: function ( array, offset ) { - }, + if ( offset === undefined ) offset = 0; - vertexShader: ShaderChunk[ 'distanceRGBA_vert' ], - fragmentShader: ShaderChunk[ 'distanceRGBA_frag' ] + this.r = array[ offset ]; + this.g = array[ offset + 1 ]; + this.b = array[ offset + 2 ]; - } + return this; - }; + }, - exports.ShaderLib[ 'physical' ] = { + toArray: function ( array, offset ) { - uniforms: exports.UniformsUtils.merge( [ + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - exports.ShaderLib[ 'standard' ].uniforms, + array[ offset ] = this.r; + array[ offset + 1 ] = this.g; + array[ offset + 2 ] = this.b; - { - "clearCoat": { value: 0 }, - "clearCoatRoughness": { value: 0 } - } + return array; - ] ), + } - vertexShader: ShaderChunk[ 'meshphysical_vert' ], - fragmentShader: ShaderChunk[ 'meshphysical_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 } - /** - * @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: - * } - */ + }, - function MeshDepthMaterial( parameters ) { + aomap: { - Material.call( this ); + "aoMap": { value: null }, + "aoMapIntensity": { value: 1 } - this.type = 'MeshDepthMaterial'; + }, - this.depthPacking = BasicDepthPacking; + lightmap: { - this.skinning = false; - this.morphTargets = false; + "lightMap": { value: null }, + "lightMapIntensity": { value: 1 } - this.map = null; + }, - this.alphaMap = null; + emissivemap: { - this.displacementMap = null; - this.displacementScale = 1; - this.displacementBias = 0; + "emissiveMap": { value: null } - this.wireframe = false; - this.wireframeLinewidth = 1; + }, - this.fog = false; - this.lights = false; + bumpmap: { - this.setValues( parameters ); + "bumpMap": { value: null }, + "bumpScale": { value: 1 } - }; + }, - MeshDepthMaterial.prototype = Object.create( Material.prototype ); - MeshDepthMaterial.prototype.constructor = MeshDepthMaterial; + normalmap: { - MeshDepthMaterial.prototype.isMeshDepthMaterial = true; + "normalMap": { value: null }, + "normalScale": { value: new Vector2( 1, 1 ) } - MeshDepthMaterial.prototype.copy = function ( source ) { + }, - Material.prototype.copy.call( this, source ); + displacementmap: { - this.depthPacking = source.depthPacking; + "displacementMap": { value: null }, + "displacementScale": { value: 1 }, + "displacementBias": { value: 0 } - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; + }, - this.map = source.map; + roughnessmap: { - this.alphaMap = source.alphaMap; + "roughnessMap": { value: null } - this.displacementMap = source.displacementMap; - this.displacementScale = source.displacementScale; - this.displacementBias = source.displacementBias; + }, - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; + metalnessmap: { - return this; + "metalnessMap": { value: null } - }; + }, - /** - * @author bhouston / http://clara.io - * @author WestLangley / http://github.com/WestLangley - */ + fog: { - function Box3( min, max ) { + "fogDensity": { value: 0.00025 }, + "fogNear": { value: 1 }, + "fogFar": { value: 2000 }, + "fogColor": { value: new Color( 0xffffff ) } - this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity ); - this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity ); + }, - }; + 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": {} + } } - Box3.prototype = { + }, - constructor: Box3, + points: { - isBox3: true, + "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 ) } - set: function ( min, max ) { + } - this.min.copy( min ); - this.max.copy( max ); + }; - return this; + /** + * Webgl Shader Library for three.js + * + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + * @author mikael emtinger / http://gomo.se/ + */ - }, - setFromArray: function ( array ) { + exports.ShaderLib = { - var minX = + Infinity; - var minY = + Infinity; - var minZ = + Infinity; + 'basic': { - var maxX = - Infinity; - var maxY = - Infinity; - var maxZ = - Infinity; + uniforms: exports.UniformsUtils.merge( [ - for ( var i = 0, l = array.length; i < l; i += 3 ) { + exports.UniformsLib[ 'common' ], + exports.UniformsLib[ 'aomap' ], + exports.UniformsLib[ 'fog' ] - 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; + vertexShader: ShaderChunk[ 'meshbasic_vert' ], + fragmentShader: ShaderChunk[ 'meshbasic_frag' ] - if ( x > maxX ) maxX = x; - if ( y > maxY ) maxY = y; - if ( z > maxZ ) maxZ = z; + }, - } + 'lambert': { - this.min.set( minX, minY, minZ ); - this.max.set( maxX, maxY, maxZ ); + uniforms: exports.UniformsUtils.merge( [ - }, + exports.UniformsLib[ 'common' ], + exports.UniformsLib[ 'aomap' ], + exports.UniformsLib[ 'lightmap' ], + exports.UniformsLib[ 'emissivemap' ], + exports.UniformsLib[ 'fog' ], + exports.UniformsLib[ 'lights' ], - setFromPoints: function ( points ) { + { + "emissive" : { value: new Color( 0x000000 ) } + } - this.makeEmpty(); + ] ), - for ( var i = 0, il = points.length; i < il; i ++ ) { + vertexShader: ShaderChunk[ 'meshlambert_vert' ], + fragmentShader: ShaderChunk[ 'meshlambert_frag' ] - this.expandByPoint( points[ i ] ); + }, - } + 'phong': { - 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[ 'fog' ], + exports.UniformsLib[ 'lights' ], - setFromCenterAndSize: function () { + { + "emissive" : { value: new Color( 0x000000 ) }, + "specular" : { value: new Color( 0x111111 ) }, + "shininess": { value: 30 } + } - var v1 = new Vector3(); + ] ), - return function setFromCenterAndSize( center, size ) { + vertexShader: ShaderChunk[ 'meshphong_vert' ], + fragmentShader: ShaderChunk[ 'meshphong_frag' ] - var halfSize = v1.copy( size ).multiplyScalar( 0.5 ); + }, - this.min.copy( center ).sub( halfSize ); - this.max.copy( center ).add( halfSize ); + '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' ], - }(), + { + "emissive" : { value: new Color( 0x000000 ) }, + "roughness": { value: 0.5 }, + "metalness": { value: 0 }, + "envMapIntensity" : { value: 1 }, // temporary + } - 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 + vertexShader: ShaderChunk[ 'meshphysical_vert' ], + fragmentShader: ShaderChunk[ 'meshphysical_frag' ] - var v1 = new Vector3(); + }, - return function setFromObject( object ) { + 'points': { - var scope = this; + uniforms: exports.UniformsUtils.merge( [ - object.updateMatrixWorld( true ); + exports.UniformsLib[ 'points' ], + exports.UniformsLib[ 'fog' ] - this.makeEmpty(); + ] ), - object.traverse( function ( node ) { + vertexShader: ShaderChunk[ 'points_vert' ], + fragmentShader: ShaderChunk[ 'points_frag' ] - var geometry = node.geometry; + }, - if ( geometry !== undefined ) { + 'dashed': { - if ( (geometry && geometry.isGeometry) ) { + uniforms: exports.UniformsUtils.merge( [ - var vertices = geometry.vertices; + exports.UniformsLib[ 'common' ], + exports.UniformsLib[ 'fog' ], - for ( var i = 0, il = vertices.length; i < il; i ++ ) { + { + "scale" : { value: 1 }, + "dashSize" : { value: 1 }, + "totalSize": { value: 2 } + } - v1.copy( vertices[ i ] ); - v1.applyMatrix4( node.matrixWorld ); + ] ), - scope.expandByPoint( v1 ); + vertexShader: ShaderChunk[ 'linedashed_vert' ], + fragmentShader: ShaderChunk[ 'linedashed_frag' ] - } + }, - } else if ( (geometry && geometry.isBufferGeometry) ) { + 'depth': { - var attribute = geometry.attributes.position; + uniforms: exports.UniformsUtils.merge( [ - if ( attribute !== undefined ) { + exports.UniformsLib[ 'common' ], + exports.UniformsLib[ 'displacementmap' ] - var array, offset, stride; + ] ), - if ( (attribute && attribute.isInterleavedBufferAttribute) ) { + vertexShader: ShaderChunk[ 'depth_vert' ], + fragmentShader: ShaderChunk[ 'depth_frag' ] - array = attribute.data.array; - offset = attribute.offset; - stride = attribute.data.stride; + }, - } else { + 'normal': { - array = attribute.array; - offset = 0; - stride = 3; + uniforms: { - } + "opacity" : { value: 1.0 } - for ( var i = offset, il = array.length; i < il; i += stride ) { + }, - v1.fromArray( array, i ); - v1.applyMatrix4( node.matrixWorld ); + vertexShader: ShaderChunk[ 'normal_vert' ], + fragmentShader: ShaderChunk[ 'normal_frag' ] - scope.expandByPoint( v1 ); + }, - } + /* ------------------------------------------------------------------------- + // Cube map shader + ------------------------------------------------------------------------- */ - } + 'cube': { - } + uniforms: { + "tCube": { value: null }, + "tFlip": { value: - 1 }, + "opacity": { value: 1.0 } + }, - } + vertexShader: ShaderChunk[ 'cube_vert' ], + fragmentShader: ShaderChunk[ 'cube_frag' ] - } ); + }, - return this; + /* ------------------------------------------------------------------------- + // Cube map shader + ------------------------------------------------------------------------- */ - }; + 'equirect': { - }(), + uniforms: { + "tEquirect": { value: null }, + "tFlip": { value: - 1 } + }, - clone: function () { + vertexShader: ShaderChunk[ 'equirect_vert' ], + fragmentShader: ShaderChunk[ 'equirect_frag' ] - return new this.constructor().copy( this ); + }, - }, + 'distanceRGBA': { - copy: function ( box ) { + uniforms: { - this.min.copy( box.min ); - this.max.copy( box.max ); + "lightPos": { value: new Vector3() } - return this; + }, - }, + vertexShader: ShaderChunk[ 'distanceRGBA_vert' ], + fragmentShader: ShaderChunk[ 'distanceRGBA_frag' ] - makeEmpty: function () { + } - this.min.x = this.min.y = this.min.z = + Infinity; - this.max.x = this.max.y = this.max.z = - Infinity; + }; - return this; + exports.ShaderLib[ 'physical' ] = { - }, + uniforms: exports.UniformsUtils.merge( [ - isEmpty: function () { + exports.ShaderLib[ 'standard' ].uniforms, - // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes + { + "clearCoat": { value: 0 }, + "clearCoatRoughness": { value: 0 } + } - return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z ); + ] ), - }, + vertexShader: ShaderChunk[ 'meshphysical_vert' ], + fragmentShader: ShaderChunk[ 'meshphysical_frag' ] - center: function ( optionalTarget ) { + }; - var result = optionalTarget || new Vector3(); - return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); + /** + * @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: + * } + */ - }, + function MeshDepthMaterial( parameters ) { - size: function ( optionalTarget ) { + Material.call( this ); - var result = optionalTarget || new Vector3(); - return result.subVectors( this.max, this.min ); + this.type = 'MeshDepthMaterial'; - }, + this.depthPacking = BasicDepthPacking; - expandByPoint: function ( point ) { + this.skinning = false; + this.morphTargets = false; - this.min.min( point ); - this.max.max( point ); + this.map = null; - return this; + this.alphaMap = null; - }, + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; - expandByVector: function ( vector ) { + this.wireframe = false; + this.wireframeLinewidth = 1; - this.min.sub( vector ); - this.max.add( vector ); + this.fog = false; + this.lights = false; - return this; + this.setValues( parameters ); - }, + }; - expandByScalar: function ( scalar ) { + MeshDepthMaterial.prototype = Object.create( Material.prototype ); + MeshDepthMaterial.prototype.constructor = MeshDepthMaterial; - this.min.addScalar( - scalar ); - this.max.addScalar( scalar ); + MeshDepthMaterial.prototype.isMeshDepthMaterial = true; - return this; + MeshDepthMaterial.prototype.copy = function ( source ) { - }, + Material.prototype.copy.call( this, source ); - containsPoint: function ( point ) { + this.depthPacking = source.depthPacking; - 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 ) { + this.skinning = source.skinning; + this.morphTargets = source.morphTargets; - return false; + this.map = source.map; - } + this.alphaMap = source.alphaMap; - return true; + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; - }, + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; - 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; + /** + * @author bhouston / http://clara.io + * @author WestLangley / http://github.com/WestLangley + */ - } + function Box3( min, max ) { - return false; + this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity ); + this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity ); - }, + }; - getParameter: function ( point, optionalTarget ) { + Box3.prototype = { - // This can potentially have a divide by zero if the box - // has a size dimension of 0. + constructor: Box3, - var result = optionalTarget || new Vector3(); + isBox3: true, - 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 ) - ); + set: function ( min, max ) { - }, + this.min.copy( min ); + this.max.copy( max ); - intersectsBox: function ( box ) { + return this; - // using 6 splitting planes to rule out intersections. + }, - 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 ) { + setFromArray: function ( array ) { - return false; + var minX = + Infinity; + var minY = + Infinity; + var minZ = + Infinity; - } + var maxX = - Infinity; + var maxY = - Infinity; + var maxZ = - Infinity; - return true; + 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 ]; - intersectsSphere: ( function () { + if ( x < minX ) minX = x; + if ( y < minY ) minY = y; + if ( z < minZ ) minZ = z; - var closestPoint; + if ( x > maxX ) maxX = x; + if ( y > maxY ) maxY = y; + if ( z > maxZ ) maxZ = z; - return function intersectsSphere( sphere ) { + } - if ( closestPoint === undefined ) closestPoint = new Vector3(); + this.min.set( minX, minY, minZ ); + this.max.set( maxX, maxY, maxZ ); - // Find the point on the AABB closest to the sphere center. - this.clampPoint( sphere.center, closestPoint ); + }, - // If that point is inside the sphere, the AABB and sphere intersect. - return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius ); + setFromPoints: function ( points ) { - }; + this.makeEmpty(); - } )(), + for ( var i = 0, il = points.length; i < il; i ++ ) { - intersectsPlane: function ( plane ) { + this.expandByPoint( points[ i ] ); - // 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. + } - var min, max; + return this; - if ( plane.normal.x > 0 ) { + }, - min = plane.normal.x * this.min.x; - max = plane.normal.x * this.max.x; + setFromCenterAndSize: function () { - } else { + var v1 = new Vector3(); - min = plane.normal.x * this.max.x; - max = plane.normal.x * this.min.x; + return function setFromCenterAndSize( center, size ) { - } + var halfSize = v1.copy( size ).multiplyScalar( 0.5 ); - if ( plane.normal.y > 0 ) { + this.min.copy( center ).sub( halfSize ); + this.max.copy( center ).add( halfSize ); - 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; + }(), - } + setFromObject: function () { - if ( plane.normal.z > 0 ) { + // Computes the world-axis-aligned bounding box of an object (including its children), + // accounting for both the object's, and children's, world transforms - min += plane.normal.z * this.min.z; - max += plane.normal.z * this.max.z; + var v1 = new Vector3(); - } else { + return function setFromObject( object ) { - min += plane.normal.z * this.max.z; - max += plane.normal.z * this.min.z; + var scope = this; - } + object.updateMatrixWorld( true ); - return ( min <= plane.constant && max >= plane.constant ); + this.makeEmpty(); - }, + object.traverse( function ( node ) { - clampPoint: function ( point, optionalTarget ) { + var geometry = node.geometry; - var result = optionalTarget || new Vector3(); - return result.copy( point ).clamp( this.min, this.max ); + if ( geometry !== undefined ) { - }, + if ( (geometry && geometry.isGeometry) ) { - distanceToPoint: function () { + var vertices = geometry.vertices; - var v1 = new Vector3(); + for ( var i = 0, il = vertices.length; i < il; i ++ ) { - return function distanceToPoint( point ) { + v1.copy( vertices[ i ] ); + v1.applyMatrix4( node.matrixWorld ); - var clampedPoint = v1.copy( point ).clamp( this.min, this.max ); - return clampedPoint.sub( point ).length(); + scope.expandByPoint( v1 ); - }; + } - }(), + } else if ( (geometry && geometry.isBufferGeometry) ) { - getBoundingSphere: function () { + var attribute = geometry.attributes.position; - var v1 = new Vector3(); + if ( attribute !== undefined ) { - return function getBoundingSphere( optionalTarget ) { + var array, offset, stride; - var result = optionalTarget || new Sphere(); + if ( (attribute && attribute.isInterleavedBufferAttribute) ) { - result.center = this.center(); - result.radius = this.size( v1 ).length() * 0.5; + array = attribute.data.array; + offset = attribute.offset; + stride = attribute.data.stride; - return result; + } else { - }; + array = attribute.array; + offset = 0; + stride = 3; - }(), + } - intersect: function ( box ) { + for ( var i = offset, il = array.length; i < il; i += stride ) { - this.min.max( box.min ); - this.max.min( box.max ); + v1.fromArray( array, i ); + v1.applyMatrix4( node.matrixWorld ); - // 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(); + scope.expandByPoint( v1 ); - return this; + } - }, + } - union: function ( box ) { + } - this.min.min( box.min ); - this.max.max( box.max ); + } - return this; + } ); - }, + return this; - applyMatrix4: function () { + }; - var points = [ - new Vector3(), - new Vector3(), - new Vector3(), - new Vector3(), - new Vector3(), - new Vector3(), - new Vector3(), - new Vector3() - ]; + }(), - return function applyMatrix4( matrix ) { + clone: function () { - // transform of empty box is an empty box. - if( this.isEmpty() ) return this; + return new this.constructor().copy( this ); - // 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 ); + copy: function ( box ) { - return this; + this.min.copy( box.min ); + this.max.copy( box.max ); - }; + return this; - }(), + }, - translate: function ( offset ) { + makeEmpty: function () { - this.min.add( offset ); - this.max.add( offset ); + this.min.x = this.min.y = this.min.z = + Infinity; + this.max.x = this.max.y = this.max.z = - Infinity; - return this; + return this; - }, + }, - equals: function ( box ) { + isEmpty: function () { - return box.min.equals( this.min ) && box.max.equals( this.max ); + // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes - } + return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z ); - }; + }, - /** - * @author bhouston / http://clara.io - * @author mrdoob / http://mrdoob.com/ - */ + center: function ( optionalTarget ) { - function Sphere( center, radius ) { + var result = optionalTarget || new Vector3(); + return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); - this.center = ( center !== undefined ) ? center : new Vector3(); - this.radius = ( radius !== undefined ) ? radius : 0; + }, - }; + size: function ( optionalTarget ) { - Sphere.prototype = { + var result = optionalTarget || new Vector3(); + return result.subVectors( this.max, this.min ); - constructor: Sphere, + }, - set: function ( center, radius ) { + expandByPoint: function ( point ) { - this.center.copy( center ); - this.radius = radius; + this.min.min( point ); + this.max.max( point ); - return this; + return this; - }, + }, - setFromPoints: function () { + expandByVector: function ( vector ) { - var box = new Box3(); + this.min.sub( vector ); + this.max.add( vector ); - return function setFromPoints( points, optionalCenter ) { + return this; - var center = this.center; + }, - if ( optionalCenter !== undefined ) { + expandByScalar: function ( scalar ) { - center.copy( optionalCenter ); + this.min.addScalar( - scalar ); + this.max.addScalar( scalar ); - } else { + return this; - box.setFromPoints( points ).center( center ); + }, - } + containsPoint: function ( point ) { - var maxRadiusSq = 0; + 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 ) { - for ( var i = 0, il = points.length; i < il; i ++ ) { + return false; - maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) ); + } - } + return true; - this.radius = Math.sqrt( maxRadiusSq ); + }, - 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; - clone: function () { + } - return new this.constructor().copy( this ); + return false; - }, + }, - copy: function ( sphere ) { + getParameter: function ( point, optionalTarget ) { - this.center.copy( sphere.center ); - this.radius = sphere.radius; + // This can potentially have a divide by zero if the box + // has a size dimension of 0. - return this; + var result = optionalTarget || new Vector3(); - }, + 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 ) + ); - empty: function () { + }, - return ( this.radius <= 0 ); + intersectsBox: function ( box ) { - }, + // using 6 splitting planes to rule out intersections. - containsPoint: function ( point ) { + 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 ) { - return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) ); + return false; - }, + } - distanceToPoint: function ( point ) { + return true; - return ( point.distanceTo( this.center ) - this.radius ); + }, - }, + intersectsSphere: ( function () { - intersectsSphere: function ( sphere ) { + var closestPoint; - var radiusSum = this.radius + sphere.radius; + return function intersectsSphere( sphere ) { - return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum ); + if ( closestPoint === undefined ) closestPoint = new Vector3(); - }, + // Find the point on the AABB closest to the sphere center. + this.clampPoint( sphere.center, closestPoint ); - intersectsBox: function ( box ) { + // If that point is inside the sphere, the AABB and sphere intersect. + return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius ); - return box.intersectsSphere( this ); + }; - }, + } )(), - intersectsPlane: function ( plane ) { + 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. + // 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. - return Math.abs( this.center.dot( plane.normal ) - plane.constant ) <= this.radius; + var min, max; - }, + if ( plane.normal.x > 0 ) { - clampPoint: function ( point, optionalTarget ) { + min = plane.normal.x * this.min.x; + max = plane.normal.x * this.max.x; - var deltaLengthSq = this.center.distanceToSquared( point ); + } else { - var result = optionalTarget || new Vector3(); + min = plane.normal.x * this.max.x; + max = plane.normal.x * this.min.x; - result.copy( point ); + } - if ( deltaLengthSq > ( this.radius * this.radius ) ) { + if ( plane.normal.y > 0 ) { - result.sub( this.center ).normalize(); - result.multiplyScalar( this.radius ).add( this.center ); + min += plane.normal.y * this.min.y; + max += plane.normal.y * this.max.y; - } + } else { - return result; + min += plane.normal.y * this.max.y; + max += plane.normal.y * this.min.y; - }, + } - getBoundingBox: function ( optionalTarget ) { + if ( plane.normal.z > 0 ) { - var box = optionalTarget || new Box3(); + min += plane.normal.z * this.min.z; + max += plane.normal.z * this.max.z; - box.set( this.center, this.center ); - box.expandByScalar( this.radius ); + } else { - return box; + min += plane.normal.z * this.max.z; + max += plane.normal.z * this.min.z; - }, + } - applyMatrix4: function ( matrix ) { + return ( min <= plane.constant && max >= plane.constant ); - this.center.applyMatrix4( matrix ); - this.radius = this.radius * matrix.getMaxScaleOnAxis(); + }, - return this; + clampPoint: function ( point, optionalTarget ) { - }, + var result = optionalTarget || new Vector3(); + return result.copy( point ).clamp( this.min, this.max ); - translate: function ( offset ) { + }, - this.center.add( offset ); + distanceToPoint: function () { - return this; + var v1 = new Vector3(); - }, + return function distanceToPoint( point ) { - equals: function ( sphere ) { + var clampedPoint = v1.copy( point ).clamp( this.min, this.max ); + return clampedPoint.sub( point ).length(); - return sphere.center.equals( this.center ) && ( sphere.radius === this.radius ); + }; - } + }(), - }; + getBoundingSphere: function () { - /** - * @author alteredq / http://alteredqualia.com/ - * @author WestLangley / http://github.com/WestLangley - * @author bhouston / http://clara.io - * @author tschw - */ + var v1 = new Vector3(); - function Matrix3() { + return function getBoundingSphere( optionalTarget ) { - this.elements = new Float32Array( [ + var result = optionalTarget || new Sphere(); - 1, 0, 0, - 0, 1, 0, - 0, 0, 1 + result.center = this.center(); + result.radius = this.size( v1 ).length() * 0.5; - ] ); + return result; - if ( arguments.length > 0 ) { + }; - console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' ); + }(), - } + intersect: function ( box ) { - }; + this.min.max( box.min ); + this.max.min( box.max ); - Matrix3.prototype = { + // 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(); - constructor: Matrix3, + return this; - isMatrix3: true, + }, - set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) { + union: function ( box ) { - var te = this.elements; + this.min.min( box.min ); + this.max.max( box.max ); - 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; + return this; - return this; + }, - }, + applyMatrix4: function () { - identity: function () { + var points = [ + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3() + ]; - this.set( + return function applyMatrix4( matrix ) { - 1, 0, 0, - 0, 1, 0, - 0, 0, 1 + // transform of empty box is an empty box. + if( this.isEmpty() ) return this; - ); + // 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 - return this; + this.setFromPoints( points ); - }, + return this; - clone: function () { + }; - return new this.constructor().fromArray( this.elements ); + }(), - }, + translate: function ( offset ) { - copy: function ( m ) { + this.min.add( offset ); + this.max.add( offset ); - var me = m.elements; + return this; - this.set( + }, - me[ 0 ], me[ 3 ], me[ 6 ], - me[ 1 ], me[ 4 ], me[ 7 ], - me[ 2 ], me[ 5 ], me[ 8 ] + equals: function ( box ) { - ); + return box.min.equals( this.min ) && box.max.equals( this.max ); - return this; + } - }, + }; - setFromMatrix4: function( m ) { + /** + * @author bhouston / http://clara.io + * @author mrdoob / http://mrdoob.com/ + */ - var me = m.elements; + function Sphere( center, radius ) { - this.set( + this.center = ( center !== undefined ) ? center : new Vector3(); + this.radius = ( radius !== undefined ) ? radius : 0; - me[ 0 ], me[ 4 ], me[ 8 ], - me[ 1 ], me[ 5 ], me[ 9 ], - me[ 2 ], me[ 6 ], me[ 10 ] + }; - ); + Sphere.prototype = { - return this; + constructor: Sphere, - }, + set: function ( center, radius ) { - applyToVector3Array: function () { + this.center.copy( center ); + this.radius = radius; - var v1; + return this; - return function applyToVector3Array( array, offset, length ) { + }, - if ( v1 === undefined ) v1 = new Vector3(); - if ( offset === undefined ) offset = 0; - if ( length === undefined ) length = array.length; + setFromPoints: function () { - for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) { + var box = new Box3(); - v1.fromArray( array, j ); - v1.applyMatrix3( this ); - v1.toArray( array, j ); + return function setFromPoints( points, optionalCenter ) { - } + var center = this.center; - return array; + if ( optionalCenter !== undefined ) { - }; + center.copy( optionalCenter ); - }(), + } else { - applyToBuffer: function () { + box.setFromPoints( points ).center( center ); - var v1; + } - return function applyToBuffer( buffer, offset, length ) { + var maxRadiusSq = 0; - if ( v1 === undefined ) v1 = new Vector3(); - if ( offset === undefined ) offset = 0; - if ( length === undefined ) length = buffer.length / buffer.itemSize; + for ( var i = 0, il = points.length; i < il; i ++ ) { - for ( var i = 0, j = offset; i < length; i ++, j ++ ) { + maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) ); - v1.x = buffer.getX( j ); - v1.y = buffer.getY( j ); - v1.z = buffer.getZ( j ); + } - v1.applyMatrix3( this ); + this.radius = Math.sqrt( maxRadiusSq ); - buffer.setXYZ( v1.x, v1.y, v1.z ); + return this; - } + }; - return buffer; + }(), - }; + clone: function () { - }(), + return new this.constructor().copy( this ); - multiplyScalar: function ( s ) { + }, - var te = this.elements; + copy: function ( sphere ) { - 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; + this.center.copy( sphere.center ); + this.radius = sphere.radius; - return this; + return this; - }, + }, - determinant: function () { + empty: function () { - var te = this.elements; + return ( this.radius <= 0 ); - 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; + containsPoint: function ( point ) { - }, + return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) ); - getInverse: function ( matrix, throwOnDegenerate ) { + }, - if ( (matrix && matrix.isMatrix4) ) { + distanceToPoint: function ( point ) { - console.error( "THREE.Matrix3.getInverse no longer takes a Matrix4 argument." ); + return ( point.distanceTo( this.center ) - this.radius ); - } + }, - var me = matrix.elements, - te = this.elements, + intersectsSphere: function ( sphere ) { - 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 ], + var radiusSum = this.radius + sphere.radius; - t11 = n33 * n22 - n32 * n23, - t12 = n32 * n13 - n33 * n12, - t13 = n23 * n12 - n22 * n13, + return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum ); - det = n11 * t11 + n21 * t12 + n31 * t13; + }, - if ( det === 0 ) { + intersectsBox: function ( box ) { - var msg = "THREE.Matrix3.getInverse(): can't invert matrix, determinant is 0"; + return box.intersectsSphere( this ); - if ( throwOnDegenerate || false ) {} else { + }, - console.warn( msg ); + 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 this.identity(); - } + return Math.abs( this.center.dot( plane.normal ) - plane.constant ) <= this.radius; - var detInv = 1 / det; + }, - te[ 0 ] = t11 * detInv; - te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv; - te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv; + clampPoint: function ( point, optionalTarget ) { - te[ 3 ] = t12 * detInv; - te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv; - te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv; + var deltaLengthSq = this.center.distanceToSquared( point ); - te[ 6 ] = t13 * detInv; - te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv; - te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv; + var result = optionalTarget || new Vector3(); - return this; + result.copy( point ); - }, + if ( deltaLengthSq > ( this.radius * this.radius ) ) { - transpose: function () { + result.sub( this.center ).normalize(); + result.multiplyScalar( this.radius ).add( this.center ); - 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; + return result; - return this; + }, - }, + getBoundingBox: function ( optionalTarget ) { - flattenToArrayOffset: function ( array, offset ) { + var box = optionalTarget || new Box3(); - console.warn( "THREE.Matrix3: .flattenToArrayOffset is deprecated " + - "- just use .toArray instead." ); + box.set( this.center, this.center ); + box.expandByScalar( this.radius ); - return this.toArray( array, offset ); + return box; - }, + }, - getNormalMatrix: function ( matrix4 ) { + applyMatrix4: function ( matrix ) { - return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose(); + this.center.applyMatrix4( matrix ); + this.radius = this.radius * matrix.getMaxScaleOnAxis(); - }, + return this; - transposeIntoArray: function ( r ) { + }, - var m = this.elements; + translate: function ( offset ) { - 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 ]; + this.center.add( offset ); - return this; + return this; - }, + }, - fromArray: function ( array ) { + equals: function ( sphere ) { - this.elements.set( array ); + return sphere.center.equals( this.center ) && ( sphere.radius === this.radius ); - return this; + } - }, + }; - toArray: function ( array, offset ) { + /** + * @author alteredq / http://alteredqualia.com/ + * @author WestLangley / http://github.com/WestLangley + * @author bhouston / http://clara.io + * @author tschw + */ - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + function Matrix3() { - var te = this.elements; + this.elements = new Float32Array( [ - array[ offset ] = te[ 0 ]; - array[ offset + 1 ] = te[ 1 ]; - array[ offset + 2 ] = te[ 2 ]; + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 - array[ offset + 3 ] = te[ 3 ]; - array[ offset + 4 ] = te[ 4 ]; - array[ offset + 5 ] = te[ 5 ]; + ] ); - array[ offset + 6 ] = te[ 6 ]; - array[ offset + 7 ] = te[ 7 ]; - array[ offset + 8 ] = te[ 8 ]; + if ( arguments.length > 0 ) { - return array; + console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' ); - } + } - }; + }; - /** - * @author bhouston / http://clara.io - */ + Matrix3.prototype = { - function Plane( normal, constant ) { + constructor: Matrix3, - this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 ); - this.constant = ( constant !== undefined ) ? constant : 0; + isMatrix3: true, - }; + set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) { - Plane.prototype = { + var te = this.elements; - constructor: Plane, + 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; - set: function ( normal, constant ) { + return this; - this.normal.copy( normal ); - this.constant = constant; + }, - return this; + identity: function () { - }, + this.set( - setComponents: function ( x, y, z, w ) { + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 - this.normal.set( x, y, z ); - this.constant = w; + ); - return this; + return this; - }, + }, - setFromNormalAndCoplanarPoint: function ( normal, point ) { + clone: function () { - this.normal.copy( normal ); - this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized + return new this.constructor().fromArray( this.elements ); - return this; + }, - }, + copy: function ( m ) { - setFromCoplanarPoints: function () { + var me = m.elements; - var v1 = new Vector3(); - var v2 = new Vector3(); + this.set( - return function setFromCoplanarPoints( a, b, c ) { + me[ 0 ], me[ 3 ], me[ 6 ], + me[ 1 ], me[ 4 ], me[ 7 ], + me[ 2 ], me[ 5 ], me[ 8 ] - 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)? + return this; - this.setFromNormalAndCoplanarPoint( normal, a ); + }, - return this; + setFromMatrix4: function( m ) { - }; + var me = m.elements; - }(), + this.set( - clone: function () { + me[ 0 ], me[ 4 ], me[ 8 ], + me[ 1 ], me[ 5 ], me[ 9 ], + me[ 2 ], me[ 6 ], me[ 10 ] - return new this.constructor().copy( this ); + ); - }, + return this; - copy: function ( plane ) { + }, - this.normal.copy( plane.normal ); - this.constant = plane.constant; + applyToVector3Array: function () { - return this; + var v1; - }, + return function applyToVector3Array( array, offset, length ) { - normalize: function () { + if ( v1 === undefined ) v1 = new Vector3(); + if ( offset === undefined ) offset = 0; + if ( length === undefined ) length = array.length; - // Note: will lead to a divide by zero if the plane is invalid. + for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) { - var inverseNormalLength = 1.0 / this.normal.length(); - this.normal.multiplyScalar( inverseNormalLength ); - this.constant *= inverseNormalLength; + v1.fromArray( array, j ); + v1.applyMatrix3( this ); + v1.toArray( array, j ); - return this; + } - }, + return array; - negate: function () { + }; - this.constant *= - 1; - this.normal.negate(); + }(), - return this; + applyToBuffer: function () { - }, + var v1; - distanceToPoint: function ( point ) { + return function applyToBuffer( buffer, offset, length ) { - return this.normal.dot( point ) + this.constant; + 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 ++ ) { - distanceToSphere: function ( sphere ) { + v1.x = buffer.getX( j ); + v1.y = buffer.getY( j ); + v1.z = buffer.getZ( j ); - return this.distanceToPoint( sphere.center ) - sphere.radius; + v1.applyMatrix3( this ); - }, + buffer.setXYZ( v1.x, v1.y, v1.z ); - projectPoint: function ( point, optionalTarget ) { + } - return this.orthoPoint( point, optionalTarget ).sub( point ).negate(); + return buffer; - }, + }; - orthoPoint: function ( point, optionalTarget ) { + }(), - var perpendicularMagnitude = this.distanceToPoint( point ); + multiplyScalar: function ( s ) { - var result = optionalTarget || new Vector3(); - return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude ); + var te = this.elements; - }, + 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; - intersectLine: function () { + return this; - var v1 = new Vector3(); + }, - return function intersectLine( line, optionalTarget ) { + determinant: function () { - var result = optionalTarget || new Vector3(); + var te = this.elements; - var direction = line.delta( v1 ); + 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 ]; - var denominator = this.normal.dot( direction ); + return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g; - if ( denominator === 0 ) { + }, - // line is coplanar, return origin - if ( this.distanceToPoint( line.start ) === 0 ) { + getInverse: function ( matrix, throwOnDegenerate ) { - return result.copy( line.start ); + if ( (matrix && matrix.isMatrix4) ) { - } + console.error( "THREE.Matrix3.getInverse no longer takes a Matrix4 argument." ); - // Unsure if this is the correct method to handle this case. - return undefined; + } - } + var me = matrix.elements, + te = this.elements, - var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator; + 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 ], - if ( t < 0 || t > 1 ) { + t11 = n33 * n22 - n32 * n23, + t12 = n32 * n13 - n33 * n12, + t13 = n23 * n12 - n22 * n13, - return undefined; + det = n11 * t11 + n21 * t12 + n31 * t13; - } + if ( det === 0 ) { - return result.copy( direction ).multiplyScalar( t ).add( line.start ); + var msg = "THREE.Matrix3.getInverse(): can't invert matrix, determinant is 0"; - }; + if ( throwOnDegenerate || false ) {} else { - }(), + console.warn( msg ); - intersectsLine: function ( line ) { + } - // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it. + return this.identity(); + } - var startSign = this.distanceToPoint( line.start ); - var endSign = this.distanceToPoint( line.end ); + var detInv = 1 / det; - return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 ); + 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; - intersectsBox: function ( box ) { + te[ 6 ] = t13 * detInv; + te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv; + te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv; - return box.intersectsPlane( this ); + return this; - }, + }, - intersectsSphere: function ( sphere ) { + transpose: function () { - return sphere.intersectsPlane( 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; - coplanarPoint: function ( optionalTarget ) { + return this; - var result = optionalTarget || new Vector3(); - return result.copy( this.normal ).multiplyScalar( - this.constant ); + }, - }, + flattenToArrayOffset: function ( array, offset ) { - applyMatrix4: function () { + console.warn( "THREE.Matrix3: .flattenToArrayOffset is deprecated " + + "- just use .toArray instead." ); - var v1 = new Vector3(); - var m1 = new Matrix3(); + return this.toArray( array, offset ); - return function applyMatrix4( matrix, optionalNormalMatrix ) { + }, - var referencePoint = this.coplanarPoint( v1 ).applyMatrix4( matrix ); + getNormalMatrix: function ( matrix4 ) { - // 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 this.setFromMatrix4( matrix4 ).getInverse( this ).transpose(); - // recalculate constant (like in setFromNormalAndCoplanarPoint) - this.constant = - referencePoint.dot( normal ); + }, - return this; + transposeIntoArray: function ( r ) { - }; + var m = this.elements; - }(), + 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 ]; - translate: function ( offset ) { + return this; - this.constant = this.constant - offset.dot( this.normal ); + }, - return this; + fromArray: function ( array ) { - }, + this.elements.set( array ); - equals: function ( plane ) { + return this; - return plane.normal.equals( this.normal ) && ( plane.constant === this.constant ); + }, - } + toArray: function ( array, offset ) { - }; + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * @author bhouston / http://clara.io - */ + var te = this.elements; - function Frustum( p0, p1, p2, p3, p4, p5 ) { + array[ offset ] = te[ 0 ]; + array[ offset + 1 ] = te[ 1 ]; + array[ offset + 2 ] = te[ 2 ]; - this.planes = [ + array[ offset + 3 ] = te[ 3 ]; + array[ offset + 4 ] = te[ 4 ]; + array[ offset + 5 ] = te[ 5 ]; - ( 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() + array[ offset + 6 ] = te[ 6 ]; + array[ offset + 7 ] = te[ 7 ]; + array[ offset + 8 ] = te[ 8 ]; - ]; + return array; - }; + } - Frustum.prototype = { + }; - constructor: Frustum, + /** + * @author bhouston / http://clara.io + */ - set: function ( p0, p1, p2, p3, p4, p5 ) { + function Plane( normal, constant ) { - var planes = this.planes; + this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 ); + this.constant = ( constant !== undefined ) ? constant : 0; - 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; + Plane.prototype = { - }, + constructor: Plane, - clone: function () { + set: function ( normal, constant ) { - return new this.constructor().copy( this ); + this.normal.copy( normal ); + this.constant = constant; - }, + return this; - copy: function ( frustum ) { + }, - var planes = this.planes; + setComponents: function ( x, y, z, w ) { - for ( var i = 0; i < 6; i ++ ) { + this.normal.set( x, y, z ); + this.constant = w; - planes[ i ].copy( frustum.planes[ i ] ); + return this; - } + }, - return this; + setFromNormalAndCoplanarPoint: function ( normal, point ) { - }, + this.normal.copy( normal ); + this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized - setFromMatrix: function ( m ) { + return this; - 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(); + setFromCoplanarPoints: function () { - return this; + var v1 = new Vector3(); + var v2 = new Vector3(); - }, + return function setFromCoplanarPoints( a, b, c ) { - intersectsObject: function () { + var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize(); - var sphere = new Sphere(); + // Q: should an error be thrown if normal is zero (e.g. degenerate plane)? - return function intersectsObject( object ) { + this.setFromNormalAndCoplanarPoint( normal, a ); - var geometry = object.geometry; + return this; - if ( geometry.boundingSphere === null ) - geometry.computeBoundingSphere(); + }; - sphere.copy( geometry.boundingSphere ) - .applyMatrix4( object.matrixWorld ); + }(), - return this.intersectsSphere( sphere ); + clone: function () { - }; + return new this.constructor().copy( this ); - }(), + }, - intersectsSprite: function () { + copy: function ( plane ) { - var sphere = new Sphere(); + this.normal.copy( plane.normal ); + this.constant = plane.constant; - return function intersectsSprite( sprite ) { + return this; - sphere.center.set( 0, 0, 0 ); - sphere.radius = 0.7071067811865476; - sphere.applyMatrix4( sprite.matrixWorld ); + }, - return this.intersectsSphere( sphere ); + normalize: function () { - }; + // Note: will lead to a divide by zero if the plane is invalid. - }(), + var inverseNormalLength = 1.0 / this.normal.length(); + this.normal.multiplyScalar( inverseNormalLength ); + this.constant *= inverseNormalLength; - intersectsSphere: function ( sphere ) { + return this; - var planes = this.planes; - var center = sphere.center; - var negRadius = - sphere.radius; + }, - for ( var i = 0; i < 6; i ++ ) { + negate: function () { - var distance = planes[ i ].distanceToPoint( center ); + this.constant *= - 1; + this.normal.negate(); - if ( distance < negRadius ) { + return this; - return false; + }, - } + distanceToPoint: function ( point ) { - } + return this.normal.dot( point ) + this.constant; - return true; + }, - }, + distanceToSphere: function ( sphere ) { - intersectsBox: function () { + return this.distanceToPoint( sphere.center ) - sphere.radius; - var p1 = new Vector3(), - p2 = new Vector3(); + }, - return function intersectsBox( box ) { + projectPoint: function ( point, optionalTarget ) { - var planes = this.planes; + return this.orthoPoint( point, optionalTarget ).sub( point ).negate(); - for ( var i = 0; i < 6 ; i ++ ) { + }, - var plane = planes[ i ]; + orthoPoint: function ( point, 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 perpendicularMagnitude = this.distanceToPoint( point ); - var d1 = plane.distanceToPoint( p1 ); - var d2 = plane.distanceToPoint( p2 ); + var result = optionalTarget || new Vector3(); + return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude ); - // if both outside plane, no intersection + }, - if ( d1 < 0 && d2 < 0 ) { + intersectLine: function () { - return false; + var v1 = new Vector3(); - } + return function intersectLine( line, optionalTarget ) { - } + var result = optionalTarget || new Vector3(); - return true; + var direction = line.delta( v1 ); - }; + var denominator = this.normal.dot( direction ); - }(), + if ( denominator === 0 ) { + // line is coplanar, return origin + if ( this.distanceToPoint( line.start ) === 0 ) { - containsPoint: function ( point ) { + return result.copy( line.start ); - var planes = this.planes; + } - for ( var i = 0; i < 6; i ++ ) { + // Unsure if this is the correct method to handle this case. + return undefined; - if ( planes[ i ].distanceToPoint( point ) < 0 ) { + } - return false; + var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator; - } + if ( t < 0 || t > 1 ) { - } + return undefined; - return true; + } - } + return result.copy( direction ).multiplyScalar( t ).add( line.start ); - }; + }; - /** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - */ + }(), - function WebGLShadowMap( _renderer, _lights, _objects, capabilities ) { + intersectsLine: function ( line ) { - var _gl = _renderer.context, - _state = _renderer.state, - _frustum = new Frustum(), - _projScreenMatrix = new Matrix4(), + // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it. - _lightShadows = _lights.shadows, + var startSign = this.distanceToPoint( line.start ); + var endSign = this.distanceToPoint( line.end ); - _shadowMapSize = new Vector2(), - _maxShadowMapSize = new Vector2( capabilities.maxTextureSize, capabilities.maxTextureSize ), + return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 ); - _lookTarget = new Vector3(), - _lightPositionWorld = new Vector3(), + }, - _renderList = [], + intersectsBox: function ( box ) { - _MorphingFlag = 1, - _SkinningFlag = 2, + return box.intersectsPlane( this ); - _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1, + }, - _depthMaterials = new Array( _NumberOfMaterialVariants ), - _distanceMaterials = new Array( _NumberOfMaterialVariants ), + intersectsSphere: function ( sphere ) { - _materialCache = {}; + return sphere.intersectsPlane( this ); - 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 ) - ]; + }, - 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 ) - ]; + coplanarPoint: function ( optionalTarget ) { - var cube2DViewPorts = [ - new Vector4(), new Vector4(), new Vector4(), - new Vector4(), new Vector4(), new Vector4() - ]; + var result = optionalTarget || new Vector3(); + return result.copy( this.normal ).multiplyScalar( - this.constant ); - // init + }, - var depthMaterialTemplate = new MeshDepthMaterial(); - depthMaterialTemplate.depthPacking = RGBADepthPacking; - depthMaterialTemplate.clipping = true; + applyMatrix4: function () { - var distanceShader = exports.ShaderLib[ "distanceRGBA" ]; - var distanceUniforms = exports.UniformsUtils.clone( distanceShader.uniforms ); + var v1 = new Vector3(); + var m1 = new Matrix3(); - for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) { + return function applyMatrix4( matrix, optionalNormalMatrix ) { - var useMorphing = ( i & _MorphingFlag ) !== 0; - var useSkinning = ( i & _SkinningFlag ) !== 0; + var referencePoint = this.coplanarPoint( v1 ).applyMatrix4( matrix ); - var depthMaterial = depthMaterialTemplate.clone(); - depthMaterial.morphTargets = useMorphing; - depthMaterial.skinning = useSkinning; + // 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(); - _depthMaterials[ i ] = depthMaterial; + // recalculate constant (like in setFromNormalAndCoplanarPoint) + this.constant = - referencePoint.dot( normal ); - var distanceMaterial = new ShaderMaterial( { - defines: { - 'USE_SHADOWMAP': '' - }, - uniforms: distanceUniforms, - vertexShader: distanceShader.vertexShader, - fragmentShader: distanceShader.fragmentShader, - morphTargets: useMorphing, - skinning: useSkinning, - clipping: true - } ); + return this; - _distanceMaterials[ i ] = distanceMaterial; + }; - } + }(), - // + translate: function ( offset ) { - var scope = this; + this.constant = this.constant - offset.dot( this.normal ); - this.enabled = false; + return this; - this.autoUpdate = true; - this.needsUpdate = false; + }, - this.type = PCFShadowMap; + equals: function ( plane ) { - this.renderReverseSided = true; - this.renderSingleSided = true; + return plane.normal.equals( this.normal ) && ( plane.constant === this.constant ); - this.render = function ( scene, camera ) { + } - if ( scope.enabled === false ) return; - if ( scope.autoUpdate === false && scope.needsUpdate === false ) return; + }; - if ( _lightShadows.length === 0 ) return; + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * @author bhouston / http://clara.io + */ - // Set GL state for depth map. - _state.clearColor( 1, 1, 1, 1 ); - _state.disable( _gl.BLEND ); - _state.setDepthTest( true ); - _state.setScissorTest( false ); + function Frustum( p0, p1, p2, p3, p4, p5 ) { - // render depth map + this.planes = [ - var faceCount, isPointLight; + ( 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() - for ( var i = 0, il = _lightShadows.length; i < il; i ++ ) { + ]; - var light = _lightShadows[ i ]; - var shadow = light.shadow; + }; - if ( shadow === undefined ) { + Frustum.prototype = { - console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' ); - continue; + constructor: Frustum, - } + set: function ( p0, p1, p2, p3, p4, p5 ) { - var shadowCamera = shadow.camera; + var planes = this.planes; - _shadowMapSize.copy( shadow.mapSize ); - _shadowMapSize.min( _maxShadowMapSize ); + planes[ 0 ].copy( p0 ); + planes[ 1 ].copy( p1 ); + planes[ 2 ].copy( p2 ); + planes[ 3 ].copy( p3 ); + planes[ 4 ].copy( p4 ); + planes[ 5 ].copy( p5 ); - if ( (light && light.isPointLight) ) { + return this; - faceCount = 6; - isPointLight = true; + }, - var vpWidth = _shadowMapSize.x; - var vpHeight = _shadowMapSize.y; + clone: function () { - // 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 + return new this.constructor().copy( this ); - // 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 ); + }, - _shadowMapSize.x *= 4.0; - _shadowMapSize.y *= 2.0; + copy: function ( frustum ) { - } else { + var planes = this.planes; - faceCount = 1; - isPointLight = false; + for ( var i = 0; i < 6; i ++ ) { - } + planes[ i ].copy( frustum.planes[ i ] ); - if ( shadow.map === null ) { + } - var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat }; + return this; - shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars ); + }, - shadowCamera.updateProjectionMatrix(); + setFromMatrix: function ( m ) { - } + 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 ]; - if ( (shadow && shadow.isSpotLightShadow) ) { + 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(); - shadow.update( light ); + return this; - } + }, - var shadowMap = shadow.map; - var shadowMatrix = shadow.matrix; + intersectsObject: function () { - _lightPositionWorld.setFromMatrixPosition( light.matrixWorld ); - shadowCamera.position.copy( _lightPositionWorld ); + var sphere = new Sphere(); - _renderer.setRenderTarget( shadowMap ); - _renderer.clear(); + return function intersectsObject( object ) { - // render shadow map for each cube face (if omni-directional) or - // run a single pass if not + var geometry = object.geometry; - for ( var face = 0; face < faceCount; face ++ ) { + if ( geometry.boundingSphere === null ) + geometry.computeBoundingSphere(); - if ( isPointLight ) { + sphere.copy( geometry.boundingSphere ) + .applyMatrix4( object.matrixWorld ); - _lookTarget.copy( shadowCamera.position ); - _lookTarget.add( cubeDirections[ face ] ); - shadowCamera.up.copy( cubeUps[ face ] ); - shadowCamera.lookAt( _lookTarget ); + return this.intersectsSphere( sphere ); - var vpDimensions = cube2DViewPorts[ face ]; - _state.viewport( vpDimensions ); + }; - } else { + }(), - _lookTarget.setFromMatrixPosition( light.target.matrixWorld ); - shadowCamera.lookAt( _lookTarget ); + intersectsSprite: function () { - } + var sphere = new Sphere(); - shadowCamera.updateMatrixWorld(); - shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld ); + return function intersectsSprite( sprite ) { - // compute shadow matrix + sphere.center.set( 0, 0, 0 ); + sphere.radius = 0.7071067811865476; + sphere.applyMatrix4( sprite.matrixWorld ); - 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 this.intersectsSphere( sphere ); - shadowMatrix.multiply( shadowCamera.projectionMatrix ); - shadowMatrix.multiply( shadowCamera.matrixWorldInverse ); + }; - // update camera matrices and frustum + }(), - _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse ); - _frustum.setFromMatrix( _projScreenMatrix ); + intersectsSphere: function ( sphere ) { - // set object matrices & frustum culling + var planes = this.planes; + var center = sphere.center; + var negRadius = - sphere.radius; - _renderList.length = 0; + for ( var i = 0; i < 6; i ++ ) { - projectObject( scene, camera, shadowCamera ); + var distance = planes[ i ].distanceToPoint( center ); - // render shadow map - // render regular objects + if ( distance < negRadius ) { - for ( var j = 0, jl = _renderList.length; j < jl; j ++ ) { + return false; - var object = _renderList[ j ]; - var geometry = _objects.update( object ); - var material = object.material; + } - if ( (material && material.isMultiMaterial) ) { + } - var groups = geometry.groups; - var materials = material.materials; + return true; - for ( var k = 0, kl = groups.length; k < kl; k ++ ) { + }, - var group = groups[ k ]; - var groupMaterial = materials[ group.materialIndex ]; + intersectsBox: function () { - if ( groupMaterial.visible === true ) { + var p1 = new Vector3(), + p2 = new Vector3(); - var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld ); - _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group ); + return function intersectsBox( box ) { - } + var planes = this.planes; - } + for ( var i = 0; i < 6 ; i ++ ) { - } else { + var plane = planes[ i ]; - var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld ); - _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null ); + 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 ); - } + // if both outside plane, no intersection - } + if ( d1 < 0 && d2 < 0 ) { - } + return false; - // Restore GL state. - var clearColor = _renderer.getClearColor(), - clearAlpha = _renderer.getClearAlpha(); - _renderer.setClearColor( clearColor, clearAlpha ); + } - scope.needsUpdate = false; + } - }; + return true; - function getDepthMaterial( object, material, isPointLight, lightPositionWorld ) { + }; - var geometry = object.geometry; + }(), - var result = null; - var materialVariants = _depthMaterials; - var customMaterial = object.customDepthMaterial; + containsPoint: function ( point ) { - if ( isPointLight ) { + var planes = this.planes; - materialVariants = _distanceMaterials; - customMaterial = object.customDistanceMaterial; + for ( var i = 0; i < 6; i ++ ) { - } + if ( planes[ i ].distanceToPoint( point ) < 0 ) { - if ( ! customMaterial ) { + return false; - var useMorphing = false; + } - if ( material.morphTargets ) { + } - if ( (geometry && geometry.isBufferGeometry) ) { + return true; - useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0; + } - } else if ( (geometry && geometry.isGeometry) ) { + }; - useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0; + /** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + */ - } + function WebGLShadowMap( _renderer, _lights, _objects, capabilities ) { - } + var _gl = _renderer.context, + _state = _renderer.state, + _frustum = new Frustum(), + _projScreenMatrix = new Matrix4(), - var useSkinning = (object && object.isSkinnedMesh) && material.skinning; + _lightShadows = _lights.shadows, - var variantIndex = 0; + _shadowMapSize = new Vector2(), + _maxShadowMapSize = new Vector2( capabilities.maxTextureSize, capabilities.maxTextureSize ), - if ( useMorphing ) variantIndex |= _MorphingFlag; - if ( useSkinning ) variantIndex |= _SkinningFlag; + _lookTarget = new Vector3(), + _lightPositionWorld = new Vector3(), - result = materialVariants[ variantIndex ]; + _renderList = [], - } else { + _MorphingFlag = 1, + _SkinningFlag = 2, - result = customMaterial; + _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1, - } + _depthMaterials = new Array( _NumberOfMaterialVariants ), + _distanceMaterials = new Array( _NumberOfMaterialVariants ), - if ( _renderer.localClippingEnabled && - material.clipShadows === true && - material.clippingPlanes.length !== 0 ) { + _materialCache = {}; - // in this case we need a unique material instance reflecting the - // appropriate state + 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 ) + ]; - var keyA = result.uuid, keyB = material.uuid; + 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 materialsForVariant = _materialCache[ keyA ]; + var cube2DViewPorts = [ + new Vector4(), new Vector4(), new Vector4(), + new Vector4(), new Vector4(), new Vector4() + ]; - if ( materialsForVariant === undefined ) { + // init - materialsForVariant = {}; - _materialCache[ keyA ] = materialsForVariant; + var depthMaterialTemplate = new MeshDepthMaterial(); + depthMaterialTemplate.depthPacking = RGBADepthPacking; + depthMaterialTemplate.clipping = true; - } + var distanceShader = exports.ShaderLib[ "distanceRGBA" ]; + var distanceUniforms = exports.UniformsUtils.clone( distanceShader.uniforms ); - var cachedMaterial = materialsForVariant[ keyB ]; + for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) { - if ( cachedMaterial === undefined ) { + var useMorphing = ( i & _MorphingFlag ) !== 0; + var useSkinning = ( i & _SkinningFlag ) !== 0; - cachedMaterial = result.clone(); - materialsForVariant[ keyB ] = cachedMaterial; + var depthMaterial = depthMaterialTemplate.clone(); + depthMaterial.morphTargets = useMorphing; + depthMaterial.skinning = useSkinning; - } + _depthMaterials[ i ] = depthMaterial; - result = cachedMaterial; + var distanceMaterial = new ShaderMaterial( { + defines: { + 'USE_SHADOWMAP': '' + }, + uniforms: distanceUniforms, + vertexShader: distanceShader.vertexShader, + fragmentShader: distanceShader.fragmentShader, + morphTargets: useMorphing, + skinning: useSkinning, + clipping: true + } ); - } + _distanceMaterials[ i ] = distanceMaterial; - result.visible = material.visible; - result.wireframe = material.wireframe; + } - var side = material.side; + // - if ( scope.renderSingleSided && side == DoubleSide ) { + var scope = this; - side = FrontSide; + this.enabled = false; - } + this.autoUpdate = true; + this.needsUpdate = false; - if ( scope.renderReverseSided ) { + this.type = PCFShadowMap; - if ( side === FrontSide ) side = BackSide; - else if ( side === BackSide ) side = FrontSide; + this.renderReverseSided = true; + this.renderSingleSided = true; - } + this.render = function ( scene, camera ) { - result.side = side; + if ( scope.enabled === false ) return; + if ( scope.autoUpdate === false && scope.needsUpdate === false ) return; - result.clipShadows = material.clipShadows; - result.clippingPlanes = material.clippingPlanes; + if ( _lightShadows.length === 0 ) return; - result.wireframeLinewidth = material.wireframeLinewidth; - result.linewidth = material.linewidth; + // Set GL state for depth map. + _state.clearColor( 1, 1, 1, 1 ); + _state.disable( _gl.BLEND ); + _state.setDepthTest( true ); + _state.setScissorTest( false ); - if ( isPointLight && result.uniforms.lightPos !== undefined ) { + // render depth map - result.uniforms.lightPos.value.copy( lightPositionWorld ); + var faceCount, isPointLight; - } + for ( var i = 0, il = _lightShadows.length; i < il; i ++ ) { - return result; + var light = _lightShadows[ i ]; + var shadow = light.shadow; - } + if ( shadow === undefined ) { - function projectObject( object, camera, shadowCamera ) { + console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' ); + continue; - if ( object.visible === false ) return; + } - if ( object.layers.test( camera.layers ) && ( (object && object.isMesh) || (object && object.isLine) || (object && object.isPoints) ) ) { + var shadowCamera = shadow.camera; - if ( object.castShadow && ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) ) { + _shadowMapSize.copy( shadow.mapSize ); + _shadowMapSize.min( _maxShadowMapSize ); - var material = object.material; + if ( (light && light.isPointLight) ) { - if ( material.visible === true ) { + faceCount = 6; + isPointLight = true; - object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld ); - _renderList.push( object ); + var vpWidth = _shadowMapSize.x; + var vpHeight = _shadowMapSize.y; - } + // 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 - } + // 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 ); - } + _shadowMapSize.x *= 4.0; + _shadowMapSize.y *= 2.0; - var children = object.children; + } else { - for ( var i = 0, l = children.length; i < l; i ++ ) { + faceCount = 1; + isPointLight = false; - projectObject( children[ i ], camera, shadowCamera ); + } - } + if ( shadow.map === null ) { - } + var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat }; - }; + shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars ); - exports.WebGLShader = ( function () { + shadowCamera.updateProjectionMatrix(); - function addLineNumbers( string ) { + } - var lines = string.split( '\n' ); + if ( (shadow && shadow.isSpotLightShadow) ) { - for ( var i = 0; i < lines.length; i ++ ) { + shadow.update( light ); - lines[ i ] = ( i + 1 ) + ': ' + lines[ i ]; + } - } + var shadowMap = shadow.map; + var shadowMatrix = shadow.matrix; - return lines.join( '\n' ); + _lightPositionWorld.setFromMatrixPosition( light.matrixWorld ); + shadowCamera.position.copy( _lightPositionWorld ); - } + _renderer.setRenderTarget( shadowMap ); + _renderer.clear(); - return function WebGLShader( gl, type, string ) { + // render shadow map for each cube face (if omni-directional) or + // run a single pass if not - var shader = gl.createShader( type ); + for ( var face = 0; face < faceCount; face ++ ) { - gl.shaderSource( shader, string ); - gl.compileShader( shader ); + if ( isPointLight ) { - if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) { + _lookTarget.copy( shadowCamera.position ); + _lookTarget.add( cubeDirections[ face ] ); + shadowCamera.up.copy( cubeUps[ face ] ); + shadowCamera.lookAt( _lookTarget ); - console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' ); + var vpDimensions = cube2DViewPorts[ face ]; + _state.viewport( vpDimensions ); - } + } else { - if ( gl.getShaderInfoLog( shader ) !== '' ) { + _lookTarget.setFromMatrixPosition( light.target.matrixWorld ); + shadowCamera.lookAt( _lookTarget ); - console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) ); + } - } + shadowCamera.updateMatrixWorld(); + shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld ); - // --enable-privileged-webgl-extension - // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) ); + // compute shadow matrix - return shader; + 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 + ); - }; + shadowMatrix.multiply( shadowCamera.projectionMatrix ); + shadowMatrix.multiply( shadowCamera.matrixWorldInverse ); - } )(); + // update camera matrices and frustum - /** - * @author fordacious / fordacious.github.io - */ + _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse ); + _frustum.setFromMatrix( _projScreenMatrix ); - function WebGLProperties() { + // set object matrices & frustum culling - var properties = {}; + _renderList.length = 0; - this.get = function ( object ) { + projectObject( scene, camera, shadowCamera ); - var uuid = object.uuid; - var map = properties[ uuid ]; + // render shadow map + // render regular objects - if ( map === undefined ) { + for ( var j = 0, jl = _renderList.length; j < jl; j ++ ) { - map = {}; - properties[ uuid ] = map; + var object = _renderList[ j ]; + var geometry = _objects.update( object ); + var material = object.material; - } + if ( (material && material.isMultiMaterial) ) { - return map; + var groups = geometry.groups; + var materials = material.materials; - }; + for ( var k = 0, kl = groups.length; k < kl; k ++ ) { - this.delete = function ( object ) { + var group = groups[ k ]; + var groupMaterial = materials[ group.materialIndex ]; - delete properties[ object.uuid ]; + if ( groupMaterial.visible === true ) { - }; + var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld ); + _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group ); - this.clear = function () { + } - properties = {}; + } - }; + } else { - }; + var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld ); + _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null ); - exports.WebGLProgram = ( function () { + } - var programIdCount = 0; + } - function getEncodingComponents( encoding ) { + } - switch ( encoding ) { + } - 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 ); + // Restore GL state. + var clearColor = _renderer.getClearColor(), + clearAlpha = _renderer.getClearAlpha(); + _renderer.setClearColor( clearColor, clearAlpha ); - } + scope.needsUpdate = false; - } + }; - function getTexelDecodingFunction( functionName, encoding ) { + function getDepthMaterial( object, material, isPointLight, lightPositionWorld ) { - var components = getEncodingComponents( encoding ); - return "vec4 " + functionName + "( vec4 value ) { return " + components[ 0 ] + "ToLinear" + components[ 1 ] + "; }"; + var geometry = object.geometry; - } + var result = null; - function getTexelEncodingFunction( functionName, encoding ) { + var materialVariants = _depthMaterials; + var customMaterial = object.customDepthMaterial; - var components = getEncodingComponents( encoding ); - return "vec4 " + functionName + "( vec4 value ) { return LinearTo" + components[ 0 ] + components[ 1 ] + "; }"; + if ( isPointLight ) { - } + materialVariants = _distanceMaterials; + customMaterial = object.customDistanceMaterial; - function getToneMappingFunction( functionName, toneMapping ) { + } - var toneMappingName; + if ( ! customMaterial ) { - switch ( toneMapping ) { + var useMorphing = false; - case LinearToneMapping: - toneMappingName = "Linear"; - break; + if ( material.morphTargets ) { - case ReinhardToneMapping: - toneMappingName = "Reinhard"; - break; + if ( (geometry && geometry.isBufferGeometry) ) { - case Uncharted2ToneMapping: - toneMappingName = "Uncharted2"; - break; + useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0; - case CineonToneMapping: - toneMappingName = "OptimizedCineon"; - break; + } else if ( (geometry && geometry.isGeometry) ) { - default: - throw new Error( 'unsupported toneMapping: ' + toneMapping ); + useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0; - } + } - return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }"; + } - } + var useSkinning = (object && object.isSkinnedMesh) && material.skinning; - function generateExtensions( extensions, parameters, rendererExtensions ) { + var variantIndex = 0; - extensions = extensions || {}; + if ( useMorphing ) variantIndex |= _MorphingFlag; + if ( useSkinning ) variantIndex |= _SkinningFlag; - 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' : '', - ]; + result = materialVariants[ variantIndex ]; - return chunks.filter( filterEmptyLine ).join( '\n' ); + } else { - } + result = customMaterial; - function generateDefines( defines ) { + } - var chunks = []; + if ( _renderer.localClippingEnabled && + material.clipShadows === true && + material.clippingPlanes.length !== 0 ) { - for ( var name in defines ) { + // in this case we need a unique material instance reflecting the + // appropriate state - var value = defines[ name ]; + var keyA = result.uuid, keyB = material.uuid; - if ( value === false ) continue; + var materialsForVariant = _materialCache[ keyA ]; - chunks.push( '#define ' + name + ' ' + value ); + if ( materialsForVariant === undefined ) { - } + materialsForVariant = {}; + _materialCache[ keyA ] = materialsForVariant; - return chunks.join( '\n' ); + } - } + var cachedMaterial = materialsForVariant[ keyB ]; - function fetchAttributeLocations( gl, program, identifiers ) { + if ( cachedMaterial === undefined ) { - var attributes = {}; + cachedMaterial = result.clone(); + materialsForVariant[ keyB ] = cachedMaterial; - var n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES ); + } - for ( var i = 0; i < n; i ++ ) { + result = cachedMaterial; - var info = gl.getActiveAttrib( program, i ); - var name = info.name; + } - // console.log("THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:", name, i ); + result.visible = material.visible; + result.wireframe = material.wireframe; - attributes[ name ] = gl.getAttribLocation( program, name ); + var side = material.side; - } + if ( scope.renderSingleSided && side == DoubleSide ) { - return attributes; + side = FrontSide; - } + } - function filterEmptyLine( string ) { + if ( scope.renderReverseSided ) { - return string !== ''; + if ( side === FrontSide ) side = BackSide; + else if ( side === BackSide ) side = FrontSide; - } + } - function replaceLightNums( string, parameters ) { + result.side = side; - 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 ); + result.clipShadows = material.clipShadows; + result.clippingPlanes = material.clippingPlanes; - } + result.wireframeLinewidth = material.wireframeLinewidth; + result.linewidth = material.linewidth; - function parseIncludes( string ) { + if ( isPointLight && result.uniforms.lightPos !== undefined ) { - var pattern = /#include +<([\w\d.]+)>/g; + result.uniforms.lightPos.value.copy( lightPositionWorld ); - function replace( match, include ) { + } - var replace = ShaderChunk[ include ]; + return result; - if ( replace === undefined ) { + } - throw new Error( 'Can not resolve #include <' + include + '>' ); + function projectObject( object, camera, shadowCamera ) { - } + if ( object.visible === false ) return; - return parseIncludes( replace ); + if ( object.layers.test( camera.layers ) && ( (object && object.isMesh) || (object && object.isLine) || (object && object.isPoints) ) ) { - } + if ( object.castShadow && ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) ) { - return string.replace( pattern, replace ); + var material = object.material; - } + if ( material.visible === true ) { - function unrollLoops( string ) { + object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld ); + _renderList.push( object ); - var pattern = /for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g; + } - function replace( match, start, end, snippet ) { + } - var unroll = ''; + } - for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) { + var children = object.children; - unroll += snippet.replace( /\[ i \]/g, '[ ' + i + ' ]' ); + for ( var i = 0, l = children.length; i < l; i ++ ) { - } + projectObject( children[ i ], camera, shadowCamera ); - return unroll; + } - } + } - return string.replace( pattern, replace ); + }; - } + exports.WebGLShader = ( function () { - return function WebGLProgram( renderer, code, material, parameters ) { + function addLineNumbers( string ) { - var gl = renderer.context; + var lines = string.split( '\n' ); - var extensions = material.extensions; - var defines = material.defines; + for ( var i = 0; i < lines.length; i ++ ) { - var vertexShader = material.__webglShader.vertexShader; - var fragmentShader = material.__webglShader.fragmentShader; + lines[ i ] = ( i + 1 ) + ': ' + lines[ i ]; - var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC'; + } - if ( parameters.shadowMapType === PCFShadowMap ) { + return lines.join( '\n' ); - shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF'; + } - } else if ( parameters.shadowMapType === PCFSoftShadowMap ) { + return function WebGLShader( gl, type, string ) { - shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT'; + var shader = gl.createShader( type ); - } + gl.shaderSource( shader, string ); + gl.compileShader( shader ); - var envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; - var envMapModeDefine = 'ENVMAP_MODE_REFLECTION'; - var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY'; + if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) { - if ( parameters.envMap ) { + console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' ); - switch ( material.envMap.mapping ) { + } - case CubeReflectionMapping: - case CubeRefractionMapping: - envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; - break; + if ( gl.getShaderInfoLog( shader ) !== '' ) { - case CubeUVReflectionMapping: - case CubeUVRefractionMapping: - envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV'; - break; + console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) ); - case EquirectangularReflectionMapping: - case EquirectangularRefractionMapping: - envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC'; - break; + } - case SphericalReflectionMapping: - envMapTypeDefine = 'ENVMAP_TYPE_SPHERE'; - break; + // --enable-privileged-webgl-extension + // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) ); - } + return shader; - switch ( material.envMap.mapping ) { + }; - case CubeRefractionMapping: - case EquirectangularRefractionMapping: - envMapModeDefine = 'ENVMAP_MODE_REFRACTION'; - break; + } )(); - } + /** + * @author fordacious / fordacious.github.io + */ - switch ( material.combine ) { + function WebGLProperties() { - case MultiplyOperation: - envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY'; - break; + var properties = {}; - case MixOperation: - envMapBlendingDefine = 'ENVMAP_BLENDING_MIX'; - break; + this.get = function ( object ) { - case AddOperation: - envMapBlendingDefine = 'ENVMAP_BLENDING_ADD'; - break; + var uuid = object.uuid; + var map = properties[ uuid ]; - } + if ( map === undefined ) { - } + map = {}; + properties[ uuid ] = map; - var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0; + } - // console.log( 'building new program ' ); + return map; - // + }; - var customExtensions = generateExtensions( extensions, parameters, renderer.extensions ); + this.delete = function ( object ) { - var customDefines = generateDefines( defines ); + delete properties[ object.uuid ]; - // + }; - var program = gl.createProgram(); + this.clear = function () { - var prefixVertex, prefixFragment; + properties = {}; - if ( (material && material.isRawShaderMaterial) ) { + }; - prefixVertex = [ + }; - customDefines + exports.WebGLProgram = ( function () { - ].filter( filterEmptyLine ).join( '\n' ); + var programIdCount = 0; - prefixFragment = [ + function getEncodingComponents( encoding ) { - customDefines + switch ( encoding ) { - ].filter( filterEmptyLine ).join( '\n' ); + 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 ); - } else { + } - prefixVertex = [ + } - 'precision ' + parameters.precision + ' float;', - 'precision ' + parameters.precision + ' int;', + function getTexelDecodingFunction( functionName, encoding ) { - '#define SHADER_NAME ' + material.__webglShader.name, + var components = getEncodingComponents( encoding ); + return "vec4 " + functionName + "( vec4 value ) { return " + components[ 0 ] + "ToLinear" + components[ 1 ] + "; }"; - customDefines, + } - parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', + function getTexelEncodingFunction( functionName, encoding ) { - '#define GAMMA_FACTOR ' + gammaFactorDefine, + var components = getEncodingComponents( encoding ); + return "vec4 " + functionName + "( vec4 value ) { return LinearTo" + components[ 0 ] + components[ 1 ] + "; }"; - '#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' : '', + function getToneMappingFunction( functionName, toneMapping ) { - parameters.flatShading ? '#define FLAT_SHADED' : '', + var toneMappingName; - parameters.skinning ? '#define USE_SKINNING' : '', - parameters.useVertexTexture ? '#define BONE_TEXTURE' : '', + switch ( toneMapping ) { - parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', - parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', - parameters.doubleSided ? '#define DOUBLE_SIDED' : '', - parameters.flipSided ? '#define FLIP_SIDED' : '', + case LinearToneMapping: + toneMappingName = "Linear"; + break; - '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes, + case ReinhardToneMapping: + toneMappingName = "Reinhard"; + break; - parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', - parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', + case Uncharted2ToneMapping: + toneMappingName = "Uncharted2"; + break; - parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '', + case CineonToneMapping: + toneMappingName = "OptimizedCineon"; + break; - parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', - parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '', + default: + throw new Error( 'unsupported toneMapping: ' + toneMapping ); - '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;', + return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }"; - '#ifdef USE_COLOR', + } - ' attribute vec3 color;', + function generateExtensions( extensions, parameters, rendererExtensions ) { - '#endif', + extensions = extensions || {}; - '#ifdef USE_MORPHTARGETS', + 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' : '', + ]; - ' attribute vec3 morphTarget0;', - ' attribute vec3 morphTarget1;', - ' attribute vec3 morphTarget2;', - ' attribute vec3 morphTarget3;', + return chunks.filter( filterEmptyLine ).join( '\n' ); - ' #ifdef USE_MORPHNORMALS', + } - ' attribute vec3 morphNormal0;', - ' attribute vec3 morphNormal1;', - ' attribute vec3 morphNormal2;', - ' attribute vec3 morphNormal3;', + function generateDefines( defines ) { - ' #else', + var chunks = []; - ' attribute vec3 morphTarget4;', - ' attribute vec3 morphTarget5;', - ' attribute vec3 morphTarget6;', - ' attribute vec3 morphTarget7;', + for ( var name in defines ) { - ' #endif', + var value = defines[ name ]; - '#endif', + if ( value === false ) continue; - '#ifdef USE_SKINNING', + chunks.push( '#define ' + name + ' ' + value ); - ' attribute vec4 skinIndex;', - ' attribute vec4 skinWeight;', + } - '#endif', + return chunks.join( '\n' ); - '\n' + } - ].filter( filterEmptyLine ).join( '\n' ); + function fetchAttributeLocations( gl, program, identifiers ) { - prefixFragment = [ + var attributes = {}; - customExtensions, + var n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES ); - 'precision ' + parameters.precision + ' float;', - 'precision ' + parameters.precision + ' int;', + for ( var i = 0; i < n; i ++ ) { - '#define SHADER_NAME ' + material.__webglShader.name, + var info = gl.getActiveAttrib( program, i ); + var name = info.name; - customDefines, + // console.log("THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:", name, i ); - parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '', + attributes[ name ] = gl.getAttribLocation( program, name ); - '#define GAMMA_FACTOR ' + gammaFactorDefine, + } - ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '', - ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '', + return attributes; - 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' : '', + function filterEmptyLine( string ) { - 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.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : '', + 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.physicallyCorrectLights ? "#define PHYSICALLY_CORRECT_LIGHTS" : '', + } - parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', - parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '', + function parseIncludes( string ) { - parameters.envMap && renderer.extensions.get( 'EXT_shader_texture_lod' ) ? '#define TEXTURE_LOD_EXT' : '', + var pattern = /#include +<([\w\d.]+)>/g; - 'uniform mat4 viewMatrix;', - 'uniform vec3 cameraPosition;', + function replace( match, include ) { - ( 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 ) : '', + var replace = ShaderChunk[ include ]; - ( 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 ) : '', + if ( replace === undefined ) { - parameters.depthPacking ? "#define DEPTH_PACKING " + material.depthPacking : '', + throw new Error( 'Can not resolve #include <' + include + '>' ); - '\n' + } - ].filter( filterEmptyLine ).join( '\n' ); + return parseIncludes( replace ); - } + } - vertexShader = parseIncludes( vertexShader, parameters ); - vertexShader = replaceLightNums( vertexShader, parameters ); + return string.replace( pattern, replace ); - fragmentShader = parseIncludes( fragmentShader, parameters ); - fragmentShader = replaceLightNums( fragmentShader, parameters ); + } - if ( (material && material.isShaderMaterial) === false ) { + function unrollLoops( string ) { - vertexShader = unrollLoops( vertexShader ); - fragmentShader = unrollLoops( fragmentShader ); + var pattern = /for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g; - } + function replace( match, start, end, snippet ) { - var vertexGlsl = prefixVertex + vertexShader; - var fragmentGlsl = prefixFragment + fragmentShader; + var unroll = ''; - // console.log( '*VERTEX*', vertexGlsl ); - // console.log( '*FRAGMENT*', fragmentGlsl ); + for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) { - var glVertexShader = exports.WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl ); - var glFragmentShader = exports.WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl ); + unroll += snippet.replace( /\[ i \]/g, '[ ' + i + ' ]' ); - gl.attachShader( program, glVertexShader ); - gl.attachShader( program, glFragmentShader ); + } - // Force a particular attribute to index 0. + return unroll; - if ( material.index0AttributeName !== undefined ) { + } - gl.bindAttribLocation( program, 0, material.index0AttributeName ); + return string.replace( pattern, replace ); - } else if ( parameters.morphTargets === true ) { + } - // programs with morphTargets displace position out of attribute 0 - gl.bindAttribLocation( program, 0, 'position' ); + return function WebGLProgram( renderer, code, material, parameters ) { - } + var gl = renderer.context; - gl.linkProgram( program ); + var extensions = material.extensions; + var defines = material.defines; - var programLog = gl.getProgramInfoLog( program ); - var vertexLog = gl.getShaderInfoLog( glVertexShader ); - var fragmentLog = gl.getShaderInfoLog( glFragmentShader ); + var vertexShader = material.__webglShader.vertexShader; + var fragmentShader = material.__webglShader.fragmentShader; - var runnable = true; - var haveDiagnostics = true; + var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC'; - // console.log( '**VERTEX**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glVertexShader ) ); - // console.log( '**FRAGMENT**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glFragmentShader ) ); + if ( parameters.shadowMapType === PCFShadowMap ) { - if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) { + shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF'; - runnable = false; + } else if ( parameters.shadowMapType === PCFSoftShadowMap ) { - console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter( program, gl.VALIDATE_STATUS ), 'gl.getProgramInfoLog', programLog, vertexLog, fragmentLog ); + shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT'; - } else if ( programLog !== '' ) { + } - console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog ); + var envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; + var envMapModeDefine = 'ENVMAP_MODE_REFLECTION'; + var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY'; - } else if ( vertexLog === '' || fragmentLog === '' ) { + if ( parameters.envMap ) { - haveDiagnostics = false; + switch ( material.envMap.mapping ) { - } + case CubeReflectionMapping: + case CubeRefractionMapping: + envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; + break; - if ( haveDiagnostics ) { + case CubeUVReflectionMapping: + case CubeUVRefractionMapping: + envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV'; + break; - this.diagnostics = { + case EquirectangularReflectionMapping: + case EquirectangularRefractionMapping: + envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC'; + break; - runnable: runnable, - material: material, + case SphericalReflectionMapping: + envMapTypeDefine = 'ENVMAP_TYPE_SPHERE'; + break; - programLog: programLog, + } - vertexShader: { + switch ( material.envMap.mapping ) { - log: vertexLog, - prefix: prefixVertex + case CubeRefractionMapping: + case EquirectangularRefractionMapping: + envMapModeDefine = 'ENVMAP_MODE_REFRACTION'; + break; - }, + } - fragmentShader: { + switch ( material.combine ) { - log: fragmentLog, - prefix: prefixFragment + case MultiplyOperation: + envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY'; + break; - } + case MixOperation: + envMapBlendingDefine = 'ENVMAP_BLENDING_MIX'; + break; - }; + case AddOperation: + envMapBlendingDefine = 'ENVMAP_BLENDING_ADD'; + break; - } + } - // clean up + } - gl.deleteShader( glVertexShader ); - gl.deleteShader( glFragmentShader ); + var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0; - // set up caching for uniform locations + // console.log( 'building new program ' ); - var cachedUniforms; + // - this.getUniforms = function() { + var customExtensions = generateExtensions( extensions, parameters, renderer.extensions ); - if ( cachedUniforms === undefined ) { + var customDefines = generateDefines( defines ); - cachedUniforms = - new exports.WebGLUniforms( gl, program, renderer ); + // - } + var program = gl.createProgram(); - return cachedUniforms; + var prefixVertex, prefixFragment; - }; + if ( (material && material.isRawShaderMaterial) ) { - // set up caching for attribute locations + prefixVertex = [ - var cachedAttributes; + customDefines - this.getAttributes = function() { + ].filter( filterEmptyLine ).join( '\n' ); - if ( cachedAttributes === undefined ) { + prefixFragment = [ - cachedAttributes = fetchAttributeLocations( gl, program ); + customDefines - } + ].filter( filterEmptyLine ).join( '\n' ); - return cachedAttributes; + } else { - }; + prefixVertex = [ - // free resource + 'precision ' + parameters.precision + ' float;', + 'precision ' + parameters.precision + ' int;', - this.destroy = function() { + '#define SHADER_NAME ' + material.__webglShader.name, - gl.deleteProgram( program ); - this.program = undefined; + customDefines, - }; + parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', - // DEPRECATED + '#define GAMMA_FACTOR ' + gammaFactorDefine, - Object.defineProperties( this, { + '#define MAX_BONES ' + parameters.maxBones, - uniforms: { - get: function() { + 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' : '', - console.warn( 'THREE.WebGLProgram: .uniforms is now .getUniforms().' ); - return this.getUniforms(); + parameters.flatShading ? '#define FLAT_SHADED' : '', - } - }, + parameters.skinning ? '#define USE_SKINNING' : '', + parameters.useVertexTexture ? '#define BONE_TEXTURE' : '', - attributes: { - get: function() { + parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', + parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', + 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.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;', - this.id = programIdCount ++; - this.code = code; - this.usedTimes = 1; - this.program = program; - this.vertexShader = glVertexShader; - this.fragmentShader = glFragmentShader; + 'attribute vec3 position;', + 'attribute vec3 normal;', + 'attribute vec2 uv;', - return this; + '#ifdef USE_COLOR', - }; + ' attribute vec3 color;', - } )(); + '#endif', - function WebGLPrograms( renderer, capabilities ) { + '#ifdef USE_MORPHTARGETS', - var programs = []; + ' attribute vec3 morphTarget0;', + ' attribute vec3 morphTarget1;', + ' attribute vec3 morphTarget2;', + ' attribute vec3 morphTarget3;', - var shaderIDs = { - MeshDepthMaterial: 'depth', - MeshNormalMaterial: 'normal', - MeshBasicMaterial: 'basic', - MeshLambertMaterial: 'lambert', - MeshPhongMaterial: 'phong', - MeshStandardMaterial: 'physical', - MeshPhysicalMaterial: 'physical', - LineBasicMaterial: 'basic', - LineDashedMaterial: 'dashed', - PointsMaterial: 'points' - }; + ' #ifdef USE_MORPHNORMALS', - 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" - ]; + ' attribute vec3 morphNormal0;', + ' attribute vec3 morphNormal1;', + ' attribute vec3 morphNormal2;', + ' attribute vec3 morphNormal3;', + ' #else', - function allocateBones( object ) { + ' attribute vec3 morphTarget4;', + ' attribute vec3 morphTarget5;', + ' attribute vec3 morphTarget6;', + ' attribute vec3 morphTarget7;', - if ( capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture ) { + ' #endif', - return 1024; + '#endif', - } else { + '#ifdef USE_SKINNING', - // 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) + ' attribute vec4 skinIndex;', + ' attribute vec4 skinWeight;', - var nVertexUniforms = capabilities.maxVertexUniforms; - var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 ); + '#endif', - var maxBones = nVertexMatrices; + '\n' - if ( object !== undefined && (object && object.isSkinnedMesh) ) { + ].filter( filterEmptyLine ).join( '\n' ); - maxBones = Math.min( object.skeleton.bones.length, maxBones ); + prefixFragment = [ - if ( maxBones < object.skeleton.bones.length ) { + customExtensions, - console.warn( 'WebGLRenderer: too many bones - ' + object.skeleton.bones.length + ', this GPU supports just ' + maxBones + ' (try OpenGL instead of ANGLE)' ); + 'precision ' + parameters.precision + ' float;', + 'precision ' + parameters.precision + ' int;', - } + '#define SHADER_NAME ' + material.__webglShader.name, - } + customDefines, - return maxBones; + parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '', - } + '#define GAMMA_FACTOR ' + gammaFactorDefine, - } + ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '', + ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '', - function getTextureEncodingFromMap( map, gammaOverrideLinear ) { + 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 encoding; + parameters.flatShading ? '#define FLAT_SHADED' : '', - if ( ! map ) { + parameters.doubleSided ? '#define DOUBLE_SIDED' : '', + parameters.flipSided ? '#define FLIP_SIDED' : '', - encoding = LinearEncoding; + '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes, - } else if ( (map && map.isTexture) ) { + parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', + parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', - encoding = map.encoding; + parameters.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : '', - } else if ( (map && map.isWebGLRenderTarget) ) { + parameters.physicallyCorrectLights ? "#define PHYSICALLY_CORRECT_LIGHTS" : '', - console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." ); - encoding = map.texture.encoding; + parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', + parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '', - } + parameters.envMap && renderer.extensions.get( 'EXT_shader_texture_lod' ) ? '#define TEXTURE_LOD_EXT' : '', - // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point. - if ( encoding === LinearEncoding && gammaOverrideLinear ) { + 'uniform mat4 viewMatrix;', + 'uniform vec3 cameraPosition;', - encoding = GammaEncoding; + ( 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 ) : '', - return encoding; + parameters.depthPacking ? "#define DEPTH_PACKING " + material.depthPacking : '', - } + '\n' - this.getParameters = function ( material, lights, fog, nClipPlanes, object ) { + ].filter( filterEmptyLine ).join( '\n' ); - var shaderID = shaderIDs[ material.type ]; + } - // heuristics to create shader parameters according to lights in the scene - // (not to blow over maxLights budget) + vertexShader = parseIncludes( vertexShader, parameters ); + vertexShader = replaceLightNums( vertexShader, parameters ); - var maxBones = allocateBones( object ); - var precision = renderer.getPrecision(); + fragmentShader = parseIncludes( fragmentShader, parameters ); + fragmentShader = replaceLightNums( fragmentShader, parameters ); - if ( material.precision !== null ) { + if ( (material && material.isShaderMaterial) === false ) { - precision = capabilities.getMaxPrecision( material.precision ); + vertexShader = unrollLoops( vertexShader ); + fragmentShader = unrollLoops( fragmentShader ); - if ( precision !== material.precision ) { + } - console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' ); + 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 currentRenderTarget = renderer.getCurrentRenderTarget(); + gl.attachShader( program, glVertexShader ); + gl.attachShader( program, glFragmentShader ); - var parameters = { + // Force a particular attribute to index 0. - shaderID: shaderID, + if ( material.index0AttributeName !== undefined ) { - 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, + gl.bindAttribLocation( program, 0, material.index0AttributeName ); - combine: material.combine, + } else if ( parameters.morphTargets === true ) { - vertexColors: material.vertexColors, + // programs with morphTargets displace position out of attribute 0 + gl.bindAttribLocation( program, 0, 'position' ); - fog: !! fog, - useFog: material.fog, - fogExp: (fog && fog.isFogExp2), + } - flatShading: material.shading === FlatShading, + gl.linkProgram( program ); - sizeAttenuation: material.sizeAttenuation, - logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer, + var programLog = gl.getProgramInfoLog( program ); + var vertexLog = gl.getShaderInfoLog( glVertexShader ); + var fragmentLog = gl.getShaderInfoLog( glFragmentShader ); - skinning: material.skinning, - maxBones: maxBones, - useVertexTexture: capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture, + var runnable = true; + var haveDiagnostics = true; - morphTargets: material.morphTargets, - morphNormals: material.morphNormals, - maxMorphTargets: renderer.maxMorphTargets, - maxMorphNormals: renderer.maxMorphNormals, + // console.log( '**VERTEX**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glVertexShader ) ); + // console.log( '**FRAGMENT**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glFragmentShader ) ); - numDirLights: lights.directional.length, - numPointLights: lights.point.length, - numSpotLights: lights.spot.length, - numHemiLights: lights.hemi.length, + if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) { - numClippingPlanes: nClipPlanes, + runnable = false; - shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && lights.shadows.length > 0, - shadowMapType: renderer.shadowMap.type, + console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter( program, gl.VALIDATE_STATUS ), 'gl.getProgramInfoLog', programLog, vertexLog, fragmentLog ); - toneMapping: renderer.toneMapping, - physicallyCorrectLights: renderer.physicallyCorrectLights, + } else if ( programLog !== '' ) { - premultipliedAlpha: material.premultipliedAlpha, + console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog ); - alphaTest: material.alphaTest, - doubleSided: material.side === DoubleSide, - flipSided: material.side === BackSide, + } else if ( vertexLog === '' || fragmentLog === '' ) { - depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false + haveDiagnostics = false; - }; + } - return parameters; + if ( haveDiagnostics ) { - }; + this.diagnostics = { - this.getProgramCode = function ( material, parameters ) { + runnable: runnable, + material: material, - var array = []; + programLog: programLog, - if ( parameters.shaderID ) { + vertexShader: { - array.push( parameters.shaderID ); + log: vertexLog, + prefix: prefixVertex - } else { + }, - array.push( material.fragmentShader ); - array.push( material.vertexShader ); + fragmentShader: { - } + log: fragmentLog, + prefix: prefixFragment - if ( material.defines !== undefined ) { + } - for ( var name in material.defines ) { + }; - array.push( name ); - array.push( material.defines[ name ] ); + } - } + // clean up - } + gl.deleteShader( glVertexShader ); + gl.deleteShader( glFragmentShader ); - for ( var i = 0; i < parameterNames.length; i ++ ) { + // set up caching for uniform locations - array.push( parameters[ parameterNames[ i ] ] ); + var cachedUniforms; - } + this.getUniforms = function() { - return array.join(); + if ( cachedUniforms === undefined ) { - }; + cachedUniforms = + new exports.WebGLUniforms( gl, program, renderer ); - this.acquireProgram = function ( material, parameters, code ) { + } - var program; + return cachedUniforms; - // Check if code has been already compiled - for ( var p = 0, pl = programs.length; p < pl; p ++ ) { + }; - var programInfo = programs[ p ]; + // set up caching for attribute locations - if ( programInfo.code === code ) { + var cachedAttributes; - program = programInfo; - ++ program.usedTimes; + this.getAttributes = function() { - break; + if ( cachedAttributes === undefined ) { - } + cachedAttributes = fetchAttributeLocations( gl, program ); - } + } - if ( program === undefined ) { + return cachedAttributes; - program = new exports.WebGLProgram( renderer, code, material, parameters ); - programs.push( program ); + }; - } + // free resource - return program; + this.destroy = function() { - }; + gl.deleteProgram( program ); + this.program = undefined; - this.releaseProgram = function( program ) { + }; - if ( -- program.usedTimes === 0 ) { + // DEPRECATED - // Remove from unordered set - var i = programs.indexOf( program ); - programs[ i ] = programs[ programs.length - 1 ]; - programs.pop(); + Object.defineProperties( this, { - // Free WebGL resources - program.destroy(); + uniforms: { + get: function() { - } + console.warn( 'THREE.WebGLProgram: .uniforms is now .getUniforms().' ); + return this.getUniforms(); - }; + } + }, - // Exposed for resource monitoring & error feedback via renderer.info: - this.programs = programs; + attributes: { + get: function() { - }; + console.warn( 'THREE.WebGLProgram: .attributes is now .getAttributes().' ); + return this.getAttributes(); - /** - * @author mrdoob / http://mrdoob.com/ - */ + } + } - function BufferAttribute( array, itemSize, normalized ) { + } ); - this.uuid = exports.Math.generateUUID(); - this.array = array; - this.itemSize = itemSize; + // - this.dynamic = false; - this.updateRange = { offset: 0, count: - 1 }; + this.id = programIdCount ++; + this.code = code; + this.usedTimes = 1; + this.program = program; + this.vertexShader = glVertexShader; + this.fragmentShader = glFragmentShader; - this.version = 0; - this.normalized = normalized === true; + return this; - } + }; - BufferAttribute.prototype = { + } )(); - constructor: BufferAttribute, + function WebGLPrograms( renderer, capabilities ) { - isBufferAttribute: true, + var programs = []; - get count() { + var shaderIDs = { + MeshDepthMaterial: 'depth', + MeshNormalMaterial: 'normal', + MeshBasicMaterial: 'basic', + MeshLambertMaterial: 'lambert', + MeshPhongMaterial: 'phong', + MeshStandardMaterial: 'physical', + MeshPhysicalMaterial: 'physical', + LineBasicMaterial: 'basic', + LineDashedMaterial: 'dashed', + PointsMaterial: 'points' + }; - return this.array.length / this.itemSize; + 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" + ]; - }, - set needsUpdate( value ) { + function allocateBones( object ) { - if ( value === true ) this.version ++; + if ( capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture ) { - }, + return 1024; - setDynamic: function ( value ) { + } else { - this.dynamic = value; + // 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) - return this; + var nVertexUniforms = capabilities.maxVertexUniforms; + var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 ); - }, + var maxBones = nVertexMatrices; - copy: function ( source ) { + if ( object !== undefined && (object && object.isSkinnedMesh) ) { - this.array = new source.array.constructor( source.array ); - this.itemSize = source.itemSize; + maxBones = Math.min( object.skeleton.bones.length, maxBones ); - this.dynamic = source.dynamic; + if ( maxBones < object.skeleton.bones.length ) { - return this; + console.warn( 'WebGLRenderer: too many bones - ' + object.skeleton.bones.length + ', this GPU supports just ' + maxBones + ' (try OpenGL instead of ANGLE)' ); - }, + } - copyAt: function ( index1, attribute, index2 ) { + } - index1 *= this.itemSize; - index2 *= attribute.itemSize; + return maxBones; - for ( var i = 0, l = this.itemSize; i < l; i ++ ) { + } - this.array[ index1 + i ] = attribute.array[ index2 + i ]; + } - } + function getTextureEncodingFromMap( map, gammaOverrideLinear ) { - return this; + var encoding; - }, + if ( ! map ) { - copyArray: function ( array ) { + encoding = LinearEncoding; - this.array.set( array ); + } else if ( (map && map.isTexture) ) { - return this; + encoding = map.encoding; - }, + } else if ( (map && map.isWebGLRenderTarget) ) { - copyColorsArray: function ( colors ) { + console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." ); + encoding = map.texture.encoding; - var array = this.array, offset = 0; + } - for ( var i = 0, l = colors.length; i < l; i ++ ) { + // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point. + if ( encoding === LinearEncoding && gammaOverrideLinear ) { - var color = colors[ i ]; + encoding = GammaEncoding; - if ( color === undefined ) { + } - console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i ); - color = new Color(); + return encoding; - } + } - array[ offset ++ ] = color.r; - array[ offset ++ ] = color.g; - array[ offset ++ ] = color.b; + this.getParameters = function ( material, lights, fog, nClipPlanes, object ) { - } + var shaderID = shaderIDs[ material.type ]; - return this; + // 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(); - copyIndicesArray: function ( indices ) { + if ( material.precision !== null ) { - var array = this.array, offset = 0; + precision = capabilities.getMaxPrecision( material.precision ); - for ( var i = 0, l = indices.length; i < l; i ++ ) { + if ( precision !== material.precision ) { - var index = indices[ i ]; + console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' ); - array[ offset ++ ] = index.a; - array[ offset ++ ] = index.b; - array[ offset ++ ] = index.c; + } - } + } - return this; + var currentRenderTarget = renderer.getCurrentRenderTarget(); - }, + var parameters = { - copyVector2sArray: function ( vectors ) { + shaderID: shaderID, - var array = this.array, offset = 0; + 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, - for ( var i = 0, l = vectors.length; i < l; i ++ ) { + combine: material.combine, - var vector = vectors[ i ]; + vertexColors: material.vertexColors, - if ( vector === undefined ) { + fog: !! fog, + useFog: material.fog, + fogExp: (fog && fog.isFogExp2), - console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i ); - vector = new Vector2(); + flatShading: material.shading === FlatShading, - } + sizeAttenuation: material.sizeAttenuation, + logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer, - array[ offset ++ ] = vector.x; - array[ offset ++ ] = vector.y; + skinning: material.skinning, + maxBones: maxBones, + useVertexTexture: capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture, - } + morphTargets: material.morphTargets, + morphNormals: material.morphNormals, + maxMorphTargets: renderer.maxMorphTargets, + maxMorphNormals: renderer.maxMorphNormals, - return this; + numDirLights: lights.directional.length, + numPointLights: lights.point.length, + numSpotLights: lights.spot.length, + numHemiLights: lights.hemi.length, - }, + numClippingPlanes: nClipPlanes, - copyVector3sArray: function ( vectors ) { + shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && lights.shadows.length > 0, + shadowMapType: renderer.shadowMap.type, - var array = this.array, offset = 0; + toneMapping: renderer.toneMapping, + physicallyCorrectLights: renderer.physicallyCorrectLights, - for ( var i = 0, l = vectors.length; i < l; i ++ ) { + premultipliedAlpha: material.premultipliedAlpha, - var vector = vectors[ i ]; + alphaTest: material.alphaTest, + doubleSided: material.side === DoubleSide, + flipSided: material.side === BackSide, - if ( vector === undefined ) { + depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false - console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i ); - vector = new Vector3(); + }; - } + return parameters; - array[ offset ++ ] = vector.x; - array[ offset ++ ] = vector.y; - array[ offset ++ ] = vector.z; + }; - } + this.getProgramCode = function ( material, parameters ) { - return this; + var array = []; - }, + if ( parameters.shaderID ) { - copyVector4sArray: function ( vectors ) { + array.push( parameters.shaderID ); - var array = this.array, offset = 0; + } else { - for ( var i = 0, l = vectors.length; i < l; i ++ ) { + array.push( material.fragmentShader ); + array.push( material.vertexShader ); - var vector = vectors[ i ]; + } - if ( vector === undefined ) { + if ( material.defines !== undefined ) { - console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i ); - vector = new Vector4(); + for ( var name in material.defines ) { - } + array.push( name ); + array.push( material.defines[ name ] ); - array[ offset ++ ] = vector.x; - array[ offset ++ ] = vector.y; - array[ offset ++ ] = vector.z; - array[ offset ++ ] = vector.w; + } - } + } - return this; + for ( var i = 0; i < parameterNames.length; i ++ ) { - }, + array.push( parameters[ parameterNames[ i ] ] ); - set: function ( value, offset ) { + } - if ( offset === undefined ) offset = 0; + return array.join(); - this.array.set( value, offset ); + }; - return this; + this.acquireProgram = function ( material, parameters, code ) { - }, + var program; - getX: function ( index ) { + // Check if code has been already compiled + for ( var p = 0, pl = programs.length; p < pl; p ++ ) { - return this.array[ index * this.itemSize ]; + var programInfo = programs[ p ]; - }, + if ( programInfo.code === code ) { - setX: function ( index, x ) { + program = programInfo; + ++ program.usedTimes; - this.array[ index * this.itemSize ] = x; + break; - return this; + } - }, + } - getY: function ( index ) { + if ( program === undefined ) { - return this.array[ index * this.itemSize + 1 ]; + program = new exports.WebGLProgram( renderer, code, material, parameters ); + programs.push( program ); - }, + } - setY: function ( index, y ) { + return program; - this.array[ index * this.itemSize + 1 ] = y; + }; - return this; + this.releaseProgram = function( program ) { - }, + if ( -- program.usedTimes === 0 ) { - getZ: function ( index ) { + // Remove from unordered set + var i = programs.indexOf( program ); + programs[ i ] = programs[ programs.length - 1 ]; + programs.pop(); - return this.array[ index * this.itemSize + 2 ]; + // Free WebGL resources + program.destroy(); - }, + } - setZ: function ( index, z ) { + }; - this.array[ index * this.itemSize + 2 ] = z; + // Exposed for resource monitoring & error feedback via renderer.info: + this.programs = programs; - return this; + }; - }, + /** + * @author mrdoob / http://mrdoob.com/ + */ - getW: function ( index ) { + function BufferAttribute( array, itemSize, normalized ) { - return this.array[ index * this.itemSize + 3 ]; + this.uuid = exports.Math.generateUUID(); - }, + this.array = array; + this.itemSize = itemSize; - setW: function ( index, w ) { + this.dynamic = false; + this.updateRange = { offset: 0, count: - 1 }; - this.array[ index * this.itemSize + 3 ] = w; + this.version = 0; + this.normalized = normalized === true; - return this; + } - }, + BufferAttribute.prototype = { - setXY: function ( index, x, y ) { + constructor: BufferAttribute, - index *= this.itemSize; + isBufferAttribute: true, - this.array[ index + 0 ] = x; - this.array[ index + 1 ] = y; + get count() { - return this; + return this.array.length / this.itemSize; - }, + }, - setXYZ: function ( index, x, y, z ) { + set needsUpdate( value ) { - index *= this.itemSize; + if ( value === true ) this.version ++; - this.array[ index + 0 ] = x; - this.array[ index + 1 ] = y; - this.array[ index + 2 ] = z; + }, - return this; + setDynamic: function ( value ) { - }, + this.dynamic = value; - setXYZW: function ( index, x, y, z, w ) { + return this; - index *= this.itemSize; + }, - this.array[ index + 0 ] = x; - this.array[ index + 1 ] = y; - this.array[ index + 2 ] = z; - this.array[ index + 3 ] = w; + copy: function ( source ) { - return this; + this.array = new source.array.constructor( source.array ); + this.itemSize = source.itemSize; - }, + this.dynamic = source.dynamic; - clone: function () { + return this; - return new this.constructor().copy( this ); + }, - } + copyAt: function ( index1, attribute, index2 ) { - }; + index1 *= this.itemSize; + index2 *= attribute.itemSize; - // + for ( var i = 0, l = this.itemSize; i < l; i ++ ) { - function Int8Attribute( array, itemSize ) { + this.array[ index1 + i ] = attribute.array[ index2 + i ]; - return new BufferAttribute( new Int8Array( array ), itemSize ); + } - } + return this; - function Uint8Attribute( array, itemSize ) { + }, - return new BufferAttribute( new Uint8Array( array ), itemSize ); + copyArray: function ( array ) { - } + this.array.set( array ); - function Uint8ClampedAttribute( array, itemSize ) { + return this; - return new BufferAttribute( new Uint8ClampedArray( array ), itemSize ); + }, - } + copyColorsArray: function ( colors ) { - function Int16Attribute( array, itemSize ) { + var array = this.array, offset = 0; - return new BufferAttribute( new Int16Array( array ), itemSize ); + for ( var i = 0, l = colors.length; i < l; i ++ ) { - } + var color = colors[ i ]; - function Uint16Attribute( array, itemSize ) { + if ( color === undefined ) { - return new BufferAttribute( new Uint16Array( array ), itemSize ); + console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i ); + color = new Color(); - } + } - function Int32Attribute( array, itemSize ) { + array[ offset ++ ] = color.r; + array[ offset ++ ] = color.g; + array[ offset ++ ] = color.b; - return new BufferAttribute( new Int32Array( array ), itemSize ); + } - } + return this; - function Uint32Attribute( array, itemSize ) { + }, - return new BufferAttribute( new Uint32Array( array ), itemSize ); + copyIndicesArray: function ( indices ) { - } + var array = this.array, offset = 0; - function Float32Attribute( array, itemSize ) { + for ( var i = 0, l = indices.length; i < l; i ++ ) { - return new BufferAttribute( new Float32Array( array ), itemSize ); + var index = indices[ i ]; - } + array[ offset ++ ] = index.a; + array[ offset ++ ] = index.b; + array[ offset ++ ] = index.c; - function Float64Attribute( array, itemSize ) { + } - return new BufferAttribute( new Float64Array( array ), itemSize ); + return this; - } + }, - // Deprecated + copyVector2sArray: function ( vectors ) { - function DynamicBufferAttribute( array, itemSize ) { + var array = this.array, offset = 0; - console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' ); - return new BufferAttribute( array, itemSize ).setDynamic( true ); + for ( var i = 0, l = vectors.length; i < l; i ++ ) { - } + var vector = vectors[ i ]; - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + if ( vector === undefined ) { - function Face3( a, b, c, normal, color, materialIndex ) { + console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i ); + vector = new Vector2(); - this.a = a; - this.b = b; - this.c = c; + } - this.normal = (normal && normal.isVector3) ? normal : new Vector3(); - this.vertexNormals = Array.isArray( normal ) ? normal : []; + array[ offset ++ ] = vector.x; + array[ offset ++ ] = vector.y; - this.color = (color && color.isColor) ? color : new Color(); - this.vertexColors = Array.isArray( color ) ? color : []; + } - this.materialIndex = materialIndex !== undefined ? materialIndex : 0; + return this; - }; + }, - Face3.prototype = { + copyVector3sArray: function ( vectors ) { - constructor: Face3, + var array = this.array, offset = 0; - clone: function () { + for ( var i = 0, l = vectors.length; i < l; i ++ ) { - return new this.constructor().copy( this ); + var vector = vectors[ i ]; - }, + if ( vector === undefined ) { - copy: function ( source ) { + console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i ); + vector = new Vector3(); - this.a = source.a; - this.b = source.b; - this.c = source.c; + } - this.normal.copy( source.normal ); - this.color.copy( source.color ); + array[ offset ++ ] = vector.x; + array[ offset ++ ] = vector.y; + array[ offset ++ ] = vector.z; - this.materialIndex = source.materialIndex; + } - for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) { + return this; - this.vertexNormals[ i ] = source.vertexNormals[ i ].clone(); + }, - } + copyVector4sArray: function ( vectors ) { - for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) { + var array = this.array, offset = 0; - this.vertexColors[ i ] = source.vertexColors[ i ].clone(); + for ( var i = 0, l = vectors.length; i < l; i ++ ) { - } + var vector = vectors[ i ]; - return this; + if ( vector === undefined ) { - } + console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i ); + vector = new Vector4(); - }; + } - /** - * @author mrdoob / http://mrdoob.com/ - * @author WestLangley / http://github.com/WestLangley - * @author bhouston / http://clara.io - */ + array[ offset ++ ] = vector.x; + array[ offset ++ ] = vector.y; + array[ offset ++ ] = vector.z; + array[ offset ++ ] = vector.w; - function Euler( x, y, z, order ) { + } - this._x = x || 0; - this._y = y || 0; - this._z = z || 0; - this._order = order || Euler.DefaultOrder; + return this; - }; + }, - Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ]; + set: function ( value, offset ) { - Euler.DefaultOrder = 'XYZ'; + if ( offset === undefined ) offset = 0; - Euler.prototype = { + this.array.set( value, offset ); - constructor: Euler, + return this; - isEuler: true, + }, - get x () { + getX: function ( index ) { - return this._x; + return this.array[ index * this.itemSize ]; - }, + }, - set x ( value ) { + setX: function ( index, x ) { - this._x = value; - this.onChangeCallback(); + this.array[ index * this.itemSize ] = x; - }, + return this; - get y () { + }, - return this._y; + getY: function ( index ) { - }, + return this.array[ index * this.itemSize + 1 ]; - set y ( value ) { + }, - this._y = value; - this.onChangeCallback(); + setY: function ( index, y ) { - }, + this.array[ index * this.itemSize + 1 ] = y; - get z () { + return this; - return this._z; + }, - }, + getZ: function ( index ) { - set z ( value ) { + return this.array[ index * this.itemSize + 2 ]; - this._z = value; - this.onChangeCallback(); + }, - }, + setZ: function ( index, z ) { - get order () { + this.array[ index * this.itemSize + 2 ] = z; - return this._order; + return this; - }, + }, - set order ( value ) { + getW: function ( index ) { - this._order = value; - this.onChangeCallback(); + return this.array[ index * this.itemSize + 3 ]; - }, + }, - set: function ( x, y, z, order ) { + setW: function ( index, w ) { - this._x = x; - this._y = y; - this._z = z; - this._order = order || this._order; + this.array[ index * this.itemSize + 3 ] = w; - this.onChangeCallback(); + return this; - return this; + }, - }, + setXY: function ( index, x, y ) { - clone: function () { + index *= this.itemSize; - return new this.constructor( this._x, this._y, this._z, this._order ); + this.array[ index + 0 ] = x; + this.array[ index + 1 ] = y; - }, + return this; - copy: function ( euler ) { + }, - this._x = euler._x; - this._y = euler._y; - this._z = euler._z; - this._order = euler._order; + setXYZ: function ( index, x, y, z ) { - this.onChangeCallback(); + index *= this.itemSize; - return this; + this.array[ index + 0 ] = x; + this.array[ index + 1 ] = y; + this.array[ index + 2 ] = z; - }, + return this; - setFromRotationMatrix: function ( m, order, update ) { + }, - var clamp = exports.Math.clamp; + setXYZW: function ( index, x, y, z, w ) { - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + index *= this.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 ]; + this.array[ index + 0 ] = x; + this.array[ index + 1 ] = y; + this.array[ index + 2 ] = z; + this.array[ index + 3 ] = w; - order = order || this._order; + return this; - if ( order === 'XYZ' ) { + }, - this._y = Math.asin( clamp( m13, - 1, 1 ) ); + clone: function () { - if ( Math.abs( m13 ) < 0.99999 ) { + return new this.constructor().copy( this ); - this._x = Math.atan2( - m23, m33 ); - this._z = Math.atan2( - m12, m11 ); + } - } else { + }; - this._x = Math.atan2( m32, m22 ); - this._z = 0; + // - } + function Int8Attribute( array, itemSize ) { - } else if ( order === 'YXZ' ) { + return new BufferAttribute( new Int8Array( array ), itemSize ); - this._x = Math.asin( - clamp( m23, - 1, 1 ) ); + } - if ( Math.abs( m23 ) < 0.99999 ) { + function Uint8Attribute( array, itemSize ) { - this._y = Math.atan2( m13, m33 ); - this._z = Math.atan2( m21, m22 ); + return new BufferAttribute( new Uint8Array( array ), itemSize ); - } else { + } - this._y = Math.atan2( - m31, m11 ); - this._z = 0; + function Uint8ClampedAttribute( array, itemSize ) { - } + return new BufferAttribute( new Uint8ClampedArray( array ), itemSize ); - } else if ( order === 'ZXY' ) { + } - this._x = Math.asin( clamp( m32, - 1, 1 ) ); + function Int16Attribute( array, itemSize ) { - if ( Math.abs( m32 ) < 0.99999 ) { + return new BufferAttribute( new Int16Array( array ), itemSize ); - this._y = Math.atan2( - m31, m33 ); - this._z = Math.atan2( - m12, m22 ); + } - } else { + function Uint16Attribute( array, itemSize ) { - this._y = 0; - this._z = Math.atan2( m21, m11 ); + return new BufferAttribute( new Uint16Array( array ), itemSize ); - } + } - } else if ( order === 'ZYX' ) { + function Int32Attribute( array, itemSize ) { - this._y = Math.asin( - clamp( m31, - 1, 1 ) ); + return new BufferAttribute( new Int32Array( array ), itemSize ); - if ( Math.abs( m31 ) < 0.99999 ) { + } - this._x = Math.atan2( m32, m33 ); - this._z = Math.atan2( m21, m11 ); + function Uint32Attribute( array, itemSize ) { - } else { + return new BufferAttribute( new Uint32Array( array ), itemSize ); - this._x = 0; - this._z = Math.atan2( - m12, m22 ); + } - } + function Float32Attribute( array, itemSize ) { - } else if ( order === 'YZX' ) { + return new BufferAttribute( new Float32Array( array ), itemSize ); - this._z = Math.asin( clamp( m21, - 1, 1 ) ); + } - if ( Math.abs( m21 ) < 0.99999 ) { + function Float64Attribute( array, itemSize ) { - this._x = Math.atan2( - m23, m22 ); - this._y = Math.atan2( - m31, m11 ); + return new BufferAttribute( new Float64Array( array ), itemSize ); - } else { + } - this._x = 0; - this._y = Math.atan2( m13, m33 ); + // Deprecated - } + function DynamicBufferAttribute( array, itemSize ) { - } else if ( order === 'XZY' ) { + console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' ); + return new BufferAttribute( array, itemSize ).setDynamic( true ); - this._z = Math.asin( - clamp( m12, - 1, 1 ) ); + } - if ( Math.abs( m12 ) < 0.99999 ) { + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - this._x = Math.atan2( m32, m22 ); - this._y = Math.atan2( m13, m11 ); + function Face3( a, b, c, normal, color, materialIndex ) { - } else { + this.a = a; + this.b = b; + this.c = c; - this._x = Math.atan2( - m23, m33 ); - this._y = 0; + 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 : []; - } else { + this.materialIndex = materialIndex !== undefined ? materialIndex : 0; - console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order ); + }; - } + Face3.prototype = { - this._order = order; + constructor: Face3, - if ( update !== false ) this.onChangeCallback(); + clone: function () { - return this; + return new this.constructor().copy( this ); - }, + }, - setFromQuaternion: function () { + copy: function ( source ) { - var matrix; + this.a = source.a; + this.b = source.b; + this.c = source.c; - return function setFromQuaternion( q, order, update ) { + this.normal.copy( source.normal ); + this.color.copy( source.color ); - if ( matrix === undefined ) matrix = new Matrix4(); + this.materialIndex = source.materialIndex; - matrix.makeRotationFromQuaternion( q ); + for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) { - return this.setFromRotationMatrix( matrix, order, update ); + this.vertexNormals[ i ] = source.vertexNormals[ i ].clone(); - }; + } - }(), + for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) { - setFromVector3: function ( v, order ) { + this.vertexColors[ i ] = source.vertexColors[ i ].clone(); - return this.set( v.x, v.y, v.z, order || this._order ); + } - }, + return this; - reorder: function () { + } - // WARNING: this discards revolution information -bhouston + }; - var q = new Quaternion(); + /** + * @author mrdoob / http://mrdoob.com/ + * @author WestLangley / http://github.com/WestLangley + * @author bhouston / http://clara.io + */ - return function reorder( newOrder ) { + function Euler( x, y, z, order ) { - q.setFromEuler( this ); + this._x = x || 0; + this._y = y || 0; + this._z = z || 0; + this._order = order || Euler.DefaultOrder; - return this.setFromQuaternion( q, newOrder ); + }; - }; + Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ]; - }(), + Euler.DefaultOrder = 'XYZ'; - equals: function ( euler ) { + Euler.prototype = { - return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order ); + constructor: Euler, - }, + isEuler: true, - fromArray: function ( array ) { + get x () { - this._x = array[ 0 ]; - this._y = array[ 1 ]; - this._z = array[ 2 ]; - if ( array[ 3 ] !== undefined ) this._order = array[ 3 ]; + return this._x; - this.onChangeCallback(); + }, - return this; + set x ( value ) { - }, + this._x = value; + this.onChangeCallback(); - toArray: function ( array, offset ) { + }, - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + get y () { - array[ offset ] = this._x; - array[ offset + 1 ] = this._y; - array[ offset + 2 ] = this._z; - array[ offset + 3 ] = this._order; + return this._y; - return array; + }, - }, + set y ( value ) { - toVector3: function ( optionalResult ) { + this._y = value; + this.onChangeCallback(); - if ( optionalResult ) { + }, - return optionalResult.set( this._x, this._y, this._z ); + get z () { - } else { + return this._z; - return new Vector3( this._x, this._y, this._z ); + }, - } + set z ( value ) { - }, + this._z = value; + this.onChangeCallback(); - onChange: function ( callback ) { + }, - this.onChangeCallback = callback; + get order () { - return this; + return this._order; - }, + }, - onChangeCallback: function () {} + set order ( value ) { - }; + this._order = value; + this.onChangeCallback(); - /** - * @author mrdoob / http://mrdoob.com/ - */ + }, - function Layers() { + set: function ( x, y, z, order ) { - this.mask = 1; + this._x = x; + this._y = y; + this._z = z; + this._order = order || this._order; - }; + this.onChangeCallback(); - Layers.prototype = { + return this; - constructor: Layers, + }, - set: function ( channel ) { + clone: function () { - this.mask = 1 << channel; + return new this.constructor( this._x, this._y, this._z, this._order ); - }, + }, - enable: function ( channel ) { + copy: function ( euler ) { - this.mask |= 1 << channel; + this._x = euler._x; + this._y = euler._y; + this._z = euler._z; + this._order = euler._order; - }, + this.onChangeCallback(); - toggle: function ( channel ) { + return this; - this.mask ^= 1 << channel; + }, - }, + setFromRotationMatrix: function ( m, order, update ) { - disable: function ( channel ) { + var clamp = exports.Math.clamp; - this.mask &= ~ ( 1 << channel ); + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - }, + 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 ]; - test: function ( layers ) { + order = order || this._order; - return ( this.mask & layers.mask ) !== 0; + if ( order === 'XYZ' ) { - } + this._y = Math.asin( clamp( m13, - 1, 1 ) ); - }; + if ( Math.abs( m13 ) < 0.99999 ) { - /** - * @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 = Math.atan2( - m23, m33 ); + this._z = Math.atan2( - m12, m11 ); - function Object3D() { + } else { - Object.defineProperty( this, 'id', { value: Object3DIdCount() } ); + this._x = Math.atan2( m32, m22 ); + this._z = 0; - this.uuid = exports.Math.generateUUID(); + } - this.name = ''; - this.type = 'Object3D'; + } else if ( order === 'YXZ' ) { - this.parent = null; - this.children = []; + this._x = Math.asin( - clamp( m23, - 1, 1 ) ); - this.up = Object3D.DefaultUp.clone(); + if ( Math.abs( m23 ) < 0.99999 ) { - var position = new Vector3(); - var rotation = new Euler(); - var quaternion = new Quaternion(); - var scale = new Vector3( 1, 1, 1 ); + this._y = Math.atan2( m13, m33 ); + this._z = Math.atan2( m21, m22 ); - function onRotationChange() { + } else { - quaternion.setFromEuler( rotation, false ); + this._y = Math.atan2( - m31, m11 ); + this._z = 0; - } + } - function onQuaternionChange() { + } else if ( order === 'ZXY' ) { - rotation.setFromQuaternion( quaternion, undefined, false ); + this._x = Math.asin( clamp( m32, - 1, 1 ) ); - } + if ( Math.abs( m32 ) < 0.99999 ) { - rotation.onChange( onRotationChange ); - quaternion.onChange( onQuaternionChange ); + this._y = Math.atan2( - m31, m33 ); + this._z = Math.atan2( - m12, m22 ); - 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() - } - } ); + } else { - this.matrix = new Matrix4(); - this.matrixWorld = new Matrix4(); + this._y = 0; + this._z = Math.atan2( m21, m11 ); - this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate; - this.matrixWorldNeedsUpdate = false; + } - this.layers = new Layers(); - this.visible = true; + } else if ( order === 'ZYX' ) { - this.castShadow = false; - this.receiveShadow = false; + this._y = Math.asin( - clamp( m31, - 1, 1 ) ); - this.frustumCulled = true; - this.renderOrder = 0; + if ( Math.abs( m31 ) < 0.99999 ) { - this.userData = {}; + this._x = Math.atan2( m32, m33 ); + this._z = Math.atan2( m21, m11 ); - }; + } else { - Object3D.DefaultUp = new Vector3( 0, 1, 0 ); - Object3D.DefaultMatrixAutoUpdate = true; + this._x = 0; + this._z = Math.atan2( - m12, m22 ); - Object.assign( Object3D.prototype, EventDispatcher.prototype, { + } - isObject3D: true, + } else if ( order === 'YZX' ) { - applyMatrix: function ( matrix ) { + this._z = Math.asin( clamp( m21, - 1, 1 ) ); - this.matrix.multiplyMatrices( matrix, this.matrix ); + if ( Math.abs( m21 ) < 0.99999 ) { - this.matrix.decompose( this.position, this.quaternion, this.scale ); + this._x = Math.atan2( - m23, m22 ); + this._y = Math.atan2( - m31, m11 ); - }, + } else { - setRotationFromAxisAngle: function ( axis, angle ) { + this._x = 0; + this._y = Math.atan2( m13, m33 ); - // assumes axis is normalized + } - this.quaternion.setFromAxisAngle( axis, angle ); + } else if ( order === 'XZY' ) { - }, + this._z = Math.asin( - clamp( m12, - 1, 1 ) ); - setRotationFromEuler: function ( euler ) { + if ( Math.abs( m12 ) < 0.99999 ) { - this.quaternion.setFromEuler( euler, true ); + this._x = Math.atan2( m32, m22 ); + this._y = Math.atan2( m13, m11 ); - }, + } else { - setRotationFromMatrix: function ( m ) { + this._x = Math.atan2( - m23, m33 ); + this._y = 0; - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + } - this.quaternion.setFromRotationMatrix( m ); + } else { - }, + console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order ); - setRotationFromQuaternion: function ( q ) { + } - // assumes q is normalized + this._order = order; - this.quaternion.copy( q ); + if ( update !== false ) this.onChangeCallback(); - }, + return this; - rotateOnAxis: function () { + }, - // rotate object on axis in object space - // axis is assumed to be normalized + setFromQuaternion: function () { - var q1 = new Quaternion(); + var matrix; - return function rotateOnAxis( axis, angle ) { + return function setFromQuaternion( q, order, update ) { - q1.setFromAxisAngle( axis, angle ); + if ( matrix === undefined ) matrix = new Matrix4(); - this.quaternion.multiply( q1 ); + matrix.makeRotationFromQuaternion( q ); - return this; + return this.setFromRotationMatrix( matrix, order, update ); - }; + }; - }(), + }(), - rotateX: function () { + setFromVector3: function ( v, order ) { - var v1 = new Vector3( 1, 0, 0 ); + return this.set( v.x, v.y, v.z, order || this._order ); - return function rotateX( angle ) { + }, - return this.rotateOnAxis( v1, angle ); + reorder: function () { - }; + // WARNING: this discards revolution information -bhouston - }(), + var q = new Quaternion(); - rotateY: function () { + return function reorder( newOrder ) { - var v1 = new Vector3( 0, 1, 0 ); + q.setFromEuler( this ); - return function rotateY( angle ) { + return this.setFromQuaternion( q, newOrder ); - return this.rotateOnAxis( v1, angle ); + }; - }; + }(), - }(), + equals: function ( euler ) { - rotateZ: function () { + return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order ); - var v1 = new Vector3( 0, 0, 1 ); + }, - return function rotateZ( angle ) { + fromArray: function ( array ) { - return this.rotateOnAxis( v1, angle ); + this._x = array[ 0 ]; + this._y = array[ 1 ]; + this._z = array[ 2 ]; + if ( array[ 3 ] !== undefined ) this._order = array[ 3 ]; - }; + this.onChangeCallback(); - }(), + return this; - translateOnAxis: function () { + }, - // translate object by distance along axis in object space - // axis is assumed to be normalized + toArray: function ( array, offset ) { - var v1 = new Vector3(); + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - return function translateOnAxis( axis, distance ) { + array[ offset ] = this._x; + array[ offset + 1 ] = this._y; + array[ offset + 2 ] = this._z; + array[ offset + 3 ] = this._order; - v1.copy( axis ).applyQuaternion( this.quaternion ); + return array; - this.position.add( v1.multiplyScalar( distance ) ); + }, - return this; + toVector3: function ( optionalResult ) { - }; + if ( optionalResult ) { - }(), + return optionalResult.set( this._x, this._y, this._z ); - translateX: function () { + } else { - var v1 = new Vector3( 1, 0, 0 ); + return new Vector3( this._x, this._y, this._z ); - return function translateX( distance ) { + } - return this.translateOnAxis( v1, distance ); + }, - }; + onChange: function ( callback ) { - }(), + this.onChangeCallback = callback; - translateY: function () { + return this; - var v1 = new Vector3( 0, 1, 0 ); + }, - return function translateY( distance ) { + onChangeCallback: function () {} - return this.translateOnAxis( v1, distance ); + }; - }; + /** + * @author mrdoob / http://mrdoob.com/ + */ - }(), + function Layers() { - translateZ: function () { + this.mask = 1; - var v1 = new Vector3( 0, 0, 1 ); + }; - return function translateZ( distance ) { + Layers.prototype = { - return this.translateOnAxis( v1, distance ); + constructor: Layers, - }; + set: function ( channel ) { - }(), + this.mask = 1 << channel; - localToWorld: function ( vector ) { + }, - return vector.applyMatrix4( this.matrixWorld ); + enable: function ( channel ) { - }, + this.mask |= 1 << channel; - worldToLocal: function () { + }, - var m1 = new Matrix4(); + toggle: function ( channel ) { - return function worldToLocal( vector ) { + this.mask ^= 1 << channel; - return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) ); + }, - }; + disable: function ( channel ) { - }(), + this.mask &= ~ ( 1 << channel ); - lookAt: function () { + }, - // This routine does not support objects with rotated and/or translated parent(s) + test: function ( layers ) { - var m1 = new Matrix4(); + return ( this.mask & layers.mask ) !== 0; - return function lookAt( vector ) { + } - m1.lookAt( vector, this.position, this.up ); + }; - this.quaternion.setFromRotationMatrix( m1 ); + /** + * @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 + */ - }; + function Object3D() { - }(), + Object.defineProperty( this, 'id', { value: Object3DIdCount() } ); - add: function ( object ) { + this.uuid = exports.Math.generateUUID(); - if ( arguments.length > 1 ) { + this.name = ''; + this.type = 'Object3D'; - for ( var i = 0; i < arguments.length; i ++ ) { + this.parent = null; + this.children = []; - this.add( arguments[ i ] ); + this.up = Object3D.DefaultUp.clone(); - } + var position = new Vector3(); + var rotation = new Euler(); + var quaternion = new Quaternion(); + var scale = new Vector3( 1, 1, 1 ); - return this; + function onRotationChange() { - } + quaternion.setFromEuler( rotation, false ); - if ( object === this ) { + } - console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object ); - return this; + function onQuaternionChange() { - } + rotation.setFromQuaternion( quaternion, undefined, false ); - if ( (object && object.isObject3D) ) { + } - if ( object.parent !== null ) { + 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() + } + } ); - object.parent.remove( object ); + this.matrix = new Matrix4(); + this.matrixWorld = new Matrix4(); - } + this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate; + this.matrixWorldNeedsUpdate = false; - object.parent = this; - object.dispatchEvent( { type: 'added' } ); + this.layers = new Layers(); + this.visible = true; - this.children.push( object ); + this.castShadow = false; + this.receiveShadow = false; - } else { + this.frustumCulled = true; + this.renderOrder = 0; - console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object ); + this.userData = {}; - } + }; - return this; + Object3D.DefaultUp = new Vector3( 0, 1, 0 ); + Object3D.DefaultMatrixAutoUpdate = true; - }, + Object.assign( Object3D.prototype, EventDispatcher.prototype, { - remove: function ( object ) { + isObject3D: true, - if ( arguments.length > 1 ) { + applyMatrix: function ( matrix ) { - for ( var i = 0; i < arguments.length; i ++ ) { + this.matrix.multiplyMatrices( matrix, this.matrix ); - this.remove( arguments[ i ] ); + this.matrix.decompose( this.position, this.quaternion, this.scale ); - } + }, - } + setRotationFromAxisAngle: function ( axis, angle ) { - var index = this.children.indexOf( object ); + // assumes axis is normalized - if ( index !== - 1 ) { + this.quaternion.setFromAxisAngle( axis, angle ); - object.parent = null; + }, - object.dispatchEvent( { type: 'removed' } ); + setRotationFromEuler: function ( euler ) { - this.children.splice( index, 1 ); + this.quaternion.setFromEuler( euler, true ); - } + }, - }, + setRotationFromMatrix: function ( m ) { - getObjectById: function ( id ) { + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - return this.getObjectByProperty( 'id', id ); + this.quaternion.setFromRotationMatrix( m ); - }, + }, - getObjectByName: function ( name ) { + setRotationFromQuaternion: function ( q ) { - return this.getObjectByProperty( 'name', name ); + // assumes q is normalized - }, + this.quaternion.copy( q ); - getObjectByProperty: function ( name, value ) { + }, - if ( this[ name ] === value ) return this; + rotateOnAxis: function () { - for ( var i = 0, l = this.children.length; i < l; i ++ ) { + // rotate object on axis in object space + // axis is assumed to be normalized - var child = this.children[ i ]; - var object = child.getObjectByProperty( name, value ); + var q1 = new Quaternion(); - if ( object !== undefined ) { + return function rotateOnAxis( axis, angle ) { - return object; + q1.setFromAxisAngle( axis, angle ); - } + this.quaternion.multiply( q1 ); - } + return this; - return undefined; + }; - }, + }(), - getWorldPosition: function ( optionalTarget ) { + rotateX: function () { - var result = optionalTarget || new Vector3(); + var v1 = new Vector3( 1, 0, 0 ); - this.updateMatrixWorld( true ); + return function rotateX( angle ) { - return result.setFromMatrixPosition( this.matrixWorld ); + return this.rotateOnAxis( v1, angle ); - }, + }; - getWorldQuaternion: function () { + }(), - var position = new Vector3(); - var scale = new Vector3(); + rotateY: function () { - return function getWorldQuaternion( optionalTarget ) { + var v1 = new Vector3( 0, 1, 0 ); - var result = optionalTarget || new Quaternion(); + return function rotateY( angle ) { - this.updateMatrixWorld( true ); + return this.rotateOnAxis( v1, angle ); - this.matrixWorld.decompose( position, result, scale ); + }; - return result; + }(), - }; + rotateZ: function () { - }(), + var v1 = new Vector3( 0, 0, 1 ); - getWorldRotation: function () { + return function rotateZ( angle ) { - var quaternion = new Quaternion(); + return this.rotateOnAxis( v1, angle ); - return function getWorldRotation( optionalTarget ) { + }; - var result = optionalTarget || new Euler(); + }(), - this.getWorldQuaternion( quaternion ); + translateOnAxis: function () { - return result.setFromQuaternion( quaternion, this.rotation.order, false ); + // translate object by distance along axis in object space + // axis is assumed to be normalized - }; + var v1 = new Vector3(); - }(), + return function translateOnAxis( axis, distance ) { - getWorldScale: function () { + v1.copy( axis ).applyQuaternion( this.quaternion ); - var position = new Vector3(); - var quaternion = new Quaternion(); + this.position.add( v1.multiplyScalar( distance ) ); - return function getWorldScale( optionalTarget ) { + return this; - var result = optionalTarget || new Vector3(); + }; - this.updateMatrixWorld( true ); + }(), - this.matrixWorld.decompose( position, quaternion, result ); + translateX: function () { - return result; + var v1 = new Vector3( 1, 0, 0 ); - }; + return function translateX( distance ) { - }(), + return this.translateOnAxis( v1, distance ); - getWorldDirection: function () { + }; - var quaternion = new Quaternion(); + }(), - return function getWorldDirection( optionalTarget ) { + translateY: function () { - var result = optionalTarget || new Vector3(); + var v1 = new Vector3( 0, 1, 0 ); - this.getWorldQuaternion( quaternion ); + return function translateY( distance ) { - return result.set( 0, 0, 1 ).applyQuaternion( quaternion ); + return this.translateOnAxis( v1, distance ); - }; + }; - }(), + }(), - raycast: function () {}, + translateZ: function () { - traverse: function ( callback ) { + var v1 = new Vector3( 0, 0, 1 ); - callback( this ); + return function translateZ( distance ) { - var children = this.children; + return this.translateOnAxis( v1, distance ); - for ( var i = 0, l = children.length; i < l; i ++ ) { + }; - children[ i ].traverse( callback ); + }(), - } + localToWorld: function ( vector ) { - }, + return vector.applyMatrix4( this.matrixWorld ); - traverseVisible: function ( callback ) { + }, - if ( this.visible === false ) return; + worldToLocal: function () { - callback( this ); + var m1 = new Matrix4(); - var children = this.children; + return function worldToLocal( vector ) { - for ( var i = 0, l = children.length; i < l; i ++ ) { + return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) ); - children[ i ].traverseVisible( callback ); + }; - } + }(), - }, + lookAt: function () { - traverseAncestors: function ( callback ) { + // This routine does not support objects with rotated and/or translated parent(s) - var parent = this.parent; + var m1 = new Matrix4(); - if ( parent !== null ) { + return function lookAt( vector ) { - callback( parent ); + m1.lookAt( vector, this.position, this.up ); - parent.traverseAncestors( callback ); + this.quaternion.setFromRotationMatrix( m1 ); - } + }; - }, + }(), - updateMatrix: function () { + add: function ( object ) { - this.matrix.compose( this.position, this.quaternion, this.scale ); + if ( arguments.length > 1 ) { - this.matrixWorldNeedsUpdate = true; + for ( var i = 0; i < arguments.length; i ++ ) { - }, + this.add( arguments[ i ] ); - updateMatrixWorld: function ( force ) { + } - if ( this.matrixAutoUpdate === true ) this.updateMatrix(); + return this; - if ( this.matrixWorldNeedsUpdate === true || force === true ) { + } - if ( this.parent === null ) { + if ( object === this ) { - this.matrixWorld.copy( this.matrix ); + console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object ); + return this; - } else { + } - this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); + if ( (object && object.isObject3D) ) { - } + if ( object.parent !== null ) { - this.matrixWorldNeedsUpdate = false; + object.parent.remove( object ); - force = true; + } - } + object.parent = this; + object.dispatchEvent( { type: 'added' } ); - // update children + this.children.push( object ); - for ( var i = 0, l = this.children.length; i < l; i ++ ) { + } else { - this.children[ i ].updateMatrixWorld( force ); + console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object ); - } + } - }, + return this; - toJSON: function ( meta ) { + }, - // meta is '' when called from JSON.stringify - var isRootObject = ( meta === undefined || meta === '' ); + remove: function ( object ) { - var output = {}; + if ( arguments.length > 1 ) { - // 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; i < arguments.length; i ++ ) { - // initialize meta obj - meta = { - geometries: {}, - materials: {}, - textures: {}, - images: {} - }; + this.remove( arguments[ i ] ); - output.metadata = { - version: 4.4, - type: 'Object', - generator: 'Object3D.toJSON' - }; + } - } + } - // standard Object3D serialization + var index = this.children.indexOf( object ); - var object = {}; + if ( index !== - 1 ) { - object.uuid = this.uuid; - object.type = this.type; + object.parent = 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; + object.dispatchEvent( { type: 'removed' } ); - object.matrix = this.matrix.toArray(); + this.children.splice( index, 1 ); - // + } - if ( this.geometry !== undefined ) { + }, - if ( meta.geometries[ this.geometry.uuid ] === undefined ) { + getObjectById: function ( id ) { - meta.geometries[ this.geometry.uuid ] = this.geometry.toJSON( meta ); + return this.getObjectByProperty( 'id', id ); - } + }, - object.geometry = this.geometry.uuid; + getObjectByName: function ( name ) { - } + return this.getObjectByProperty( 'name', name ); - if ( this.material !== undefined ) { + }, - if ( meta.materials[ this.material.uuid ] === undefined ) { + getObjectByProperty: function ( name, value ) { - meta.materials[ this.material.uuid ] = this.material.toJSON( meta ); + if ( this[ name ] === value ) return this; - } + for ( var i = 0, l = this.children.length; i < l; i ++ ) { - object.material = this.material.uuid; + var child = this.children[ i ]; + var object = child.getObjectByProperty( name, value ); - } + if ( object !== undefined ) { - // + return object; - if ( this.children.length > 0 ) { + } - object.children = []; + } - for ( var i = 0; i < this.children.length; i ++ ) { + return undefined; - object.children.push( this.children[ i ].toJSON( meta ).object ); + }, - } + getWorldPosition: function ( optionalTarget ) { - } + var result = optionalTarget || new Vector3(); - if ( isRootObject ) { + this.updateMatrixWorld( true ); - var geometries = extractFromCache( meta.geometries ); - var materials = extractFromCache( meta.materials ); - var textures = extractFromCache( meta.textures ); - var images = extractFromCache( meta.images ); + return result.setFromMatrixPosition( this.matrixWorld ); - 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; + }, - } + getWorldQuaternion: function () { - output.object = object; + var position = new Vector3(); + var scale = new Vector3(); - return output; + return function getWorldQuaternion( optionalTarget ) { - // extract data from the cache hash - // remove metadata on each item - // and return as array - function extractFromCache( cache ) { + var result = optionalTarget || new Quaternion(); - var values = []; - for ( var key in cache ) { + this.updateMatrixWorld( true ); - var data = cache[ key ]; - delete data.metadata; - values.push( data ); + this.matrixWorld.decompose( position, result, scale ); - } - return values; + return result; - } + }; - }, + }(), - clone: function ( recursive ) { + getWorldRotation: function () { - return new this.constructor().copy( this, recursive ); + var quaternion = new Quaternion(); - }, + return function getWorldRotation( optionalTarget ) { - copy: function ( source, recursive ) { + var result = optionalTarget || new Euler(); - if ( recursive === undefined ) recursive = true; + this.getWorldQuaternion( quaternion ); - this.name = source.name; + return result.setFromQuaternion( quaternion, this.rotation.order, false ); - this.up.copy( source.up ); + }; - this.position.copy( source.position ); - this.quaternion.copy( source.quaternion ); - this.scale.copy( source.scale ); + }(), - this.matrix.copy( source.matrix ); - this.matrixWorld.copy( source.matrixWorld ); + getWorldScale: function () { - this.matrixAutoUpdate = source.matrixAutoUpdate; - this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate; + var position = new Vector3(); + var quaternion = new Quaternion(); - this.visible = source.visible; + return function getWorldScale( optionalTarget ) { - this.castShadow = source.castShadow; - this.receiveShadow = source.receiveShadow; + var result = optionalTarget || new Vector3(); - this.frustumCulled = source.frustumCulled; - this.renderOrder = source.renderOrder; + this.updateMatrixWorld( true ); - this.userData = JSON.parse( JSON.stringify( source.userData ) ); + this.matrixWorld.decompose( position, quaternion, result ); - if ( recursive === true ) { + return result; - for ( var i = 0; i < source.children.length; i ++ ) { + }; - var child = source.children[ i ]; - this.add( child.clone() ); + }(), - } + getWorldDirection: function () { - } + var quaternion = new Quaternion(); - return this; + return function getWorldDirection( optionalTarget ) { - } + var result = optionalTarget || new Vector3(); - } ); + this.getWorldQuaternion( quaternion ); - var count$3 = 0; - function Object3DIdCount() { return count$3++; }; + return result.set( 0, 0, 1 ).applyQuaternion( quaternion ); - /** - * @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() { + }(), - Object.defineProperty( this, 'id', { value: GeometryIdCount() } ); + raycast: function () {}, - this.uuid = exports.Math.generateUUID(); + traverse: function ( callback ) { - this.name = ''; - this.type = 'Geometry'; + callback( this ); - this.vertices = []; - this.colors = []; - this.faces = []; - this.faceVertexUvs = [ [] ]; + var children = this.children; - this.morphTargets = []; - this.morphNormals = []; + for ( var i = 0, l = children.length; i < l; i ++ ) { - this.skinWeights = []; - this.skinIndices = []; + children[ i ].traverse( callback ); - this.lineDistances = []; + } - this.boundingBox = null; - this.boundingSphere = null; + }, - // update flags + traverseVisible: function ( callback ) { - this.elementsNeedUpdate = false; - this.verticesNeedUpdate = false; - this.uvsNeedUpdate = false; - this.normalsNeedUpdate = false; - this.colorsNeedUpdate = false; - this.lineDistancesNeedUpdate = false; - this.groupsNeedUpdate = false; + if ( this.visible === false ) return; - }; + callback( this ); - Object.assign( Geometry.prototype, EventDispatcher.prototype, { + var children = this.children; - isGeometry: true, + for ( var i = 0, l = children.length; i < l; i ++ ) { - applyMatrix: function ( matrix ) { + children[ i ].traverseVisible( callback ); - var normalMatrix = new Matrix3().getNormalMatrix( matrix ); + } - for ( var i = 0, il = this.vertices.length; i < il; i ++ ) { + }, - var vertex = this.vertices[ i ]; - vertex.applyMatrix4( matrix ); + traverseAncestors: function ( callback ) { - } + var parent = this.parent; - for ( var i = 0, il = this.faces.length; i < il; i ++ ) { + if ( parent !== null ) { - var face = this.faces[ i ]; - face.normal.applyMatrix3( normalMatrix ).normalize(); + callback( parent ); - for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) { + parent.traverseAncestors( callback ); - face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize(); + } - } + }, - } + updateMatrix: function () { - if ( this.boundingBox !== null ) { + this.matrix.compose( this.position, this.quaternion, this.scale ); - this.computeBoundingBox(); + this.matrixWorldNeedsUpdate = true; - } + }, - if ( this.boundingSphere !== null ) { + updateMatrixWorld: function ( force ) { - this.computeBoundingSphere(); + if ( this.matrixAutoUpdate === true ) this.updateMatrix(); - } + if ( this.matrixWorldNeedsUpdate === true || force === true ) { - this.verticesNeedUpdate = true; - this.normalsNeedUpdate = true; + if ( this.parent === null ) { - return this; + this.matrixWorld.copy( this.matrix ); - }, + } else { - rotateX: function () { + this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); - // rotate geometry around world x-axis + } - var m1; + this.matrixWorldNeedsUpdate = false; - return function rotateX( angle ) { + force = true; - if ( m1 === undefined ) m1 = new Matrix4(); + } - m1.makeRotationX( angle ); + // update children - this.applyMatrix( m1 ); + for ( var i = 0, l = this.children.length; i < l; i ++ ) { - return this; + this.children[ i ].updateMatrixWorld( force ); - }; + } - }(), + }, - rotateY: function () { + toJSON: function ( meta ) { - // rotate geometry around world y-axis + // meta is '' when called from JSON.stringify + var isRootObject = ( meta === undefined || meta === '' ); - var m1; + var output = {}; - return function rotateY( angle ) { + // meta is a hash used to collect geometries, materials. + // not providing it implies that this is the root object + // being serialized. + if ( isRootObject ) { - if ( m1 === undefined ) m1 = new Matrix4(); + // initialize meta obj + meta = { + geometries: {}, + materials: {}, + textures: {}, + images: {} + }; - m1.makeRotationY( angle ); + output.metadata = { + version: 4.4, + type: 'Object', + generator: 'Object3D.toJSON' + }; - this.applyMatrix( m1 ); + } - return this; + // standard Object3D serialization - }; + var object = {}; - }(), + object.uuid = this.uuid; + object.type = this.type; - rotateZ: function () { + 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; - // rotate geometry around world z-axis + object.matrix = this.matrix.toArray(); - var m1; + // - return function rotateZ( angle ) { + if ( this.geometry !== undefined ) { - if ( m1 === undefined ) m1 = new Matrix4(); + if ( meta.geometries[ this.geometry.uuid ] === undefined ) { - m1.makeRotationZ( angle ); + meta.geometries[ this.geometry.uuid ] = this.geometry.toJSON( meta ); - this.applyMatrix( m1 ); + } - return this; + object.geometry = this.geometry.uuid; - }; + } - }(), + if ( this.material !== undefined ) { - translate: function () { + if ( meta.materials[ this.material.uuid ] === undefined ) { - // translate geometry + meta.materials[ this.material.uuid ] = this.material.toJSON( meta ); - var m1; + } - return function translate( x, y, z ) { + object.material = this.material.uuid; - if ( m1 === undefined ) m1 = new Matrix4(); + } - m1.makeTranslation( x, y, z ); + // - this.applyMatrix( m1 ); + if ( this.children.length > 0 ) { - return this; + object.children = []; - }; + for ( var i = 0; i < this.children.length; i ++ ) { - }(), + object.children.push( this.children[ i ].toJSON( meta ).object ); - scale: function () { + } - // scale geometry + } - var m1; + if ( isRootObject ) { - return function scale( x, y, z ) { + var geometries = extractFromCache( meta.geometries ); + var materials = extractFromCache( meta.materials ); + var textures = extractFromCache( meta.textures ); + var images = extractFromCache( meta.images ); - if ( m1 === undefined ) m1 = new Matrix4(); + 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; - m1.makeScale( x, y, z ); + } - this.applyMatrix( m1 ); + output.object = object; - return this; + 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 ) { - lookAt: function () { + var data = cache[ key ]; + delete data.metadata; + values.push( data ); - var obj; + } + return values; - return function lookAt( vector ) { + } - if ( obj === undefined ) obj = new Object3D(); + }, - obj.lookAt( vector ); + clone: function ( recursive ) { - obj.updateMatrix(); + return new this.constructor().copy( this, recursive ); - this.applyMatrix( obj.matrix ); + }, - }; + copy: function ( source, recursive ) { - }(), + if ( recursive === undefined ) recursive = true; - fromBufferGeometry: function ( geometry ) { + this.name = source.name; - var scope = this; + this.up.copy( source.up ); - var indices = geometry.index !== null ? geometry.index.array : undefined; - var attributes = geometry.attributes; + this.position.copy( source.position ); + this.quaternion.copy( source.quaternion ); + this.scale.copy( source.scale ); - 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; + this.matrix.copy( source.matrix ); + this.matrixWorld.copy( source.matrixWorld ); - if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = []; + this.matrixAutoUpdate = source.matrixAutoUpdate; + this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate; - var tempNormals = []; - var tempUVs = []; - var tempUVs2 = []; + this.visible = source.visible; - for ( var i = 0, j = 0; i < positions.length; i += 3, j += 2 ) { + this.castShadow = source.castShadow; + this.receiveShadow = source.receiveShadow; - scope.vertices.push( new Vector3( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ) ); + this.frustumCulled = source.frustumCulled; + this.renderOrder = source.renderOrder; - if ( normals !== undefined ) { + this.userData = JSON.parse( JSON.stringify( source.userData ) ); - tempNormals.push( new Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) ); + if ( recursive === true ) { - } + for ( var i = 0; i < source.children.length; i ++ ) { - if ( colors !== undefined ) { + var child = source.children[ i ]; + this.add( child.clone() ); - scope.colors.push( new Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) ); + } - } + } - if ( uvs !== undefined ) { + return this; - tempUVs.push( new Vector2( uvs[ j ], uvs[ j + 1 ] ) ); + } - } + } ); - if ( uvs2 !== undefined ) { + var count$3 = 0; + function Object3DIdCount() { return count$3++; }; - tempUVs2.push( new Vector2( uvs2[ j ], uvs2[ j + 1 ] ) ); + /** + * @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() { - } + Object.defineProperty( this, 'id', { value: GeometryIdCount() } ); - function addFace( a, b, c, materialIndex ) { + this.uuid = exports.Math.generateUUID(); - 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() ] : []; + this.name = ''; + this.type = 'Geometry'; - var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex ); + this.vertices = []; + this.colors = []; + this.faces = []; + this.faceVertexUvs = [ [] ]; - scope.faces.push( face ); + this.morphTargets = []; + this.morphNormals = []; - if ( uvs !== undefined ) { + this.skinWeights = []; + this.skinIndices = []; - scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] ); + this.lineDistances = []; - } + this.boundingBox = null; + this.boundingSphere = null; - if ( uvs2 !== undefined ) { + // update flags - scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] ); + this.elementsNeedUpdate = false; + this.verticesNeedUpdate = false; + this.uvsNeedUpdate = false; + this.normalsNeedUpdate = false; + this.colorsNeedUpdate = false; + this.lineDistancesNeedUpdate = false; + this.groupsNeedUpdate = false; - } + }; - } + Object.assign( Geometry.prototype, EventDispatcher.prototype, { - if ( indices !== undefined ) { + isGeometry: true, - var groups = geometry.groups; + applyMatrix: function ( matrix ) { - if ( groups.length > 0 ) { + var normalMatrix = new Matrix3().getNormalMatrix( matrix ); - for ( var i = 0; i < groups.length; i ++ ) { + for ( var i = 0, il = this.vertices.length; i < il; i ++ ) { - var group = groups[ i ]; + var vertex = this.vertices[ i ]; + vertex.applyMatrix4( matrix ); - var start = group.start; - var count = group.count; + } - for ( var j = start, jl = start + count; j < jl; j += 3 ) { + for ( var i = 0, il = this.faces.length; i < il; i ++ ) { - addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex ); + var face = this.faces[ i ]; + face.normal.applyMatrix3( normalMatrix ).normalize(); - } + for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) { - } + face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize(); - } else { + } - for ( var i = 0; i < indices.length; i += 3 ) { + } - addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] ); + if ( this.boundingBox !== null ) { - } + this.computeBoundingBox(); - } + } - } else { + if ( this.boundingSphere !== null ) { - for ( var i = 0; i < positions.length / 3; i += 3 ) { + this.computeBoundingSphere(); - addFace( i, i + 1, i + 2 ); + } - } + this.verticesNeedUpdate = true; + this.normalsNeedUpdate = true; - } + return this; - this.computeFaceNormals(); + }, - if ( geometry.boundingBox !== null ) { + rotateX: function () { - this.boundingBox = geometry.boundingBox.clone(); + // rotate geometry around world x-axis - } + var m1; - if ( geometry.boundingSphere !== null ) { + return function rotateX( angle ) { - this.boundingSphere = geometry.boundingSphere.clone(); + if ( m1 === undefined ) m1 = new Matrix4(); - } + m1.makeRotationX( angle ); - return this; + this.applyMatrix( m1 ); - }, + return this; - center: function () { + }; - this.computeBoundingBox(); + }(), - var offset = this.boundingBox.center().negate(); + rotateY: function () { - this.translate( offset.x, offset.y, offset.z ); + // rotate geometry around world y-axis - return offset; + var m1; - }, + return function rotateY( angle ) { - normalize: function () { + if ( m1 === undefined ) m1 = new Matrix4(); - this.computeBoundingSphere(); + m1.makeRotationY( angle ); - var center = this.boundingSphere.center; - var radius = this.boundingSphere.radius; + this.applyMatrix( m1 ); - var s = radius === 0 ? 1 : 1.0 / radius; + return this; - 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 - ); + }; - this.applyMatrix( matrix ); + }(), - return this; + rotateZ: function () { - }, + // rotate geometry around world z-axis - computeFaceNormals: function () { + var m1; - var cb = new Vector3(), ab = new Vector3(); + return function rotateZ( angle ) { - for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) { + if ( m1 === undefined ) m1 = new Matrix4(); - var face = this.faces[ f ]; + m1.makeRotationZ( angle ); - var vA = this.vertices[ face.a ]; - var vB = this.vertices[ face.b ]; - var vC = this.vertices[ face.c ]; + this.applyMatrix( m1 ); - cb.subVectors( vC, vB ); - ab.subVectors( vA, vB ); - cb.cross( ab ); + return this; - cb.normalize(); + }; - face.normal.copy( cb ); + }(), - } + translate: function () { - }, + // translate geometry - computeVertexNormals: function ( areaWeighted ) { + var m1; - if ( areaWeighted === undefined ) areaWeighted = true; + return function translate( x, y, z ) { - var v, vl, f, fl, face, vertices; + if ( m1 === undefined ) m1 = new Matrix4(); - vertices = new Array( this.vertices.length ); + m1.makeTranslation( x, y, z ); - for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) { + this.applyMatrix( m1 ); - vertices[ v ] = new Vector3(); + return this; - } + }; - if ( areaWeighted ) { + }(), - // vertex normals weighted by triangle areas - // http://www.iquilezles.org/www/articles/normals/normals.htm + scale: function () { - var vA, vB, vC; - var cb = new Vector3(), ab = new Vector3(); + // scale geometry - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + var m1; - face = this.faces[ f ]; + return function scale( x, y, z ) { - vA = this.vertices[ face.a ]; - vB = this.vertices[ face.b ]; - vC = this.vertices[ face.c ]; + if ( m1 === undefined ) m1 = new Matrix4(); - cb.subVectors( vC, vB ); - ab.subVectors( vA, vB ); - cb.cross( ab ); + m1.makeScale( x, y, z ); - vertices[ face.a ].add( cb ); - vertices[ face.b ].add( cb ); - vertices[ face.c ].add( cb ); + this.applyMatrix( m1 ); - } + return this; - } else { + }; - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + }(), - face = this.faces[ f ]; + lookAt: function () { - vertices[ face.a ].add( face.normal ); - vertices[ face.b ].add( face.normal ); - vertices[ face.c ].add( face.normal ); + var obj; - } + return function lookAt( vector ) { - } + if ( obj === undefined ) obj = new Object3D(); - for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) { + obj.lookAt( vector ); - vertices[ v ].normalize(); + obj.updateMatrix(); - } + this.applyMatrix( obj.matrix ); - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + }; - face = this.faces[ f ]; + }(), - var vertexNormals = face.vertexNormals; + fromBufferGeometry: function ( geometry ) { - if ( vertexNormals.length === 3 ) { + var scope = this; - vertexNormals[ 0 ].copy( vertices[ face.a ] ); - vertexNormals[ 1 ].copy( vertices[ face.b ] ); - vertexNormals[ 2 ].copy( vertices[ face.c ] ); + var indices = geometry.index !== null ? geometry.index.array : undefined; + var attributes = geometry.attributes; - } else { + 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; - vertexNormals[ 0 ] = vertices[ face.a ].clone(); - vertexNormals[ 1 ] = vertices[ face.b ].clone(); - vertexNormals[ 2 ] = vertices[ face.c ].clone(); + if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = []; - } + var tempNormals = []; + var tempUVs = []; + var tempUVs2 = []; - } + for ( var i = 0, j = 0; i < positions.length; i += 3, j += 2 ) { - if ( this.faces.length > 0 ) { + scope.vertices.push( new Vector3( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ) ); - this.normalsNeedUpdate = true; + if ( normals !== undefined ) { - } + tempNormals.push( new Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) ); - }, + } - computeMorphNormals: function () { + if ( colors !== undefined ) { - var i, il, f, fl, face; + scope.colors.push( new Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) ); - // save original normals - // - create temp variables on first access - // otherwise just copy (for faster repeated calls) + } - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + if ( uvs !== undefined ) { - face = this.faces[ f ]; + tempUVs.push( new Vector2( uvs[ j ], uvs[ j + 1 ] ) ); - if ( ! face.__originalFaceNormal ) { + } - face.__originalFaceNormal = face.normal.clone(); + if ( uvs2 !== undefined ) { - } else { + tempUVs2.push( new Vector2( uvs2[ j ], uvs2[ j + 1 ] ) ); - face.__originalFaceNormal.copy( face.normal ); + } - } + } - if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = []; + function addFace( a, b, c, materialIndex ) { - for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) { + 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() ] : []; - if ( ! face.__originalVertexNormals[ i ] ) { + var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex ); - face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone(); + scope.faces.push( face ); - } else { + if ( uvs !== undefined ) { - face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] ); + scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] ); - } + } - } + if ( uvs2 !== undefined ) { - } + scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] ); - // use temp geometry to compute face and vertex normals for each morph + } - var tmpGeo = new Geometry(); - tmpGeo.faces = this.faces; + } - for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) { + if ( indices !== undefined ) { - // create on first access + var groups = geometry.groups; - if ( ! this.morphNormals[ i ] ) { + if ( groups.length > 0 ) { - this.morphNormals[ i ] = {}; - this.morphNormals[ i ].faceNormals = []; - this.morphNormals[ i ].vertexNormals = []; + for ( var i = 0; i < groups.length; i ++ ) { - var dstNormalsFace = this.morphNormals[ i ].faceNormals; - var dstNormalsVertex = this.morphNormals[ i ].vertexNormals; + var group = groups[ i ]; - var faceNormal, vertexNormals; + var start = group.start; + var count = group.count; - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + for ( var j = start, jl = start + count; j < jl; j += 3 ) { - faceNormal = new Vector3(); - vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() }; + addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex ); - dstNormalsFace.push( faceNormal ); - dstNormalsVertex.push( vertexNormals ); + } - } + } - } + } else { - var morphNormals = this.morphNormals[ i ]; + for ( var i = 0; i < indices.length; i += 3 ) { - // set vertices to morph target + addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] ); - tmpGeo.vertices = this.morphTargets[ i ].vertices; + } - // compute morph normals + } - tmpGeo.computeFaceNormals(); - tmpGeo.computeVertexNormals(); + } else { - // store morph normals + for ( var i = 0; i < positions.length / 3; i += 3 ) { - var faceNormal, vertexNormals; + addFace( i, i + 1, i + 2 ); - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + } - face = this.faces[ f ]; + } - faceNormal = morphNormals.faceNormals[ f ]; - vertexNormals = morphNormals.vertexNormals[ f ]; + this.computeFaceNormals(); - faceNormal.copy( face.normal ); + if ( geometry.boundingBox !== null ) { - vertexNormals.a.copy( face.vertexNormals[ 0 ] ); - vertexNormals.b.copy( face.vertexNormals[ 1 ] ); - vertexNormals.c.copy( face.vertexNormals[ 2 ] ); + this.boundingBox = geometry.boundingBox.clone(); - } + } - } + if ( geometry.boundingSphere !== null ) { - // restore original normals + this.boundingSphere = geometry.boundingSphere.clone(); - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + } - face = this.faces[ f ]; + return this; - face.normal = face.__originalFaceNormal; - face.vertexNormals = face.__originalVertexNormals; + }, - } + center: function () { - }, + this.computeBoundingBox(); - computeTangents: function () { + var offset = this.boundingBox.center().negate(); - console.warn( 'THREE.Geometry: .computeTangents() has been removed.' ); + this.translate( offset.x, offset.y, offset.z ); - }, + return offset; - computeLineDistances: function () { + }, - var d = 0; - var vertices = this.vertices; + normalize: function () { - for ( var i = 0, il = vertices.length; i < il; i ++ ) { + this.computeBoundingSphere(); - if ( i > 0 ) { + var center = this.boundingSphere.center; + var radius = this.boundingSphere.radius; - d += vertices[ i ].distanceTo( vertices[ i - 1 ] ); + 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 + ); - this.lineDistances[ i ] = d; + this.applyMatrix( matrix ); - } + return this; - }, + }, - computeBoundingBox: function () { + computeFaceNormals: function () { - if ( this.boundingBox === null ) { + var cb = new Vector3(), ab = new Vector3(); - this.boundingBox = new Box3(); + for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) { - } + var face = this.faces[ f ]; - this.boundingBox.setFromPoints( this.vertices ); + var vA = this.vertices[ face.a ]; + var vB = this.vertices[ face.b ]; + var vC = this.vertices[ face.c ]; - }, + cb.subVectors( vC, vB ); + ab.subVectors( vA, vB ); + cb.cross( ab ); - computeBoundingSphere: function () { + cb.normalize(); - if ( this.boundingSphere === null ) { + face.normal.copy( cb ); - this.boundingSphere = new Sphere(); + } - } + }, - this.boundingSphere.setFromPoints( this.vertices ); + computeVertexNormals: function ( areaWeighted ) { - }, + if ( areaWeighted === undefined ) areaWeighted = true; - merge: function ( geometry, matrix, materialIndexOffset ) { + var v, vl, f, fl, face, vertices; - if ( (geometry && geometry.isGeometry) === false ) { + vertices = new Array( this.vertices.length ); - console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry ); - return; + for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) { - } + vertices[ v ] = new Vector3(); - 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 ]; + } - if ( materialIndexOffset === undefined ) materialIndexOffset = 0; + if ( areaWeighted ) { - if ( matrix !== undefined ) { + // vertex normals weighted by triangle areas + // http://www.iquilezles.org/www/articles/normals/normals.htm - normalMatrix = new Matrix3().getNormalMatrix( matrix ); + var vA, vB, vC; + var cb = new Vector3(), ab = new Vector3(); - } + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - // vertices + face = this.faces[ f ]; - for ( var i = 0, il = vertices2.length; i < il; i ++ ) { + vA = this.vertices[ face.a ]; + vB = this.vertices[ face.b ]; + vC = this.vertices[ face.c ]; - var vertex = vertices2[ i ]; + cb.subVectors( vC, vB ); + ab.subVectors( vA, vB ); + cb.cross( ab ); - var vertexCopy = vertex.clone(); + vertices[ face.a ].add( cb ); + vertices[ face.b ].add( cb ); + vertices[ face.c ].add( cb ); - if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix ); + } - vertices1.push( vertexCopy ); + } else { - } + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - // faces + face = this.faces[ f ]; - for ( i = 0, il = faces2.length; i < il; i ++ ) { + vertices[ face.a ].add( face.normal ); + vertices[ face.b ].add( face.normal ); + vertices[ face.c ].add( face.normal ); - var face = faces2[ i ], faceCopy, normal, color, - faceVertexNormals = face.vertexNormals, - faceVertexColors = face.vertexColors; + } - faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset ); - faceCopy.normal.copy( face.normal ); + } - if ( normalMatrix !== undefined ) { + for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) { - faceCopy.normal.applyMatrix3( normalMatrix ).normalize(); + vertices[ v ].normalize(); - } + } - for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) { + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - normal = faceVertexNormals[ j ].clone(); + face = this.faces[ f ]; - if ( normalMatrix !== undefined ) { + var vertexNormals = face.vertexNormals; - normal.applyMatrix3( normalMatrix ).normalize(); + if ( vertexNormals.length === 3 ) { - } + vertexNormals[ 0 ].copy( vertices[ face.a ] ); + vertexNormals[ 1 ].copy( vertices[ face.b ] ); + vertexNormals[ 2 ].copy( vertices[ face.c ] ); - faceCopy.vertexNormals.push( normal ); + } else { - } + vertexNormals[ 0 ] = vertices[ face.a ].clone(); + vertexNormals[ 1 ] = vertices[ face.b ].clone(); + vertexNormals[ 2 ] = vertices[ face.c ].clone(); - faceCopy.color.copy( face.color ); + } - for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) { + } - color = faceVertexColors[ j ]; - faceCopy.vertexColors.push( color.clone() ); + if ( this.faces.length > 0 ) { - } + this.normalsNeedUpdate = true; - faceCopy.materialIndex = face.materialIndex + materialIndexOffset; + } - faces1.push( faceCopy ); + }, - } + computeMorphNormals: function () { - // uvs + var i, il, f, fl, face; - for ( i = 0, il = uvs2.length; i < il; i ++ ) { + // save original normals + // - create temp variables on first access + // otherwise just copy (for faster repeated calls) - var uv = uvs2[ i ], uvCopy = []; + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - if ( uv === undefined ) { + face = this.faces[ f ]; - continue; + if ( ! face.__originalFaceNormal ) { - } + face.__originalFaceNormal = face.normal.clone(); - for ( var j = 0, jl = uv.length; j < jl; j ++ ) { + } else { - uvCopy.push( uv[ j ].clone() ); + face.__originalFaceNormal.copy( face.normal ); - } + } - uvs1.push( uvCopy ); + if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = []; - } + for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) { - }, + if ( ! face.__originalVertexNormals[ i ] ) { - mergeMesh: function ( mesh ) { + face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone(); - if ( (mesh && mesh.isMesh) === false ) { + } else { - console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh ); - return; + face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] ); - } + } - mesh.matrixAutoUpdate && mesh.updateMatrix(); + } - this.merge( mesh.geometry, mesh.matrix ); + } - }, + // use temp geometry to compute face and vertex normals for each morph - /* - * Checks for duplicate vertices with hashmap. - * Duplicated vertices are removed - * and faces' vertices are updated. - */ + var tmpGeo = new Geometry(); + tmpGeo.faces = this.faces; - mergeVertices: function () { + for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) { - var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique) - var unique = [], changes = []; + // create on first access - 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; + if ( ! this.morphNormals[ i ] ) { - for ( i = 0, il = this.vertices.length; i < il; i ++ ) { + this.morphNormals[ i ] = {}; + this.morphNormals[ i ].faceNormals = []; + this.morphNormals[ i ].vertexNormals = []; - v = this.vertices[ i ]; - key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision ); + var dstNormalsFace = this.morphNormals[ i ].faceNormals; + var dstNormalsVertex = this.morphNormals[ i ].vertexNormals; - if ( verticesMap[ key ] === undefined ) { + var faceNormal, vertexNormals; - verticesMap[ key ] = i; - unique.push( this.vertices[ i ] ); - changes[ i ] = unique.length - 1; + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - } else { + faceNormal = new Vector3(); + vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() }; - //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]); - changes[ i ] = changes[ verticesMap[ key ] ]; + dstNormalsFace.push( faceNormal ); + dstNormalsVertex.push( vertexNormals ); - } + } - } + } + var morphNormals = this.morphNormals[ i ]; - // if faces are completely degenerate after merging vertices, we - // have to remove them from the geometry. - var faceIndicesToRemove = []; + // set vertices to morph target - for ( i = 0, il = this.faces.length; i < il; i ++ ) { + tmpGeo.vertices = this.morphTargets[ i ].vertices; - face = this.faces[ i ]; + // compute morph normals - face.a = changes[ face.a ]; - face.b = changes[ face.b ]; - face.c = changes[ face.c ]; + tmpGeo.computeFaceNormals(); + tmpGeo.computeVertexNormals(); - indices = [ face.a, face.b, face.c ]; + // store morph normals - var dupIndex = - 1; + var faceNormal, vertexNormals; - // 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 ++ ) { + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) { + face = this.faces[ f ]; - dupIndex = n; - faceIndicesToRemove.push( i ); - break; + faceNormal = morphNormals.faceNormals[ f ]; + vertexNormals = morphNormals.vertexNormals[ f ]; - } + faceNormal.copy( face.normal ); - } + vertexNormals.a.copy( face.vertexNormals[ 0 ] ); + vertexNormals.b.copy( face.vertexNormals[ 1 ] ); + vertexNormals.c.copy( face.vertexNormals[ 2 ] ); - } + } - for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) { + } - var idx = faceIndicesToRemove[ i ]; + // restore original normals - this.faces.splice( idx, 1 ); + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) { + face = this.faces[ f ]; - this.faceVertexUvs[ j ].splice( idx, 1 ); + face.normal = face.__originalFaceNormal; + face.vertexNormals = face.__originalVertexNormals; - } + } - } + }, - // Use unique set of vertices + computeTangents: function () { - var diff = this.vertices.length - unique.length; - this.vertices = unique; - return diff; + console.warn( 'THREE.Geometry: .computeTangents() has been removed.' ); - }, + }, - sortFacesByMaterialIndex: function () { + computeLineDistances: function () { - var faces = this.faces; - var length = faces.length; + var d = 0; + var vertices = this.vertices; - // tag faces + for ( var i = 0, il = vertices.length; i < il; i ++ ) { - for ( var i = 0; i < length; i ++ ) { + if ( i > 0 ) { - faces[ i ]._id = i; + d += vertices[ i ].distanceTo( vertices[ i - 1 ] ); - } + } - // sort faces + this.lineDistances[ i ] = d; - function materialIndexSort( a, b ) { + } - return a.materialIndex - b.materialIndex; + }, - } + computeBoundingBox: function () { - faces.sort( materialIndexSort ); + if ( this.boundingBox === null ) { - // sort uvs + this.boundingBox = new Box3(); - var uvs1 = this.faceVertexUvs[ 0 ]; - var uvs2 = this.faceVertexUvs[ 1 ]; + } - var newUvs1, newUvs2; + this.boundingBox.setFromPoints( this.vertices ); - if ( uvs1 && uvs1.length === length ) newUvs1 = []; - if ( uvs2 && uvs2.length === length ) newUvs2 = []; + }, - for ( var i = 0; i < length; i ++ ) { + computeBoundingSphere: function () { - var id = faces[ i ]._id; + if ( this.boundingSphere === null ) { - if ( newUvs1 ) newUvs1.push( uvs1[ id ] ); - if ( newUvs2 ) newUvs2.push( uvs2[ id ] ); + this.boundingSphere = new Sphere(); - } + } - if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1; - if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2; + this.boundingSphere.setFromPoints( this.vertices ); - }, + }, - toJSON: function () { + merge: function ( geometry, matrix, materialIndexOffset ) { - var data = { - metadata: { - version: 4.4, - type: 'Geometry', - generator: 'Geometry.toJSON' - } - }; + if ( (geometry && geometry.isGeometry) === false ) { - // standard Geometry serialization + console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry ); + return; - data.uuid = this.uuid; - data.type = this.type; - if ( this.name !== '' ) data.name = this.name; + } - if ( this.parameters !== undefined ) { + 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 ]; - var parameters = this.parameters; + if ( materialIndexOffset === undefined ) materialIndexOffset = 0; - for ( var key in parameters ) { + if ( matrix !== undefined ) { - if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ]; + normalMatrix = new Matrix3().getNormalMatrix( matrix ); - } + } - return data; + // vertices - } + for ( var i = 0, il = vertices2.length; i < il; i ++ ) { - var vertices = []; + var vertex = vertices2[ i ]; - for ( var i = 0; i < this.vertices.length; i ++ ) { + var vertexCopy = vertex.clone(); - var vertex = this.vertices[ i ]; - vertices.push( vertex.x, vertex.y, vertex.z ); + if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix ); - } + vertices1.push( vertexCopy ); - var faces = []; - var normals = []; - var normalsHash = {}; - var colors = []; - var colorsHash = {}; - var uvs = []; - var uvsHash = {}; + } - for ( var i = 0; i < this.faces.length; i ++ ) { + // faces - var face = this.faces[ i ]; + for ( i = 0, il = faces2.length; i < il; i ++ ) { - 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 face = faces2[ i ], faceCopy, normal, color, + faceVertexNormals = face.vertexNormals, + faceVertexColors = face.vertexColors; - var faceType = 0; + faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset ); + faceCopy.normal.copy( face.normal ); - 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 ); + if ( normalMatrix !== undefined ) { - faces.push( faceType ); - faces.push( face.a, face.b, face.c ); - faces.push( face.materialIndex ); + faceCopy.normal.applyMatrix3( normalMatrix ).normalize(); - if ( hasFaceVertexUv ) { + } - var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ]; + for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) { - faces.push( - getUvIndex( faceVertexUvs[ 0 ] ), - getUvIndex( faceVertexUvs[ 1 ] ), - getUvIndex( faceVertexUvs[ 2 ] ) - ); + normal = faceVertexNormals[ j ].clone(); - } + if ( normalMatrix !== undefined ) { - if ( hasFaceNormal ) { + normal.applyMatrix3( normalMatrix ).normalize(); - faces.push( getNormalIndex( face.normal ) ); + } - } + faceCopy.vertexNormals.push( normal ); - if ( hasFaceVertexNormal ) { + } - var vertexNormals = face.vertexNormals; + faceCopy.color.copy( face.color ); - faces.push( - getNormalIndex( vertexNormals[ 0 ] ), - getNormalIndex( vertexNormals[ 1 ] ), - getNormalIndex( vertexNormals[ 2 ] ) - ); + for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) { - } + color = faceVertexColors[ j ]; + faceCopy.vertexColors.push( color.clone() ); - if ( hasFaceColor ) { + } - faces.push( getColorIndex( face.color ) ); + faceCopy.materialIndex = face.materialIndex + materialIndexOffset; - } + faces1.push( faceCopy ); - if ( hasFaceVertexColor ) { + } - var vertexColors = face.vertexColors; + // uvs - faces.push( - getColorIndex( vertexColors[ 0 ] ), - getColorIndex( vertexColors[ 1 ] ), - getColorIndex( vertexColors[ 2 ] ) - ); + for ( i = 0, il = uvs2.length; i < il; i ++ ) { - } + var uv = uvs2[ i ], uvCopy = []; - } + if ( uv === undefined ) { - function setBit( value, position, enabled ) { + continue; - return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) ); + } - } + for ( var j = 0, jl = uv.length; j < jl; j ++ ) { - function getNormalIndex( normal ) { + uvCopy.push( uv[ j ].clone() ); - var hash = normal.x.toString() + normal.y.toString() + normal.z.toString(); + } - if ( normalsHash[ hash ] !== undefined ) { + uvs1.push( uvCopy ); - return normalsHash[ hash ]; + } - } + }, - normalsHash[ hash ] = normals.length / 3; - normals.push( normal.x, normal.y, normal.z ); + mergeMesh: function ( mesh ) { - return normalsHash[ hash ]; + if ( (mesh && mesh.isMesh) === false ) { - } + console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh ); + return; - function getColorIndex( color ) { + } - var hash = color.r.toString() + color.g.toString() + color.b.toString(); + mesh.matrixAutoUpdate && mesh.updateMatrix(); - if ( colorsHash[ hash ] !== undefined ) { + this.merge( mesh.geometry, mesh.matrix ); - return colorsHash[ hash ]; + }, - } + /* + * Checks for duplicate vertices with hashmap. + * Duplicated vertices are removed + * and faces' vertices are updated. + */ - colorsHash[ hash ] = colors.length; - colors.push( color.getHex() ); + mergeVertices: function () { - return colorsHash[ hash ]; + 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; - function getUvIndex( uv ) { + for ( i = 0, il = this.vertices.length; i < il; i ++ ) { - var hash = uv.x.toString() + uv.y.toString(); + v = this.vertices[ i ]; + key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision ); - if ( uvsHash[ hash ] !== undefined ) { + if ( verticesMap[ key ] === undefined ) { - return uvsHash[ hash ]; + verticesMap[ key ] = i; + unique.push( this.vertices[ i ] ); + changes[ i ] = unique.length - 1; - } + } else { - uvsHash[ hash ] = uvs.length / 2; - uvs.push( uv.x, uv.y ); + //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]); + changes[ i ] = changes[ verticesMap[ key ] ]; - return uvsHash[ hash ]; + } - } + } - data.data = {}; - 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; + // if faces are completely degenerate after merging vertices, we + // have to remove them from the geometry. + var faceIndicesToRemove = []; - return data; + for ( i = 0, il = this.faces.length; i < il; i ++ ) { - }, + face = this.faces[ i ]; - clone: function () { + face.a = changes[ face.a ]; + face.b = changes[ face.b ]; + face.c = changes[ face.c ]; - /* - // Handle primitives + indices = [ face.a, face.b, face.c ]; - var parameters = this.parameters; + var dupIndex = - 1; - if ( parameters !== 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 ++ ) { - var values = []; + if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) { - for ( var key in parameters ) { + dupIndex = n; + faceIndicesToRemove.push( i ); + break; - values.push( parameters[ key ] ); + } - } + } - var geometry = Object.create( this.constructor.prototype ); - this.constructor.apply( geometry, values ); - return geometry; + } - } + for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) { - return new this.constructor().copy( this ); - */ + var idx = faceIndicesToRemove[ i ]; - return new Geometry().copy( this ); + this.faces.splice( idx, 1 ); - }, + for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) { - copy: function ( source ) { + this.faceVertexUvs[ j ].splice( idx, 1 ); - this.vertices = []; - this.faces = []; - this.faceVertexUvs = [ [] ]; + } - var vertices = source.vertices; + } - for ( var i = 0, il = vertices.length; i < il; i ++ ) { + // Use unique set of vertices - this.vertices.push( vertices[ i ].clone() ); + var diff = this.vertices.length - unique.length; + this.vertices = unique; + return diff; - } + }, - var faces = source.faces; + sortFacesByMaterialIndex: function () { - for ( var i = 0, il = faces.length; i < il; i ++ ) { + var faces = this.faces; + var length = faces.length; - this.faces.push( faces[ i ].clone() ); + // tag faces - } + for ( var i = 0; i < length; i ++ ) { - for ( var i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) { + faces[ i ]._id = i; - var faceVertexUvs = source.faceVertexUvs[ i ]; + } - if ( this.faceVertexUvs[ i ] === undefined ) { + // sort faces - this.faceVertexUvs[ i ] = []; + function materialIndexSort( a, b ) { - } + return a.materialIndex - b.materialIndex; - for ( var j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) { + } - var uvs = faceVertexUvs[ j ], uvsCopy = []; + faces.sort( materialIndexSort ); - for ( var k = 0, kl = uvs.length; k < kl; k ++ ) { + // sort uvs - var uv = uvs[ k ]; + var uvs1 = this.faceVertexUvs[ 0 ]; + var uvs2 = this.faceVertexUvs[ 1 ]; - uvsCopy.push( uv.clone() ); + var newUvs1, newUvs2; - } + if ( uvs1 && uvs1.length === length ) newUvs1 = []; + if ( uvs2 && uvs2.length === length ) newUvs2 = []; - this.faceVertexUvs[ i ].push( uvsCopy ); + for ( var i = 0; i < length; i ++ ) { - } + var id = faces[ i ]._id; - } + if ( newUvs1 ) newUvs1.push( uvs1[ id ] ); + if ( newUvs2 ) newUvs2.push( uvs2[ id ] ); - return this; + } - }, + if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1; + if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2; - dispose: function () { + }, - this.dispatchEvent( { type: 'dispose' } ); + toJSON: function () { - } + var data = { + metadata: { + version: 4.4, + type: 'Geometry', + generator: 'Geometry.toJSON' + } + }; - } ); + // standard Geometry serialization - var count$2 = 0; - function GeometryIdCount() { return count$2++; }; + data.uuid = this.uuid; + data.type = this.type; + if ( this.name !== '' ) data.name = this.name; - /** - * @author mrdoob / http://mrdoob.com/ - */ + if ( this.parameters !== undefined ) { - function DirectGeometry() { + var parameters = this.parameters; - Object.defineProperty( this, 'id', { value: GeometryIdCount() } ); + for ( var key in parameters ) { - this.uuid = exports.Math.generateUUID(); + if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ]; - this.name = ''; - this.type = 'DirectGeometry'; + } - this.indices = []; - this.vertices = []; - this.normals = []; - this.colors = []; - this.uvs = []; - this.uvs2 = []; + return data; - this.groups = []; + } - this.morphTargets = {}; + var vertices = []; - this.skinWeights = []; - this.skinIndices = []; + for ( var i = 0; i < this.vertices.length; i ++ ) { - // this.lineDistances = []; + var vertex = this.vertices[ i ]; + vertices.push( vertex.x, vertex.y, vertex.z ); - this.boundingBox = null; - this.boundingSphere = null; + } - // update flags + var faces = []; + var normals = []; + var normalsHash = {}; + var colors = []; + var colorsHash = {}; + var uvs = []; + var uvsHash = {}; - this.verticesNeedUpdate = false; - this.normalsNeedUpdate = false; - this.colorsNeedUpdate = false; - this.uvsNeedUpdate = false; - this.groupsNeedUpdate = false; + for ( var i = 0; i < this.faces.length; i ++ ) { - }; + var face = this.faces[ i ]; - Object.assign( DirectGeometry.prototype, EventDispatcher.prototype, { + 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; - computeBoundingBox: Geometry.prototype.computeBoundingBox, - computeBoundingSphere: Geometry.prototype.computeBoundingSphere, + var faceType = 0; - computeFaceNormals: function () { + 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 ); - console.warn( 'THREE.DirectGeometry: computeFaceNormals() is not a method of this type of geometry.' ); + faces.push( faceType ); + faces.push( face.a, face.b, face.c ); + faces.push( face.materialIndex ); - }, + if ( hasFaceVertexUv ) { - computeVertexNormals: function () { + var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ]; - console.warn( 'THREE.DirectGeometry: computeVertexNormals() is not a method of this type of geometry.' ); + faces.push( + getUvIndex( faceVertexUvs[ 0 ] ), + getUvIndex( faceVertexUvs[ 1 ] ), + getUvIndex( faceVertexUvs[ 2 ] ) + ); - }, + } - computeGroups: function ( geometry ) { + if ( hasFaceNormal ) { - var group; - var groups = []; - var materialIndex; + faces.push( getNormalIndex( face.normal ) ); - var faces = geometry.faces; + } - for ( var i = 0; i < faces.length; i ++ ) { + if ( hasFaceVertexNormal ) { - var face = faces[ i ]; + var vertexNormals = face.vertexNormals; - // materials + faces.push( + getNormalIndex( vertexNormals[ 0 ] ), + getNormalIndex( vertexNormals[ 1 ] ), + getNormalIndex( vertexNormals[ 2 ] ) + ); - if ( face.materialIndex !== materialIndex ) { + } - materialIndex = face.materialIndex; + if ( hasFaceColor ) { - if ( group !== undefined ) { + faces.push( getColorIndex( face.color ) ); - group.count = ( i * 3 ) - group.start; - groups.push( group ); + } - } + if ( hasFaceVertexColor ) { - group = { - start: i * 3, - materialIndex: materialIndex - }; + var vertexColors = face.vertexColors; - } + faces.push( + getColorIndex( vertexColors[ 0 ] ), + getColorIndex( vertexColors[ 1 ] ), + getColorIndex( vertexColors[ 2 ] ) + ); - } + } - if ( group !== undefined ) { + } - group.count = ( i * 3 ) - group.start; - groups.push( group ); + function setBit( value, position, enabled ) { - } + return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) ); - this.groups = groups; + } - }, + function getNormalIndex( normal ) { - fromGeometry: function ( geometry ) { + var hash = normal.x.toString() + normal.y.toString() + normal.z.toString(); - var faces = geometry.faces; - var vertices = geometry.vertices; - var faceVertexUvs = geometry.faceVertexUvs; + if ( normalsHash[ hash ] !== undefined ) { - var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0; - var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0; + return normalsHash[ hash ]; - // morphs + } - var morphTargets = geometry.morphTargets; - var morphTargetsLength = morphTargets.length; + normalsHash[ hash ] = normals.length / 3; + normals.push( normal.x, normal.y, normal.z ); - var morphTargetsPosition; + return normalsHash[ hash ]; - if ( morphTargetsLength > 0 ) { + } - morphTargetsPosition = []; + function getColorIndex( color ) { - for ( var i = 0; i < morphTargetsLength; i ++ ) { + var hash = color.r.toString() + color.g.toString() + color.b.toString(); - morphTargetsPosition[ i ] = []; + if ( colorsHash[ hash ] !== undefined ) { - } + return colorsHash[ hash ]; - this.morphTargets.position = morphTargetsPosition; + } - } + colorsHash[ hash ] = colors.length; + colors.push( color.getHex() ); - var morphNormals = geometry.morphNormals; - var morphNormalsLength = morphNormals.length; + return colorsHash[ hash ]; - var morphTargetsNormal; + } - if ( morphNormalsLength > 0 ) { + function getUvIndex( uv ) { - morphTargetsNormal = []; + var hash = uv.x.toString() + uv.y.toString(); - for ( var i = 0; i < morphNormalsLength; i ++ ) { + if ( uvsHash[ hash ] !== undefined ) { - morphTargetsNormal[ i ] = []; + return uvsHash[ hash ]; - } + } - this.morphTargets.normal = morphTargetsNormal; + uvsHash[ hash ] = uvs.length / 2; + uvs.push( uv.x, uv.y ); - } + return uvsHash[ hash ]; - // skins + } - var skinIndices = geometry.skinIndices; - var skinWeights = geometry.skinWeights; + data.data = {}; - var hasSkinIndices = skinIndices.length === vertices.length; - var hasSkinWeights = skinWeights.length === vertices.length; + 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; - // + return data; - for ( var i = 0; i < faces.length; i ++ ) { + }, - var face = faces[ i ]; + clone: function () { - this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] ); + /* + // Handle primitives - var vertexNormals = face.vertexNormals; + var parameters = this.parameters; - if ( vertexNormals.length === 3 ) { + if ( parameters !== undefined ) { - this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] ); + var values = []; - } else { + for ( var key in parameters ) { - var normal = face.normal; + values.push( parameters[ key ] ); - this.normals.push( normal, normal, normal ); + } - } + var geometry = Object.create( this.constructor.prototype ); + this.constructor.apply( geometry, values ); + return geometry; - var vertexColors = face.vertexColors; + } - if ( vertexColors.length === 3 ) { + return new this.constructor().copy( this ); + */ - this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] ); + return new Geometry().copy( this ); - } else { + }, - var color = face.color; + copy: function ( source ) { - this.colors.push( color, color, color ); + this.vertices = []; + this.faces = []; + this.faceVertexUvs = [ [] ]; - } + var vertices = source.vertices; - if ( hasFaceVertexUv === true ) { + for ( var i = 0, il = vertices.length; i < il; i ++ ) { - var vertexUvs = faceVertexUvs[ 0 ][ i ]; + this.vertices.push( vertices[ i ].clone() ); - if ( vertexUvs !== undefined ) { + } - this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] ); + var faces = source.faces; - } else { + for ( var i = 0, il = faces.length; i < il; i ++ ) { - console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i ); + this.faces.push( faces[ i ].clone() ); - this.uvs.push( new Vector2(), new Vector2(), new Vector2() ); + } - } + for ( var i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) { - } + var faceVertexUvs = source.faceVertexUvs[ i ]; - if ( hasFaceVertexUv2 === true ) { + if ( this.faceVertexUvs[ i ] === undefined ) { - var vertexUvs = faceVertexUvs[ 1 ][ i ]; + this.faceVertexUvs[ i ] = []; - if ( vertexUvs !== undefined ) { + } - this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] ); + for ( var j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) { - } else { + var uvs = faceVertexUvs[ j ], uvsCopy = []; - console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i ); + for ( var k = 0, kl = uvs.length; k < kl; k ++ ) { - this.uvs2.push( new Vector2(), new Vector2(), new Vector2() ); + var uv = uvs[ k ]; - } + uvsCopy.push( uv.clone() ); - } + } - // morphs + this.faceVertexUvs[ i ].push( uvsCopy ); - for ( var j = 0; j < morphTargetsLength; j ++ ) { + } - var morphTarget = morphTargets[ j ].vertices; + } - morphTargetsPosition[ j ].push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] ); + return this; - } + }, - for ( var j = 0; j < morphNormalsLength; j ++ ) { + dispose: function () { - var morphNormal = morphNormals[ j ].vertexNormals[ i ]; + this.dispatchEvent( { type: 'dispose' } ); - morphTargetsNormal[ j ].push( morphNormal.a, morphNormal.b, morphNormal.c ); + } - } + } ); - // skins + var count$2 = 0; + function GeometryIdCount() { return count$2++; }; - if ( hasSkinIndices ) { + /** + * @author mrdoob / http://mrdoob.com/ + */ - this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] ); + function DirectGeometry() { - } + Object.defineProperty( this, 'id', { value: GeometryIdCount() } ); - if ( hasSkinWeights ) { + this.uuid = exports.Math.generateUUID(); - this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] ); + this.name = ''; + this.type = 'DirectGeometry'; - } + this.indices = []; + this.vertices = []; + this.normals = []; + this.colors = []; + this.uvs = []; + this.uvs2 = []; - } + this.groups = []; - this.computeGroups( geometry ); + this.morphTargets = {}; - this.verticesNeedUpdate = geometry.verticesNeedUpdate; - this.normalsNeedUpdate = geometry.normalsNeedUpdate; - this.colorsNeedUpdate = geometry.colorsNeedUpdate; - this.uvsNeedUpdate = geometry.uvsNeedUpdate; - this.groupsNeedUpdate = geometry.groupsNeedUpdate; + this.skinWeights = []; + this.skinIndices = []; - return this; + // this.lineDistances = []; - }, + this.boundingBox = null; + this.boundingSphere = null; - dispose: function () { + // update flags - this.dispatchEvent( { type: 'dispose' } ); + this.verticesNeedUpdate = false; + this.normalsNeedUpdate = false; + this.colorsNeedUpdate = false; + this.uvsNeedUpdate = false; + this.groupsNeedUpdate = false; - } + }; - } ); + Object.assign( DirectGeometry.prototype, EventDispatcher.prototype, { - /** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - */ + computeBoundingBox: Geometry.prototype.computeBoundingBox, + computeBoundingSphere: Geometry.prototype.computeBoundingSphere, - function BufferGeometry() { + computeFaceNormals: function () { - Object.defineProperty( this, 'id', { value: GeometryIdCount() } ); + console.warn( 'THREE.DirectGeometry: computeFaceNormals() is not a method of this type of geometry.' ); - this.uuid = exports.Math.generateUUID(); + }, - this.name = ''; - this.type = 'BufferGeometry'; + computeVertexNormals: function () { - this.index = null; - this.attributes = {}; + console.warn( 'THREE.DirectGeometry: computeVertexNormals() is not a method of this type of geometry.' ); - this.morphAttributes = {}; + }, - this.groups = []; + computeGroups: function ( geometry ) { - this.boundingBox = null; - this.boundingSphere = null; + var group; + var groups = []; + var materialIndex; - this.drawRange = { start: 0, count: Infinity }; + var faces = geometry.faces; - }; + for ( var i = 0; i < faces.length; i ++ ) { - Object.assign( BufferGeometry.prototype, EventDispatcher.prototype, { + var face = faces[ i ]; - isBufferGeometry: true, + // materials - getIndex: function () { + if ( face.materialIndex !== materialIndex ) { - return this.index; + materialIndex = face.materialIndex; - }, + if ( group !== undefined ) { - setIndex: function ( index ) { + group.count = ( i * 3 ) - group.start; + groups.push( group ); - this.index = index; + } - }, + group = { + start: i * 3, + materialIndex: materialIndex + }; - addAttribute: function ( name, attribute ) { + } - if ( (attribute && attribute.isBufferAttribute) === false && (attribute && attribute.isInterleavedBufferAttribute) === false ) { + } - console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' ); + if ( group !== undefined ) { - this.addAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) ); + group.count = ( i * 3 ) - group.start; + groups.push( group ); - return; + } - } + this.groups = groups; - if ( name === 'index' ) { + }, - console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' ); - this.setIndex( attribute ); + fromGeometry: function ( geometry ) { - return; + 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; - this.attributes[ name ] = attribute; + // morphs - return this; + var morphTargets = geometry.morphTargets; + var morphTargetsLength = morphTargets.length; - }, + var morphTargetsPosition; - getAttribute: function ( name ) { + if ( morphTargetsLength > 0 ) { - return this.attributes[ name ]; + morphTargetsPosition = []; - }, + for ( var i = 0; i < morphTargetsLength; i ++ ) { - removeAttribute: function ( name ) { + morphTargetsPosition[ i ] = []; - delete this.attributes[ name ]; + } - return this; + this.morphTargets.position = morphTargetsPosition; - }, + } - addGroup: function ( start, count, materialIndex ) { + var morphNormals = geometry.morphNormals; + var morphNormalsLength = morphNormals.length; - this.groups.push( { + var morphTargetsNormal; - start: start, - count: count, - materialIndex: materialIndex !== undefined ? materialIndex : 0 + if ( morphNormalsLength > 0 ) { - } ); + morphTargetsNormal = []; - }, + for ( var i = 0; i < morphNormalsLength; i ++ ) { - clearGroups: function () { + morphTargetsNormal[ i ] = []; - this.groups = []; + } - }, + this.morphTargets.normal = morphTargetsNormal; - setDrawRange: function ( start, count ) { + } - this.drawRange.start = start; - this.drawRange.count = count; + // skins - }, + var skinIndices = geometry.skinIndices; + var skinWeights = geometry.skinWeights; - applyMatrix: function ( matrix ) { + var hasSkinIndices = skinIndices.length === vertices.length; + var hasSkinWeights = skinWeights.length === vertices.length; - var position = this.attributes.position; + // - if ( position !== undefined ) { + for ( var i = 0; i < faces.length; i ++ ) { - matrix.applyToVector3Array( position.array ); - position.needsUpdate = true; + var face = faces[ i ]; - } + this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] ); - var normal = this.attributes.normal; + var vertexNormals = face.vertexNormals; - if ( normal !== undefined ) { + if ( vertexNormals.length === 3 ) { - var normalMatrix = new Matrix3().getNormalMatrix( matrix ); + this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] ); - normalMatrix.applyToVector3Array( normal.array ); - normal.needsUpdate = true; + } else { - } + var normal = face.normal; - if ( this.boundingBox !== null ) { + this.normals.push( normal, normal, normal ); - this.computeBoundingBox(); + } - } + var vertexColors = face.vertexColors; - if ( this.boundingSphere !== null ) { + if ( vertexColors.length === 3 ) { - this.computeBoundingSphere(); + this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] ); - } + } else { - return this; + var color = face.color; - }, + this.colors.push( color, color, color ); - rotateX: function () { + } - // rotate geometry around world x-axis + if ( hasFaceVertexUv === true ) { - var m1; + var vertexUvs = faceVertexUvs[ 0 ][ i ]; - return function rotateX( angle ) { + if ( vertexUvs !== undefined ) { - if ( m1 === undefined ) m1 = new Matrix4(); + this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] ); - m1.makeRotationX( angle ); + } else { - this.applyMatrix( m1 ); + console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i ); - return this; + this.uvs.push( new Vector2(), new Vector2(), new Vector2() ); - }; + } - }(), + } - rotateY: function () { + if ( hasFaceVertexUv2 === true ) { - // rotate geometry around world y-axis + var vertexUvs = faceVertexUvs[ 1 ][ i ]; - var m1; + if ( vertexUvs !== undefined ) { - return function rotateY( angle ) { + this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] ); - if ( m1 === undefined ) m1 = new Matrix4(); + } else { - m1.makeRotationY( angle ); + console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i ); - this.applyMatrix( m1 ); + this.uvs2.push( new Vector2(), new Vector2(), new Vector2() ); - return this; + } - }; + } - }(), + // morphs - rotateZ: function () { + for ( var j = 0; j < morphTargetsLength; j ++ ) { - // rotate geometry around world z-axis + var morphTarget = morphTargets[ j ].vertices; - var m1; + morphTargetsPosition[ j ].push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] ); - return function rotateZ( angle ) { + } - if ( m1 === undefined ) m1 = new Matrix4(); + for ( var j = 0; j < morphNormalsLength; j ++ ) { - m1.makeRotationZ( angle ); + var morphNormal = morphNormals[ j ].vertexNormals[ i ]; - this.applyMatrix( m1 ); + morphTargetsNormal[ j ].push( morphNormal.a, morphNormal.b, morphNormal.c ); - return this; + } - }; + // skins - }(), + if ( hasSkinIndices ) { - translate: function () { + this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] ); - // translate geometry + } - var m1; + if ( hasSkinWeights ) { - return function translate( x, y, z ) { + this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] ); - if ( m1 === undefined ) m1 = new Matrix4(); + } - m1.makeTranslation( x, y, z ); + } - this.applyMatrix( m1 ); + this.computeGroups( geometry ); - return this; + this.verticesNeedUpdate = geometry.verticesNeedUpdate; + this.normalsNeedUpdate = geometry.normalsNeedUpdate; + this.colorsNeedUpdate = geometry.colorsNeedUpdate; + this.uvsNeedUpdate = geometry.uvsNeedUpdate; + this.groupsNeedUpdate = geometry.groupsNeedUpdate; - }; + return this; - }(), + }, - scale: function () { + dispose: function () { - // scale geometry + this.dispatchEvent( { type: 'dispose' } ); - var m1; + } - return function scale( x, y, z ) { + } ); - if ( m1 === undefined ) m1 = new Matrix4(); + /** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + */ - m1.makeScale( x, y, z ); + function BufferGeometry() { - this.applyMatrix( m1 ); + Object.defineProperty( this, 'id', { value: GeometryIdCount() } ); - return this; + this.uuid = exports.Math.generateUUID(); - }; + this.name = ''; + this.type = 'BufferGeometry'; - }(), + this.index = null; + this.attributes = {}; - lookAt: function () { + this.morphAttributes = {}; - var obj; + this.groups = []; - return function lookAt( vector ) { + this.boundingBox = null; + this.boundingSphere = null; - if ( obj === undefined ) obj = new Object3D(); + this.drawRange = { start: 0, count: Infinity }; - obj.lookAt( vector ); + }; - obj.updateMatrix(); + Object.assign( BufferGeometry.prototype, EventDispatcher.prototype, { - this.applyMatrix( obj.matrix ); + isBufferGeometry: true, - }; + getIndex: function () { - }(), + return this.index; - center: function () { + }, - this.computeBoundingBox(); + setIndex: function ( index ) { - var offset = this.boundingBox.center().negate(); + this.index = index; - this.translate( offset.x, offset.y, offset.z ); + }, - return offset; + addAttribute: function ( name, attribute ) { - }, + if ( (attribute && attribute.isBufferAttribute) === false && (attribute && attribute.isInterleavedBufferAttribute) === false ) { - setFromObject: function ( object ) { + console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' ); - // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this ); + this.addAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) ); - var geometry = object.geometry; + return; - 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 ( name === 'index' ) { - this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) ); - this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) ); + console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' ); + this.setIndex( attribute ); - if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) { + return; - var lineDistances = new Float32Attribute( geometry.lineDistances.length, 1 ); + } - this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) ); + this.attributes[ name ] = attribute; - } + return this; - if ( geometry.boundingSphere !== null ) { + }, - this.boundingSphere = geometry.boundingSphere.clone(); + getAttribute: function ( name ) { - } + return this.attributes[ name ]; - if ( geometry.boundingBox !== null ) { + }, - this.boundingBox = geometry.boundingBox.clone(); + removeAttribute: function ( name ) { - } + delete this.attributes[ name ]; - } else if ( (object && object.isMesh) ) { + return this; - if ( (geometry && geometry.isGeometry) ) { + }, - this.fromGeometry( geometry ); + addGroup: function ( start, count, materialIndex ) { - } + this.groups.push( { - } + start: start, + count: count, + materialIndex: materialIndex !== undefined ? materialIndex : 0 - return this; + } ); - }, + }, - updateFromObject: function ( object ) { + clearGroups: function () { - var geometry = object.geometry; + this.groups = []; - if ( (object && object.isMesh) ) { + }, - var direct = geometry.__directGeometry; + setDrawRange: function ( start, count ) { - if ( direct === undefined || geometry.elementsNeedUpdate === true ) { + this.drawRange.start = start; + this.drawRange.count = count; - return this.fromGeometry( geometry ); + }, - } + applyMatrix: function ( matrix ) { - 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 position = this.attributes.position; - geometry.elementsNeedUpdate = false; - geometry.verticesNeedUpdate = false; - geometry.normalsNeedUpdate = false; - geometry.colorsNeedUpdate = false; - geometry.uvsNeedUpdate = false; - geometry.groupsNeedUpdate = false; + if ( position !== undefined ) { - geometry = direct; + matrix.applyToVector3Array( position.array ); + position.needsUpdate = true; - } + } - var attribute; + var normal = this.attributes.normal; - if ( geometry.verticesNeedUpdate === true ) { + if ( normal !== undefined ) { - attribute = this.attributes.position; + var normalMatrix = new Matrix3().getNormalMatrix( matrix ); - if ( attribute !== undefined ) { + normalMatrix.applyToVector3Array( normal.array ); + normal.needsUpdate = true; - attribute.copyVector3sArray( geometry.vertices ); - attribute.needsUpdate = true; + } - } + if ( this.boundingBox !== null ) { - geometry.verticesNeedUpdate = false; + this.computeBoundingBox(); - } + } - if ( geometry.normalsNeedUpdate === true ) { + if ( this.boundingSphere !== null ) { - attribute = this.attributes.normal; + this.computeBoundingSphere(); - if ( attribute !== undefined ) { + } - attribute.copyVector3sArray( geometry.normals ); - attribute.needsUpdate = true; + return this; - } + }, - geometry.normalsNeedUpdate = false; + rotateX: function () { - } + // rotate geometry around world x-axis - if ( geometry.colorsNeedUpdate === true ) { + var m1; - attribute = this.attributes.color; + return function rotateX( angle ) { - if ( attribute !== undefined ) { + if ( m1 === undefined ) m1 = new Matrix4(); - attribute.copyColorsArray( geometry.colors ); - attribute.needsUpdate = true; + m1.makeRotationX( angle ); - } + this.applyMatrix( m1 ); - geometry.colorsNeedUpdate = false; + return this; - } + }; - if ( geometry.uvsNeedUpdate ) { + }(), - attribute = this.attributes.uv; + rotateY: function () { - if ( attribute !== undefined ) { + // rotate geometry around world y-axis - attribute.copyVector2sArray( geometry.uvs ); - attribute.needsUpdate = true; + var m1; - } + return function rotateY( angle ) { - geometry.uvsNeedUpdate = false; + if ( m1 === undefined ) m1 = new Matrix4(); - } + m1.makeRotationY( angle ); - if ( geometry.lineDistancesNeedUpdate ) { + this.applyMatrix( m1 ); - attribute = this.attributes.lineDistance; + return this; - if ( attribute !== undefined ) { + }; - attribute.copyArray( geometry.lineDistances ); - attribute.needsUpdate = true; + }(), - } + rotateZ: function () { - geometry.lineDistancesNeedUpdate = false; + // rotate geometry around world z-axis - } + var m1; - if ( geometry.groupsNeedUpdate ) { + return function rotateZ( angle ) { - geometry.computeGroups( object.geometry ); - this.groups = geometry.groups; + if ( m1 === undefined ) m1 = new Matrix4(); - geometry.groupsNeedUpdate = false; + m1.makeRotationZ( angle ); - } + this.applyMatrix( m1 ); - return this; + return this; - }, + }; - fromGeometry: function ( geometry ) { + }(), - geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry ); + translate: function () { - return this.fromDirectGeometry( geometry.__directGeometry ); + // translate geometry - }, + var m1; - fromDirectGeometry: function ( geometry ) { + return function translate( x, y, z ) { - var positions = new Float32Array( geometry.vertices.length * 3 ); - this.addAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) ); + if ( m1 === undefined ) m1 = new Matrix4(); - if ( geometry.normals.length > 0 ) { + m1.makeTranslation( x, y, z ); - var normals = new Float32Array( geometry.normals.length * 3 ); - this.addAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) ); + this.applyMatrix( m1 ); - } + return this; - if ( geometry.colors.length > 0 ) { + }; - var colors = new Float32Array( geometry.colors.length * 3 ); - this.addAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) ); + }(), - } + scale: function () { - if ( geometry.uvs.length > 0 ) { + // scale geometry - var uvs = new Float32Array( geometry.uvs.length * 2 ); - this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) ); + var m1; - } + return function scale( x, y, z ) { - if ( geometry.uvs2.length > 0 ) { + if ( m1 === undefined ) m1 = new Matrix4(); - var uvs2 = new Float32Array( geometry.uvs2.length * 2 ); - this.addAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) ); + m1.makeScale( x, y, z ); - } + this.applyMatrix( m1 ); - if ( geometry.indices.length > 0 ) { + return this; - 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 ) ); + }; - } + }(), - // groups + lookAt: function () { - this.groups = geometry.groups; + var obj; - // morphs + return function lookAt( vector ) { - for ( var name in geometry.morphTargets ) { + if ( obj === undefined ) obj = new Object3D(); - var array = []; - var morphTargets = geometry.morphTargets[ name ]; + obj.lookAt( vector ); - for ( var i = 0, l = morphTargets.length; i < l; i ++ ) { + obj.updateMatrix(); - var morphTarget = morphTargets[ i ]; + this.applyMatrix( obj.matrix ); - var attribute = new Float32Attribute( morphTarget.length * 3, 3 ); + }; - array.push( attribute.copyVector3sArray( morphTarget ) ); + }(), - } + center: function () { - this.morphAttributes[ name ] = array; + this.computeBoundingBox(); - } + var offset = this.boundingBox.center().negate(); - // skinning + this.translate( offset.x, offset.y, offset.z ); - if ( geometry.skinIndices.length > 0 ) { + return offset; - var skinIndices = new Float32Attribute( geometry.skinIndices.length * 4, 4 ); - this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) ); + }, - } + setFromObject: function ( object ) { - if ( geometry.skinWeights.length > 0 ) { + // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this ); - var skinWeights = new Float32Attribute( geometry.skinWeights.length * 4, 4 ); - this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) ); + var geometry = object.geometry; - } + 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.boundingSphere !== null ) { + this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) ); + this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) ); - this.boundingSphere = geometry.boundingSphere.clone(); + if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) { - } + var lineDistances = new Float32Attribute( geometry.lineDistances.length, 1 ); - if ( geometry.boundingBox !== null ) { + this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) ); - this.boundingBox = geometry.boundingBox.clone(); + } - } + if ( geometry.boundingSphere !== null ) { - return this; + this.boundingSphere = geometry.boundingSphere.clone(); - }, + } - computeBoundingBox: function () { + if ( geometry.boundingBox !== null ) { - if ( this.boundingBox === null ) { + this.boundingBox = geometry.boundingBox.clone(); - this.boundingBox = new Box3(); + } - } + } else if ( (object && object.isMesh) ) { - var positions = this.attributes.position.array; + if ( (geometry && geometry.isGeometry) ) { - if ( positions !== undefined ) { + this.fromGeometry( geometry ); - this.boundingBox.setFromArray( positions ); + } - } else { + } - this.boundingBox.makeEmpty(); + return this; - } + }, - if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) { + updateFromObject: function ( object ) { - console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this ); + var geometry = object.geometry; - } + if ( (object && object.isMesh) ) { - }, + var direct = geometry.__directGeometry; - computeBoundingSphere: function () { + if ( direct === undefined || geometry.elementsNeedUpdate === true ) { - var box = new Box3(); - var vector = new Vector3(); + return this.fromGeometry( geometry ); - return function computeBoundingSphere() { + } - if ( this.boundingSphere === null ) { + 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; - this.boundingSphere = new Sphere(); + geometry.elementsNeedUpdate = false; + geometry.verticesNeedUpdate = false; + geometry.normalsNeedUpdate = false; + geometry.colorsNeedUpdate = false; + geometry.uvsNeedUpdate = false; + geometry.groupsNeedUpdate = false; - } + geometry = direct; - var positions = this.attributes.position; + } - if ( positions ) { + var attribute; - var array = positions.array; - var center = this.boundingSphere.center; + if ( geometry.verticesNeedUpdate === true ) { - box.setFromArray( array ); - box.center( center ); + attribute = this.attributes.position; - // hoping to find a boundingSphere with a radius smaller than the - // boundingSphere of the boundingBox: sqrt(3) smaller in the best case + if ( attribute !== undefined ) { - var maxRadiusSq = 0; + attribute.copyVector3sArray( geometry.vertices ); + attribute.needsUpdate = true; - for ( var i = 0, il = array.length; i < il; i += 3 ) { + } - vector.fromArray( array, i ); - maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) ); + geometry.verticesNeedUpdate = false; - } + } - this.boundingSphere.radius = Math.sqrt( maxRadiusSq ); + if ( geometry.normalsNeedUpdate === true ) { - if ( isNaN( this.boundingSphere.radius ) ) { + attribute = this.attributes.normal; - console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this ); + if ( attribute !== undefined ) { - } + attribute.copyVector3sArray( geometry.normals ); + attribute.needsUpdate = true; - } + } - }; + geometry.normalsNeedUpdate = false; - }(), + } - computeFaceNormals: function () { + if ( geometry.colorsNeedUpdate === true ) { - // backwards compatibility + attribute = this.attributes.color; - }, + if ( attribute !== undefined ) { - computeVertexNormals: function () { + attribute.copyColorsArray( geometry.colors ); + attribute.needsUpdate = true; - var index = this.index; - var attributes = this.attributes; - var groups = this.groups; + } - if ( attributes.position ) { + geometry.colorsNeedUpdate = false; - var positions = attributes.position.array; + } - if ( attributes.normal === undefined ) { + if ( geometry.uvsNeedUpdate ) { - this.addAttribute( 'normal', new BufferAttribute( new Float32Array( positions.length ), 3 ) ); + attribute = this.attributes.uv; - } else { + if ( attribute !== undefined ) { - // reset existing normals to zero + attribute.copyVector2sArray( geometry.uvs ); + attribute.needsUpdate = true; - var array = attributes.normal.array; + } - for ( var i = 0, il = array.length; i < il; i ++ ) { + geometry.uvsNeedUpdate = false; - array[ i ] = 0; + } - } + if ( geometry.lineDistancesNeedUpdate ) { - } + attribute = this.attributes.lineDistance; - var normals = attributes.normal.array; + if ( attribute !== undefined ) { - var vA, vB, vC, + attribute.copyArray( geometry.lineDistances ); + attribute.needsUpdate = true; - pA = new Vector3(), - pB = new Vector3(), - pC = new Vector3(), + } - cb = new Vector3(), - ab = new Vector3(); + geometry.lineDistancesNeedUpdate = false; - // indexed elements + } - if ( index ) { + if ( geometry.groupsNeedUpdate ) { - var indices = index.array; + geometry.computeGroups( object.geometry ); + this.groups = geometry.groups; - if ( groups.length === 0 ) { + geometry.groupsNeedUpdate = false; - this.addGroup( 0, indices.length ); + } - } + return this; - for ( var j = 0, jl = groups.length; j < jl; ++ j ) { + }, - var group = groups[ j ]; + fromGeometry: function ( geometry ) { - var start = group.start; - var count = group.count; + geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry ); - for ( var i = start, il = start + count; i < il; i += 3 ) { + return this.fromDirectGeometry( geometry.__directGeometry ); - 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 ); + fromDirectGeometry: function ( geometry ) { - cb.subVectors( pC, pB ); - ab.subVectors( pA, pB ); - cb.cross( ab ); + var positions = new Float32Array( geometry.vertices.length * 3 ); + this.addAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) ); - normals[ vA ] += cb.x; - normals[ vA + 1 ] += cb.y; - normals[ vA + 2 ] += cb.z; + if ( geometry.normals.length > 0 ) { - normals[ vB ] += cb.x; - normals[ vB + 1 ] += cb.y; - normals[ vB + 2 ] += cb.z; + var normals = new Float32Array( geometry.normals.length * 3 ); + this.addAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) ); - normals[ vC ] += cb.x; - normals[ vC + 1 ] += cb.y; - normals[ vC + 2 ] += cb.z; + } - } + if ( geometry.colors.length > 0 ) { - } + var colors = new Float32Array( geometry.colors.length * 3 ); + this.addAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) ); - } else { + } - // non-indexed elements (unconnected triangle soup) + if ( geometry.uvs.length > 0 ) { - for ( var i = 0, il = positions.length; i < il; i += 9 ) { + var uvs = new Float32Array( geometry.uvs.length * 2 ); + this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) ); - 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.uvs2.length > 0 ) { - normals[ i ] = cb.x; - normals[ i + 1 ] = cb.y; - normals[ i + 2 ] = cb.z; + var uvs2 = new Float32Array( geometry.uvs2.length * 2 ); + this.addAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) ); - 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; + if ( geometry.indices.length > 0 ) { - } + 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 ) ); - } + } - this.normalizeNormals(); + // groups - attributes.normal.needsUpdate = true; + this.groups = geometry.groups; - } + // morphs - }, + for ( var name in geometry.morphTargets ) { - merge: function ( geometry, offset ) { + var array = []; + var morphTargets = geometry.morphTargets[ name ]; - if ( (geometry && geometry.isBufferGeometry) === false ) { + for ( var i = 0, l = morphTargets.length; i < l; i ++ ) { - console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry ); - return; + var morphTarget = morphTargets[ i ]; - } + var attribute = new Float32Attribute( morphTarget.length * 3, 3 ); - if ( offset === undefined ) offset = 0; + array.push( attribute.copyVector3sArray( morphTarget ) ); - var attributes = this.attributes; + } - for ( var key in attributes ) { + this.morphAttributes[ name ] = array; - if ( geometry.attributes[ key ] === undefined ) continue; + } - var attribute1 = attributes[ key ]; - var attributeArray1 = attribute1.array; + // skinning - var attribute2 = geometry.attributes[ key ]; - var attributeArray2 = attribute2.array; + if ( geometry.skinIndices.length > 0 ) { - var attributeSize = attribute2.itemSize; + var skinIndices = new Float32Attribute( geometry.skinIndices.length * 4, 4 ); + this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) ); - for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) { + } - attributeArray1[ j ] = attributeArray2[ i ]; + if ( geometry.skinWeights.length > 0 ) { - } + var skinWeights = new Float32Attribute( geometry.skinWeights.length * 4, 4 ); + this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) ); - } + } - return this; + // - }, + if ( geometry.boundingSphere !== null ) { - normalizeNormals: function () { + this.boundingSphere = geometry.boundingSphere.clone(); - var normals = this.attributes.normal.array; + } - var x, y, z, n; + if ( geometry.boundingBox !== null ) { - for ( var i = 0, il = normals.length; i < il; i += 3 ) { + this.boundingBox = geometry.boundingBox.clone(); - 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; + }, - } + computeBoundingBox: function () { - }, + if ( this.boundingBox === null ) { - toNonIndexed: function () { + this.boundingBox = new Box3(); - if ( this.index === null ) { + } - console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' ); - return this; + var positions = this.attributes.position.array; - } + if ( positions !== undefined ) { - var geometry2 = new BufferGeometry(); + this.boundingBox.setFromArray( positions ); - var indices = this.index.array; - var attributes = this.attributes; + } else { - for ( var name in attributes ) { + this.boundingBox.makeEmpty(); - var attribute = attributes[ name ]; + } - var array = attribute.array; - var itemSize = attribute.itemSize; + if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) { - var array2 = new array.constructor( indices.length * itemSize ); + console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this ); - var index = 0, index2 = 0; + } - for ( var i = 0, l = indices.length; i < l; i ++ ) { + }, - index = indices[ i ] * itemSize; + computeBoundingSphere: function () { - for ( var j = 0; j < itemSize; j ++ ) { + var box = new Box3(); + var vector = new Vector3(); - array2[ index2 ++ ] = array[ index ++ ]; + return function computeBoundingSphere() { - } + if ( this.boundingSphere === null ) { - } + this.boundingSphere = new Sphere(); - geometry2.addAttribute( name, new BufferAttribute( array2, itemSize ) ); + } - } + var positions = this.attributes.position; - return geometry2; + if ( positions ) { - }, + var array = positions.array; + var center = this.boundingSphere.center; - toJSON: function () { + box.setFromArray( array ); + box.center( center ); - var data = { - metadata: { - version: 4.4, - type: 'BufferGeometry', - generator: 'BufferGeometry.toJSON' - } - }; + // hoping to find a boundingSphere with a radius smaller than the + // boundingSphere of the boundingBox: sqrt(3) smaller in the best case - // standard BufferGeometry serialization + var maxRadiusSq = 0; - data.uuid = this.uuid; - data.type = this.type; - if ( this.name !== '' ) data.name = this.name; + for ( var i = 0, il = array.length; i < il; i += 3 ) { - if ( this.parameters !== undefined ) { + vector.fromArray( array, i ); + maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) ); - var parameters = this.parameters; + } - for ( var key in parameters ) { + this.boundingSphere.radius = Math.sqrt( maxRadiusSq ); - if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ]; + if ( isNaN( this.boundingSphere.radius ) ) { - } + console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this ); - return data; + } - } + } - data.data = { attributes: {} }; + }; - var index = this.index; + }(), - if ( index !== null ) { + computeFaceNormals: function () { - var array = Array.prototype.slice.call( index.array ); + // backwards compatibility - data.data.index = { - type: index.array.constructor.name, - array: array - }; + }, - } + computeVertexNormals: function () { - var attributes = this.attributes; + var index = this.index; + var attributes = this.attributes; + var groups = this.groups; - for ( var key in attributes ) { + if ( attributes.position ) { - var attribute = attributes[ key ]; + var positions = attributes.position.array; - var array = Array.prototype.slice.call( attribute.array ); + if ( attributes.normal === undefined ) { - data.data.attributes[ key ] = { - itemSize: attribute.itemSize, - type: attribute.array.constructor.name, - array: array, - normalized: attribute.normalized - }; + this.addAttribute( 'normal', new BufferAttribute( new Float32Array( positions.length ), 3 ) ); - } + } else { - var groups = this.groups; + // reset existing normals to zero - if ( groups.length > 0 ) { + var array = attributes.normal.array; - data.data.groups = JSON.parse( JSON.stringify( groups ) ); + for ( var i = 0, il = array.length; i < il; i ++ ) { - } + array[ i ] = 0; - var boundingSphere = this.boundingSphere; + } - if ( boundingSphere !== null ) { + } - data.data.boundingSphere = { - center: boundingSphere.center.toArray(), - radius: boundingSphere.radius - }; + var normals = attributes.normal.array; - } + var vA, vB, vC, - return data; + pA = new Vector3(), + pB = new Vector3(), + pC = new Vector3(), - }, + cb = new Vector3(), + ab = new Vector3(); - clone: function () { + // indexed elements - /* - // Handle primitives + if ( index ) { - var parameters = this.parameters; + var indices = index.array; - if ( parameters !== undefined ) { + if ( groups.length === 0 ) { - var values = []; + this.addGroup( 0, indices.length ); - for ( var key in parameters ) { + } - values.push( parameters[ key ] ); + for ( var j = 0, jl = groups.length; j < jl; ++ j ) { - } + var group = groups[ j ]; - var geometry = Object.create( this.constructor.prototype ); - this.constructor.apply( geometry, values ); - return geometry; + var start = group.start; + var count = group.count; - } + for ( var i = start, il = start + count; i < il; i += 3 ) { - return new this.constructor().copy( this ); - */ + vA = indices[ i + 0 ] * 3; + vB = indices[ i + 1 ] * 3; + vC = indices[ i + 2 ] * 3; - return new BufferGeometry().copy( this ); + pA.fromArray( positions, vA ); + pB.fromArray( positions, vB ); + pC.fromArray( positions, vC ); - }, + cb.subVectors( pC, pB ); + ab.subVectors( pA, pB ); + cb.cross( ab ); - copy: function ( source ) { + normals[ vA ] += cb.x; + normals[ vA + 1 ] += cb.y; + normals[ vA + 2 ] += cb.z; - var index = source.index; + normals[ vB ] += cb.x; + normals[ vB + 1 ] += cb.y; + normals[ vB + 2 ] += cb.z; - if ( index !== null ) { + normals[ vC ] += cb.x; + normals[ vC + 1 ] += cb.y; + normals[ vC + 2 ] += cb.z; - this.setIndex( index.clone() ); + } - } + } - var attributes = source.attributes; + } else { - for ( var name in attributes ) { + // non-indexed elements (unconnected triangle soup) - var attribute = attributes[ name ]; - this.addAttribute( name, attribute.clone() ); + for ( var i = 0, il = positions.length; i < il; i += 9 ) { - } + pA.fromArray( positions, i ); + pB.fromArray( positions, i + 3 ); + pC.fromArray( positions, i + 6 ); - var groups = source.groups; + cb.subVectors( pC, pB ); + ab.subVectors( pA, pB ); + cb.cross( ab ); - for ( var i = 0, l = groups.length; i < l; i ++ ) { + normals[ i ] = cb.x; + normals[ i + 1 ] = cb.y; + normals[ i + 2 ] = cb.z; - var group = groups[ i ]; - this.addGroup( group.start, group.count, group.materialIndex ); + 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; + } - }, + } - dispose: function () { + this.normalizeNormals(); - this.dispatchEvent( { type: 'dispose' } ); + attributes.normal.needsUpdate = true; - } + } - } ); + }, - BufferGeometry.MaxIndex = 65535; + merge: function ( geometry, offset ) { - /** - * @author mrdoob / http://mrdoob.com/ - */ + if ( (geometry && geometry.isBufferGeometry) === false ) { - function WebGLGeometries( gl, properties, info ) { + console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry ); + return; - var geometries = {}; + } - function get( object ) { + if ( offset === undefined ) offset = 0; - var geometry = object.geometry; + var attributes = this.attributes; - if ( geometries[ geometry.id ] !== undefined ) { + for ( var key in attributes ) { - return geometries[ geometry.id ]; + if ( geometry.attributes[ key ] === undefined ) continue; - } + var attribute1 = attributes[ key ]; + var attributeArray1 = attribute1.array; - geometry.addEventListener( 'dispose', onGeometryDispose ); + var attribute2 = geometry.attributes[ key ]; + var attributeArray2 = attribute2.array; - var buffergeometry; + var attributeSize = attribute2.itemSize; - if ( (geometry && geometry.isBufferGeometry) ) { + for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) { - buffergeometry = geometry; + attributeArray1[ j ] = attributeArray2[ i ]; - } else if ( (geometry && geometry.isGeometry) ) { + } - if ( geometry._bufferGeometry === undefined ) { + } - geometry._bufferGeometry = new BufferGeometry().setFromObject( object ); + return this; - } + }, - buffergeometry = geometry._bufferGeometry; + normalizeNormals: function () { - } + var normals = this.attributes.normal.array; - geometries[ geometry.id ] = buffergeometry; + var x, y, z, n; - info.memory.geometries ++; + for ( var i = 0, il = normals.length; i < il; i += 3 ) { - return buffergeometry; + x = normals[ i ]; + y = normals[ i + 1 ]; + z = normals[ i + 2 ]; - } + n = 1.0 / Math.sqrt( x * x + y * y + z * z ); - function onGeometryDispose( event ) { + normals[ i ] *= n; + normals[ i + 1 ] *= n; + normals[ i + 2 ] *= n; - var geometry = event.target; - var buffergeometry = geometries[ geometry.id ]; + } - if ( buffergeometry.index !== null ) { + }, - deleteAttribute( buffergeometry.index ); + toNonIndexed: function () { - } + if ( this.index === null ) { - deleteAttributes( buffergeometry.attributes ); + console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' ); + return this; - geometry.removeEventListener( 'dispose', onGeometryDispose ); + } - delete geometries[ geometry.id ]; + var geometry2 = new BufferGeometry(); - // TODO + var indices = this.index.array; + var attributes = this.attributes; - var property = properties.get( geometry ); + for ( var name in attributes ) { - if ( property.wireframe ) { + var attribute = attributes[ name ]; - deleteAttribute( property.wireframe ); + var array = attribute.array; + var itemSize = attribute.itemSize; - } + var array2 = new array.constructor( indices.length * itemSize ); - properties.delete( geometry ); + var index = 0, index2 = 0; - var bufferproperty = properties.get( buffergeometry ); + for ( var i = 0, l = indices.length; i < l; i ++ ) { - if ( bufferproperty.wireframe ) { + index = indices[ i ] * itemSize; - deleteAttribute( bufferproperty.wireframe ); + for ( var j = 0; j < itemSize; j ++ ) { - } + array2[ index2 ++ ] = array[ index ++ ]; - properties.delete( buffergeometry ); + } - // + } - info.memory.geometries --; + geometry2.addAttribute( name, new BufferAttribute( array2, itemSize ) ); - } + } - function getAttributeBuffer( attribute ) { + return geometry2; - if ( (attribute && attribute.isInterleavedBufferAttribute) ) { + }, - return properties.get( attribute.data ).__webglBuffer; + toJSON: function () { - } + var data = { + metadata: { + version: 4.4, + type: 'BufferGeometry', + generator: 'BufferGeometry.toJSON' + } + }; - return properties.get( attribute ).__webglBuffer; + // standard BufferGeometry serialization - } + data.uuid = this.uuid; + data.type = this.type; + if ( this.name !== '' ) data.name = this.name; - function deleteAttribute( attribute ) { + if ( this.parameters !== undefined ) { - var buffer = getAttributeBuffer( attribute ); + var parameters = this.parameters; - if ( buffer !== undefined ) { + for ( var key in parameters ) { - gl.deleteBuffer( buffer ); - removeAttributeBuffer( attribute ); + if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ]; - } + } - } + return data; - function deleteAttributes( attributes ) { + } - for ( var name in attributes ) { + data.data = { attributes: {} }; - deleteAttribute( attributes[ name ] ); + var index = this.index; - } + if ( index !== null ) { - } + var array = Array.prototype.slice.call( index.array ); - function removeAttributeBuffer( attribute ) { + data.data.index = { + type: index.array.constructor.name, + array: array + }; - if ( (attribute && attribute.isInterleavedBufferAttribute) ) { + } - properties.delete( attribute.data ); + var attributes = this.attributes; - } else { + for ( var key in attributes ) { - properties.delete( attribute ); + var attribute = attributes[ key ]; - } + 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 + }; - this.get = get; + } - }; + var groups = this.groups; - /** - * @author mrdoob / http://mrdoob.com/ - */ + if ( groups.length > 0 ) { - function WebGLObjects( gl, properties, info ) { + data.data.groups = JSON.parse( JSON.stringify( groups ) ); - var geometries = new WebGLGeometries( gl, properties, info ); + } - // + var boundingSphere = this.boundingSphere; - function update( object ) { + if ( boundingSphere !== null ) { - // TODO: Avoid updating twice (when using shadowMap). Maybe add frame counter. + data.data.boundingSphere = { + center: boundingSphere.center.toArray(), + radius: boundingSphere.radius + }; - var geometry = geometries.get( object ); + } - if ( (object.geometry && object.geometry.isGeometry) ) { + return data; - geometry.updateFromObject( object ); + }, - } + clone: function () { - var index = geometry.index; - var attributes = geometry.attributes; + /* + // Handle primitives - if ( index !== null ) { + var parameters = this.parameters; - updateAttribute( index, gl.ELEMENT_ARRAY_BUFFER ); + if ( parameters !== undefined ) { - } + var values = []; - for ( var name in attributes ) { + for ( var key in parameters ) { - updateAttribute( attributes[ name ], gl.ARRAY_BUFFER ); + values.push( parameters[ key ] ); - } + } - // morph targets + var geometry = Object.create( this.constructor.prototype ); + this.constructor.apply( geometry, values ); + return geometry; - var morphAttributes = geometry.morphAttributes; + } - for ( var name in morphAttributes ) { + return new this.constructor().copy( this ); + */ - var array = morphAttributes[ name ]; + return new BufferGeometry().copy( this ); - for ( var i = 0, l = array.length; i < l; i ++ ) { + }, - updateAttribute( array[ i ], gl.ARRAY_BUFFER ); + copy: function ( source ) { - } + var index = source.index; - } + if ( index !== null ) { - return geometry; + this.setIndex( index.clone() ); - } + } - function updateAttribute( attribute, bufferType ) { + var attributes = source.attributes; - var data = ( (attribute && attribute.isInterleavedBufferAttribute) ) ? attribute.data : attribute; + for ( var name in attributes ) { - var attributeProperties = properties.get( data ); + var attribute = attributes[ name ]; + this.addAttribute( name, attribute.clone() ); - if ( attributeProperties.__webglBuffer === undefined ) { + } - createBuffer( attributeProperties, data, bufferType ); + var groups = source.groups; - } else if ( attributeProperties.version !== data.version ) { + for ( var i = 0, l = groups.length; i < l; i ++ ) { - updateBuffer( attributeProperties, data, bufferType ); + var group = groups[ i ]; + this.addGroup( group.start, group.count, group.materialIndex ); - } + } - } + return this; - function createBuffer( attributeProperties, data, bufferType ) { + }, - attributeProperties.__webglBuffer = gl.createBuffer(); - gl.bindBuffer( bufferType, attributeProperties.__webglBuffer ); + dispose: function () { - var usage = data.dynamic ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW; + this.dispatchEvent( { type: 'dispose' } ); - gl.bufferData( bufferType, data.array, usage ); + } - attributeProperties.version = data.version; + } ); - } + BufferGeometry.MaxIndex = 65535; - function updateBuffer( attributeProperties, data, bufferType ) { + /** + * @author mrdoob / http://mrdoob.com/ + */ - gl.bindBuffer( bufferType, attributeProperties.__webglBuffer ); + function WebGLGeometries( gl, properties, info ) { - if ( data.dynamic === false || data.updateRange.count === - 1 ) { + var geometries = {}; - // Not using update ranges + function get( object ) { - gl.bufferSubData( bufferType, 0, data.array ); + var geometry = object.geometry; - } else if ( data.updateRange.count === 0 ) { + if ( geometries[ geometry.id ] !== undefined ) { - 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.' ); + return geometries[ geometry.id ]; - } else { + } - gl.bufferSubData( bufferType, data.updateRange.offset * data.array.BYTES_PER_ELEMENT, - data.array.subarray( data.updateRange.offset, data.updateRange.offset + data.updateRange.count ) ); + geometry.addEventListener( 'dispose', onGeometryDispose ); - data.updateRange.count = 0; // reset range + var buffergeometry; - } + if ( (geometry && geometry.isBufferGeometry) ) { - attributeProperties.version = data.version; + buffergeometry = geometry; - } + } else if ( (geometry && geometry.isGeometry) ) { - function getAttributeBuffer( attribute ) { + if ( geometry._bufferGeometry === undefined ) { - if ( (attribute && attribute.isInterleavedBufferAttribute) ) { + geometry._bufferGeometry = new BufferGeometry().setFromObject( object ); - return properties.get( attribute.data ).__webglBuffer; + } - } + buffergeometry = geometry._bufferGeometry; - return properties.get( attribute ).__webglBuffer; + } - } + geometries[ geometry.id ] = buffergeometry; - function getWireframeAttribute( geometry ) { + info.memory.geometries ++; - var property = properties.get( geometry ); + return buffergeometry; - if ( property.wireframe !== undefined ) { + } - return property.wireframe; + function onGeometryDispose( event ) { - } + var geometry = event.target; + var buffergeometry = geometries[ geometry.id ]; - var indices = []; + if ( buffergeometry.index !== null ) { - var index = geometry.index; - var attributes = geometry.attributes; - var position = attributes.position; + deleteAttribute( buffergeometry.index ); - // console.time( 'wireframe' ); + } - if ( index !== null ) { + deleteAttributes( buffergeometry.attributes ); - var edges = {}; - var array = index.array; + geometry.removeEventListener( 'dispose', onGeometryDispose ); - for ( var i = 0, l = array.length; i < l; i += 3 ) { + delete geometries[ geometry.id ]; - var a = array[ i + 0 ]; - var b = array[ i + 1 ]; - var c = array[ i + 2 ]; + // TODO - 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 ); + var property = properties.get( geometry ); - } + if ( property.wireframe ) { - } else { + deleteAttribute( property.wireframe ); - var array = attributes.position.array; + } - for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) { + properties.delete( geometry ); - var a = i + 0; - var b = i + 1; - var c = i + 2; + var bufferproperty = properties.get( buffergeometry ); - indices.push( a, b, b, c, c, a ); + if ( bufferproperty.wireframe ) { - } + deleteAttribute( bufferproperty.wireframe ); - } + } - // console.timeEnd( 'wireframe' ); + properties.delete( buffergeometry ); - var TypeArray = position.count > 65535 ? Uint32Array : Uint16Array; - var attribute = new BufferAttribute( new TypeArray( indices ), 1 ); + // - updateAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER ); + info.memory.geometries --; - property.wireframe = attribute; + } - return attribute; + function getAttributeBuffer( attribute ) { - } + if ( (attribute && attribute.isInterleavedBufferAttribute) ) { - function checkEdge( edges, a, b ) { + return properties.get( attribute.data ).__webglBuffer; - if ( a > b ) { + } - var tmp = a; - a = b; - b = tmp; + return properties.get( attribute ).__webglBuffer; - } + } - var list = edges[ a ]; + function deleteAttribute( attribute ) { - if ( list === undefined ) { + var buffer = getAttributeBuffer( attribute ); - edges[ a ] = [ b ]; - return true; + if ( buffer !== undefined ) { - } else if ( list.indexOf( b ) === -1 ) { + gl.deleteBuffer( buffer ); + removeAttributeBuffer( attribute ); - list.push( b ); - return true; + } - } + } - return false; + function deleteAttributes( attributes ) { - } + for ( var name in attributes ) { - this.getAttributeBuffer = getAttributeBuffer; - this.getWireframeAttribute = getWireframeAttribute; + deleteAttribute( attributes[ name ] ); - this.update = update; + } - }; + } - /** - * @author mrdoob / http://mrdoob.com/ - */ + function removeAttributeBuffer( attribute ) { - function WebGLLights() { + if ( (attribute && attribute.isInterleavedBufferAttribute) ) { - var lights = {}; + properties.delete( attribute.data ); - this.get = function ( light ) { + } else { - if ( lights[ light.id ] !== undefined ) { + properties.delete( attribute ); - return lights[ light.id ]; + } - } + } - var uniforms; + this.get = get; - switch ( light.type ) { + }; - case 'DirectionalLight': - uniforms = { - direction: new Vector3(), - color: new Color(), + /** + * @author mrdoob / http://mrdoob.com/ + */ - shadow: false, - shadowBias: 0, - shadowRadius: 1, - shadowMapSize: new Vector2() - }; - break; + function WebGLObjects( gl, properties, info ) { - case 'SpotLight': - uniforms = { - position: new Vector3(), - direction: new Vector3(), - color: new Color(), - distance: 0, - coneCos: 0, - penumbraCos: 0, - decay: 0, + var geometries = new WebGLGeometries( gl, properties, info ); - shadow: false, - shadowBias: 0, - shadowRadius: 1, - shadowMapSize: new Vector2() - }; - break; + // - case 'PointLight': - uniforms = { - position: new Vector3(), - color: new Color(), - distance: 0, - decay: 0, + function update( object ) { - shadow: false, - shadowBias: 0, - shadowRadius: 1, - shadowMapSize: new Vector2() - }; - break; + // TODO: Avoid updating twice (when using shadowMap). Maybe add frame counter. - case 'HemisphereLight': - uniforms = { - direction: new Vector3(), - skyColor: new Color(), - groundColor: new Color() - }; - break; + var geometry = geometries.get( object ); - } + if ( (object.geometry && object.geometry.isGeometry) ) { - lights[ light.id ] = uniforms; + geometry.updateFromObject( object ); - return uniforms; + } - }; + var index = geometry.index; + var attributes = geometry.attributes; - }; + if ( index !== null ) { - function WebGLCapabilities( gl, extensions, parameters ) { + updateAttribute( index, gl.ELEMENT_ARRAY_BUFFER ); - var maxAnisotropy; + } - function getMaxAnisotropy() { + for ( var name in attributes ) { - if ( maxAnisotropy !== undefined ) return maxAnisotropy; + updateAttribute( attributes[ name ], gl.ARRAY_BUFFER ); - var extension = extensions.get( 'EXT_texture_filter_anisotropic' ); + } - if ( extension !== null ) { + // morph targets - maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT ); + var morphAttributes = geometry.morphAttributes; - } else { + for ( var name in morphAttributes ) { - maxAnisotropy = 0; + var array = morphAttributes[ name ]; - } + for ( var i = 0, l = array.length; i < l; i ++ ) { - return maxAnisotropy; + updateAttribute( array[ i ], gl.ARRAY_BUFFER ); - } + } - function getMaxPrecision( precision ) { + } - if ( precision === 'highp' ) { + return geometry; - if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 && - gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) { + } - return 'highp'; + function updateAttribute( attribute, bufferType ) { - } + var data = ( (attribute && attribute.isInterleavedBufferAttribute) ) ? attribute.data : attribute; - precision = 'mediump'; + var attributeProperties = properties.get( data ); - } + if ( attributeProperties.__webglBuffer === undefined ) { - if ( precision === 'mediump' ) { + createBuffer( attributeProperties, data, bufferType ); - if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 && - gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) { + } else if ( attributeProperties.version !== data.version ) { - return 'mediump'; + updateBuffer( attributeProperties, data, bufferType ); - } + } - } + } - return 'lowp'; + function createBuffer( attributeProperties, data, bufferType ) { - } + attributeProperties.__webglBuffer = gl.createBuffer(); + gl.bindBuffer( bufferType, attributeProperties.__webglBuffer ); - this.getMaxAnisotropy = getMaxAnisotropy; - this.getMaxPrecision = getMaxPrecision; + var usage = data.dynamic ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW; - this.precision = parameters.precision !== undefined ? parameters.precision : 'highp'; - this.logarithmicDepthBuffer = parameters.logarithmicDepthBuffer !== undefined ? parameters.logarithmicDepthBuffer : false; + gl.bufferData( bufferType, data.array, usage ); - 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 ); + attributeProperties.version = data.version; - 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 ); + } - this.vertexTextures = this.maxVertexTextures > 0; - this.floatFragmentTextures = !! extensions.get( 'OES_texture_float' ); - this.floatVertexTextures = this.vertexTextures && this.floatFragmentTextures; + function updateBuffer( attributeProperties, data, bufferType ) { - var _maxPrecision = getMaxPrecision( this.precision ); + gl.bindBuffer( bufferType, attributeProperties.__webglBuffer ); - if ( _maxPrecision !== this.precision ) { + if ( data.dynamic === false || data.updateRange.count === - 1 ) { - console.warn( 'THREE.WebGLRenderer:', this.precision, 'not supported, using', _maxPrecision, 'instead.' ); - this.precision = _maxPrecision; + // Not using update ranges - } + gl.bufferSubData( bufferType, 0, data.array ); - if ( this.logarithmicDepthBuffer ) { + } else if ( data.updateRange.count === 0 ) { - this.logarithmicDepthBuffer = !! extensions.get( 'EXT_frag_depth' ); + 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.' ); - } + } else { - }; + gl.bufferSubData( bufferType, data.updateRange.offset * data.array.BYTES_PER_ELEMENT, + data.array.subarray( data.updateRange.offset, data.updateRange.offset + data.updateRange.count ) ); - /** - * @author mrdoob / http://mrdoob.com/ - */ + data.updateRange.count = 0; // reset range - function WebGLExtensions( gl ) { + } - var extensions = {}; + attributeProperties.version = data.version; - this.get = function ( name ) { + } - if ( extensions[ name ] !== undefined ) { + function getAttributeBuffer( attribute ) { - return extensions[ name ]; + if ( (attribute && attribute.isInterleavedBufferAttribute) ) { - } + return properties.get( attribute.data ).__webglBuffer; - var extension; + } - switch ( name ) { + return properties.get( attribute ).__webglBuffer; - case 'WEBGL_depth_texture': - extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' ); - break; + } - 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; + function getWireframeAttribute( geometry ) { - 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; + var property = properties.get( geometry ); - case 'WEBGL_compressed_texture_pvrtc': - extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' ); - break; + if ( property.wireframe !== undefined ) { - case 'WEBGL_compressed_texture_etc1': - extension = gl.getExtension( 'WEBGL_compressed_texture_etc1' ); - break; + return property.wireframe; - default: - extension = gl.getExtension( name ); + } - } + var indices = []; - if ( extension === null ) { + var index = geometry.index; + var attributes = geometry.attributes; + var position = attributes.position; - console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' ); + // console.time( 'wireframe' ); - } + if ( index !== null ) { - extensions[ name ] = extension; + var edges = {}; + var array = index.array; - return extension; + for ( var i = 0, l = array.length; i < l; i += 3 ) { - }; + 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 ); - /** - * @author mrdoob / http://mrdoob.com/ - */ + } - function WebGLIndexedBufferRenderer( _gl, extensions, _infoRender ) { + } else { - var mode; + var array = attributes.position.array; - function setMode( value ) { + for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) { - mode = value; + var a = i + 0; + var b = i + 1; + var c = i + 2; - } + indices.push( a, b, b, c, c, a ); - var type, size; + } - function setIndex( index ) { + } - if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) { + // console.timeEnd( 'wireframe' ); - type = _gl.UNSIGNED_INT; - size = 4; + var TypeArray = position.count > 65535 ? Uint32Array : Uint16Array; + var attribute = new BufferAttribute( new TypeArray( indices ), 1 ); - } else { + updateAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER ); - type = _gl.UNSIGNED_SHORT; - size = 2; + property.wireframe = attribute; - } + return attribute; - } + } - function render( start, count ) { + function checkEdge( edges, a, b ) { - _gl.drawElements( mode, count, type, start * size ); + if ( a > b ) { - _infoRender.calls ++; - _infoRender.vertices += count; - if ( mode === _gl.TRIANGLES ) _infoRender.faces += count / 3; + var tmp = a; + a = b; + b = tmp; - } + } - function renderInstances( geometry, start, count ) { + var list = edges[ a ]; - var extension = extensions.get( 'ANGLE_instanced_arrays' ); + if ( list === undefined ) { - if ( extension === null ) { + edges[ a ] = [ b ]; + return true; - console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); - return; + } else if ( list.indexOf( b ) === -1 ) { - } + list.push( b ); + return true; - extension.drawElementsInstancedANGLE( mode, count, type, start * size, geometry.maxInstancedCount ); + } - _infoRender.calls ++; - _infoRender.vertices += count * geometry.maxInstancedCount; - if ( mode === _gl.TRIANGLES ) _infoRender.faces += geometry.maxInstancedCount * count / 3; - } + return false; - this.setMode = setMode; - this.setIndex = setIndex; - this.render = render; - this.renderInstances = renderInstances; + } - }; + this.getAttributeBuffer = getAttributeBuffer; + this.getWireframeAttribute = getWireframeAttribute; - function WebGLClipping() { + this.update = update; - var scope = this, + }; - globalState = null, - numGlobalPlanes = 0, - localClippingEnabled = false, - renderingShadows = false, + /** + * @author mrdoob / http://mrdoob.com/ + */ - plane = new Plane(), - viewNormalMatrix = new Matrix3(), + function WebGLLights() { - uniform = { value: null, needsUpdate: false }; + var lights = {}; - this.uniform = uniform; - this.numPlanes = 0; + this.get = function ( light ) { - this.init = function( planes, enableLocalClipping, camera ) { + if ( lights[ light.id ] !== undefined ) { - 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; + return lights[ light.id ]; - localClippingEnabled = enableLocalClipping; + } - globalState = projectPlanes( planes, camera, 0 ); - numGlobalPlanes = planes.length; + var uniforms; - return enabled; + switch ( light.type ) { - }; + case 'DirectionalLight': + uniforms = { + direction: new Vector3(), + color: new Color(), - this.beginShadows = function() { + shadow: false, + shadowBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2() + }; + break; - renderingShadows = true; - projectPlanes( null ); + 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; - this.endShadows = function() { + case 'PointLight': + uniforms = { + position: new Vector3(), + color: new Color(), + distance: 0, + decay: 0, - renderingShadows = false; - resetGlobalState(); + shadow: false, + shadowBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2() + }; + break; - }; + case 'HemisphereLight': + uniforms = { + direction: new Vector3(), + skyColor: new Color(), + groundColor: new Color() + }; + break; - this.setState = function( planes, clipShadows, camera, cache, fromCache ) { + } - if ( ! localClippingEnabled || - planes === null || planes.length === 0 || - renderingShadows && ! clipShadows ) { - // there's no local clipping + lights[ light.id ] = uniforms; - if ( renderingShadows ) { - // there's no global clipping + return uniforms; - projectPlanes( null ); + }; - } else { + }; - resetGlobalState(); - } + function WebGLCapabilities( gl, extensions, parameters ) { - } else { + var maxAnisotropy; - var nGlobal = renderingShadows ? 0 : numGlobalPlanes, - lGlobal = nGlobal * 4, + function getMaxAnisotropy() { - dstArray = cache.clippingState || null; + if ( maxAnisotropy !== undefined ) return maxAnisotropy; - uniform.value = dstArray; // ensure unique state + var extension = extensions.get( 'EXT_texture_filter_anisotropic' ); - dstArray = projectPlanes( planes, camera, lGlobal, fromCache ); + if ( extension !== null ) { - for ( var i = 0; i !== lGlobal; ++ i ) { + maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT ); - dstArray[ i ] = globalState[ i ]; + } else { - } + maxAnisotropy = 0; - cache.clippingState = dstArray; - this.numPlanes += nGlobal; + } - } + return maxAnisotropy; + } - }; + function getMaxPrecision( precision ) { - function resetGlobalState() { + if ( precision === 'highp' ) { - if ( uniform.value !== globalState ) { + if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 && + gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) { - uniform.value = globalState; - uniform.needsUpdate = numGlobalPlanes > 0; + return 'highp'; - } + } - scope.numPlanes = numGlobalPlanes; + precision = 'mediump'; - } + } - function projectPlanes( planes, camera, dstOffset, skipTransform ) { + if ( precision === 'mediump' ) { - var nPlanes = planes !== null ? planes.length : 0, - dstArray = null; + if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 && + gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) { - if ( nPlanes !== 0 ) { + return 'mediump'; - dstArray = uniform.value; + } - if ( skipTransform !== true || dstArray === null ) { + } - var flatSize = dstOffset + nPlanes * 4, - viewMatrix = camera.matrixWorldInverse; + return 'lowp'; - viewNormalMatrix.getNormalMatrix( viewMatrix ); + } - if ( dstArray === null || dstArray.length < flatSize ) { + this.getMaxAnisotropy = getMaxAnisotropy; + this.getMaxPrecision = getMaxPrecision; - dstArray = new Float32Array( flatSize ); + this.precision = parameters.precision !== undefined ? parameters.precision : 'highp'; + this.logarithmicDepthBuffer = parameters.logarithmicDepthBuffer !== undefined ? parameters.logarithmicDepthBuffer : false; - } + 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 ); - for ( var i = 0, i4 = dstOffset; - i !== nPlanes; ++ i, i4 += 4 ) { + 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 ); - plane.copy( planes[ i ] ). - applyMatrix4( viewMatrix, viewNormalMatrix ); + this.vertexTextures = this.maxVertexTextures > 0; + this.floatFragmentTextures = !! extensions.get( 'OES_texture_float' ); + this.floatVertexTextures = this.vertexTextures && this.floatFragmentTextures; - plane.normal.toArray( dstArray, i4 ); - dstArray[ i4 + 3 ] = plane.constant; + var _maxPrecision = getMaxPrecision( this.precision ); - } + if ( _maxPrecision !== this.precision ) { - } + console.warn( 'THREE.WebGLRenderer:', this.precision, 'not supported, using', _maxPrecision, 'instead.' ); + this.precision = _maxPrecision; - uniform.value = dstArray; - uniform.needsUpdate = true; + } - } + if ( this.logarithmicDepthBuffer ) { - scope.numPlanes = nPlanes; - return dstArray; + this.logarithmicDepthBuffer = !! extensions.get( 'EXT_frag_depth' ); - } + } - }; + }; - /** - * @author mrdoob / http://mrdoob.com/ - */ + /** + * @author mrdoob / http://mrdoob.com/ + */ - function WebGLBufferRenderer( _gl, extensions, _infoRender ) { + function WebGLExtensions( gl ) { - var mode; + var extensions = {}; - function setMode( value ) { + this.get = function ( name ) { - mode = value; + if ( extensions[ name ] !== undefined ) { - } + return extensions[ name ]; - function render( start, count ) { + } - _gl.drawArrays( mode, start, count ); + var extension; - _infoRender.calls ++; - _infoRender.vertices += count; - if ( mode === _gl.TRIANGLES ) _infoRender.faces += count / 3; + switch ( name ) { - } + case 'WEBGL_depth_texture': + extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' ); + break; - function renderInstances( geometry ) { + 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 extension = extensions.get( 'ANGLE_instanced_arrays' ); + 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; - if ( extension === null ) { + case 'WEBGL_compressed_texture_pvrtc': + extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' ); + break; - console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); - return; + case 'WEBGL_compressed_texture_etc1': + extension = gl.getExtension( 'WEBGL_compressed_texture_etc1' ); + break; - } + default: + extension = gl.getExtension( name ); - var position = geometry.attributes.position; + } - var count = 0; + if ( extension === null ) { - if ( (position && position.isInterleavedBufferAttribute) ) { + console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' ); - count = position.data.count; + } - extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount ); + extensions[ name ] = extension; - } else { + return extension; - count = position.count; + }; - extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount ); + }; - } + /** + * @author mrdoob / http://mrdoob.com/ + */ - _infoRender.calls ++; - _infoRender.vertices += count * geometry.maxInstancedCount; - if ( mode === _gl.TRIANGLES ) _infoRender.faces += geometry.maxInstancedCount * count / 3; + function WebGLIndexedBufferRenderer( _gl, extensions, _infoRender ) { - } + var mode; - this.setMode = setMode; - this.render = render; - this.renderInstances = renderInstances; + function setMode( value ) { - }; + mode = value; - /** - * @author alteredq / http://alteredqualia.com - */ + } - function WebGLRenderTargetCube( width, height, options ) { + var type, size; - WebGLRenderTarget.call( this, width, height, options ); + function setIndex( index ) { - this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5 - this.activeMipMapLevel = 0; + if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) { - }; + type = _gl.UNSIGNED_INT; + size = 4; - WebGLRenderTargetCube.prototype = Object.create( WebGLRenderTarget.prototype ); - WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube; + } else { - WebGLRenderTargetCube.prototype.isWebGLRenderTargetCube = true; + type = _gl.UNSIGNED_SHORT; + size = 2; - /** - * @author Mugen87 / https://github.com/Mugen87 - */ + } - function BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) { + } - BufferGeometry.call( this ); + function render( start, count ) { - this.type = 'BoxBufferGeometry'; + _gl.drawElements( mode, count, type, start * size ); - this.parameters = { - width: width, - height: height, - depth: depth, - widthSegments: widthSegments, - heightSegments: heightSegments, - depthSegments: depthSegments - }; + _infoRender.calls ++; + _infoRender.vertices += count; + if ( mode === _gl.TRIANGLES ) _infoRender.faces += count / 3; - var scope = this; + } - // segments - widthSegments = Math.floor( widthSegments ) || 1; - heightSegments = Math.floor( heightSegments ) || 1; - depthSegments = Math.floor( depthSegments ) || 1; + function renderInstances( geometry, start, count ) { - // these are used to calculate buffer length - var vertexCount = calculateVertexCount( widthSegments, heightSegments, depthSegments ); - var indexCount = calculateIndexCount( widthSegments, heightSegments, depthSegments ); + var extension = extensions.get( 'ANGLE_instanced_arrays' ); - // 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 ( extension === null ) { - // offset variables - var vertexBufferOffset = 0; - var uvBufferOffset = 0; - var indexBufferOffset = 0; - var numberOfVertices = 0; + console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); + return; - // 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 + extension.drawElementsInstancedANGLE( mode, count, type, start * size, geometry.maxInstancedCount ); - // 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 ) ); + _infoRender.calls ++; + _infoRender.vertices += count * geometry.maxInstancedCount; + if ( mode === _gl.TRIANGLES ) _infoRender.faces += geometry.maxInstancedCount * count / 3; + } - // helper functions + this.setMode = setMode; + this.setIndex = setIndex; + this.render = render; + this.renderInstances = renderInstances; - function calculateVertexCount( w, h, d ) { + }; - var vertices = 0; + function WebGLClipping() { - // 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 + var scope = this, - return vertices; + globalState = null, + numGlobalPlanes = 0, + localClippingEnabled = false, + renderingShadows = false, - } + plane = new Plane(), + viewNormalMatrix = new Matrix3(), - function calculateIndexCount( w, h, d ) { + uniform = { value: null, needsUpdate: false }; - var index = 0; + this.uniform = uniform; + this.numPlanes = 0; - // calculate the amount of squares for each side - index += w * h * 2; // xy - index += w * d * 2; // xz - index += d * h * 2; // zy + this.init = function( planes, enableLocalClipping, camera ) { - return index * 6; // two triangles per square => six vertices per square + 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; - } + localClippingEnabled = enableLocalClipping; - function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) { + globalState = projectPlanes( planes, camera, 0 ); + numGlobalPlanes = planes.length; - var segmentWidth = width / gridX; - var segmentHeight = height / gridY; + return enabled; - var widthHalf = width / 2; - var heightHalf = height / 2; - var depthHalf = depth / 2; + }; - var gridX1 = gridX + 1; - var gridY1 = gridY + 1; + this.beginShadows = function() { - var vertexCounter = 0; - var groupCount = 0; + renderingShadows = true; + projectPlanes( null ); - var vector = new Vector3(); + }; - // generate vertices, normals and uvs + this.endShadows = function() { - for ( var iy = 0; iy < gridY1; iy ++ ) { + renderingShadows = false; + resetGlobalState(); - var y = iy * segmentHeight - heightHalf; + }; - for ( var ix = 0; ix < gridX1; ix ++ ) { + this.setState = function( planes, clipShadows, camera, cache, fromCache ) { - var x = ix * segmentWidth - widthHalf; + if ( ! localClippingEnabled || + planes === null || planes.length === 0 || + renderingShadows && ! clipShadows ) { + // there's no local clipping - // set values to correct vector component - vector[ u ] = x * udir; - vector[ v ] = y * vdir; - vector[ w ] = depthHalf; + if ( renderingShadows ) { + // there's no global clipping - // now apply vector to vertex buffer - vertices[ vertexBufferOffset ] = vector.x; - vertices[ vertexBufferOffset + 1 ] = vector.y; - vertices[ vertexBufferOffset + 2 ] = vector.z; + projectPlanes( null ); - // set values to correct vector component - vector[ u ] = 0; - vector[ v ] = 0; - vector[ w ] = depth > 0 ? 1 : - 1; + } else { - // now apply vector to normal buffer - normals[ vertexBufferOffset ] = vector.x; - normals[ vertexBufferOffset + 1 ] = vector.y; - normals[ vertexBufferOffset + 2 ] = vector.z; + resetGlobalState(); + } - // uvs - uvs[ uvBufferOffset ] = ix / gridX; - uvs[ uvBufferOffset + 1 ] = 1 - ( iy / gridY ); + } else { - // update offsets and counters - vertexBufferOffset += 3; - uvBufferOffset += 2; - vertexCounter += 1; + var nGlobal = renderingShadows ? 0 : numGlobalPlanes, + lGlobal = nGlobal * 4, - } + dstArray = cache.clippingState || null; - } + uniform.value = dstArray; // ensure unique state - // 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 + dstArray = projectPlanes( planes, camera, lGlobal, fromCache ); - for ( iy = 0; iy < gridY; iy ++ ) { + for ( var i = 0; i !== lGlobal; ++ i ) { - for ( ix = 0; ix < gridX; ix ++ ) { + dstArray[ i ] = globalState[ i ]; - // 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; + cache.clippingState = dstArray; + this.numPlanes += nGlobal; - // face two - indices[ indexBufferOffset + 3 ] = b; - indices[ indexBufferOffset + 4 ] = c; - indices[ indexBufferOffset + 5 ] = d; + } - // update offsets and counters - indexBufferOffset += 6; - groupCount += 6; - } + }; - } + function resetGlobalState() { - // add a group to the geometry. this will ensure multi material support - scope.addGroup( groupStart, groupCount, materialIndex ); + if ( uniform.value !== globalState ) { - // calculate new start value for groups - groupStart += groupCount; + uniform.value = globalState; + uniform.needsUpdate = numGlobalPlanes > 0; - // update total number of vertices - numberOfVertices += vertexCounter; + } - } + scope.numPlanes = numGlobalPlanes; - }; + } - BoxBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); - BoxBufferGeometry.prototype.constructor = BoxBufferGeometry; + function projectPlanes( planes, camera, dstOffset, skipTransform ) { - /** - * @author bhouston / http://clara.io - */ + var nPlanes = planes !== null ? planes.length : 0, + dstArray = null; - function Ray( origin, direction ) { + if ( nPlanes !== 0 ) { - this.origin = ( origin !== undefined ) ? origin : new Vector3(); - this.direction = ( direction !== undefined ) ? direction : new Vector3(); + dstArray = uniform.value; - }; + if ( skipTransform !== true || dstArray === null ) { - Ray.prototype = { + var flatSize = dstOffset + nPlanes * 4, + viewMatrix = camera.matrixWorldInverse; - constructor: Ray, + viewNormalMatrix.getNormalMatrix( viewMatrix ); - set: function ( origin, direction ) { + if ( dstArray === null || dstArray.length < flatSize ) { - this.origin.copy( origin ); - this.direction.copy( direction ); + dstArray = new Float32Array( flatSize ); - return this; + } - }, + for ( var i = 0, i4 = dstOffset; + i !== nPlanes; ++ i, i4 += 4 ) { - clone: function () { + plane.copy( planes[ i ] ). + applyMatrix4( viewMatrix, viewNormalMatrix ); - return new this.constructor().copy( this ); + plane.normal.toArray( dstArray, i4 ); + dstArray[ i4 + 3 ] = plane.constant; - }, + } - copy: function ( ray ) { + } - this.origin.copy( ray.origin ); - this.direction.copy( ray.direction ); + uniform.value = dstArray; + uniform.needsUpdate = true; - return this; + } - }, + scope.numPlanes = nPlanes; + return dstArray; - at: function ( t, optionalTarget ) { + } - var result = optionalTarget || new Vector3(); + }; - return result.copy( this.direction ).multiplyScalar( t ).add( this.origin ); + /** + * @author mrdoob / http://mrdoob.com/ + */ - }, + function WebGLBufferRenderer( _gl, extensions, _infoRender ) { - lookAt: function ( v ) { + var mode; - this.direction.copy( v ).sub( this.origin ).normalize(); + function setMode( value ) { - return this; + mode = value; - }, + } - recast: function () { + function render( start, count ) { - var v1 = new Vector3(); + _gl.drawArrays( mode, start, count ); - return function recast( t ) { + _infoRender.calls ++; + _infoRender.vertices += count; + if ( mode === _gl.TRIANGLES ) _infoRender.faces += count / 3; - this.origin.copy( this.at( t, v1 ) ); + } - return this; + function renderInstances( geometry ) { - }; + var extension = extensions.get( 'ANGLE_instanced_arrays' ); - }(), + if ( extension === null ) { - closestPointToPoint: function ( point, optionalTarget ) { + console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); + return; - var result = optionalTarget || new Vector3(); - result.subVectors( point, this.origin ); - var directionDistance = result.dot( this.direction ); + } - if ( directionDistance < 0 ) { + var position = geometry.attributes.position; - return result.copy( this.origin ); + var count = 0; - } + if ( (position && position.isInterleavedBufferAttribute) ) { - return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); + count = position.data.count; - }, + extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount ); - distanceToPoint: function ( point ) { + } else { - return Math.sqrt( this.distanceSqToPoint( point ) ); + count = position.count; - }, + extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount ); - distanceSqToPoint: function () { + } - var v1 = new Vector3(); + _infoRender.calls ++; + _infoRender.vertices += count * geometry.maxInstancedCount; + if ( mode === _gl.TRIANGLES ) _infoRender.faces += geometry.maxInstancedCount * count / 3; - return function distanceSqToPoint( point ) { + } - var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction ); + this.setMode = setMode; + this.render = render; + this.renderInstances = renderInstances; - // point behind the ray + }; - if ( directionDistance < 0 ) { + /** + * @author alteredq / http://alteredqualia.com + */ - return this.origin.distanceToSquared( point ); + function WebGLRenderTargetCube( width, height, options ) { - } + WebGLRenderTarget.call( this, width, height, options ); - v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); + this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5 + this.activeMipMapLevel = 0; - return v1.distanceToSquared( point ); + }; - }; + WebGLRenderTargetCube.prototype = Object.create( WebGLRenderTarget.prototype ); + WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube; - }(), + WebGLRenderTargetCube.prototype.isWebGLRenderTargetCube = true; - distanceSqToSegment: function () { + /** + * @author Mugen87 / https://github.com/Mugen87 + */ - var segCenter = new Vector3(); - var segDir = new Vector3(); - var diff = new Vector3(); + function BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) { - return function distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) { + BufferGeometry.call( this ); - // 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 + this.type = 'BoxBufferGeometry'; - segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 ); - segDir.copy( v1 ).sub( v0 ).normalize(); - diff.copy( this.origin ).sub( segCenter ); + this.parameters = { + width: width, + height: height, + depth: depth, + widthSegments: widthSegments, + heightSegments: heightSegments, + depthSegments: depthSegments + }; - 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 scope = this; - if ( det > 0 ) { + // segments + widthSegments = Math.floor( widthSegments ) || 1; + heightSegments = Math.floor( heightSegments ) || 1; + depthSegments = Math.floor( depthSegments ) || 1; - // The ray and segment are not parallel. + // these are used to calculate buffer length + var vertexCount = calculateVertexCount( widthSegments, heightSegments, depthSegments ); + var indexCount = calculateIndexCount( widthSegments, heightSegments, depthSegments ); - s0 = a01 * b1 - b0; - s1 = a01 * b0 - b1; - extDet = segExtent * det; + // 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 ( s0 >= 0 ) { + // offset variables + var vertexBufferOffset = 0; + var uvBufferOffset = 0; + var indexBufferOffset = 0; + var numberOfVertices = 0; - if ( s1 >= - extDet ) { + // group variables + var groupStart = 0; - if ( s1 <= extDet ) { + // 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 - // region 0 - // Minimum at interior points of ray and segment. + // 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 ) ); - var invDet = 1 / det; - s0 *= invDet; - s1 *= invDet; - sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c; + // helper functions - } else { + function calculateVertexCount( w, h, d ) { - // region 1 + var vertices = 0; - s1 = segExtent; - s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + // 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 - } + return vertices; - } else { + } - // region 5 + function calculateIndexCount( w, h, d ) { - s1 = - segExtent; - s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + 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 - } else { + return index * 6; // two triangles per square => six vertices per square - if ( s1 <= - extDet ) { + } - // region 4 + function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) { - 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; + var segmentWidth = width / gridX; + var segmentHeight = height / gridY; - } else if ( s1 <= extDet ) { + var widthHalf = width / 2; + var heightHalf = height / 2; + var depthHalf = depth / 2; - // region 3 + var gridX1 = gridX + 1; + var gridY1 = gridY + 1; - s0 = 0; - s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent ); - sqrDist = s1 * ( s1 + 2 * b1 ) + c; + var vertexCounter = 0; + var groupCount = 0; - } else { + var vector = new Vector3(); - // region 2 + // generate vertices, normals and uvs - 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; + for ( var iy = 0; iy < gridY1; iy ++ ) { - } + var y = iy * segmentHeight - heightHalf; - } + for ( var ix = 0; ix < gridX1; ix ++ ) { - } else { + var x = ix * segmentWidth - widthHalf; - // Ray and segment are parallel. + // set values to correct vector component + vector[ u ] = x * udir; + vector[ v ] = y * vdir; + vector[ w ] = depthHalf; - s1 = ( a01 > 0 ) ? - segExtent : segExtent; - s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + // now apply vector to vertex buffer + vertices[ vertexBufferOffset ] = vector.x; + vertices[ vertexBufferOffset + 1 ] = vector.y; + vertices[ vertexBufferOffset + 2 ] = vector.z; - } + // set values to correct vector component + vector[ u ] = 0; + vector[ v ] = 0; + vector[ w ] = depth > 0 ? 1 : - 1; - if ( optionalPointOnRay ) { + // now apply vector to normal buffer + normals[ vertexBufferOffset ] = vector.x; + normals[ vertexBufferOffset + 1 ] = vector.y; + normals[ vertexBufferOffset + 2 ] = vector.z; - optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin ); + // uvs + uvs[ uvBufferOffset ] = ix / gridX; + uvs[ uvBufferOffset + 1 ] = 1 - ( iy / gridY ); - } + // update offsets and counters + vertexBufferOffset += 3; + uvBufferOffset += 2; + vertexCounter += 1; - if ( optionalPointOnSegment ) { + } - optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter ); + } - } + // 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 - return sqrDist; + for ( iy = 0; iy < gridY; iy ++ ) { - }; + 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; - intersectSphere: function () { + // face one + indices[ indexBufferOffset ] = a; + indices[ indexBufferOffset + 1 ] = b; + indices[ indexBufferOffset + 2 ] = d; - var v1 = new Vector3(); + // face two + indices[ indexBufferOffset + 3 ] = b; + indices[ indexBufferOffset + 4 ] = c; + indices[ indexBufferOffset + 5 ] = d; - return function intersectSphere( sphere, optionalTarget ) { + // update offsets and counters + indexBufferOffset += 6; + groupCount += 6; - 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; + } - if ( d2 > radius2 ) return null; + } - var thc = Math.sqrt( radius2 - d2 ); + // add a group to the geometry. this will ensure multi material support + scope.addGroup( groupStart, groupCount, materialIndex ); - // t0 = first intersect point - entrance on front of sphere - var t0 = tca - thc; + // calculate new start value for groups + groupStart += groupCount; - // t1 = second intersect point - exit point on back of sphere - var t1 = tca + thc; + // update total number of vertices + numberOfVertices += vertexCounter; - // test to see if both t0 and t1 are behind the ray - if so, return null - if ( t0 < 0 && t1 < 0 ) return null; + } - // 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 ); + }; - // else t0 is in front of the ray, so return the first collision point scaled by t0 - return this.at( t0, optionalTarget ); + BoxBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + BoxBufferGeometry.prototype.constructor = BoxBufferGeometry; - }; + /** + * @author bhouston / http://clara.io + */ - }(), + function Ray( origin, direction ) { - intersectsSphere: function ( sphere ) { + this.origin = ( origin !== undefined ) ? origin : new Vector3(); + this.direction = ( direction !== undefined ) ? direction : new Vector3(); - return this.distanceToPoint( sphere.center ) <= sphere.radius; + }; - }, + Ray.prototype = { - distanceToPlane: function ( plane ) { + constructor: Ray, - var denominator = plane.normal.dot( this.direction ); + set: function ( origin, direction ) { - if ( denominator === 0 ) { + this.origin.copy( origin ); + this.direction.copy( direction ); - // line is coplanar, return origin - if ( plane.distanceToPoint( this.origin ) === 0 ) { + return this; - return 0; + }, - } + clone: function () { - // Null is preferable to undefined since undefined means.... it is undefined + return new this.constructor().copy( this ); - return null; + }, - } + copy: function ( ray ) { - var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator; + this.origin.copy( ray.origin ); + this.direction.copy( ray.direction ); - // Return if the ray never intersects the plane + return this; - return t >= 0 ? t : null; + }, - }, + at: function ( t, optionalTarget ) { - intersectPlane: function ( plane, optionalTarget ) { + var result = optionalTarget || new Vector3(); - var t = this.distanceToPlane( plane ); + return result.copy( this.direction ).multiplyScalar( t ).add( this.origin ); - if ( t === null ) { + }, - return null; + lookAt: function ( v ) { - } + this.direction.copy( v ).sub( this.origin ).normalize(); - return this.at( t, optionalTarget ); + return this; - }, + }, + recast: function () { + var v1 = new Vector3(); - intersectsPlane: function ( plane ) { + return function recast( t ) { - // check if the ray lies on the plane first + this.origin.copy( this.at( t, v1 ) ); - var distToPoint = plane.distanceToPoint( this.origin ); + return this; - if ( distToPoint === 0 ) { + }; - return true; + }(), - } + closestPointToPoint: function ( point, optionalTarget ) { - var denominator = plane.normal.dot( this.direction ); + var result = optionalTarget || new Vector3(); + result.subVectors( point, this.origin ); + var directionDistance = result.dot( this.direction ); - if ( denominator * distToPoint < 0 ) { + if ( directionDistance < 0 ) { - return true; + return result.copy( this.origin ); - } + } - // ray origin is behind the plane (and is pointing behind it) + return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); - return false; + }, - }, + distanceToPoint: function ( point ) { - intersectBox: function ( box, optionalTarget ) { + return Math.sqrt( this.distanceSqToPoint( point ) ); - var tmin, tmax, tymin, tymax, tzmin, tzmax; + }, - var invdirx = 1 / this.direction.x, - invdiry = 1 / this.direction.y, - invdirz = 1 / this.direction.z; + distanceSqToPoint: function () { - var origin = this.origin; + var v1 = new Vector3(); - if ( invdirx >= 0 ) { + return function distanceSqToPoint( point ) { - tmin = ( box.min.x - origin.x ) * invdirx; - tmax = ( box.max.x - origin.x ) * invdirx; + var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction ); - } else { + // point behind the ray - tmin = ( box.max.x - origin.x ) * invdirx; - tmax = ( box.min.x - origin.x ) * invdirx; + if ( directionDistance < 0 ) { - } + return this.origin.distanceToSquared( point ); - if ( invdiry >= 0 ) { + } - tymin = ( box.min.y - origin.y ) * invdiry; - tymax = ( box.max.y - origin.y ) * invdiry; + v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); - } else { + return v1.distanceToSquared( point ); - tymin = ( box.max.y - origin.y ) * invdiry; - tymax = ( box.min.y - origin.y ) * invdiry; + }; - } + }(), - if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null; + distanceSqToSegment: 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 + var segCenter = new Vector3(); + var segDir = new Vector3(); + var diff = new Vector3(); - if ( tymin > tmin || tmin !== tmin ) tmin = tymin; + return function distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) { - if ( tymax < tmax || tmax !== tmax ) tmax = tymax; + // 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 - if ( invdirz >= 0 ) { + segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 ); + segDir.copy( v1 ).sub( v0 ).normalize(); + diff.copy( this.origin ).sub( segCenter ); - tzmin = ( box.min.z - origin.z ) * invdirz; - tzmax = ( box.max.z - origin.z ) * invdirz; + 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; - } else { + if ( det > 0 ) { - tzmin = ( box.max.z - origin.z ) * invdirz; - tzmax = ( box.min.z - origin.z ) * invdirz; + // The ray and segment are not parallel. - } + s0 = a01 * b1 - b0; + s1 = a01 * b0 - b1; + extDet = segExtent * det; - if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null; + if ( s0 >= 0 ) { - if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin; + if ( s1 >= - extDet ) { - if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax; + if ( s1 <= extDet ) { - //return point closest to the ray (positive side) + // region 0 + // Minimum at interior points of ray and segment. - if ( tmax < 0 ) return null; + var invDet = 1 / det; + s0 *= invDet; + s1 *= invDet; + sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c; - return this.at( tmin >= 0 ? tmin : tmax, optionalTarget ); + } else { - }, + // region 1 - intersectsBox: ( function () { + s1 = segExtent; + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - var v = new Vector3(); + } - return function intersectsBox( box ) { + } else { - return this.intersectBox( box, v ) !== null; + // region 5 - }; + s1 = - segExtent; + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - } )(), + } - intersectTriangle: function () { + } else { - // Compute the offset origin, edges, and normal. - var diff = new Vector3(); - var edge1 = new Vector3(); - var edge2 = new Vector3(); - var normal = new Vector3(); + if ( s1 <= - extDet ) { - return function intersectTriangle( a, b, c, backfaceCulling, optionalTarget ) { + // region 4 - // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h + 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; - edge1.subVectors( b, a ); - edge2.subVectors( c, a ); - normal.crossVectors( edge1, edge2 ); + } else if ( s1 <= extDet ) { - // 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; + // region 3 - if ( DdN > 0 ) { + s0 = 0; + s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent ); + sqrDist = s1 * ( s1 + 2 * b1 ) + c; - if ( backfaceCulling ) return null; - sign = 1; + } else { - } else if ( DdN < 0 ) { + // region 2 - sign = - 1; - DdN = - DdN; + 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 { + } - return null; + } - } + } else { - diff.subVectors( this.origin, a ); - var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) ); + // Ray and segment are parallel. - // b1 < 0, no intersection - if ( DdQxE2 < 0 ) { + s1 = ( a01 > 0 ) ? - segExtent : segExtent; + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - return null; + } - } + if ( optionalPointOnRay ) { - var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) ); + optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin ); - // b2 < 0, no intersection - if ( DdE1xQ < 0 ) { + } - return null; + if ( optionalPointOnSegment ) { - } + optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter ); - // b1+b2 > 1, no intersection - if ( DdQxE2 + DdE1xQ > DdN ) { + } - return null; + return sqrDist; - } + }; - // Line intersects triangle, check if ray does. - var QdN = - sign * diff.dot( normal ); + }(), - // t < 0, no intersection - if ( QdN < 0 ) { + intersectSphere: function () { - return null; + var v1 = new Vector3(); - } + return function intersectSphere( sphere, optionalTarget ) { - // Ray intersects triangle. - return this.at( QdN / DdN, 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; - }; + if ( d2 > radius2 ) return null; - }(), + var thc = Math.sqrt( radius2 - d2 ); - applyMatrix4: function ( matrix4 ) { + // t0 = first intersect point - entrance on front of sphere + var t0 = tca - thc; - this.direction.add( this.origin ).applyMatrix4( matrix4 ); - this.origin.applyMatrix4( matrix4 ); - this.direction.sub( this.origin ); - this.direction.normalize(); + // t1 = second intersect point - exit point on back of sphere + var t1 = tca + thc; - return this; + // test to see if both t0 and t1 are behind the ray - if so, return null + if ( t0 < 0 && t1 < 0 ) return null; - }, + // 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 ); - equals: function ( ray ) { + // else t0 is in front of the ray, so return the first collision point scaled by t0 + return this.at( t0, optionalTarget ); - return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction ); + }; - } + }(), - }; + intersectsSphere: function ( sphere ) { - /** - * @author bhouston / http://clara.io - */ + return this.distanceToPoint( sphere.center ) <= sphere.radius; - function Line3( start, end ) { + }, - this.start = ( start !== undefined ) ? start : new Vector3(); - this.end = ( end !== undefined ) ? end : new Vector3(); + distanceToPlane: function ( plane ) { - }; + var denominator = plane.normal.dot( this.direction ); - Line3.prototype = { + if ( denominator === 0 ) { - constructor: Line3, + // line is coplanar, return origin + if ( plane.distanceToPoint( this.origin ) === 0 ) { - set: function ( start, end ) { + return 0; - this.start.copy( start ); - this.end.copy( end ); + } - return this; + // Null is preferable to undefined since undefined means.... it is undefined - }, + return null; - clone: function () { + } - return new this.constructor().copy( this ); + var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator; - }, + // Return if the ray never intersects the plane - copy: function ( line ) { + return t >= 0 ? t : null; - this.start.copy( line.start ); - this.end.copy( line.end ); + }, - return this; + intersectPlane: function ( plane, optionalTarget ) { - }, + var t = this.distanceToPlane( plane ); - center: function ( optionalTarget ) { + if ( t === null ) { - var result = optionalTarget || new Vector3(); - return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 ); + return null; - }, + } - delta: function ( optionalTarget ) { + return this.at( t, optionalTarget ); - var result = optionalTarget || new Vector3(); - return result.subVectors( this.end, this.start ); + }, - }, - distanceSq: function () { - return this.start.distanceToSquared( this.end ); + intersectsPlane: function ( plane ) { - }, + // check if the ray lies on the plane first - distance: function () { + var distToPoint = plane.distanceToPoint( this.origin ); - return this.start.distanceTo( this.end ); + if ( distToPoint === 0 ) { - }, + return true; - at: function ( t, optionalTarget ) { + } - var result = optionalTarget || new Vector3(); + var denominator = plane.normal.dot( this.direction ); - return this.delta( result ).multiplyScalar( t ).add( this.start ); + if ( denominator * distToPoint < 0 ) { - }, + return true; - closestPointToPointParameter: function () { + } - var startP = new Vector3(); - var startEnd = new Vector3(); + // ray origin is behind the plane (and is pointing behind it) - return function closestPointToPointParameter( point, clampToLine ) { + return false; - startP.subVectors( point, this.start ); - startEnd.subVectors( this.end, this.start ); + }, - var startEnd2 = startEnd.dot( startEnd ); - var startEnd_startP = startEnd.dot( startP ); + intersectBox: function ( box, optionalTarget ) { - var t = startEnd_startP / startEnd2; + var tmin, tmax, tymin, tymax, tzmin, tzmax; - if ( clampToLine ) { + var invdirx = 1 / this.direction.x, + invdiry = 1 / this.direction.y, + invdirz = 1 / this.direction.z; - t = exports.Math.clamp( t, 0, 1 ); + var origin = this.origin; - } + if ( invdirx >= 0 ) { - return t; + tmin = ( box.min.x - origin.x ) * invdirx; + tmax = ( box.max.x - origin.x ) * invdirx; - }; + } else { - }(), + tmin = ( box.max.x - origin.x ) * invdirx; + tmax = ( box.min.x - origin.x ) * invdirx; - closestPointToPoint: function ( point, clampToLine, optionalTarget ) { + } - var t = this.closestPointToPointParameter( point, clampToLine ); + if ( invdiry >= 0 ) { - var result = optionalTarget || new Vector3(); + tymin = ( box.min.y - origin.y ) * invdiry; + tymax = ( box.max.y - origin.y ) * invdiry; - return this.delta( result ).multiplyScalar( t ).add( this.start ); + } else { - }, + tymin = ( box.max.y - origin.y ) * invdiry; + tymax = ( box.min.y - origin.y ) * invdiry; - applyMatrix4: function ( matrix ) { + } - this.start.applyMatrix4( matrix ); - this.end.applyMatrix4( matrix ); + if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null; - return this; + // These lines also handle the case where tmin or tmax is NaN + // (result of 0 * Infinity). x !== x returns true if x is NaN - }, + if ( tymin > tmin || tmin !== tmin ) tmin = tymin; - equals: function ( line ) { + if ( tymax < tmax || tmax !== tmax ) tmax = tymax; - return line.start.equals( this.start ) && line.end.equals( this.end ); + if ( invdirz >= 0 ) { - } + tzmin = ( box.min.z - origin.z ) * invdirz; + tzmax = ( box.max.z - origin.z ) * invdirz; - }; + } else { - /** - * @author bhouston / http://clara.io - * @author mrdoob / http://mrdoob.com/ - */ + tzmin = ( box.max.z - origin.z ) * invdirz; + tzmax = ( box.min.z - origin.z ) * invdirz; - function Triangle( a, b, c ) { + } - this.a = ( a !== undefined ) ? a : new Vector3(); - this.b = ( b !== undefined ) ? b : new Vector3(); - this.c = ( c !== undefined ) ? c : new Vector3(); + if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null; - }; + if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin; - Triangle.normal = function () { + if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax; - var v0 = new Vector3(); + //return point closest to the ray (positive side) - return function normal( a, b, c, optionalTarget ) { + if ( tmax < 0 ) return null; - var result = optionalTarget || new Vector3(); + return this.at( tmin >= 0 ? tmin : tmax, optionalTarget ); - result.subVectors( c, b ); - v0.subVectors( a, b ); - result.cross( v0 ); + }, - var resultLengthSq = result.lengthSq(); - if ( resultLengthSq > 0 ) { + intersectsBox: ( function () { - return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) ); + var v = new Vector3(); - } + return function intersectsBox( box ) { - return result.set( 0, 0, 0 ); + return this.intersectBox( box, v ) !== null; - }; + }; - }(); + } )(), - // static/instance method to calculate barycentric coordinates - // based on: http://www.blackpawn.com/texts/pointinpoly/default.html - Triangle.barycoordFromPoint = function () { + intersectTriangle: function () { - var v0 = new Vector3(); - var v1 = new Vector3(); - var v2 = new Vector3(); + // Compute the offset origin, edges, and normal. + var diff = new Vector3(); + var edge1 = new Vector3(); + var edge2 = new Vector3(); + var normal = new Vector3(); - return function barycoordFromPoint( point, a, b, c, optionalTarget ) { + return function intersectTriangle( a, b, c, backfaceCulling, optionalTarget ) { - v0.subVectors( c, a ); - v1.subVectors( b, a ); - v2.subVectors( point, a ); + // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h - 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 ); + edge1.subVectors( b, a ); + edge2.subVectors( c, a ); + normal.crossVectors( edge1, edge2 ); - var denom = ( dot00 * dot11 - dot01 * dot01 ); + // 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; - var result = optionalTarget || new Vector3(); + if ( DdN > 0 ) { - // collinear or singular triangle - if ( denom === 0 ) { + if ( backfaceCulling ) return null; + sign = 1; - // arbitrary location outside of triangle? - // not sure if this is the best idea, maybe should be returning undefined - return result.set( - 2, - 1, - 1 ); + } else if ( DdN < 0 ) { - } + sign = - 1; + DdN = - DdN; - var invDenom = 1 / denom; - var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom; - var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom; + } else { - // barycentric coordinates must always sum to 1 - return result.set( 1 - u - v, v, u ); + return null; - }; + } - }(); + diff.subVectors( this.origin, a ); + var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) ); - Triangle.containsPoint = function () { + // b1 < 0, no intersection + if ( DdQxE2 < 0 ) { - var v1 = new Vector3(); + return null; - return function containsPoint( point, a, b, c ) { + } - var result = Triangle.barycoordFromPoint( point, a, b, c, v1 ); + var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) ); - return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 ); + // b2 < 0, no intersection + if ( DdE1xQ < 0 ) { - }; + return null; - }(); + } - Triangle.prototype = { + // b1+b2 > 1, no intersection + if ( DdQxE2 + DdE1xQ > DdN ) { - constructor: Triangle, + return null; - set: function ( a, b, c ) { + } - this.a.copy( a ); - this.b.copy( b ); - this.c.copy( c ); + // Line intersects triangle, check if ray does. + var QdN = - sign * diff.dot( normal ); - return this; + // t < 0, no intersection + if ( QdN < 0 ) { - }, + return null; - setFromPointsAndIndices: function ( points, i0, i1, i2 ) { + } - this.a.copy( points[ i0 ] ); - this.b.copy( points[ i1 ] ); - this.c.copy( points[ i2 ] ); + // Ray intersects triangle. + return this.at( QdN / DdN, optionalTarget ); - return this; + }; - }, + }(), - clone: function () { + applyMatrix4: function ( matrix4 ) { - return new this.constructor().copy( this ); + this.direction.add( this.origin ).applyMatrix4( matrix4 ); + this.origin.applyMatrix4( matrix4 ); + this.direction.sub( this.origin ); + this.direction.normalize(); - }, + return this; - copy: function ( triangle ) { + }, - this.a.copy( triangle.a ); - this.b.copy( triangle.b ); - this.c.copy( triangle.c ); + equals: function ( ray ) { - return this; + return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction ); - }, + } - area: function () { + }; - var v0 = new Vector3(); - var v1 = new Vector3(); + /** + * @author bhouston / http://clara.io + */ - return function area() { + function Line3( start, end ) { - v0.subVectors( this.c, this.b ); - v1.subVectors( this.a, this.b ); + this.start = ( start !== undefined ) ? start : new Vector3(); + this.end = ( end !== undefined ) ? end : new Vector3(); - return v0.cross( v1 ).length() * 0.5; + }; - }; + Line3.prototype = { - }(), + constructor: Line3, - midpoint: function ( optionalTarget ) { + set: function ( start, end ) { - var result = optionalTarget || new Vector3(); - return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 ); + this.start.copy( start ); + this.end.copy( end ); - }, + return this; - normal: function ( optionalTarget ) { + }, - return Triangle.normal( this.a, this.b, this.c, optionalTarget ); + clone: function () { - }, + return new this.constructor().copy( this ); - plane: function ( optionalTarget ) { + }, - var result = optionalTarget || new Plane(); + copy: function ( line ) { - return result.setFromCoplanarPoints( this.a, this.b, this.c ); + this.start.copy( line.start ); + this.end.copy( line.end ); - }, + return this; - barycoordFromPoint: function ( point, optionalTarget ) { + }, - return Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget ); + center: function ( optionalTarget ) { - }, + var result = optionalTarget || new Vector3(); + return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 ); - containsPoint: function ( point ) { + }, - return Triangle.containsPoint( point, this.a, this.b, this.c ); + delta: function ( optionalTarget ) { - }, + var result = optionalTarget || new Vector3(); + return result.subVectors( this.end, this.start ); - closestPointToPoint: function () { + }, - var plane, edgeList, projectedPoint, closestPoint; + distanceSq: function () { - return function closestPointToPoint( point, optionalTarget ) { + return this.start.distanceToSquared( this.end ); - if ( plane === undefined ) { + }, - plane = new Plane(); - edgeList = [ new Line3(), new Line3(), new Line3() ]; - projectedPoint = new Vector3(); - closestPoint = new Vector3(); + distance: function () { - } + return this.start.distanceTo( this.end ); - var result = optionalTarget || new Vector3(); - var minDistance = Infinity; + }, - // project the point onto the plane of the triangle + at: function ( t, optionalTarget ) { - plane.setFromCoplanarPoints( this.a, this.b, this.c ); - plane.projectPoint( point, projectedPoint ); + var result = optionalTarget || new Vector3(); - // check if the projection lies within the triangle + return this.delta( result ).multiplyScalar( t ).add( this.start ); - if( this.containsPoint( projectedPoint ) === true ) { + }, - // if so, this is the closest point + closestPointToPointParameter: function () { - result.copy( projectedPoint ); + var startP = new Vector3(); + var startEnd = new Vector3(); - } else { + return function closestPointToPointParameter( point, clampToLine ) { - // if not, the point falls outside the triangle. the result is the closest point to the triangle's edges or vertices + startP.subVectors( point, this.start ); + startEnd.subVectors( this.end, this.start ); - edgeList[ 0 ].set( this.a, this.b ); - edgeList[ 1 ].set( this.b, this.c ); - edgeList[ 2 ].set( this.c, this.a ); + var startEnd2 = startEnd.dot( startEnd ); + var startEnd_startP = startEnd.dot( startP ); - for( var i = 0; i < edgeList.length; i ++ ) { + var t = startEnd_startP / startEnd2; - edgeList[ i ].closestPointToPoint( projectedPoint, true, closestPoint ); + if ( clampToLine ) { - var distance = projectedPoint.distanceToSquared( closestPoint ); + t = exports.Math.clamp( t, 0, 1 ); - if( distance < minDistance ) { + } - minDistance = distance; + return t; - result.copy( closestPoint ); + }; - } + }(), - } + closestPointToPoint: function ( point, clampToLine, optionalTarget ) { - } + var t = this.closestPointToPointParameter( point, clampToLine ); - return result; + var result = optionalTarget || new Vector3(); - }; + return this.delta( result ).multiplyScalar( t ).add( this.start ); - }(), + }, - equals: function ( triangle ) { + applyMatrix4: function ( matrix ) { - return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c ); + this.start.applyMatrix4( matrix ); + this.end.applyMatrix4( matrix ); - } + return this; - }; + }, - /** - * @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: - * } - */ + equals: function ( line ) { - function MeshBasicMaterial( parameters ) { + return line.start.equals( this.start ) && line.end.equals( this.end ); - Material.call( this ); + } - this.type = 'MeshBasicMaterial'; + }; - this.color = new Color( 0xffffff ); // emissive + /** + * @author bhouston / http://clara.io + * @author mrdoob / http://mrdoob.com/ + */ - this.map = null; + function Triangle( a, b, c ) { - this.aoMap = null; - this.aoMapIntensity = 1.0; + this.a = ( a !== undefined ) ? a : new Vector3(); + this.b = ( b !== undefined ) ? b : new Vector3(); + this.c = ( c !== undefined ) ? c : new Vector3(); - this.specularMap = null; + }; - this.alphaMap = null; + Triangle.normal = function () { - this.envMap = null; - this.combine = MultiplyOperation; - this.reflectivity = 1; - this.refractionRatio = 0.98; + var v0 = new Vector3(); - this.wireframe = false; - this.wireframeLinewidth = 1; - this.wireframeLinecap = 'round'; - this.wireframeLinejoin = 'round'; + return function normal( a, b, c, optionalTarget ) { - this.skinning = false; - this.morphTargets = false; + var result = optionalTarget || new Vector3(); - this.lights = false; + result.subVectors( c, b ); + v0.subVectors( a, b ); + result.cross( v0 ); - this.setValues( parameters ); + var resultLengthSq = result.lengthSq(); + if ( resultLengthSq > 0 ) { - }; + return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) ); - MeshBasicMaterial.prototype = Object.create( Material.prototype ); - MeshBasicMaterial.prototype.constructor = MeshBasicMaterial; + } - MeshBasicMaterial.prototype.isMeshBasicMaterial = true; + return result.set( 0, 0, 0 ); - MeshBasicMaterial.prototype.copy = function ( source ) { + }; - Material.prototype.copy.call( this, source ); + }(); - this.color.copy( source.color ); + // static/instance method to calculate barycentric coordinates + // based on: http://www.blackpawn.com/texts/pointinpoly/default.html + Triangle.barycoordFromPoint = function () { - this.map = source.map; + var v0 = new Vector3(); + var v1 = new Vector3(); + var v2 = new Vector3(); - this.aoMap = source.aoMap; - this.aoMapIntensity = source.aoMapIntensity; + return function barycoordFromPoint( point, a, b, c, optionalTarget ) { - this.specularMap = source.specularMap; + v0.subVectors( c, a ); + v1.subVectors( b, a ); + v2.subVectors( point, a ); - this.alphaMap = source.alphaMap; + 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 ); - this.envMap = source.envMap; - this.combine = source.combine; - this.reflectivity = source.reflectivity; - this.refractionRatio = source.refractionRatio; + var denom = ( dot00 * dot11 - dot01 * dot01 ); - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; - this.wireframeLinecap = source.wireframeLinecap; - this.wireframeLinejoin = source.wireframeLinejoin; + var result = optionalTarget || new Vector3(); - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; + // collinear or singular triangle + if ( denom === 0 ) { - return this; + // 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/ - * @author mikael emtinger / http://gomo.se/ - * @author jonobr1 / http://jonobr1.com/ - */ + var invDenom = 1 / denom; + var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom; + var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom; - function Mesh( geometry, material ) { + // barycentric coordinates must always sum to 1 + return result.set( 1 - u - v, v, u ); - Object3D.call( this ); + }; - this.type = 'Mesh'; + }(); - this.geometry = geometry !== undefined ? geometry : new BufferGeometry(); - this.material = material !== undefined ? material : new MeshBasicMaterial( { color: Math.random() * 0xffffff } ); + Triangle.containsPoint = function () { - this.drawMode = TrianglesDrawMode; + var v1 = new Vector3(); - this.updateMorphTargets(); + return function containsPoint( point, a, b, c ) { - }; + var result = Triangle.barycoordFromPoint( point, a, b, c, v1 ); - Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), { + return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 ); - constructor: Mesh, + }; - isMesh: true, + }(); - setDrawMode: function ( value ) { + Triangle.prototype = { - this.drawMode = value; + constructor: Triangle, - }, + set: function ( a, b, c ) { - copy: function ( source ) { + this.a.copy( a ); + this.b.copy( b ); + this.c.copy( c ); - Object3D.prototype.copy.call( this, source ); + return this; - this.drawMode = source.drawMode; + }, - return this; + setFromPointsAndIndices: function ( points, i0, i1, i2 ) { - }, + this.a.copy( points[ i0 ] ); + this.b.copy( points[ i1 ] ); + this.c.copy( points[ i2 ] ); - updateMorphTargets: function () { + return this; - if ( this.geometry.morphTargets !== undefined && this.geometry.morphTargets.length > 0 ) { + }, - this.morphTargetBase = - 1; - this.morphTargetInfluences = []; - this.morphTargetDictionary = {}; + clone: function () { - for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) { + return new this.constructor().copy( this ); - this.morphTargetInfluences.push( 0 ); - this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m; + }, - } + copy: function ( triangle ) { - } + this.a.copy( triangle.a ); + this.b.copy( triangle.b ); + this.c.copy( triangle.c ); - }, + return this; - getMorphTargetIndexByName: function ( name ) { + }, - if ( this.morphTargetDictionary[ name ] !== undefined ) { + area: function () { - return this.morphTargetDictionary[ name ]; + var v0 = new Vector3(); + var v1 = new Vector3(); - } + return function area() { - console.warn( 'THREE.Mesh.getMorphTargetIndexByName: morph target ' + name + ' does not exist. Returning 0.' ); + v0.subVectors( this.c, this.b ); + v1.subVectors( this.a, this.b ); - return 0; + return v0.cross( v1 ).length() * 0.5; - }, + }; - raycast: ( function () { + }(), - var inverseMatrix = new Matrix4(); - var ray = new Ray(); - var sphere = new Sphere(); + midpoint: function ( optionalTarget ) { - var vA = new Vector3(); - var vB = new Vector3(); - var vC = new Vector3(); + var result = optionalTarget || new Vector3(); + return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 ); - var tempA = new Vector3(); - var tempB = new Vector3(); - var tempC = new Vector3(); + }, - var uvA = new Vector2(); - var uvB = new Vector2(); - var uvC = new Vector2(); + normal: function ( optionalTarget ) { - var barycoord = new Vector3(); + return Triangle.normal( this.a, this.b, this.c, optionalTarget ); - var intersectionPoint = new Vector3(); - var intersectionPointWorld = new Vector3(); + }, - function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) { + plane: function ( optionalTarget ) { - Triangle.barycoordFromPoint( point, p1, p2, p3, barycoord ); + var result = optionalTarget || new Plane(); - uv1.multiplyScalar( barycoord.x ); - uv2.multiplyScalar( barycoord.y ); - uv3.multiplyScalar( barycoord.z ); + return result.setFromCoplanarPoints( this.a, this.b, this.c ); - uv1.add( uv2 ).add( uv3 ); + }, - return uv1.clone(); + barycoordFromPoint: function ( point, optionalTarget ) { - } + return Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget ); - function checkIntersection( object, raycaster, ray, pA, pB, pC, point ) { + }, - var intersect; - var material = object.material; + containsPoint: function ( point ) { - if ( material.side === BackSide ) { + return Triangle.containsPoint( point, this.a, this.b, this.c ); - intersect = ray.intersectTriangle( pC, pB, pA, true, point ); + }, - } else { + closestPointToPoint: function () { - intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point ); + var plane, edgeList, projectedPoint, closestPoint; - } + return function closestPointToPoint( point, optionalTarget ) { - if ( intersect === null ) return null; + if ( plane === undefined ) { - intersectionPointWorld.copy( point ); - intersectionPointWorld.applyMatrix4( object.matrixWorld ); + plane = new Plane(); + edgeList = [ new Line3(), new Line3(), new Line3() ]; + projectedPoint = new Vector3(); + closestPoint = new Vector3(); - var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld ); + } - if ( distance < raycaster.near || distance > raycaster.far ) return null; + var result = optionalTarget || new Vector3(); + var minDistance = Infinity; - return { - distance: distance, - point: intersectionPointWorld.clone(), - object: object - }; + // project the point onto the plane of the triangle - } + plane.setFromCoplanarPoints( this.a, this.b, this.c ); + plane.projectPoint( point, projectedPoint ); - function checkBufferGeometryIntersection( object, raycaster, ray, positions, uvs, a, b, c ) { + // check if the projection lies within the triangle - vA.fromArray( positions, a * 3 ); - vB.fromArray( positions, b * 3 ); - vC.fromArray( positions, c * 3 ); + if( this.containsPoint( projectedPoint ) === true ) { - var intersection = checkIntersection( object, raycaster, ray, vA, vB, vC, intersectionPoint ); + // if so, this is the closest point - if ( intersection ) { + result.copy( projectedPoint ); - if ( uvs ) { + } else { - uvA.fromArray( uvs, a * 2 ); - uvB.fromArray( uvs, b * 2 ); - uvC.fromArray( uvs, c * 2 ); + // if not, the point falls outside the triangle. the result is the closest point to the triangle's edges or vertices - intersection.uv = uvIntersection( intersectionPoint, vA, vB, vC, uvA, uvB, uvC ); + edgeList[ 0 ].set( this.a, this.b ); + edgeList[ 1 ].set( this.b, this.c ); + edgeList[ 2 ].set( this.c, this.a ); - } + for( var i = 0; i < edgeList.length; i ++ ) { - intersection.face = new Face3( a, b, c, Triangle.normal( vA, vB, vC ) ); - intersection.faceIndex = a; + edgeList[ i ].closestPointToPoint( projectedPoint, true, closestPoint ); - } + var distance = projectedPoint.distanceToSquared( closestPoint ); - return intersection; + if( distance < minDistance ) { - } + minDistance = distance; - return function raycast( raycaster, intersects ) { + result.copy( closestPoint ); - var geometry = this.geometry; - var material = this.material; - var matrixWorld = this.matrixWorld; + } - if ( material === undefined ) return; + } - // Checking boundingSphere distance to ray + } - if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + return result; - sphere.copy( geometry.boundingSphere ); - sphere.applyMatrix4( matrixWorld ); + }; - if ( raycaster.ray.intersectsSphere( sphere ) === false ) return; + }(), - // + equals: function ( triangle ) { - inverseMatrix.getInverse( matrixWorld ); - ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); + return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c ); - // Check boundingBox before continuing + } - if ( geometry.boundingBox !== null ) { + }; - if ( ray.intersectsBox( geometry.boundingBox ) === false ) return; + /** + * @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 ); - } + }; - var uvs, intersection; + MeshBasicMaterial.prototype = Object.create( Material.prototype ); + MeshBasicMaterial.prototype.constructor = MeshBasicMaterial; - if ( (geometry && geometry.isBufferGeometry) ) { + MeshBasicMaterial.prototype.isMeshBasicMaterial = true; - var a, b, c; - var index = geometry.index; - var attributes = geometry.attributes; - var positions = attributes.position.array; + MeshBasicMaterial.prototype.copy = function ( source ) { - if ( attributes.uv !== undefined ) { + Material.prototype.copy.call( this, source ); - uvs = attributes.uv.array; + this.color.copy( source.color ); - } + this.map = source.map; - if ( index !== null ) { + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; - var indices = index.array; + this.specularMap = source.specularMap; - for ( var i = 0, l = indices.length; i < l; i += 3 ) { + this.alphaMap = source.alphaMap; - a = indices[ i ]; - b = indices[ i + 1 ]; - c = indices[ i + 2 ]; + this.envMap = source.envMap; + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; - intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c ); + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; - if ( intersection ) { + this.skinning = source.skinning; + this.morphTargets = source.morphTargets; - intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indices buffer semantics - intersects.push( intersection ); + return this; - } + }; - } + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * @author mikael emtinger / http://gomo.se/ + * @author jonobr1 / http://jonobr1.com/ + */ - } else { + function Mesh( geometry, material ) { + Object3D.call( this ); - for ( var i = 0, l = positions.length; i < l; i += 9 ) { + this.type = 'Mesh'; - a = i / 3; - b = a + 1; - c = a + 2; + this.geometry = geometry !== undefined ? geometry : new BufferGeometry(); + this.material = material !== undefined ? material : new MeshBasicMaterial( { color: Math.random() * 0xffffff } ); - intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c ); + this.drawMode = TrianglesDrawMode; - if ( intersection ) { + this.updateMorphTargets(); - intersection.index = a; // triangle number in positions buffer semantics - intersects.push( intersection ); + }; - } + Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), { - } + constructor: Mesh, - } + isMesh: true, - } else if ( (geometry && geometry.isGeometry) ) { + setDrawMode: function ( value ) { - var fvA, fvB, fvC; - var isFaceMaterial = (material && material.isMultiMaterial); - var materials = isFaceMaterial === true ? material.materials : null; + this.drawMode = value; - var vertices = geometry.vertices; - var faces = geometry.faces; - var faceVertexUvs = geometry.faceVertexUvs[ 0 ]; - if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs; + }, - for ( var f = 0, fl = faces.length; f < fl; f ++ ) { + copy: function ( source ) { - var face = faces[ f ]; - var faceMaterial = isFaceMaterial === true ? materials[ face.materialIndex ] : material; + Object3D.prototype.copy.call( this, source ); - if ( faceMaterial === undefined ) continue; + this.drawMode = source.drawMode; - fvA = vertices[ face.a ]; - fvB = vertices[ face.b ]; - fvC = vertices[ face.c ]; + return this; - if ( faceMaterial.morphTargets === true ) { + }, - var morphTargets = geometry.morphTargets; - var morphInfluences = this.morphTargetInfluences; + updateMorphTargets: function () { - vA.set( 0, 0, 0 ); - vB.set( 0, 0, 0 ); - vC.set( 0, 0, 0 ); + if ( this.geometry.morphTargets !== undefined && this.geometry.morphTargets.length > 0 ) { - for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) { + this.morphTargetBase = - 1; + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; - var influence = morphInfluences[ t ]; + for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) { - if ( influence === 0 ) continue; + this.morphTargetInfluences.push( 0 ); + this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m; - 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 ); + } - } + }, - vA.add( fvA ); - vB.add( fvB ); - vC.add( fvC ); + getMorphTargetIndexByName: function ( name ) { - fvA = vA; - fvB = vB; - fvC = vC; + if ( this.morphTargetDictionary[ name ] !== undefined ) { - } + return this.morphTargetDictionary[ name ]; - intersection = checkIntersection( this, raycaster, ray, fvA, fvB, fvC, intersectionPoint ); + } - if ( intersection ) { + console.warn( 'THREE.Mesh.getMorphTargetIndexByName: morph target ' + name + ' does not exist. Returning 0.' ); - if ( uvs ) { + return 0; - var uvs_f = uvs[ f ]; - uvA.copy( uvs_f[ 0 ] ); - uvB.copy( uvs_f[ 1 ] ); - uvC.copy( uvs_f[ 2 ] ); + }, - intersection.uv = uvIntersection( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC ); + raycast: ( function () { - } + var inverseMatrix = new Matrix4(); + var ray = new Ray(); + var sphere = new Sphere(); - intersection.face = face; - intersection.faceIndex = f; - 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(); - }; + var intersectionPoint = new Vector3(); + var intersectionPointWorld = new Vector3(); - }() ), + function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) { - clone: function () { + Triangle.barycoordFromPoint( point, p1, p2, p3, barycoord ); - return new this.constructor( this.geometry, this.material ).copy( this ); + uv1.multiplyScalar( barycoord.x ); + uv2.multiplyScalar( barycoord.y ); + uv3.multiplyScalar( barycoord.z ); - } + uv1.add( uv2 ).add( uv3 ); - } ); + return uv1.clone(); - /** - * @author mrdoob / http://mrdoob.com/ - * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as - */ + } - function PlaneBufferGeometry( width, height, widthSegments, heightSegments ) { + function checkIntersection( object, raycaster, ray, pA, pB, pC, point ) { - BufferGeometry.call( this ); + var intersect; + var material = object.material; - this.type = 'PlaneBufferGeometry'; + if ( material.side === BackSide ) { - this.parameters = { - width: width, - height: height, - widthSegments: widthSegments, - heightSegments: heightSegments - }; + intersect = ray.intersectTriangle( pC, pB, pA, true, point ); - var width_half = width / 2; - var height_half = height / 2; + } else { - var gridX = Math.floor( widthSegments ) || 1; - var gridY = Math.floor( heightSegments ) || 1; + intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point ); - var gridX1 = gridX + 1; - var gridY1 = gridY + 1; + } - var segment_width = width / gridX; - var segment_height = height / gridY; + if ( intersect === null ) return null; - var vertices = new Float32Array( gridX1 * gridY1 * 3 ); - var normals = new Float32Array( gridX1 * gridY1 * 3 ); - var uvs = new Float32Array( gridX1 * gridY1 * 2 ); + intersectionPointWorld.copy( point ); + intersectionPointWorld.applyMatrix4( object.matrixWorld ); - var offset = 0; - var offset2 = 0; + var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld ); - for ( var iy = 0; iy < gridY1; iy ++ ) { + if ( distance < raycaster.near || distance > raycaster.far ) return null; - var y = iy * segment_height - height_half; + return { + distance: distance, + point: intersectionPointWorld.clone(), + object: object + }; - for ( var ix = 0; ix < gridX1; ix ++ ) { + } - var x = ix * segment_width - width_half; + function checkBufferGeometryIntersection( object, raycaster, ray, positions, uvs, a, b, c ) { - vertices[ offset ] = x; - vertices[ offset + 1 ] = - y; + vA.fromArray( positions, a * 3 ); + vB.fromArray( positions, b * 3 ); + vC.fromArray( positions, c * 3 ); - normals[ offset + 2 ] = 1; + var intersection = checkIntersection( object, raycaster, ray, vA, vB, vC, intersectionPoint ); - uvs[ offset2 ] = ix / gridX; - uvs[ offset2 + 1 ] = 1 - ( iy / gridY ); + if ( intersection ) { - offset += 3; - offset2 += 2; + if ( uvs ) { - } + 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 ); - offset = 0; + } - var indices = new ( ( vertices.length / 3 ) > 65535 ? Uint32Array : Uint16Array )( gridX * gridY * 6 ); + intersection.face = new Face3( a, b, c, Triangle.normal( vA, vB, vC ) ); + intersection.faceIndex = a; - for ( var iy = 0; iy < gridY; iy ++ ) { + } - for ( var ix = 0; ix < gridX; ix ++ ) { + return intersection; - var a = ix + gridX1 * iy; - var b = ix + gridX1 * ( iy + 1 ); - var c = ( ix + 1 ) + gridX1 * ( iy + 1 ); - var d = ( ix + 1 ) + gridX1 * iy; + } - indices[ offset ] = a; - indices[ offset + 1 ] = b; - indices[ offset + 2 ] = d; + return function raycast( raycaster, intersects ) { - indices[ offset + 3 ] = b; - indices[ offset + 4 ] = c; - indices[ offset + 5 ] = d; + var geometry = this.geometry; + var material = this.material; + var matrixWorld = this.matrixWorld; - offset += 6; + if ( material === undefined ) return; - } + // Checking boundingSphere distance to ray - } + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); - 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 ) ); + sphere.copy( geometry.boundingSphere ); + sphere.applyMatrix4( matrixWorld ); - }; + if ( raycaster.ray.intersectsSphere( sphere ) === false ) return; - 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 - */ + inverseMatrix.getInverse( matrixWorld ); + ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); - function Camera() { + // Check boundingBox before continuing - Object3D.call( this ); + if ( geometry.boundingBox !== null ) { - this.type = 'Camera'; + if ( ray.intersectsBox( geometry.boundingBox ) === false ) return; - this.matrixWorldInverse = new Matrix4(); - this.projectionMatrix = new Matrix4(); + } - }; + var uvs, intersection; - Camera.prototype = Object.create( Object3D.prototype ); - Camera.prototype.constructor = Camera; + if ( (geometry && geometry.isBufferGeometry) ) { - Camera.prototype.isCamera = true; + var a, b, c; + var index = geometry.index; + var attributes = geometry.attributes; + var positions = attributes.position.array; - Camera.prototype.getWorldDirection = function () { + if ( attributes.uv !== undefined ) { - var quaternion = new Quaternion(); + uvs = attributes.uv.array; - return function getWorldDirection( optionalTarget ) { + } - var result = optionalTarget || new Vector3(); + if ( index !== null ) { - this.getWorldQuaternion( quaternion ); + var indices = index.array; - return result.set( 0, 0, - 1 ).applyQuaternion( quaternion ); + 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 ); - Camera.prototype.lookAt = function () { + if ( intersection ) { - // This routine does not support cameras with rotated and/or translated parent(s) + intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indices buffer semantics + intersects.push( intersection ); - var m1 = new Matrix4(); + } - return function lookAt( vector ) { + } - m1.lookAt( this.position, vector, this.up ); + } else { - this.quaternion.setFromRotationMatrix( m1 ); - }; + for ( var i = 0, l = positions.length; i < l; i += 9 ) { - }(); + a = i / 3; + b = a + 1; + c = a + 2; - Camera.prototype.clone = function () { + intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c ); - return new this.constructor().copy( this ); + if ( intersection ) { - }; + intersection.index = a; // triangle number in positions buffer semantics + 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; + } else if ( (geometry && geometry.isGeometry) ) { - }; + var fvA, fvB, fvC; + var isFaceMaterial = (material && material.isMultiMaterial); + var materials = isFaceMaterial === true ? material.materials : null; - /** - * @author mrdoob / http://mrdoob.com/ - * @author greggman / http://games.greggman.com/ - * @author zz85 / http://www.lab4games.net/zz85/blog - * @author tschw - */ + var vertices = geometry.vertices; + var faces = geometry.faces; + var faceVertexUvs = geometry.faceVertexUvs[ 0 ]; + if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs; - function PerspectiveCamera( fov, aspect, near, far ) { + for ( var f = 0, fl = faces.length; f < fl; f ++ ) { - Camera.call( this ); + var face = faces[ f ]; + var faceMaterial = isFaceMaterial === true ? materials[ face.materialIndex ] : material; - this.type = 'PerspectiveCamera'; + if ( faceMaterial === undefined ) continue; - this.fov = fov !== undefined ? fov : 50; - this.zoom = 1; + fvA = vertices[ face.a ]; + fvB = vertices[ face.b ]; + fvC = vertices[ face.c ]; - this.near = near !== undefined ? near : 0.1; - this.far = far !== undefined ? far : 2000; - this.focus = 10; + if ( faceMaterial.morphTargets === true ) { - this.aspect = aspect !== undefined ? aspect : 1; - this.view = null; + var morphTargets = geometry.morphTargets; + var morphInfluences = this.morphTargetInfluences; - this.filmGauge = 35; // width of the film (default in millimeters) - this.filmOffset = 0; // horizontal film offset (same unit as gauge) + vA.set( 0, 0, 0 ); + vB.set( 0, 0, 0 ); + vC.set( 0, 0, 0 ); - this.updateProjectionMatrix(); + for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) { - }; + var influence = morphInfluences[ t ]; - PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), { + if ( influence === 0 ) continue; - constructor: PerspectiveCamera, + var targets = morphTargets[ t ].vertices; - isPerspectiveCamera: true, + 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 ); - copy: function ( source ) { + } - Camera.prototype.copy.call( this, source ); + vA.add( fvA ); + vB.add( fvB ); + vC.add( fvC ); - this.fov = source.fov; - this.zoom = source.zoom; + fvA = vA; + fvB = vB; + fvC = vC; - this.near = source.near; - this.far = source.far; - this.focus = source.focus; + } - this.aspect = source.aspect; - this.view = source.view === null ? null : Object.assign( {}, source.view ); + intersection = checkIntersection( this, raycaster, ray, fvA, fvB, fvC, intersectionPoint ); - this.filmGauge = source.filmGauge; - this.filmOffset = source.filmOffset; + if ( intersection ) { - return this; + if ( uvs ) { - }, + var uvs_f = uvs[ f ]; + uvA.copy( uvs_f[ 0 ] ); + uvB.copy( uvs_f[ 1 ] ); + uvC.copy( uvs_f[ 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 ) { + intersection.uv = uvIntersection( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC ); - // see http://www.bobatkins.com/photography/technical/field_of_view.html - var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength; + } - this.fov = exports.Math.RAD2DEG * 2 * Math.atan( vExtentSlope ); - this.updateProjectionMatrix(); + intersection.face = face; + intersection.faceIndex = f; + intersects.push( intersection ); - }, + } - /** - * Calculates the focal length from the current .fov and .filmGauge. - */ - getFocalLength: function () { + } - var vExtentSlope = Math.tan( exports.Math.DEG2RAD * 0.5 * this.fov ); + } - return 0.5 * this.getFilmHeight() / vExtentSlope; + }; - }, + }() ), - getEffectiveFOV: function () { + clone: function () { - return exports.Math.RAD2DEG * 2 * Math.atan( - Math.tan( exports.Math.DEG2RAD * 0.5 * this.fov ) / this.zoom ); + return new this.constructor( this.geometry, this.material ).copy( this ); - }, + } - getFilmWidth: function () { + } ); - // film not completely covered in portrait format (aspect < 1) - return this.filmGauge * Math.min( this.aspect, 1 ); + /** + * @author mrdoob / http://mrdoob.com/ + * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as + */ - }, + function PlaneBufferGeometry( width, height, widthSegments, heightSegments ) { - getFilmHeight: function () { + BufferGeometry.call( this ); - // film not completely covered in landscape format (aspect > 1) - return this.filmGauge / Math.max( this.aspect, 1 ); + this.type = 'PlaneBufferGeometry'; - }, + this.parameters = { + width: width, + height: height, + widthSegments: widthSegments, + heightSegments: heightSegments + }; - /** - * 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 ) { + var width_half = width / 2; + var height_half = height / 2; - this.aspect = fullWidth / fullHeight; + var gridX = Math.floor( widthSegments ) || 1; + var gridY = Math.floor( heightSegments ) || 1; - this.view = { - fullWidth: fullWidth, - fullHeight: fullHeight, - offsetX: x, - offsetY: y, - width: width, - height: height - }; + var gridX1 = gridX + 1; + var gridY1 = gridY + 1; - this.updateProjectionMatrix(); + var segment_width = width / gridX; + var segment_height = height / gridY; - }, + var vertices = new Float32Array( gridX1 * gridY1 * 3 ); + var normals = new Float32Array( gridX1 * gridY1 * 3 ); + var uvs = new Float32Array( gridX1 * gridY1 * 2 ); - clearViewOffset: function() { + var offset = 0; + var offset2 = 0; - this.view = null; - this.updateProjectionMatrix(); + for ( var iy = 0; iy < gridY1; iy ++ ) { - }, + var y = iy * segment_height - height_half; - updateProjectionMatrix: function () { + for ( var ix = 0; ix < gridX1; ix ++ ) { - 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 x = ix * segment_width - width_half; - if ( view !== null ) { + vertices[ offset ] = x; + vertices[ offset + 1 ] = - y; - var fullWidth = view.fullWidth, - fullHeight = view.fullHeight; + normals[ offset + 2 ] = 1; - left += view.offsetX * width / fullWidth; - top -= view.offsetY * height / fullHeight; - width *= view.width / fullWidth; - height *= view.height / fullHeight; + uvs[ offset2 ] = ix / gridX; + uvs[ offset2 + 1 ] = 1 - ( iy / gridY ); - } + offset += 3; + offset2 += 2; - var skew = this.filmOffset; - if ( skew !== 0 ) left += near * skew / this.getFilmWidth(); + } - this.projectionMatrix.makeFrustum( - left, left + width, top - height, top, near, this.far ); + } - }, + offset = 0; - toJSON: function ( meta ) { + var indices = new ( ( vertices.length / 3 ) > 65535 ? Uint32Array : Uint16Array )( gridX * gridY * 6 ); - var data = Object3D.prototype.toJSON.call( this, meta ); + for ( var iy = 0; iy < gridY; iy ++ ) { - data.object.fov = this.fov; - data.object.zoom = this.zoom; + for ( var ix = 0; ix < gridX; ix ++ ) { - data.object.near = this.near; - data.object.far = this.far; - data.object.focus = this.focus; + var a = ix + gridX1 * iy; + var b = ix + gridX1 * ( iy + 1 ); + var c = ( ix + 1 ) + gridX1 * ( iy + 1 ); + var d = ( ix + 1 ) + gridX1 * iy; - data.object.aspect = this.aspect; + indices[ offset ] = a; + indices[ offset + 1 ] = b; + indices[ offset + 2 ] = d; - if ( this.view !== null ) data.object.view = Object.assign( {}, this.view ); + indices[ offset + 3 ] = b; + indices[ offset + 4 ] = c; + indices[ offset + 5 ] = d; - data.object.filmGauge = this.filmGauge; - data.object.filmOffset = this.filmOffset; + offset += 6; - return data; + } - } + } - } ); + 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 ) ); - /** - * @author alteredq / http://alteredqualia.com/ - * @author arose / http://github.com/arose - */ + }; - function OrthographicCamera( left, right, top, bottom, near, far ) { + PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry; - Camera.call( this ); + /** + * @author mrdoob / http://mrdoob.com/ + * @author mikael emtinger / http://gomo.se/ + * @author WestLangley / http://github.com/WestLangley + */ - this.type = 'OrthographicCamera'; + function Camera() { - this.zoom = 1; - this.view = null; + Object3D.call( this ); - this.left = left; - this.right = right; - this.top = top; - this.bottom = bottom; + this.type = 'Camera'; - this.near = ( near !== undefined ) ? near : 0.1; - this.far = ( far !== undefined ) ? far : 2000; + this.matrixWorldInverse = new Matrix4(); + this.projectionMatrix = new Matrix4(); - this.updateProjectionMatrix(); + }; - }; + Camera.prototype = Object.create( Object3D.prototype ); + Camera.prototype.constructor = Camera; - OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), { + Camera.prototype.isCamera = true; - constructor: OrthographicCamera, + Camera.prototype.getWorldDirection = function () { - isOrthographicCamera: true, + var quaternion = new Quaternion(); - copy: function ( source ) { + return function getWorldDirection( optionalTarget ) { - Camera.prototype.copy.call( this, source ); + var result = optionalTarget || new Vector3(); - 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.getWorldQuaternion( quaternion ); - this.zoom = source.zoom; - this.view = source.view === null ? null : Object.assign( {}, source.view ); + return result.set( 0, 0, - 1 ).applyQuaternion( quaternion ); - return this; + }; - }, + }(); - setViewOffset: function( fullWidth, fullHeight, x, y, width, height ) { + Camera.prototype.lookAt = function () { - this.view = { - fullWidth: fullWidth, - fullHeight: fullHeight, - offsetX: x, - offsetY: y, - width: width, - height: height - }; + // This routine does not support cameras with rotated and/or translated parent(s) - this.updateProjectionMatrix(); + var m1 = new Matrix4(); - }, + return function lookAt( vector ) { - clearViewOffset: function() { + m1.lookAt( this.position, vector, this.up ); - this.view = null; - this.updateProjectionMatrix(); + this.quaternion.setFromRotationMatrix( m1 ); - }, + }; - 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; + Camera.prototype.clone = function () { - var left = cx - dx; - var right = cx + dx; - var top = cy + dy; - var bottom = cy - dy; + return new this.constructor().copy( this ); - if ( this.view !== null ) { + }; - 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; + Camera.prototype.copy = function ( source ) { - 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 ); + Object3D.prototype.copy.call( this, source ); - } + this.matrixWorldInverse.copy( source.matrixWorldInverse ); + this.projectionMatrix.copy( source.projectionMatrix ); - this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far ); + return this; - }, + }; - toJSON: function ( meta ) { + /** + * @author mrdoob / http://mrdoob.com/ + * @author greggman / http://games.greggman.com/ + * @author zz85 / http://www.lab4games.net/zz85/blog + * @author tschw + */ - var data = Object3D.prototype.toJSON.call( this, meta ); + function PerspectiveCamera( fov, aspect, near, far ) { - 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; + Camera.call( this ); - if ( this.view !== null ) data.object.view = Object.assign( {}, this.view ); + this.type = 'PerspectiveCamera'; - return data; + this.fov = fov !== undefined ? fov : 50; + this.zoom = 1; - } + this.near = near !== undefined ? near : 0.1; + this.far = far !== undefined ? far : 2000; + this.focus = 10; - } ); + this.aspect = aspect !== undefined ? aspect : 1; + this.view = null; - /** - * @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 - */ + this.filmGauge = 35; // width of the film (default in millimeters) + this.filmOffset = 0; // horizontal film offset (same unit as gauge) - function WebGLRenderer( parameters ) { + this.updateProjectionMatrix(); - console.log( 'THREE.WebGLRenderer', "80dev" ); + }; - parameters = parameters || {}; + PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), { - var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ), - _context = parameters.context !== undefined ? parameters.context : null, + constructor: PerspectiveCamera, - _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; + isPerspectiveCamera: true, - var lights = []; + copy: function ( source ) { - var opaqueObjects = []; - var opaqueObjectsLastIndex = - 1; - var transparentObjects = []; - var transparentObjectsLastIndex = - 1; + Camera.prototype.copy.call( this, source ); - var morphInfluences = new Float32Array( 8 ); + this.fov = source.fov; + this.zoom = source.zoom; - var sprites = []; - var lensFlares = []; + this.near = source.near; + this.far = source.far; + this.focus = source.focus; - // public properties + this.aspect = source.aspect; + this.view = source.view === null ? null : Object.assign( {}, source.view ); - this.domElement = _canvas; - this.context = null; + this.filmGauge = source.filmGauge; + this.filmOffset = source.filmOffset; - // clearing + return this; - this.autoClear = true; - this.autoClearColor = true; - this.autoClearDepth = true; - this.autoClearStencil = true; + }, - // scene graph + /** + * 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 ) { - this.sortObjects = true; + // see http://www.bobatkins.com/photography/technical/field_of_view.html + var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength; - // user-defined clipping + this.fov = exports.Math.RAD2DEG * 2 * Math.atan( vExtentSlope ); + this.updateProjectionMatrix(); - this.clippingPlanes = []; - this.localClippingEnabled = false; + }, - // physically based shading + /** + * Calculates the focal length from the current .fov and .filmGauge. + */ + getFocalLength: function () { - this.gammaFactor = 2.0; // for backwards compatibility - this.gammaInput = false; - this.gammaOutput = false; + var vExtentSlope = Math.tan( exports.Math.DEG2RAD * 0.5 * this.fov ); - // physical lights + return 0.5 * this.getFilmHeight() / vExtentSlope; - this.physicallyCorrectLights = false; + }, - // tone mapping + getEffectiveFOV: function () { - this.toneMapping = LinearToneMapping; - this.toneMappingExposure = 1.0; - this.toneMappingWhitePoint = 1.0; + return exports.Math.RAD2DEG * 2 * Math.atan( + Math.tan( exports.Math.DEG2RAD * 0.5 * this.fov ) / this.zoom ); - // morphs + }, - this.maxMorphTargets = 8; - this.maxMorphNormals = 4; + getFilmWidth: function () { - // internal properties + // film not completely covered in portrait format (aspect < 1) + return this.filmGauge * Math.min( this.aspect, 1 ); - var _this = this, + }, - // internal state cache + getFilmHeight: function () { - _currentProgram = null, - _currentRenderTarget = null, - _currentFramebuffer = null, - _currentMaterialId = - 1, - _currentGeometryProgram = '', - _currentCamera = null, + // film not completely covered in landscape format (aspect > 1) + return this.filmGauge / Math.max( this.aspect, 1 ); - _currentScissor = new Vector4(), - _currentScissorTest = null, + }, - _currentViewport = new Vector4(), + /** + * 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(); - // + }, - _usedTextureUnits = 0, + clearViewOffset: function() { - // + this.view = null; + this.updateProjectionMatrix(); - _clearColor = new Color( 0x000000 ), - _clearAlpha = 0, + }, - _width = _canvas.width, - _height = _canvas.height, + updateProjectionMatrix: function () { - _pixelRatio = 1, + 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; - _scissor = new Vector4( 0, 0, _width, _height ), - _scissorTest = false, + if ( view !== null ) { - _viewport = new Vector4( 0, 0, _width, _height ), + var fullWidth = view.fullWidth, + fullHeight = view.fullHeight; - // frustum + left += view.offsetX * width / fullWidth; + top -= view.offsetY * height / fullHeight; + width *= view.width / fullWidth; + height *= view.height / fullHeight; - _frustum = new Frustum(), + } - // clipping + var skew = this.filmOffset; + if ( skew !== 0 ) left += near * skew / this.getFilmWidth(); - _clipping = new WebGLClipping(), - _clippingEnabled = false, - _localClippingEnabled = false, + this.projectionMatrix.makeFrustum( + left, left + width, top - height, top, near, this.far ); - _sphere = new Sphere(), + }, - // camera matrices cache + toJSON: function ( meta ) { - _projScreenMatrix = new Matrix4(), + var data = Object3D.prototype.toJSON.call( this, meta ); - _vector3 = new Vector3(), + data.object.fov = this.fov; + data.object.zoom = this.zoom; - // light arrays cache + data.object.near = this.near; + data.object.far = this.far; + data.object.focus = this.focus; - _lights = { + data.object.aspect = this.aspect; - hash: '', + if ( this.view !== null ) data.object.view = Object.assign( {}, this.view ); - ambient: [ 0, 0, 0 ], - directional: [], - directionalShadowMap: [], - directionalShadowMatrix: [], - spot: [], - spotShadowMap: [], - spotShadowMatrix: [], - point: [], - pointShadowMap: [], - pointShadowMatrix: [], - hemi: [], + data.object.filmGauge = this.filmGauge; + data.object.filmOffset = this.filmOffset; - shadows: [] + return data; - }, + } - // info + } ); - _infoRender = { + /** + * @author alteredq / http://alteredqualia.com/ + * @author arose / http://github.com/arose + */ - calls: 0, - vertices: 0, - faces: 0, - points: 0 + function OrthographicCamera( left, right, top, bottom, near, far ) { - }; + Camera.call( this ); - this.info = { + this.type = 'OrthographicCamera'; - render: _infoRender, - memory: { + this.zoom = 1; + this.view = null; - geometries: 0, - textures: 0 + this.left = left; + this.right = right; + this.top = top; + this.bottom = bottom; - }, - programs: null + this.near = ( near !== undefined ) ? near : 0.1; + this.far = ( far !== undefined ) ? far : 2000; - }; + this.updateProjectionMatrix(); + }; - // initialize + OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), { - var _gl; + constructor: OrthographicCamera, - try { + isOrthographicCamera: true, - var attributes = { - alpha: _alpha, - depth: _depth, - stencil: _stencil, - antialias: _antialias, - premultipliedAlpha: _premultipliedAlpha, - preserveDrawingBuffer: _preserveDrawingBuffer - }; + copy: function ( source ) { - _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes ); + Camera.prototype.copy.call( this, source ); - if ( _gl === null ) { + this.left = source.left; + this.right = source.right; + this.top = source.top; + this.bottom = source.bottom; + this.near = source.near; + this.far = source.far; - if ( _canvas.getContext( 'webgl' ) !== null ) { + this.zoom = source.zoom; + this.view = source.view === null ? null : Object.assign( {}, source.view ); - throw 'Error creating WebGL context with your selected attributes.'; + return this; - } else { + }, - throw 'Error creating WebGL context.'; + setViewOffset: function( fullWidth, fullHeight, x, y, width, height ) { - } + this.view = { + fullWidth: fullWidth, + fullHeight: fullHeight, + offsetX: x, + offsetY: y, + width: width, + height: height + }; - } + this.updateProjectionMatrix(); - // Some experimental-webgl implementations do not have getShaderPrecisionFormat + }, - if ( _gl.getShaderPrecisionFormat === undefined ) { + clearViewOffset: function() { - _gl.getShaderPrecisionFormat = function () { + this.view = null; + this.updateProjectionMatrix(); - return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 }; + }, - }; + 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; - _canvas.addEventListener( 'webglcontextlost', onContextLost, false ); + var left = cx - dx; + var right = cx + dx; + var top = cy + dy; + var bottom = cy - dy; - } catch ( error ) { + if ( this.view !== null ) { - console.error( 'THREE.WebGLRenderer: ' + error ); + 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 ); - var extensions = new WebGLExtensions( _gl ); + } - 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' ); + this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far ); - if ( extensions.get( 'OES_element_index_uint' ) ) { + }, - BufferGeometry.MaxIndex = 4294967296; + toJSON: function ( meta ) { - } + var data = Object3D.prototype.toJSON.call( this, meta ); - var capabilities = new WebGLCapabilities( _gl, extensions, parameters ); + 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; - 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(); + if ( this.view !== null ) data.object.view = Object.assign( {}, this.view ); - this.info.programs = programCache.programs; + return data; - var bufferRenderer = new WebGLBufferRenderer( _gl, extensions, _infoRender ); - var indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, _infoRender ); + } - // + } ); - 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 - } ) - ); + /** + * @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 + */ - // + function WebGLRenderer( parameters ) { - function getTargetPixelRatio() { + console.log( 'THREE.WebGLRenderer', "80dev" ); - return _currentRenderTarget === null ? _pixelRatio : 1; + 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, - function glClearColor( r, g, b, a ) { + _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; - if ( _premultipliedAlpha === true ) { + var lights = []; - r *= a; g *= a; b *= a; + var opaqueObjects = []; + var opaqueObjectsLastIndex = - 1; + var transparentObjects = []; + var transparentObjectsLastIndex = - 1; - } + var morphInfluences = new Float32Array( 8 ); - state.clearColor( r, g, b, a ); + var sprites = []; + var lensFlares = []; - } + // public properties - function setDefaultGLState() { + this.domElement = _canvas; + this.context = null; - state.init(); + // clearing - state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) ); - state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) ); + this.autoClear = true; + this.autoClearColor = true; + this.autoClearDepth = true; + this.autoClearStencil = true; - glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); + // scene graph - } + this.sortObjects = true; - function resetGLState() { + // user-defined clipping - _currentProgram = null; - _currentCamera = null; + this.clippingPlanes = []; + this.localClippingEnabled = false; - _currentGeometryProgram = ''; - _currentMaterialId = - 1; + // physically based shading - state.reset(); + this.gammaFactor = 2.0; // for backwards compatibility + this.gammaInput = false; + this.gammaOutput = false; - } + // physical lights - setDefaultGLState(); + this.physicallyCorrectLights = false; - this.context = _gl; - this.capabilities = capabilities; - this.extensions = extensions; - this.properties = properties; - this.state = state; + // tone mapping - // shadow map + this.toneMapping = LinearToneMapping; + this.toneMappingExposure = 1.0; + this.toneMappingWhitePoint = 1.0; - var shadowMap = new WebGLShadowMap( this, _lights, objects, capabilities ); + // morphs - this.shadowMap = shadowMap; + this.maxMorphTargets = 8; + this.maxMorphNormals = 4; + // internal properties - // Plugins + var _this = this, - var spritePlugin = new SpritePlugin( this, sprites ); - var lensFlarePlugin = new LensFlarePlugin( this, lensFlares ); + // internal state cache - // API + _currentProgram = null, + _currentRenderTarget = null, + _currentFramebuffer = null, + _currentMaterialId = - 1, + _currentGeometryProgram = '', + _currentCamera = null, - this.getContext = function () { + _currentScissor = new Vector4(), + _currentScissorTest = null, - return _gl; + _currentViewport = new Vector4(), - }; + // - this.getContextAttributes = function () { + _usedTextureUnits = 0, - return _gl.getContextAttributes(); + // - }; + _clearColor = new Color( 0x000000 ), + _clearAlpha = 0, - this.forceContextLoss = function () { + _width = _canvas.width, + _height = _canvas.height, - extensions.get( 'WEBGL_lose_context' ).loseContext(); + _pixelRatio = 1, - }; + _scissor = new Vector4( 0, 0, _width, _height ), + _scissorTest = false, - this.getMaxAnisotropy = function () { + _viewport = new Vector4( 0, 0, _width, _height ), - return capabilities.getMaxAnisotropy(); + // frustum - }; + _frustum = new Frustum(), - this.getPrecision = function () { + // clipping - return capabilities.precision; + _clipping = new WebGLClipping(), + _clippingEnabled = false, + _localClippingEnabled = false, - }; + _sphere = new Sphere(), - this.getPixelRatio = function () { + // camera matrices cache - return _pixelRatio; + _projScreenMatrix = new Matrix4(), - }; + _vector3 = new Vector3(), - this.setPixelRatio = function ( value ) { + // light arrays cache - if ( value === undefined ) return; + _lights = { - _pixelRatio = value; + hash: '', - this.setSize( _viewport.z, _viewport.w, false ); + ambient: [ 0, 0, 0 ], + directional: [], + directionalShadowMap: [], + directionalShadowMatrix: [], + spot: [], + spotShadowMap: [], + spotShadowMatrix: [], + point: [], + pointShadowMap: [], + pointShadowMatrix: [], + hemi: [], - }; + shadows: [] - this.getSize = function () { + }, - return { - width: _width, - height: _height - }; + // info - }; + _infoRender = { - this.setSize = function ( width, height, updateStyle ) { + calls: 0, + vertices: 0, + faces: 0, + points: 0 - _width = width; - _height = height; + }; - _canvas.width = width * _pixelRatio; - _canvas.height = height * _pixelRatio; + this.info = { - if ( updateStyle !== false ) { + render: _infoRender, + memory: { - _canvas.style.width = width + 'px'; - _canvas.style.height = height + 'px'; + geometries: 0, + textures: 0 - } + }, + programs: null - this.setViewport( 0, 0, width, height ); + }; - }; - this.setViewport = function ( x, y, width, height ) { + // initialize - state.viewport( _viewport.set( x, y, width, height ) ); + var _gl; - }; + try { - this.setScissor = function ( x, y, width, height ) { + var attributes = { + alpha: _alpha, + depth: _depth, + stencil: _stencil, + antialias: _antialias, + premultipliedAlpha: _premultipliedAlpha, + preserveDrawingBuffer: _preserveDrawingBuffer + }; - state.scissor( _scissor.set( x, y, width, height ) ); + _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes ); - }; + if ( _gl === null ) { - this.setScissorTest = function ( boolean ) { + if ( _canvas.getContext( 'webgl' ) !== null ) { - state.setScissorTest( _scissorTest = boolean ); + throw 'Error creating WebGL context with your selected attributes.'; - }; + } else { - // Clearing + throw 'Error creating WebGL context.'; - this.getClearColor = function () { + } - return _clearColor; + } - }; + // Some experimental-webgl implementations do not have getShaderPrecisionFormat - this.setClearColor = function ( color, alpha ) { + if ( _gl.getShaderPrecisionFormat === undefined ) { - _clearColor.set( color ); + _gl.getShaderPrecisionFormat = function () { - _clearAlpha = alpha !== undefined ? alpha : 1; + return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 }; - glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); + }; - }; + } - this.getClearAlpha = function () { + _canvas.addEventListener( 'webglcontextlost', onContextLost, false ); - return _clearAlpha; + } catch ( error ) { - }; + console.error( 'THREE.WebGLRenderer: ' + error ); - this.setClearAlpha = function ( alpha ) { + } - _clearAlpha = alpha; + var extensions = new WebGLExtensions( _gl ); - glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); + 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 ( extensions.get( 'OES_element_index_uint' ) ) { - this.clear = function ( color, depth, stencil ) { + BufferGeometry.MaxIndex = 4294967296; - var bits = 0; + } - 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 capabilities = new WebGLCapabilities( _gl, extensions, parameters ); - _gl.clear( bits ); + 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.info.programs = programCache.programs; - this.clearColor = function () { + var bufferRenderer = new WebGLBufferRenderer( _gl, extensions, _infoRender ); + var indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, _infoRender ); - this.clear( true, false, false ); + // - }; + 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 + } ) + ); - this.clearDepth = function () { + // - this.clear( false, true, false ); + function getTargetPixelRatio() { - }; + return _currentRenderTarget === null ? _pixelRatio : 1; - this.clearStencil = function () { + } - this.clear( false, false, true ); + function glClearColor( r, g, b, a ) { - }; + if ( _premultipliedAlpha === true ) { - this.clearTarget = function ( renderTarget, color, depth, stencil ) { + r *= a; g *= a; b *= a; - this.setRenderTarget( renderTarget ); - this.clear( color, depth, stencil ); + } - }; + state.clearColor( r, g, b, a ); - // Reset + } - this.resetGLState = resetGLState; + function setDefaultGLState() { - this.dispose = function() { + state.init(); - transparentObjects = []; - transparentObjectsLastIndex = -1; - opaqueObjects = []; - opaqueObjectsLastIndex = -1; + state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) ); + state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) ); - _canvas.removeEventListener( 'webglcontextlost', onContextLost, false ); + glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); - }; + } - // Events + function resetGLState() { - function onContextLost( event ) { + _currentProgram = null; + _currentCamera = null; - event.preventDefault(); + _currentGeometryProgram = ''; + _currentMaterialId = - 1; - resetGLState(); - setDefaultGLState(); + state.reset(); - properties.clear(); + } - } + setDefaultGLState(); - function onMaterialDispose( event ) { + this.context = _gl; + this.capabilities = capabilities; + this.extensions = extensions; + this.properties = properties; + this.state = state; - var material = event.target; + // shadow map - material.removeEventListener( 'dispose', onMaterialDispose ); + var shadowMap = new WebGLShadowMap( this, _lights, objects, capabilities ); - deallocateMaterial( material ); + this.shadowMap = shadowMap; - } - // Buffer deallocation + // Plugins - function deallocateMaterial( material ) { + var spritePlugin = new SpritePlugin( this, sprites ); + var lensFlarePlugin = new LensFlarePlugin( this, lensFlares ); - releaseMaterialProgramReference( material ); + // API - properties.delete( material ); + this.getContext = function () { - } + return _gl; + }; - function releaseMaterialProgramReference( material ) { + this.getContextAttributes = function () { - var programInfo = properties.get( material ).program; + return _gl.getContextAttributes(); - material.program = undefined; + }; - if ( programInfo !== undefined ) { + this.forceContextLoss = function () { - programCache.releaseProgram( programInfo ); + extensions.get( 'WEBGL_lose_context' ).loseContext(); - } + }; - } + this.getMaxAnisotropy = function () { - // Buffer rendering + return capabilities.getMaxAnisotropy(); - this.renderBufferImmediate = function ( object, program, material ) { + }; - state.initAttributes(); + this.getPrecision = function () { - var buffers = properties.get( object ); + return capabilities.precision; - 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(); + }; - var attributes = program.getAttributes(); + this.getPixelRatio = function () { - if ( object.hasPositions ) { + return _pixelRatio; - _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.setPixelRatio = function ( value ) { - } + if ( value === undefined ) return; - if ( object.hasNormals ) { + _pixelRatio = value; - _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal ); + this.setSize( _viewport.z, _viewport.w, false ); - 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.getSize = function () { - var array = object.normalArray; + return { + width: _width, + height: _height + }; - 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.setSize = function ( width, height, updateStyle ) { - array[ i + 3 ] = nx; - array[ i + 4 ] = ny; - array[ i + 5 ] = nz; + _width = width; + _height = height; - array[ i + 6 ] = nx; - array[ i + 7 ] = ny; - array[ i + 8 ] = nz; + _canvas.width = width * _pixelRatio; + _canvas.height = height * _pixelRatio; - } + if ( updateStyle !== false ) { - } + _canvas.style.width = width + 'px'; + _canvas.style.height = height + 'px'; - _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW ); + } - state.enableAttribute( attributes.normal ); + this.setViewport( 0, 0, width, height ); - _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 ); + }; - } + this.setViewport = function ( x, y, width, height ) { - if ( object.hasUvs && material.map ) { + state.viewport( _viewport.set( x, y, width, height ) ); - _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv ); - _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW ); + }; - state.enableAttribute( attributes.uv ); + this.setScissor = function ( x, y, width, height ) { - _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 ); + state.scissor( _scissor.set( x, y, width, height ) ); - } + }; - if ( object.hasColors && material.vertexColors !== NoColors ) { + this.setScissorTest = function ( boolean ) { - _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color ); - _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW ); + state.setScissorTest( _scissorTest = boolean ); - state.enableAttribute( attributes.color ); + }; - _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 ); + // Clearing - } + this.getClearColor = function () { - state.disableUnusedAttributes(); + return _clearColor; - _gl.drawArrays( _gl.TRIANGLES, 0, object.count ); + }; - object.count = 0; + this.setClearColor = function ( color, alpha ) { - }; + _clearColor.set( color ); - this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) { + _clearAlpha = alpha !== undefined ? alpha : 1; - setMaterial( material ); + glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); - var program = setProgram( camera, fog, material, object ); + }; - var updateBuffers = false; - var geometryProgram = geometry.id + '_' + program.id + '_' + material.wireframe; + this.getClearAlpha = function () { - if ( geometryProgram !== _currentGeometryProgram ) { + return _clearAlpha; - _currentGeometryProgram = geometryProgram; - updateBuffers = true; + }; - } + this.setClearAlpha = function ( alpha ) { - // morph targets + _clearAlpha = alpha; - var morphTargetInfluences = object.morphTargetInfluences; + glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); - if ( morphTargetInfluences !== undefined ) { + }; - var activeInfluences = []; + this.clear = function ( color, depth, stencil ) { - for ( var i = 0, l = morphTargetInfluences.length; i < l; i ++ ) { + var bits = 0; - var influence = morphTargetInfluences[ i ]; - activeInfluences.push( [ influence, i ] ); + 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.clear( bits ); - activeInfluences.sort( absNumericalSort ); + }; - if ( activeInfluences.length > 8 ) { + this.clearColor = function () { - activeInfluences.length = 8; + this.clear( true, false, false ); - } + }; - var morphAttributes = geometry.morphAttributes; + this.clearDepth = function () { - for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) { + this.clear( false, true, false ); - var influence = activeInfluences[ i ]; - morphInfluences[ i ] = influence[ 0 ]; + }; - if ( influence[ 0 ] !== 0 ) { + this.clearStencil = function () { - var index = influence[ 1 ]; + this.clear( false, false, true ); - 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 ] ); + }; - } else { + this.clearTarget = function ( renderTarget, color, depth, stencil ) { - if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i ); - if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i ); + this.setRenderTarget( renderTarget ); + this.clear( color, depth, stencil ); - } + }; - } + // Reset - program.getUniforms().setValue( - _gl, 'morphTargetInfluences', morphInfluences ); + this.resetGLState = resetGLState; - updateBuffers = true; + this.dispose = function() { - } + transparentObjects = []; + transparentObjectsLastIndex = -1; + opaqueObjects = []; + opaqueObjectsLastIndex = -1; - // + _canvas.removeEventListener( 'webglcontextlost', onContextLost, false ); - var index = geometry.index; - var position = geometry.attributes.position; + }; - if ( material.wireframe === true ) { + // Events - index = objects.getWireframeAttribute( geometry ); + function onContextLost( event ) { - } + event.preventDefault(); - var renderer; + resetGLState(); + setDefaultGLState(); - if ( index !== null ) { + properties.clear(); - renderer = indexedBufferRenderer; - renderer.setIndex( index ); + } - } else { + function onMaterialDispose( event ) { - renderer = bufferRenderer; + var material = event.target; - } + material.removeEventListener( 'dispose', onMaterialDispose ); - if ( updateBuffers ) { + deallocateMaterial( material ); - setupVertexAttributes( material, program, geometry ); + } - if ( index !== null ) { + // Buffer deallocation - _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, objects.getAttributeBuffer( index ) ); + function deallocateMaterial( material ) { - } + releaseMaterialProgramReference( material ); - } + properties.delete( material ); - // + } - var dataStart = 0; - var dataCount = Infinity; - if ( index !== null ) { + function releaseMaterialProgramReference( material ) { - dataCount = index.count; + var programInfo = properties.get( material ).program; - } else if ( position !== undefined ) { + material.program = undefined; - dataCount = position.count; + if ( programInfo !== undefined ) { - } + programCache.releaseProgram( programInfo ); - var rangeStart = geometry.drawRange.start; - var rangeCount = geometry.drawRange.count; + } - var groupStart = group !== null ? group.start : 0; - var groupCount = group !== null ? group.count : Infinity; + } - var drawStart = Math.max( dataStart, rangeStart, groupStart ); - var drawEnd = Math.min( dataStart + dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1; + // Buffer rendering - var drawCount = Math.max( 0, drawEnd - drawStart + 1 ); + this.renderBufferImmediate = function ( object, program, material ) { - // + state.initAttributes(); - if ( object && object.isMesh ) { + var buffers = properties.get( object ); - if ( material.wireframe === true ) { + 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(); - state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() ); - renderer.setMode( _gl.LINES ); + var attributes = program.getAttributes(); - } else { + if ( object.hasPositions ) { - switch ( object.drawMode ) { + _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position ); + _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW ); - case TrianglesDrawMode: - renderer.setMode( _gl.TRIANGLES ); - break; + state.enableAttribute( attributes.position ); + _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 ); - case TriangleStripDrawMode: - renderer.setMode( _gl.TRIANGLE_STRIP ); - break; + } - case TriangleFanDrawMode: - renderer.setMode( _gl.TRIANGLE_FAN ); - break; + if ( object.hasNormals ) { - } + _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal ); - } + 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 ) { - } else if ( object && object.isLine ) { + var array = object.normalArray; - var lineWidth = material.linewidth; + 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 ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material + array[ i + 0 ] = nx; + array[ i + 1 ] = ny; + array[ i + 2 ] = nz; - state.setLineWidth( lineWidth * getTargetPixelRatio() ); + array[ i + 3 ] = nx; + array[ i + 4 ] = ny; + array[ i + 5 ] = nz; - if ( object && object.isLineSegments ) { + array[ i + 6 ] = nx; + array[ i + 7 ] = ny; + array[ i + 8 ] = nz; - renderer.setMode( _gl.LINES ); + } - } else { + } - renderer.setMode( _gl.LINE_STRIP ); + _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW ); - } + state.enableAttribute( attributes.normal ); - } else if ( object && object.isPoints ) { + _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 ); - renderer.setMode( _gl.POINTS ); + } - } + if ( object.hasUvs && material.map ) { - if ( geometry && geometry.isInstancedBufferGeometry ) { + _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv ); + _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW ); - if ( geometry.maxInstancedCount > 0 ) { + state.enableAttribute( attributes.uv ); - renderer.renderInstances( geometry, drawStart, drawCount ); + _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 ); - } + } - } else { + if ( object.hasColors && material.vertexColors !== NoColors ) { - renderer.render( drawStart, drawCount ); + _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color ); + _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW ); - } + state.enableAttribute( attributes.color ); - }; + _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 ); - function setupVertexAttributes( material, program, geometry, startIndex ) { + } - var extension; + state.disableUnusedAttributes(); - if ( geometry && geometry.isInstancedBufferGeometry ) { + _gl.drawArrays( _gl.TRIANGLES, 0, object.count ); - extension = extensions.get( 'ANGLE_instanced_arrays' ); + object.count = 0; - if ( extension === null ) { + }; - console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); - return; + this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) { - } + setMaterial( material ); - } + var program = setProgram( camera, fog, material, object ); - if ( startIndex === undefined ) startIndex = 0; + var updateBuffers = false; + var geometryProgram = geometry.id + '_' + program.id + '_' + material.wireframe; - state.initAttributes(); + if ( geometryProgram !== _currentGeometryProgram ) { - var geometryAttributes = geometry.attributes; + _currentGeometryProgram = geometryProgram; + updateBuffers = true; - var programAttributes = program.getAttributes(); + } - var materialDefaultAttributeValues = material.defaultAttributeValues; + // morph targets - for ( var name in programAttributes ) { + var morphTargetInfluences = object.morphTargetInfluences; - var programAttribute = programAttributes[ name ]; + if ( morphTargetInfluences !== undefined ) { - if ( programAttribute >= 0 ) { + var activeInfluences = []; - var geometryAttribute = geometryAttributes[ name ]; + for ( var i = 0, l = morphTargetInfluences.length; i < l; i ++ ) { - if ( geometryAttribute !== undefined ) { + var influence = morphTargetInfluences[ i ]; + activeInfluences.push( [ influence, i ] ); - var type = _gl.FLOAT; - var array = geometryAttribute.array; - var normalized = geometryAttribute.normalized; + } - if ( array instanceof Float32Array ) { + activeInfluences.sort( absNumericalSort ); - type = _gl.FLOAT; + if ( activeInfluences.length > 8 ) { - } else if ( array instanceof Float64Array ) { + activeInfluences.length = 8; - console.warn( "Unsupported data buffer format: Float64Array" ); + } - } else if ( array instanceof Uint16Array ) { + var morphAttributes = geometry.morphAttributes; - type = _gl.UNSIGNED_SHORT; + for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) { - } else if ( array instanceof Int16Array ) { + var influence = activeInfluences[ i ]; + morphInfluences[ i ] = influence[ 0 ]; - type = _gl.SHORT; + if ( influence[ 0 ] !== 0 ) { - } else if ( array instanceof Uint32Array ) { + var index = influence[ 1 ]; - type = _gl.UNSIGNED_INT; + 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 ] ); - } else if ( array instanceof Int32Array ) { + } else { - type = _gl.INT; + if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i ); + if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i ); - } else if ( array instanceof Int8Array ) { + } - type = _gl.BYTE; + } - } else if ( array instanceof Uint8Array ) { + program.getUniforms().setValue( + _gl, 'morphTargetInfluences', morphInfluences ); - type = _gl.UNSIGNED_BYTE; + updateBuffers = true; - } + } - var size = geometryAttribute.itemSize; - var buffer = objects.getAttributeBuffer( geometryAttribute ); + // - if ( geometryAttribute && geometryAttribute.isInterleavedBufferAttribute ) { + var index = geometry.index; + var position = geometry.attributes.position; - var data = geometryAttribute.data; - var stride = data.stride; - var offset = geometryAttribute.offset; + if ( material.wireframe === true ) { - if ( data && data.isInstancedInterleavedBuffer ) { + index = objects.getWireframeAttribute( geometry ); - state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute, extension ); + } - if ( geometry.maxInstancedCount === undefined ) { + var renderer; - geometry.maxInstancedCount = data.meshPerAttribute * data.count; + if ( index !== null ) { - } + renderer = indexedBufferRenderer; + renderer.setIndex( index ); - } else { + } else { - state.enableAttribute( programAttribute ); + renderer = bufferRenderer; - } + } - _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 ); + if ( updateBuffers ) { - } else { + setupVertexAttributes( material, program, geometry ); - if ( geometryAttribute && geometryAttribute.isInstancedBufferAttribute ) { + if ( index !== null ) { - state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute, extension ); + _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, objects.getAttributeBuffer( index ) ); - if ( geometry.maxInstancedCount === undefined ) { + } - geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count; + } - } + // - } else { + var dataStart = 0; + var dataCount = Infinity; - state.enableAttribute( programAttribute ); + if ( index !== null ) { - } + dataCount = index.count; - _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer ); - _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, startIndex * size * geometryAttribute.array.BYTES_PER_ELEMENT ); + } else if ( position !== undefined ) { - } + dataCount = position.count; - } else if ( materialDefaultAttributeValues !== undefined ) { + } - var value = materialDefaultAttributeValues[ name ]; + var rangeStart = geometry.drawRange.start; + var rangeCount = geometry.drawRange.count; - if ( value !== undefined ) { + var groupStart = group !== null ? group.start : 0; + var groupCount = group !== null ? group.count : Infinity; - switch ( value.length ) { + var drawStart = Math.max( dataStart, rangeStart, groupStart ); + var drawEnd = Math.min( dataStart + dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1; - case 2: - _gl.vertexAttrib2fv( programAttribute, value ); - break; + var drawCount = Math.max( 0, drawEnd - drawStart + 1 ); - case 3: - _gl.vertexAttrib3fv( programAttribute, value ); - break; + // - case 4: - _gl.vertexAttrib4fv( programAttribute, value ); - break; + if ( object && object.isMesh ) { - default: - _gl.vertexAttrib1fv( programAttribute, value ); + if ( material.wireframe === true ) { - } + state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() ); + renderer.setMode( _gl.LINES ); - } + } else { - } + switch ( object.drawMode ) { - } + case TrianglesDrawMode: + renderer.setMode( _gl.TRIANGLES ); + break; - } + case TriangleStripDrawMode: + renderer.setMode( _gl.TRIANGLE_STRIP ); + break; - state.disableUnusedAttributes(); + case TriangleFanDrawMode: + renderer.setMode( _gl.TRIANGLE_FAN ); + break; - } + } - // Sorting + } - function absNumericalSort( a, b ) { - return Math.abs( b[ 0 ] ) - Math.abs( a[ 0 ] ); + } else if ( object && object.isLine ) { - } + var lineWidth = material.linewidth; - function painterSortStable( a, b ) { + if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material - if ( a.object.renderOrder !== b.object.renderOrder ) { + state.setLineWidth( lineWidth * getTargetPixelRatio() ); - return a.object.renderOrder - b.object.renderOrder; + if ( object && object.isLineSegments ) { - } else if ( a.material.program && b.material.program && a.material.program !== b.material.program ) { + renderer.setMode( _gl.LINES ); - return a.material.program.id - b.material.program.id; + } else { - } else if ( a.material.id !== b.material.id ) { + renderer.setMode( _gl.LINE_STRIP ); - return a.material.id - b.material.id; + } - } else if ( a.z !== b.z ) { + } else if ( object && object.isPoints ) { - return a.z - b.z; + renderer.setMode( _gl.POINTS ); - } else { + } - return a.id - b.id; + if ( geometry && geometry.isInstancedBufferGeometry ) { - } + if ( geometry.maxInstancedCount > 0 ) { - } + renderer.renderInstances( geometry, drawStart, drawCount ); - function reversePainterSortStable( a, b ) { + } - if ( a.object.renderOrder !== b.object.renderOrder ) { + } else { - return a.object.renderOrder - b.object.renderOrder; + renderer.render( drawStart, drawCount ); - } if ( a.z !== b.z ) { + } - return b.z - a.z; + }; - } else { + function setupVertexAttributes( material, program, geometry, startIndex ) { - return a.id - b.id; + var extension; - } + if ( geometry && geometry.isInstancedBufferGeometry ) { - } + extension = extensions.get( 'ANGLE_instanced_arrays' ); - // Rendering + if ( extension === null ) { - this.render = function ( scene, camera, renderTarget, forceClear ) { + console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); + return; - if ( ( camera && camera.isCamera ) === false ) { + } - console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' ); - return; + } - } + if ( startIndex === undefined ) startIndex = 0; - var fog = scene.fog; + state.initAttributes(); - // reset caching for this frame + var geometryAttributes = geometry.attributes; - _currentGeometryProgram = ''; - _currentMaterialId = - 1; - _currentCamera = null; + var programAttributes = program.getAttributes(); - // update scene graph + var materialDefaultAttributeValues = material.defaultAttributeValues; - if ( scene.autoUpdate === true ) scene.updateMatrixWorld(); + for ( var name in programAttributes ) { - // update camera matrices and frustum + var programAttribute = programAttributes[ name ]; - if ( camera.parent === null ) camera.updateMatrixWorld(); + if ( programAttribute >= 0 ) { - camera.matrixWorldInverse.getInverse( camera.matrixWorld ); + var geometryAttribute = geometryAttributes[ name ]; - _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); - _frustum.setFromMatrix( _projScreenMatrix ); + if ( geometryAttribute !== undefined ) { - lights.length = 0; + var type = _gl.FLOAT; + var array = geometryAttribute.array; + var normalized = geometryAttribute.normalized; - opaqueObjectsLastIndex = - 1; - transparentObjectsLastIndex = - 1; + if ( array instanceof Float32Array ) { - sprites.length = 0; - lensFlares.length = 0; + type = _gl.FLOAT; - _localClippingEnabled = this.localClippingEnabled; - _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera ); + } else if ( array instanceof Float64Array ) { - projectObject( scene, camera ); + console.warn( "Unsupported data buffer format: Float64Array" ); - opaqueObjects.length = opaqueObjectsLastIndex + 1; - transparentObjects.length = transparentObjectsLastIndex + 1; + } else if ( array instanceof Uint16Array ) { - if ( _this.sortObjects === true ) { + type = _gl.UNSIGNED_SHORT; - opaqueObjects.sort( painterSortStable ); - transparentObjects.sort( reversePainterSortStable ); + } else if ( array instanceof Int16Array ) { - } + type = _gl.SHORT; - // + } else if ( array instanceof Uint32Array ) { - if ( _clippingEnabled ) _clipping.beginShadows(); + type = _gl.UNSIGNED_INT; - setupShadows( lights ); + } else if ( array instanceof Int32Array ) { - shadowMap.render( scene, camera ); + type = _gl.INT; - setupLights( lights, camera ); + } else if ( array instanceof Int8Array ) { - if ( _clippingEnabled ) _clipping.endShadows(); + type = _gl.BYTE; - // + } else if ( array instanceof Uint8Array ) { - _infoRender.calls = 0; - _infoRender.vertices = 0; - _infoRender.faces = 0; - _infoRender.points = 0; + type = _gl.UNSIGNED_BYTE; - if ( renderTarget === undefined ) { + } - renderTarget = null; + var size = geometryAttribute.itemSize; + var buffer = objects.getAttributeBuffer( geometryAttribute ); - } + if ( geometryAttribute && geometryAttribute.isInterleavedBufferAttribute ) { - this.setRenderTarget( renderTarget ); + var data = geometryAttribute.data; + var stride = data.stride; + var offset = geometryAttribute.offset; - // + if ( data && data.isInstancedInterleavedBuffer ) { - var background = scene.background; + state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute, extension ); - if ( background === null ) { + if ( geometry.maxInstancedCount === undefined ) { - glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); + geometry.maxInstancedCount = data.meshPerAttribute * data.count; - } else if ( background && background.isColor ) { + } - glClearColor( background.r, background.g, background.b, 1 ); + } else { - } + state.enableAttribute( programAttribute ); - if ( this.autoClear || forceClear ) { + } - this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil ); + _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 ( background && background.isCubeTexture ) { + if ( geometryAttribute && geometryAttribute.isInstancedBufferAttribute ) { - backgroundCamera2.projectionMatrix.copy( camera.projectionMatrix ); + state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute, extension ); - backgroundCamera2.matrixWorld.extractRotation( camera.matrixWorld ); - backgroundCamera2.matrixWorldInverse.getInverse( backgroundCamera2.matrixWorld ); + if ( geometry.maxInstancedCount === undefined ) { - backgroundBoxMesh.material.uniforms[ "tCube" ].value = background; - backgroundBoxMesh.modelViewMatrix.multiplyMatrices( backgroundCamera2.matrixWorldInverse, backgroundBoxMesh.matrixWorld ); + geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count; - objects.update( backgroundBoxMesh ); + } - _this.renderBufferDirect( backgroundCamera2, null, backgroundBoxMesh.geometry, backgroundBoxMesh.material, backgroundBoxMesh, null ); + } else { - } else if ( background && background.isTexture ) { + state.enableAttribute( programAttribute ); - backgroundPlaneMesh.material.map = background; + } - objects.update( backgroundPlaneMesh ); + _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer ); + _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, startIndex * size * geometryAttribute.array.BYTES_PER_ELEMENT ); - _this.renderBufferDirect( backgroundCamera, null, backgroundPlaneMesh.geometry, backgroundPlaneMesh.material, backgroundPlaneMesh, null ); + } - } + } else if ( materialDefaultAttributeValues !== undefined ) { - // + var value = materialDefaultAttributeValues[ name ]; - if ( scene.overrideMaterial ) { + if ( value !== undefined ) { - var overrideMaterial = scene.overrideMaterial; + switch ( value.length ) { - renderObjects( opaqueObjects, camera, fog, overrideMaterial ); - renderObjects( transparentObjects, camera, fog, overrideMaterial ); + case 2: + _gl.vertexAttrib2fv( programAttribute, value ); + break; - } else { + case 3: + _gl.vertexAttrib3fv( programAttribute, value ); + break; - // opaque pass (front-to-back order) + case 4: + _gl.vertexAttrib4fv( programAttribute, value ); + break; - state.setBlending( NoBlending ); - renderObjects( opaqueObjects, camera, fog ); + default: + _gl.vertexAttrib1fv( programAttribute, value ); - // transparent pass (back-to-front order) + } - renderObjects( transparentObjects, camera, fog ); + } - } + } - // custom render plugins (post pass) + } - spritePlugin.render( scene, camera ); - lensFlarePlugin.render( scene, camera, _currentViewport ); + } - // Generate mipmap if we're using any kind of mipmap filtering + state.disableUnusedAttributes(); - if ( renderTarget ) { + } - textures.updateRenderTargetMipmap( renderTarget ); + // Sorting - } + function absNumericalSort( a, b ) { - // Ensure depth buffer writing is enabled so it can be cleared on next render + return Math.abs( b[ 0 ] ) - Math.abs( a[ 0 ] ); - state.setDepthTest( true ); - state.setDepthWrite( true ); - state.setColorWrite( true ); + } - // _gl.finish(); + function painterSortStable( a, b ) { - }; + if ( a.object.renderOrder !== b.object.renderOrder ) { - function pushRenderItem( object, geometry, material, z, group ) { + return a.object.renderOrder - b.object.renderOrder; - var array, index; + } else if ( a.material.program && b.material.program && a.material.program !== b.material.program ) { - // allocate the next position in the appropriate array + return a.material.program.id - b.material.program.id; - if ( material.transparent ) { + } else if ( a.material.id !== b.material.id ) { - array = transparentObjects; - index = ++ transparentObjectsLastIndex; + return a.material.id - b.material.id; - } else { + } else if ( a.z !== b.z ) { - array = opaqueObjects; - index = ++ opaqueObjectsLastIndex; + return a.z - b.z; - } + } else { - // recycle existing render item or grow the array + return a.id - b.id; - 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; + function reversePainterSortStable( a, b ) { - } else { + if ( a.object.renderOrder !== b.object.renderOrder ) { - renderItem = { - id: object.id, - object: object, - geometry: geometry, - material: material, - z: _vector3.z, - group: group - }; + return a.object.renderOrder - b.object.renderOrder; - // assert( index === array.length ); - array.push( renderItem ); + } if ( a.z !== b.z ) { - } + return b.z - a.z; - } + } else { - // TODO Duplicated code (Frustum) + return a.id - b.id; - function isObjectViewable( object ) { + } - var geometry = object.geometry; + } - if ( geometry.boundingSphere === null ) - geometry.computeBoundingSphere(); + // Rendering - _sphere.copy( geometry.boundingSphere ). - applyMatrix4( object.matrixWorld ); + this.render = function ( scene, camera, renderTarget, forceClear ) { - return isSphereViewable( _sphere ); + if ( ( camera && camera.isCamera ) === false ) { - } + console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' ); + return; - function isSpriteViewable( sprite ) { + } - _sphere.center.set( 0, 0, 0 ); - _sphere.radius = 0.7071067811865476; - _sphere.applyMatrix4( sprite.matrixWorld ); + var fog = scene.fog; - return isSphereViewable( _sphere ); + // reset caching for this frame - } + _currentGeometryProgram = ''; + _currentMaterialId = - 1; + _currentCamera = null; - function isSphereViewable( sphere ) { + // update scene graph - if ( ! _frustum.intersectsSphere( sphere ) ) return false; + if ( scene.autoUpdate === true ) scene.updateMatrixWorld(); - var numPlanes = _clipping.numPlanes; + // update camera matrices and frustum - if ( numPlanes === 0 ) return true; + if ( camera.parent === null ) camera.updateMatrixWorld(); - var planes = _this.clippingPlanes, + camera.matrixWorldInverse.getInverse( camera.matrixWorld ); - center = sphere.center, - negRad = - sphere.radius, - i = 0; + _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); + _frustum.setFromMatrix( _projScreenMatrix ); - do { + lights.length = 0; - // out when deeper than radius in the negative halfspace - if ( planes[ i ].distanceToPoint( center ) < negRad ) return false; + opaqueObjectsLastIndex = - 1; + transparentObjectsLastIndex = - 1; - } while ( ++ i !== numPlanes ); + sprites.length = 0; + lensFlares.length = 0; - return true; + _localClippingEnabled = this.localClippingEnabled; + _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera ); - } + projectObject( scene, camera ); - function projectObject( object, camera ) { + opaqueObjects.length = opaqueObjectsLastIndex + 1; + transparentObjects.length = transparentObjectsLastIndex + 1; - if ( object.visible === false ) return; + if ( _this.sortObjects === true ) { - if ( object.layers.test( camera.layers ) ) { + opaqueObjects.sort( painterSortStable ); + transparentObjects.sort( reversePainterSortStable ); - if ( object && object.isLight ) { + } - lights.push( object ); + // - } else if ( object && object.isSprite ) { + if ( _clippingEnabled ) _clipping.beginShadows(); - if ( object.frustumCulled === false || isSpriteViewable( object ) === true ) { + setupShadows( lights ); - sprites.push( object ); + shadowMap.render( scene, camera ); - } + setupLights( lights, camera ); - } else if ( object && object.isLensFlare ) { + if ( _clippingEnabled ) _clipping.endShadows(); - lensFlares.push( object ); + // - } else if ( object && object.isImmediateRenderObject ) { + _infoRender.calls = 0; + _infoRender.vertices = 0; + _infoRender.faces = 0; + _infoRender.points = 0; - if ( _this.sortObjects === true ) { + if ( renderTarget === undefined ) { - _vector3.setFromMatrixPosition( object.matrixWorld ); - _vector3.applyProjection( _projScreenMatrix ); + renderTarget = null; - } + } - pushRenderItem( object, null, object.material, _vector3.z, null ); + this.setRenderTarget( renderTarget ); - } else if ( ( object && object.isMesh ) || ( object && object.isLine ) || ( object && object.isPoints ) ) { + // - if ( object && object.isSkinnedMesh ) { + var background = scene.background; - object.skeleton.update(); + if ( background === null ) { - } + glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); - if ( object.frustumCulled === false || isObjectViewable( object ) === true ) { + } else if ( background && background.isColor ) { - var material = object.material; + glClearColor( background.r, background.g, background.b, 1 ); - if ( material.visible === true ) { + } - if ( _this.sortObjects === true ) { + if ( this.autoClear || forceClear ) { - _vector3.setFromMatrixPosition( object.matrixWorld ); - _vector3.applyProjection( _projScreenMatrix ); + this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil ); - } + } - var geometry = objects.update( object ); + if ( background && background.isCubeTexture ) { - if ( material && material.isMultiMaterial ) { + backgroundCamera2.projectionMatrix.copy( camera.projectionMatrix ); - var groups = geometry.groups; - var materials = material.materials; + backgroundCamera2.matrixWorld.extractRotation( camera.matrixWorld ); + backgroundCamera2.matrixWorldInverse.getInverse( backgroundCamera2.matrixWorld ); - for ( var i = 0, l = groups.length; i < l; i ++ ) { + backgroundBoxMesh.material.uniforms[ "tCube" ].value = background; + backgroundBoxMesh.modelViewMatrix.multiplyMatrices( backgroundCamera2.matrixWorldInverse, backgroundBoxMesh.matrixWorld ); - var group = groups[ i ]; - var groupMaterial = materials[ group.materialIndex ]; + objects.update( backgroundBoxMesh ); - if ( groupMaterial.visible === true ) { + _this.renderBufferDirect( backgroundCamera2, null, backgroundBoxMesh.geometry, backgroundBoxMesh.material, backgroundBoxMesh, null ); - pushRenderItem( object, geometry, groupMaterial, _vector3.z, group ); + } else if ( background && background.isTexture ) { - } + backgroundPlaneMesh.material.map = background; - } + objects.update( backgroundPlaneMesh ); - } else { + _this.renderBufferDirect( backgroundCamera, null, backgroundPlaneMesh.geometry, backgroundPlaneMesh.material, backgroundPlaneMesh, null ); - pushRenderItem( object, geometry, material, _vector3.z, null ); + } - } + // - } + if ( scene.overrideMaterial ) { - } + var overrideMaterial = scene.overrideMaterial; - } + renderObjects( opaqueObjects, camera, fog, overrideMaterial ); + renderObjects( transparentObjects, camera, fog, overrideMaterial ); - } + } else { - var children = object.children; + // opaque pass (front-to-back order) - for ( var i = 0, l = children.length; i < l; i ++ ) { + state.setBlending( NoBlending ); + renderObjects( opaqueObjects, camera, fog ); - projectObject( children[ i ], camera ); + // transparent pass (back-to-front order) - } + renderObjects( transparentObjects, camera, fog ); - } + } - function renderObjects( renderList, camera, fog, overrideMaterial ) { + // custom render plugins (post pass) - for ( var i = 0, l = renderList.length; i < l; i ++ ) { + spritePlugin.render( scene, camera ); + lensFlarePlugin.render( scene, camera, _currentViewport ); - var renderItem = renderList[ i ]; + // Generate mipmap if we're using any kind of mipmap filtering - var object = renderItem.object; - var geometry = renderItem.geometry; - var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial; - var group = renderItem.group; + if ( renderTarget ) { - object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld ); - object.normalMatrix.getNormalMatrix( object.modelViewMatrix ); + textures.updateRenderTargetMipmap( renderTarget ); - if ( object && object.isImmediateRenderObject ) { + } - setMaterial( material ); + // Ensure depth buffer writing is enabled so it can be cleared on next render - var program = setProgram( camera, fog, material, object ); + state.setDepthTest( true ); + state.setDepthWrite( true ); + state.setColorWrite( true ); - _currentGeometryProgram = ''; + // _gl.finish(); - object.render( function ( object ) { + }; - _this.renderBufferImmediate( object, program, material ); + function pushRenderItem( object, geometry, material, z, group ) { - } ); + var array, index; - } else { + // allocate the next position in the appropriate array - _this.renderBufferDirect( camera, fog, geometry, material, object, group ); + if ( material.transparent ) { - } + array = transparentObjects; + index = ++ transparentObjectsLastIndex; - } + } else { - } + array = opaqueObjects; + index = ++ opaqueObjectsLastIndex; - function initMaterial( material, fog, object ) { + } - var materialProperties = properties.get( material ); + // recycle existing render item or grow the array - var parameters = programCache.getParameters( - material, _lights, fog, _clipping.numPlanes, object ); + var renderItem = array[ index ]; - var code = programCache.getProgramCode( material, parameters ); + if ( renderItem !== undefined ) { - var program = materialProperties.program; - var programChange = true; + renderItem.id = object.id; + renderItem.object = object; + renderItem.geometry = geometry; + renderItem.material = material; + renderItem.z = _vector3.z; + renderItem.group = group; - if ( program === undefined ) { + } else { - // new material - material.addEventListener( 'dispose', onMaterialDispose ); + renderItem = { + id: object.id, + object: object, + geometry: geometry, + material: material, + z: _vector3.z, + group: group + }; - } else if ( program.code !== code ) { + // assert( index === array.length ); + array.push( renderItem ); - // changed glsl or parameters - releaseMaterialProgramReference( material ); + } - } else if ( parameters.shaderID !== undefined ) { + } - // same glsl and uniform list - return; + // TODO Duplicated code (Frustum) - } else { + function isObjectViewable( object ) { - // only rebuild uniform list - programChange = false; + var geometry = object.geometry; - } + if ( geometry.boundingSphere === null ) + geometry.computeBoundingSphere(); - if ( programChange ) { + _sphere.copy( geometry.boundingSphere ). + applyMatrix4( object.matrixWorld ); - if ( parameters.shaderID ) { + return isSphereViewable( _sphere ); - var shader = exports.ShaderLib[ parameters.shaderID ]; + } - materialProperties.__webglShader = { - name: material.type, - uniforms: exports.UniformsUtils.clone( shader.uniforms ), - vertexShader: shader.vertexShader, - fragmentShader: shader.fragmentShader - }; + function isSpriteViewable( sprite ) { - } else { + _sphere.center.set( 0, 0, 0 ); + _sphere.radius = 0.7071067811865476; + _sphere.applyMatrix4( sprite.matrixWorld ); - materialProperties.__webglShader = { - name: material.type, - uniforms: material.uniforms, - vertexShader: material.vertexShader, - fragmentShader: material.fragmentShader - }; + return isSphereViewable( _sphere ); - } + } - material.__webglShader = materialProperties.__webglShader; + function isSphereViewable( sphere ) { - program = programCache.acquireProgram( material, parameters, code ); + if ( ! _frustum.intersectsSphere( sphere ) ) return false; - materialProperties.program = program; - material.program = program; + var numPlanes = _clipping.numPlanes; - } + if ( numPlanes === 0 ) return true; - var attributes = program.getAttributes(); + var planes = _this.clippingPlanes, - if ( material.morphTargets ) { + center = sphere.center, + negRad = - sphere.radius, + i = 0; - material.numSupportedMorphTargets = 0; + do { - for ( var i = 0; i < _this.maxMorphTargets; i ++ ) { + // out when deeper than radius in the negative halfspace + if ( planes[ i ].distanceToPoint( center ) < negRad ) return false; - if ( attributes[ 'morphTarget' + i ] >= 0 ) { + } while ( ++ i !== numPlanes ); - material.numSupportedMorphTargets ++; + return true; - } + } - } + function projectObject( object, camera ) { - } + if ( object.visible === false ) return; - if ( material.morphNormals ) { + if ( object.layers.test( camera.layers ) ) { - material.numSupportedMorphNormals = 0; + if ( object && object.isLight ) { - for ( var i = 0; i < _this.maxMorphNormals; i ++ ) { + lights.push( object ); - if ( attributes[ 'morphNormal' + i ] >= 0 ) { + } else if ( object && object.isSprite ) { - material.numSupportedMorphNormals ++; + if ( object.frustumCulled === false || isSpriteViewable( object ) === true ) { - } + sprites.push( object ); - } + } - } + } else if ( object && object.isLensFlare ) { - var uniforms = materialProperties.__webglShader.uniforms; + lensFlares.push( object ); - if ( ! ( material && material.isShaderMaterial ) && - ! ( material && material.isRawShaderMaterial ) || - material.clipping === true ) { + } else if ( object && object.isImmediateRenderObject ) { - materialProperties.numClippingPlanes = _clipping.numPlanes; - uniforms.clippingPlanes = _clipping.uniform; + if ( _this.sortObjects === true ) { - } + _vector3.setFromMatrixPosition( object.matrixWorld ); + _vector3.applyProjection( _projScreenMatrix ); - if ( material.lights ) { + } - // store the light setup it was created for + pushRenderItem( object, null, object.material, _vector3.z, null ); - materialProperties.lightsHash = _lights.hash; + } else if ( ( object && object.isMesh ) || ( object && object.isLine ) || ( object && object.isPoints ) ) { - // wire up the material to this renderer's lighting state + if ( object && object.isSkinnedMesh ) { - 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; + object.skeleton.update(); - 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 ( object.frustumCulled === false || isObjectViewable( object ) === true ) { - var progUniforms = materialProperties.program.getUniforms(), - uniformsList = - exports.WebGLUniforms.seqWithValue( progUniforms.seq, uniforms ); + var material = object.material; - materialProperties.uniformsList = uniformsList; - materialProperties.dynamicUniforms = - exports.WebGLUniforms.splitDynamic( uniformsList, uniforms ); + if ( material.visible === true ) { - } + if ( _this.sortObjects === true ) { - function setMaterial( material ) { + _vector3.setFromMatrixPosition( object.matrixWorld ); + _vector3.applyProjection( _projScreenMatrix ); - if ( material.side !== DoubleSide ) - state.enable( _gl.CULL_FACE ); - else - state.disable( _gl.CULL_FACE ); + } - state.setFlipSided( material.side === BackSide ); + var geometry = objects.update( object ); - if ( material.transparent === true ) { + if ( material && material.isMultiMaterial ) { - state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha ); + var groups = geometry.groups; + var materials = material.materials; - } else { + for ( var i = 0, l = groups.length; i < l; i ++ ) { - state.setBlending( NoBlending ); + var group = groups[ i ]; + var groupMaterial = materials[ group.materialIndex ]; - } + if ( groupMaterial.visible === true ) { - state.setDepthFunc( material.depthFunc ); - state.setDepthTest( material.depthTest ); - state.setDepthWrite( material.depthWrite ); - state.setColorWrite( material.colorWrite ); - state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits ); + pushRenderItem( object, geometry, groupMaterial, _vector3.z, group ); - } + } - function setProgram( camera, fog, material, object ) { + } - _usedTextureUnits = 0; + } else { - var materialProperties = properties.get( material ); + pushRenderItem( object, geometry, material, _vector3.z, null ); - if ( _clippingEnabled ) { + } - if ( _localClippingEnabled || camera !== _currentCamera ) { + } - 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 ( materialProperties.numClippingPlanes !== undefined && - materialProperties.numClippingPlanes !== _clipping.numPlanes ) { + var children = object.children; - material.needsUpdate = true; + for ( var i = 0, l = children.length; i < l; i ++ ) { - } + projectObject( children[ i ], camera ); - } + } - if ( materialProperties.program === undefined ) { + } - material.needsUpdate = true; + function renderObjects( renderList, camera, fog, overrideMaterial ) { - } + for ( var i = 0, l = renderList.length; i < l; i ++ ) { - if ( materialProperties.lightsHash !== undefined && - materialProperties.lightsHash !== _lights.hash ) { + var renderItem = renderList[ i ]; - material.needsUpdate = true; + 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 ); - if ( material.needsUpdate ) { + if ( object && object.isImmediateRenderObject ) { - initMaterial( material, fog, object ); - material.needsUpdate = false; + setMaterial( material ); - } + var program = setProgram( camera, fog, material, object ); - var refreshProgram = false; - var refreshMaterial = false; - var refreshLights = false; + _currentGeometryProgram = ''; - var program = materialProperties.program, - p_uniforms = program.getUniforms(), - m_uniforms = materialProperties.__webglShader.uniforms; + object.render( function ( object ) { - if ( program.id !== _currentProgram ) { + _this.renderBufferImmediate( object, program, material ); - _gl.useProgram( program.program ); - _currentProgram = program.id; + } ); - refreshProgram = true; - refreshMaterial = true; - refreshLights = true; + } else { - } + _this.renderBufferDirect( camera, fog, geometry, material, object, group ); - if ( material.id !== _currentMaterialId ) { + } - _currentMaterialId = material.id; + } - refreshMaterial = true; + } - } + function initMaterial( material, fog, object ) { - if ( refreshProgram || camera !== _currentCamera ) { + var materialProperties = properties.get( material ); - p_uniforms.set( _gl, camera, 'projectionMatrix' ); + var parameters = programCache.getParameters( + material, _lights, fog, _clipping.numPlanes, object ); - if ( capabilities.logarithmicDepthBuffer ) { + var code = programCache.getProgramCode( material, parameters ); - p_uniforms.setValue( _gl, 'logDepthBufFC', - 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) ); + var program = materialProperties.program; + var programChange = true; - } + if ( program === undefined ) { + // new material + material.addEventListener( 'dispose', onMaterialDispose ); - if ( camera !== _currentCamera ) { + } else if ( program.code !== code ) { - _currentCamera = camera; + // changed glsl or parameters + releaseMaterialProgramReference( material ); - // 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: + } else if ( parameters.shaderID !== undefined ) { - refreshMaterial = true; // set to true on material change - refreshLights = true; // remains set until update done + // same glsl and uniform list + return; - } + } else { - // load material specific uniforms - // (shader material also gets them for the sake of genericity) + // only rebuild uniform list + programChange = false; - if ( ( material && material.isShaderMaterial ) || - ( material && material.isMeshPhongMaterial ) || - ( material && material.isMeshStandardMaterial ) || - material.envMap ) { + } - var uCamPos = p_uniforms.map.cameraPosition; + if ( programChange ) { - if ( uCamPos !== undefined ) { + if ( parameters.shaderID ) { - uCamPos.setValue( _gl, - _vector3.setFromMatrixPosition( camera.matrixWorld ) ); + var shader = exports.ShaderLib[ parameters.shaderID ]; - } + materialProperties.__webglShader = { + name: material.type, + uniforms: exports.UniformsUtils.clone( shader.uniforms ), + vertexShader: shader.vertexShader, + fragmentShader: shader.fragmentShader + }; - } + } else { - if ( ( material && material.isMeshPhongMaterial ) || - ( material && material.isMeshLambertMaterial ) || - ( material && material.isMeshBasicMaterial ) || - ( material && material.isMeshStandardMaterial ) || - ( material && material.isShaderMaterial ) || - material.skinning ) { + materialProperties.__webglShader = { + name: material.type, + uniforms: material.uniforms, + vertexShader: material.vertexShader, + fragmentShader: material.fragmentShader + }; - p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse ); + } - } + material.__webglShader = materialProperties.__webglShader; - p_uniforms.set( _gl, _this, 'toneMappingExposure' ); - p_uniforms.set( _gl, _this, 'toneMappingWhitePoint' ); + program = programCache.acquireProgram( material, parameters, code ); - } + materialProperties.program = program; + material.program = program; - // 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 + } - if ( material.skinning ) { + var attributes = program.getAttributes(); - p_uniforms.setOptional( _gl, object, 'bindMatrix' ); - p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' ); + if ( material.morphTargets ) { - var skeleton = object.skeleton; + material.numSupportedMorphTargets = 0; - if ( skeleton ) { + for ( var i = 0; i < _this.maxMorphTargets; i ++ ) { - if ( capabilities.floatVertexTextures && skeleton.useVertexTexture ) { + if ( attributes[ 'morphTarget' + i ] >= 0 ) { - p_uniforms.set( _gl, skeleton, 'boneTexture' ); - p_uniforms.set( _gl, skeleton, 'boneTextureWidth' ); - p_uniforms.set( _gl, skeleton, 'boneTextureHeight' ); + material.numSupportedMorphTargets ++; - } else { + } - p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' ); + } - } + } - } + if ( material.morphNormals ) { - } + material.numSupportedMorphNormals = 0; - if ( refreshMaterial ) { + for ( var i = 0; i < _this.maxMorphNormals; i ++ ) { - if ( material.lights ) { + if ( attributes[ 'morphNormal' + i ] >= 0 ) { - // the current material requires lighting info + material.numSupportedMorphNormals ++; - // 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 + } - markUniformsLightsNeedsUpdate( m_uniforms, refreshLights ); + } - } + } - // refresh uniforms common to several materials + var uniforms = materialProperties.__webglShader.uniforms; - if ( fog && material.fog ) { + if ( ! ( material && material.isShaderMaterial ) && + ! ( material && material.isRawShaderMaterial ) || + material.clipping === true ) { - refreshUniformsFog( m_uniforms, fog ); + materialProperties.numClippingPlanes = _clipping.numPlanes; + uniforms.clippingPlanes = _clipping.uniform; - } + } - if ( ( material && material.isMeshBasicMaterial ) || - ( material && material.isMeshLambertMaterial ) || - ( material && material.isMeshPhongMaterial ) || - ( material && material.isMeshStandardMaterial ) || - ( material && material.isMeshDepthMaterial ) ) { + if ( material.lights ) { - refreshUniformsCommon( m_uniforms, material ); + // store the light setup it was created for - } + materialProperties.lightsHash = _lights.hash; - // refresh single material specific uniforms + // wire up the material to this renderer's lighting state - if ( material && material.isLineBasicMaterial ) { + 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; - refreshUniformsLine( m_uniforms, material ); + 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; - } else if ( material && material.isLineDashedMaterial ) { + } - refreshUniformsLine( m_uniforms, material ); - refreshUniformsDash( m_uniforms, material ); + var progUniforms = materialProperties.program.getUniforms(), + uniformsList = + exports.WebGLUniforms.seqWithValue( progUniforms.seq, uniforms ); - } else if ( material && material.isPointsMaterial ) { + materialProperties.uniformsList = uniformsList; + materialProperties.dynamicUniforms = + exports.WebGLUniforms.splitDynamic( uniformsList, uniforms ); - refreshUniformsPoints( m_uniforms, material ); + } - } else if ( material && material.isMeshLambertMaterial ) { + function setMaterial( material ) { - refreshUniformsLambert( m_uniforms, material ); + if ( material.side !== DoubleSide ) + state.enable( _gl.CULL_FACE ); + else + state.disable( _gl.CULL_FACE ); - } else if ( material && material.isMeshPhongMaterial ) { + state.setFlipSided( material.side === BackSide ); - refreshUniformsPhong( m_uniforms, material ); + if ( material.transparent === true ) { - } else if ( material && material.isMeshPhysicalMaterial ) { + state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha ); - refreshUniformsPhysical( m_uniforms, material ); + } else { - } else if ( material && material.isMeshStandardMaterial ) { + state.setBlending( NoBlending ); - refreshUniformsStandard( m_uniforms, material ); + } - } else if ( material && material.isMeshDepthMaterial ) { + state.setDepthFunc( material.depthFunc ); + state.setDepthTest( material.depthTest ); + state.setDepthWrite( material.depthWrite ); + state.setColorWrite( material.colorWrite ); + state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits ); - if ( material.displacementMap ) { + } - m_uniforms.displacementMap.value = material.displacementMap; - m_uniforms.displacementScale.value = material.displacementScale; - m_uniforms.displacementBias.value = material.displacementBias; + function setProgram( camera, fog, material, object ) { - } + _usedTextureUnits = 0; - } else if ( material && material.isMeshNormalMaterial ) { + var materialProperties = properties.get( material ); - m_uniforms.opacity.value = material.opacity; + if ( _clippingEnabled ) { - } + if ( _localClippingEnabled || camera !== _currentCamera ) { - exports.WebGLUniforms.upload( - _gl, materialProperties.uniformsList, m_uniforms, _this ); + 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 ); + } - // common matrices + if ( materialProperties.numClippingPlanes !== undefined && + materialProperties.numClippingPlanes !== _clipping.numPlanes ) { - p_uniforms.set( _gl, object, 'modelViewMatrix' ); - p_uniforms.set( _gl, object, 'normalMatrix' ); - p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld ); + material.needsUpdate = true; + } - // dynamic uniforms + } - var dynUniforms = materialProperties.dynamicUniforms; + if ( materialProperties.program === undefined ) { - if ( dynUniforms !== null ) { + material.needsUpdate = true; - exports.WebGLUniforms.evalDynamic( - dynUniforms, m_uniforms, object, camera ); + } - exports.WebGLUniforms.upload( _gl, dynUniforms, m_uniforms, _this ); + if ( materialProperties.lightsHash !== undefined && + materialProperties.lightsHash !== _lights.hash ) { - } + material.needsUpdate = true; - return program; + } - } + if ( material.needsUpdate ) { - // Uniforms (refresh uniforms objects) + initMaterial( material, fog, object ); + material.needsUpdate = false; - function refreshUniformsCommon( uniforms, material ) { + } - uniforms.opacity.value = material.opacity; + var refreshProgram = false; + var refreshMaterial = false; + var refreshLights = false; - uniforms.diffuse.value = material.color; + var program = materialProperties.program, + p_uniforms = program.getUniforms(), + m_uniforms = materialProperties.__webglShader.uniforms; - if ( material.emissive ) { + if ( program.id !== _currentProgram ) { - uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity ); + _gl.useProgram( program.program ); + _currentProgram = program.id; - } + refreshProgram = true; + refreshMaterial = true; + refreshLights = true; - uniforms.map.value = material.map; - uniforms.specularMap.value = material.specularMap; - uniforms.alphaMap.value = material.alphaMap; + } - if ( material.aoMap ) { + if ( material.id !== _currentMaterialId ) { - uniforms.aoMap.value = material.aoMap; - uniforms.aoMapIntensity.value = material.aoMapIntensity; + _currentMaterialId = material.id; - } + refreshMaterial = true; - // uv repeat and offset setting priorities - // 1. color map - // 2. specular map - // 3. normal map - // 4. bump map - // 5. alpha map - // 6. emissive map + } - var uvScaleMap; + if ( refreshProgram || camera !== _currentCamera ) { - if ( material.map ) { + p_uniforms.set( _gl, camera, 'projectionMatrix' ); - uvScaleMap = material.map; + if ( capabilities.logarithmicDepthBuffer ) { - } else if ( material.specularMap ) { + p_uniforms.setValue( _gl, 'logDepthBufFC', + 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) ); - uvScaleMap = material.specularMap; + } - } else if ( material.displacementMap ) { - uvScaleMap = material.displacementMap; + if ( camera !== _currentCamera ) { - } else if ( material.normalMap ) { + _currentCamera = camera; - uvScaleMap = material.normalMap; + // 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: - } else if ( material.bumpMap ) { + refreshMaterial = true; // set to true on material change + refreshLights = true; // remains set until update done - uvScaleMap = material.bumpMap; + } - } else if ( material.roughnessMap ) { + // load material specific uniforms + // (shader material also gets them for the sake of genericity) - uvScaleMap = material.roughnessMap; + if ( ( material && material.isShaderMaterial ) || + ( material && material.isMeshPhongMaterial ) || + ( material && material.isMeshStandardMaterial ) || + material.envMap ) { - } else if ( material.metalnessMap ) { + var uCamPos = p_uniforms.map.cameraPosition; - uvScaleMap = material.metalnessMap; + if ( uCamPos !== undefined ) { - } else if ( material.alphaMap ) { + uCamPos.setValue( _gl, + _vector3.setFromMatrixPosition( camera.matrixWorld ) ); - uvScaleMap = material.alphaMap; + } - } else if ( material.emissiveMap ) { + } - uvScaleMap = material.emissiveMap; + if ( ( material && material.isMeshPhongMaterial ) || + ( material && material.isMeshLambertMaterial ) || + ( material && material.isMeshBasicMaterial ) || + ( material && material.isMeshStandardMaterial ) || + ( material && material.isShaderMaterial ) || + material.skinning ) { - } + p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse ); - if ( uvScaleMap !== undefined ) { + } - // backwards compatibility - if ( (uvScaleMap && uvScaleMap.isWebGLRenderTarget) ) { + p_uniforms.set( _gl, _this, 'toneMappingExposure' ); + p_uniforms.set( _gl, _this, 'toneMappingWhitePoint' ); - uvScaleMap = uvScaleMap.texture; + } - } + // 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 offset = uvScaleMap.offset; - var repeat = uvScaleMap.repeat; + if ( material.skinning ) { - uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y ); + p_uniforms.setOptional( _gl, object, 'bindMatrix' ); + p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' ); - } + var skeleton = object.skeleton; - uniforms.envMap.value = material.envMap; + if ( skeleton ) { - // 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; + if ( capabilities.floatVertexTextures && skeleton.useVertexTexture ) { - uniforms.reflectivity.value = material.reflectivity; - uniforms.refractionRatio.value = material.refractionRatio; + p_uniforms.set( _gl, skeleton, 'boneTexture' ); + p_uniforms.set( _gl, skeleton, 'boneTextureWidth' ); + p_uniforms.set( _gl, skeleton, 'boneTextureHeight' ); - } + } else { - function refreshUniformsLine( uniforms, material ) { + p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' ); - uniforms.diffuse.value = material.color; - uniforms.opacity.value = material.opacity; + } - } + } - function refreshUniformsDash( uniforms, material ) { + } - uniforms.dashSize.value = material.dashSize; - uniforms.totalSize.value = material.dashSize + material.gapSize; - uniforms.scale.value = material.scale; + if ( refreshMaterial ) { - } + if ( material.lights ) { - function refreshUniformsPoints( uniforms, material ) { + // the current material requires lighting info - uniforms.diffuse.value = material.color; - uniforms.opacity.value = material.opacity; - uniforms.size.value = material.size * _pixelRatio; - uniforms.scale.value = _canvas.clientHeight * 0.5; + // 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 - uniforms.map.value = material.map; + markUniformsLightsNeedsUpdate( m_uniforms, refreshLights ); - if ( material.map !== null ) { + } - var offset = material.map.offset; - var repeat = material.map.repeat; + // refresh uniforms common to several materials - uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y ); + if ( fog && material.fog ) { - } + refreshUniformsFog( m_uniforms, fog ); - } + } - function refreshUniformsFog( uniforms, fog ) { + if ( ( material && material.isMeshBasicMaterial ) || + ( material && material.isMeshLambertMaterial ) || + ( material && material.isMeshPhongMaterial ) || + ( material && material.isMeshStandardMaterial ) || + ( material && material.isMeshDepthMaterial ) ) { - uniforms.fogColor.value = fog.color; + refreshUniformsCommon( m_uniforms, material ); - if ( fog && fog.isFog ) { + } - uniforms.fogNear.value = fog.near; - uniforms.fogFar.value = fog.far; + // refresh single material specific uniforms - } else if ( fog && fog.isFogExp2 ) { + if ( material && material.isLineBasicMaterial ) { - uniforms.fogDensity.value = fog.density; + refreshUniformsLine( m_uniforms, material ); - } + } else if ( material && material.isLineDashedMaterial ) { - } + refreshUniformsLine( m_uniforms, material ); + refreshUniformsDash( m_uniforms, material ); - function refreshUniformsLambert( uniforms, material ) { + } else if ( material && material.isPointsMaterial ) { - if ( material.lightMap ) { + refreshUniformsPoints( m_uniforms, material ); - uniforms.lightMap.value = material.lightMap; - uniforms.lightMapIntensity.value = material.lightMapIntensity; + } else if ( material && material.isMeshLambertMaterial ) { - } + refreshUniformsLambert( m_uniforms, material ); - if ( material.emissiveMap ) { + } else if ( material && material.isMeshPhongMaterial ) { - uniforms.emissiveMap.value = material.emissiveMap; + refreshUniformsPhong( m_uniforms, material ); - } + } else if ( material && material.isMeshPhysicalMaterial ) { - } + refreshUniformsPhysical( m_uniforms, material ); - function refreshUniformsPhong( uniforms, material ) { + } else if ( material && material.isMeshStandardMaterial ) { - uniforms.specular.value = material.specular; - uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 ) + refreshUniformsStandard( m_uniforms, material ); - if ( material.lightMap ) { + } else if ( material && material.isMeshDepthMaterial ) { - uniforms.lightMap.value = material.lightMap; - uniforms.lightMapIntensity.value = material.lightMapIntensity; + if ( material.displacementMap ) { - } + m_uniforms.displacementMap.value = material.displacementMap; + m_uniforms.displacementScale.value = material.displacementScale; + m_uniforms.displacementBias.value = material.displacementBias; - if ( material.emissiveMap ) { + } - uniforms.emissiveMap.value = material.emissiveMap; + } else if ( material && material.isMeshNormalMaterial ) { - } + m_uniforms.opacity.value = material.opacity; - if ( material.bumpMap ) { + } - uniforms.bumpMap.value = material.bumpMap; - uniforms.bumpScale.value = material.bumpScale; + exports.WebGLUniforms.upload( + _gl, materialProperties.uniformsList, m_uniforms, _this ); - } + } - if ( material.normalMap ) { - uniforms.normalMap.value = material.normalMap; - uniforms.normalScale.value.copy( material.normalScale ); + // common matrices - } + p_uniforms.set( _gl, object, 'modelViewMatrix' ); + p_uniforms.set( _gl, object, 'normalMatrix' ); + p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld ); - if ( material.displacementMap ) { - uniforms.displacementMap.value = material.displacementMap; - uniforms.displacementScale.value = material.displacementScale; - uniforms.displacementBias.value = material.displacementBias; + // dynamic uniforms - } + var dynUniforms = materialProperties.dynamicUniforms; - } + if ( dynUniforms !== null ) { - function refreshUniformsStandard( uniforms, material ) { + exports.WebGLUniforms.evalDynamic( + dynUniforms, m_uniforms, object, camera ); - uniforms.roughness.value = material.roughness; - uniforms.metalness.value = material.metalness; + exports.WebGLUniforms.upload( _gl, dynUniforms, m_uniforms, _this ); - if ( material.roughnessMap ) { + } - uniforms.roughnessMap.value = material.roughnessMap; + return program; - } + } - if ( material.metalnessMap ) { + // Uniforms (refresh uniforms objects) - uniforms.metalnessMap.value = material.metalnessMap; + function refreshUniformsCommon( uniforms, material ) { - } + 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 ) { - if ( material.envMap ) { + uvScaleMap = material.displacementMap; - //uniforms.envMap.value = material.envMap; // part of uniforms common - uniforms.envMapIntensity.value = material.envMapIntensity; + } else if ( material.normalMap ) { - } + uvScaleMap = material.normalMap; - } + } else if ( material.bumpMap ) { - function refreshUniformsPhysical( uniforms, material ) { + uvScaleMap = material.bumpMap; - uniforms.clearCoat.value = material.clearCoat; - uniforms.clearCoatRoughness.value = material.clearCoatRoughness; + } else if ( material.roughnessMap ) { - refreshUniformsStandard( uniforms, material ); + uvScaleMap = material.roughnessMap; - } + } else if ( material.metalnessMap ) { - // If uniforms are marked as clean, they don't need to be loaded to the GPU. + uvScaleMap = material.metalnessMap; - function markUniformsLightsNeedsUpdate( uniforms, value ) { + } else if ( material.alphaMap ) { - uniforms.ambientLightColor.needsUpdate = value; + uvScaleMap = material.alphaMap; - uniforms.directionalLights.needsUpdate = value; - uniforms.pointLights.needsUpdate = value; - uniforms.spotLights.needsUpdate = value; - uniforms.hemisphereLights.needsUpdate = value; + } else if ( material.emissiveMap ) { - } + uvScaleMap = material.emissiveMap; - // Lighting + } - function setupShadows( lights ) { + if ( uvScaleMap !== undefined ) { - var lightShadowsLength = 0; + // backwards compatibility + if ( (uvScaleMap && uvScaleMap.isWebGLRenderTarget) ) { - for ( var i = 0, l = lights.length; i < l; i ++ ) { + uvScaleMap = uvScaleMap.texture; - var light = lights[ i ]; + } - if ( light.castShadow ) { + var offset = uvScaleMap.offset; + var repeat = uvScaleMap.repeat; - _lights.shadows[ lightShadowsLength ++ ] = light; + uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y ); - } + } - } + uniforms.envMap.value = material.envMap; - _lights.shadows.length = lightShadowsLength; + // 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; - function setupLights( lights, camera ) { + } - var l, ll, light, - r = 0, g = 0, b = 0, - color, - intensity, - distance, - shadowMap, + function refreshUniformsLine( uniforms, material ) { - viewMatrix = camera.matrixWorldInverse, + uniforms.diffuse.value = material.color; + uniforms.opacity.value = material.opacity; - directionalLength = 0, - pointLength = 0, - spotLength = 0, - hemiLength = 0; + } - for ( l = 0, ll = lights.length; l < ll; l ++ ) { + function refreshUniformsDash( uniforms, material ) { - light = lights[ l ]; + uniforms.dashSize.value = material.dashSize; + uniforms.totalSize.value = material.dashSize + material.gapSize; + uniforms.scale.value = material.scale; - color = light.color; - intensity = light.intensity; - distance = light.distance; + } - shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null; + function refreshUniformsPoints( uniforms, material ) { - if ( light && light.isAmbientLight ) { + uniforms.diffuse.value = material.color; + uniforms.opacity.value = material.opacity; + uniforms.size.value = material.size * _pixelRatio; + uniforms.scale.value = _canvas.clientHeight * 0.5; - r += color.r * intensity; - g += color.g * intensity; - b += color.b * intensity; + uniforms.map.value = material.map; - } else if ( light && light.isDirectionalLight ) { + if ( material.map !== null ) { - var uniforms = lightCache.get( light ); + var offset = material.map.offset; + var repeat = material.map.repeat; - 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.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y ); - uniforms.shadow = light.castShadow; + } - if ( light.castShadow ) { + } - uniforms.shadowBias = light.shadow.bias; - uniforms.shadowRadius = light.shadow.radius; - uniforms.shadowMapSize = light.shadow.mapSize; + function refreshUniformsFog( uniforms, fog ) { - } + uniforms.fogColor.value = fog.color; - _lights.directionalShadowMap[ directionalLength ] = shadowMap; - _lights.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix; - _lights.directional[ directionalLength ++ ] = uniforms; + if ( fog && fog.isFog ) { - } else if ( light && light.isSpotLight ) { + uniforms.fogNear.value = fog.near; + uniforms.fogFar.value = fog.far; - var uniforms = lightCache.get( light ); + } else if ( fog && fog.isFogExp2 ) { - uniforms.position.setFromMatrixPosition( light.matrixWorld ); - uniforms.position.applyMatrix4( viewMatrix ); + uniforms.fogDensity.value = fog.density; - uniforms.color.copy( color ).multiplyScalar( intensity ); - uniforms.distance = distance; + } - 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; + function refreshUniformsLambert( uniforms, material ) { - 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.spotShadowMap[ spotLength ] = shadowMap; - _lights.spotShadowMatrix[ spotLength ] = light.shadow.matrix; - _lights.spot[ spotLength ++ ] = uniforms; + uniforms.emissiveMap.value = material.emissiveMap; - } else if ( light && light.isPointLight ) { + } - var uniforms = lightCache.get( light ); + } - uniforms.position.setFromMatrixPosition( light.matrixWorld ); - uniforms.position.applyMatrix4( viewMatrix ); + function refreshUniformsPhong( uniforms, material ) { - uniforms.color.copy( light.color ).multiplyScalar( light.intensity ); - uniforms.distance = light.distance; - uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay; + uniforms.specular.value = material.specular; + uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 ) - 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; + } - } + } - } + function refreshUniformsStandard( uniforms, material ) { - _lights.ambient[ 0 ] = r; - _lights.ambient[ 1 ] = g; - _lights.ambient[ 2 ] = b; + uniforms.roughness.value = material.roughness; + uniforms.metalness.value = material.metalness; - _lights.directional.length = directionalLength; - _lights.spot.length = spotLength; - _lights.point.length = pointLength; - _lights.hemi.length = hemiLength; + if ( material.roughnessMap ) { - _lights.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + hemiLength + ',' + _lights.shadows.length; + uniforms.roughnessMap.value = material.roughnessMap; - } + } - // GL state setting + if ( material.metalnessMap ) { - this.setFaceCulling = function ( cullFace, frontFaceDirection ) { + uniforms.metalnessMap.value = material.metalnessMap; - state.setCullFace( cullFace ); - state.setFlipSided( frontFaceDirection === FrontFaceDirectionCW ); + } - }; + if ( material.lightMap ) { - // Textures + uniforms.lightMap.value = material.lightMap; + uniforms.lightMapIntensity.value = material.lightMapIntensity; - function allocTextureUnit() { + } - var textureUnit = _usedTextureUnits; + if ( material.emissiveMap ) { - if ( textureUnit >= capabilities.maxTextures ) { + uniforms.emissiveMap.value = material.emissiveMap; - console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures ); + } - } + if ( material.bumpMap ) { - _usedTextureUnits += 1; + uniforms.bumpMap.value = material.bumpMap; + uniforms.bumpScale.value = material.bumpScale; - return textureUnit; + } - } + if ( material.normalMap ) { - this.allocTextureUnit = allocTextureUnit; + uniforms.normalMap.value = material.normalMap; + uniforms.normalScale.value.copy( material.normalScale ); - // this.setTexture2D = setTexture2D; - this.setTexture2D = ( function() { + } - var warned = false; + if ( material.displacementMap ) { - // backwards compatibility: peel texture.texture - return function setTexture2D( texture, slot ) { + uniforms.displacementMap.value = material.displacementMap; + uniforms.displacementScale.value = material.displacementScale; + uniforms.displacementBias.value = material.displacementBias; - if ( texture && texture.isWebGLRenderTarget ) { + } - if ( ! warned ) { + if ( material.envMap ) { - console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." ); - warned = true; + //uniforms.envMap.value = material.envMap; // part of uniforms common + uniforms.envMapIntensity.value = material.envMapIntensity; - } + } - texture = texture.texture; + } - } + function refreshUniformsPhysical( uniforms, material ) { - textures.setTexture2D( texture, slot ); + uniforms.clearCoat.value = material.clearCoat; + uniforms.clearCoatRoughness.value = material.clearCoatRoughness; - }; + refreshUniformsStandard( uniforms, material ); - }() ); + } - this.setTexture = ( function() { + // If uniforms are marked as clean, they don't need to be loaded to the GPU. - var warned = false; + function markUniformsLightsNeedsUpdate( uniforms, value ) { - return function setTexture( texture, slot ) { + uniforms.ambientLightColor.needsUpdate = value; - if ( ! warned ) { + uniforms.directionalLights.needsUpdate = value; + uniforms.pointLights.needsUpdate = value; + uniforms.spotLights.needsUpdate = value; + uniforms.hemisphereLights.needsUpdate = value; - console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead." ); - warned = true; + } - } + // Lighting - textures.setTexture2D( texture, slot ); + function setupShadows( lights ) { - }; + var lightShadowsLength = 0; - }() ); + for ( var i = 0, l = lights.length; i < l; i ++ ) { - this.setTextureCube = ( function() { + var light = lights[ i ]; - var warned = false; + if ( light.castShadow ) { - return function setTextureCube( texture, slot ) { + _lights.shadows[ lightShadowsLength ++ ] = light; - // backwards compatibility: peel texture.texture - if ( texture && texture.isWebGLRenderTargetCube ) { + } - if ( ! warned ) { + } - console.warn( "THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead." ); - warned = true; + _lights.shadows.length = lightShadowsLength; - } + } - texture = texture.texture; + function setupLights( lights, camera ) { - } + var l, ll, light, + r = 0, g = 0, b = 0, + color, + intensity, + distance, + shadowMap, - // 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 ) ) { + viewMatrix = camera.matrixWorldInverse, - // CompressedTexture can have Array in image :/ + directionalLength = 0, + pointLength = 0, + spotLength = 0, + hemiLength = 0; - // this function alone should take care of cube textures - textures.setTextureCube( texture, slot ); + for ( l = 0, ll = lights.length; l < ll; l ++ ) { - } else { + light = lights[ l ]; - // assumed: texture property of THREE.WebGLRenderTargetCube + color = light.color; + intensity = light.intensity; + distance = light.distance; - textures.setTextureCubeDynamic( texture, slot ); + shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null; - } + if ( light && light.isAmbientLight ) { - }; + r += color.r * intensity; + g += color.g * intensity; + b += color.b * intensity; - }() ); + } else if ( light && light.isDirectionalLight ) { - this.getCurrentRenderTarget = function() { + var uniforms = lightCache.get( light ); - return _currentRenderTarget; + 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; - this.setRenderTarget = function ( renderTarget ) { + if ( light.castShadow ) { - _currentRenderTarget = renderTarget; + uniforms.shadowBias = light.shadow.bias; + uniforms.shadowRadius = light.shadow.radius; + uniforms.shadowMapSize = light.shadow.mapSize; - if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) { + } - textures.setupRenderTarget( renderTarget ); + _lights.directionalShadowMap[ directionalLength ] = shadowMap; + _lights.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix; + _lights.directional[ directionalLength ++ ] = uniforms; - } + } else if ( light && light.isSpotLight ) { - var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube ); - var framebuffer; + var uniforms = lightCache.get( light ); - if ( renderTarget ) { + uniforms.position.setFromMatrixPosition( light.matrixWorld ); + uniforms.position.applyMatrix4( viewMatrix ); - var renderTargetProperties = properties.get( renderTarget ); + uniforms.color.copy( color ).multiplyScalar( intensity ); + uniforms.distance = distance; - if ( isCube ) { + uniforms.direction.setFromMatrixPosition( light.matrixWorld ); + _vector3.setFromMatrixPosition( light.target.matrixWorld ); + uniforms.direction.sub( _vector3 ); + uniforms.direction.transformDirection( viewMatrix ); - framebuffer = renderTargetProperties.__webglFramebuffer[ renderTarget.activeCubeFace ]; + uniforms.coneCos = Math.cos( light.angle ); + uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) ); + uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay; - } else { + uniforms.shadow = light.castShadow; - framebuffer = renderTargetProperties.__webglFramebuffer; + if ( light.castShadow ) { - } + uniforms.shadowBias = light.shadow.bias; + uniforms.shadowRadius = light.shadow.radius; + uniforms.shadowMapSize = light.shadow.mapSize; - _currentScissor.copy( renderTarget.scissor ); - _currentScissorTest = renderTarget.scissorTest; + } - _currentViewport.copy( renderTarget.viewport ); + _lights.spotShadowMap[ spotLength ] = shadowMap; + _lights.spotShadowMatrix[ spotLength ] = light.shadow.matrix; + _lights.spot[ spotLength ++ ] = uniforms; - } else { + } else if ( light && light.isPointLight ) { - framebuffer = null; + var uniforms = lightCache.get( light ); - _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ); - _currentScissorTest = _scissorTest; + uniforms.position.setFromMatrixPosition( light.matrixWorld ); + uniforms.position.applyMatrix4( viewMatrix ); - _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ); + 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 ( _currentFramebuffer !== framebuffer ) { + if ( light.castShadow ) { - _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); - _currentFramebuffer = framebuffer; + uniforms.shadowBias = light.shadow.bias; + uniforms.shadowRadius = light.shadow.radius; + uniforms.shadowMapSize = light.shadow.mapSize; - } + } - state.scissor( _currentScissor ); - state.setScissorTest( _currentScissorTest ); + _lights.pointShadowMap[ pointLength ] = shadowMap; - state.viewport( _currentViewport ); + if ( _lights.pointShadowMatrix[ pointLength ] === undefined ) { - if ( isCube ) { + _lights.pointShadowMatrix[ pointLength ] = new Matrix4(); - 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 ); + } - } + // 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; - this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) { + } else if ( light && light.isHemisphereLight ) { - if ( ( renderTarget && renderTarget.isWebGLRenderTarget ) === false ) { + var uniforms = lightCache.get( light ); - console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' ); - return; + uniforms.direction.setFromMatrixPosition( light.matrixWorld ); + uniforms.direction.transformDirection( viewMatrix ); + uniforms.direction.normalize(); - } + uniforms.skyColor.copy( light.color ).multiplyScalar( intensity ); + uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity ); - var framebuffer = properties.get( renderTarget ).__webglFramebuffer; + _lights.hemi[ hemiLength ++ ] = uniforms; - if ( framebuffer ) { + } - var restore = false; + } - if ( framebuffer !== _currentFramebuffer ) { + _lights.ambient[ 0 ] = r; + _lights.ambient[ 1 ] = g; + _lights.ambient[ 2 ] = b; - _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + _lights.directional.length = directionalLength; + _lights.spot.length = spotLength; + _lights.point.length = pointLength; + _lights.hemi.length = hemiLength; - restore = true; + _lights.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + hemiLength + ',' + _lights.shadows.length; - } + } - try { + // GL state setting - var texture = renderTarget.texture; + this.setFaceCulling = function ( cullFace, frontFaceDirection ) { - if ( texture.format !== RGBAFormat && paramThreeToGL( texture.format ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) { + state.setCullFace( cullFace ); + state.setFlipSided( frontFaceDirection === FrontFaceDirectionCW ); - console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' ); - return; + }; - } + // Textures - 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' ) ) ) { + function allocTextureUnit() { - console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' ); - return; + var textureUnit = _usedTextureUnits; - } + if ( textureUnit >= capabilities.maxTextures ) { - if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) { + console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures ); - // 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 ) ) ) { + _usedTextureUnits += 1; - _gl.readPixels( x, y, width, height, paramThreeToGL( texture.format ), paramThreeToGL( texture.type ), buffer ); + return textureUnit; - } + } - } else { + this.allocTextureUnit = allocTextureUnit; - console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' ); + // this.setTexture2D = setTexture2D; + this.setTexture2D = ( function() { - } + var warned = false; - } finally { + // backwards compatibility: peel texture.texture + return function setTexture2D( texture, slot ) { - if ( restore ) { + if ( texture && texture.isWebGLRenderTarget ) { - _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer ); + if ( ! warned ) { - } + console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." ); + warned = true; - } + } - } + texture = texture.texture; - }; + } - // Map three.js constants to WebGL constants + textures.setTexture2D( texture, slot ); - function paramThreeToGL( p ) { + }; - var extension; + }() ); - if ( p === RepeatWrapping ) return _gl.REPEAT; - if ( p === ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE; - if ( p === MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT; + this.setTexture = ( function() { - if ( p === NearestFilter ) return _gl.NEAREST; - if ( p === NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST; - if ( p === NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR; + var warned = false; - if ( p === LinearFilter ) return _gl.LINEAR; - if ( p === LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST; - if ( p === LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR; + return function setTexture( texture, slot ) { - 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; + if ( ! warned ) { - 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; + console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead." ); + warned = true; - extension = extensions.get( 'OES_texture_half_float' ); + } - if ( extension !== null ) { + textures.setTexture2D( texture, slot ); - if ( p === HalfFloatType ) return extension.HALF_FLOAT_OES; + }; - } + }() ); - 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; + this.setTextureCube = ( function() { - if ( p === AddEquation ) return _gl.FUNC_ADD; - if ( p === SubtractEquation ) return _gl.FUNC_SUBTRACT; - if ( p === ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT; + var warned = false; - 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; + return function setTextureCube( texture, slot ) { - if ( p === DstColorFactor ) return _gl.DST_COLOR; - if ( p === OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR; - if ( p === SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE; + // backwards compatibility: peel texture.texture + if ( texture && texture.isWebGLRenderTargetCube ) { - extension = extensions.get( 'WEBGL_compressed_texture_s3tc' ); + if ( ! warned ) { - if ( extension !== null ) { + console.warn( "THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead." ); + warned = true; - 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; + } - } + texture = texture.texture; - extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' ); + } - if ( extension !== null ) { + // 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 ) ) { - 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; + // CompressedTexture can have Array in image :/ - } + // this function alone should take care of cube textures + textures.setTextureCube( texture, slot ); - extension = extensions.get( 'WEBGL_compressed_texture_etc1' ); + } else { - if ( extension !== null ) { + // assumed: texture property of THREE.WebGLRenderTargetCube - if ( p === RGB_ETC1_Format ) return extension.COMPRESSED_RGB_ETC1_WEBGL; + textures.setTextureCubeDynamic( texture, slot ); - } + } - extension = extensions.get( 'EXT_blend_minmax' ); + }; - if ( extension !== null ) { + }() ); - if ( p === MinEquation ) return extension.MIN_EXT; - if ( p === MaxEquation ) return extension.MAX_EXT; + this.getCurrentRenderTarget = function() { - } + return _currentRenderTarget; - extension = extensions.get( 'WEBGL_depth_texture' ); + }; - if ( extension !== null ){ + this.setRenderTarget = function ( renderTarget ) { - if ( p === THREE.UnsignedInt248Type ) return extension.UNSIGNED_INT_24_8_WEBGL; + _currentRenderTarget = renderTarget; - } + if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) { - return 0; + textures.setupRenderTarget( renderTarget ); - } + } - }; + var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube ); + var framebuffer; - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + if ( renderTarget ) { - function FogExp2 ( color, density ) { + var renderTargetProperties = properties.get( renderTarget ); - this.name = ''; + if ( isCube ) { - this.color = new Color( color ); - this.density = ( density !== undefined ) ? density : 0.00025; + framebuffer = renderTargetProperties.__webglFramebuffer[ renderTarget.activeCubeFace ]; - } + } else { - FogExp2.prototype.isFogExp2 = true; + framebuffer = renderTargetProperties.__webglFramebuffer; - FogExp2.prototype.clone = function () { + } - return new FogExp2( this.color.getHex(), this.density ); + _currentScissor.copy( renderTarget.scissor ); + _currentScissorTest = renderTarget.scissorTest; - }; + _currentViewport.copy( renderTarget.viewport ); - FogExp2.prototype.toJSON = function ( meta ) { + } else { - return { - type: 'FogExp2', - color: this.color.getHex(), - density: this.density - }; + framebuffer = null; - }; + _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ); + _currentScissorTest = _scissorTest; - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ); - function Fog ( color, near, far ) { + } - this.name = ''; + if ( _currentFramebuffer !== framebuffer ) { - this.color = new Color( color ); + _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + _currentFramebuffer = framebuffer; - this.near = ( near !== undefined ) ? near : 1; - this.far = ( far !== undefined ) ? far : 1000; + } - } + state.scissor( _currentScissor ); + state.setScissorTest( _currentScissorTest ); - Fog.prototype.isFog = true; + state.viewport( _currentViewport ); - Fog.prototype.clone = function () { + if ( isCube ) { - return new Fog( this.color.getHex(), this.near, this.far ); + 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 ); - }; + } - Fog.prototype.toJSON = function ( meta ) { + }; - return { - type: 'Fog', - color: this.color.getHex(), - near: this.near, - far: this.far - }; + this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) { - }; + if ( ( renderTarget && renderTarget.isWebGLRenderTarget ) === false ) { - /** - * @author mrdoob / http://mrdoob.com/ - */ + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' ); + return; - function Scene () { - - Object3D.call( this ); + } - this.type = 'Scene'; + var framebuffer = properties.get( renderTarget ).__webglFramebuffer; - this.background = null; - this.fog = null; - this.overrideMaterial = null; + if ( framebuffer ) { - this.autoUpdate = true; // checked by the renderer + var restore = false; - } + if ( framebuffer !== _currentFramebuffer ) { - Scene.prototype = Object.create( Object3D.prototype ); + _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); - Scene.prototype.constructor = Scene; + restore = true; - Scene.prototype.copy = function ( source, recursive ) { + } - Object3D.prototype.copy.call( this, source, recursive ); + try { - 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 texture = renderTarget.texture; - this.autoUpdate = source.autoUpdate; - this.matrixAutoUpdate = source.matrixAutoUpdate; + if ( texture.format !== RGBAFormat && paramThreeToGL( texture.format ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) { - return this; + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' ); + return; - }; + } - Scene.prototype.toJSON = function ( meta ) { + 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' ) ) ) { - var data = Object3D.prototype.toJSON.call( this, meta ); - - if ( this.fog != null ) { - - data.object.fog = this.fog.toJSON(); + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' ); + return; - } + } - return data; + if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) { - }; + // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604) - /** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - */ + if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) { - function LensFlare( texture, size, distance, blending, color ) { + _gl.readPixels( x, y, width, height, paramThreeToGL( texture.format ), paramThreeToGL( texture.type ), buffer ); - Object3D.call( this ); + } - this.lensFlares = []; + } else { - this.positionScreen = new Vector3(); - this.customUpdateCallback = undefined; + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' ); - if ( texture !== undefined ) { + } - this.add( texture, size, distance, blending, color ); + } finally { - } + if ( restore ) { - }; + _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer ); - LensFlare.prototype = Object.assign( Object.create( Object3D.prototype ), { + } - constructor: LensFlare, + } - isLensFlare: true, + } - copy: function ( source ) { + }; - Object3D.prototype.copy.call( this, source ); + // Map three.js constants to WebGL constants - this.positionScreen.copy( source.positionScreen ); - this.customUpdateCallback = source.customUpdateCallback; + function paramThreeToGL( p ) { - for ( var i = 0, l = source.lensFlares.length; i < l; i ++ ) { + var extension; - this.lensFlares.push( source.lensFlares[ i ] ); + 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; - return this; + 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; - add: function ( texture, size, distance, blending, color, opacity ) { + 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; - 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( 'OES_texture_half_float' ); - 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 === HalfFloatType ) return extension.HALF_FLOAT_OES; - }, + } - /* - * 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. - */ + 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; - updateLensFlares: function () { + if ( p === AddEquation ) return _gl.FUNC_ADD; + if ( p === SubtractEquation ) return _gl.FUNC_SUBTRACT; + if ( p === ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT; - var f, fl = this.lensFlares.length; - var flare; - var vecX = - this.positionScreen.x * 2; - var vecY = - this.positionScreen.y * 2; + 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; - for ( f = 0; f < fl; f ++ ) { + if ( p === DstColorFactor ) return _gl.DST_COLOR; + if ( p === OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR; + if ( p === SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE; - flare = this.lensFlares[ f ]; + extension = extensions.get( 'WEBGL_compressed_texture_s3tc' ); - flare.x = this.positionScreen.x + vecX * flare.distance; - flare.y = this.positionScreen.y + vecY * flare.distance; + if ( extension !== null ) { - flare.wantedRotation = flare.x * Math.PI * 0.25; - flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25; + 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; - } + } - } + extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' ); - } ); + if ( extension !== null ) { - /** - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * opacity: , - * map: new THREE.Texture( ), - * - * uvOffset: new THREE.Vector2(), - * uvScale: new THREE.Vector2() - * } - */ + 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; - function SpriteMaterial( parameters ) { + } - Material.call( this ); + extension = extensions.get( 'WEBGL_compressed_texture_etc1' ); - this.type = 'SpriteMaterial'; + if ( extension !== null ) { - this.color = new Color( 0xffffff ); - this.map = null; + if ( p === RGB_ETC1_Format ) return extension.COMPRESSED_RGB_ETC1_WEBGL; - this.rotation = 0; + } - this.fog = false; - this.lights = false; + extension = extensions.get( 'EXT_blend_minmax' ); - this.setValues( parameters ); + if ( extension !== null ) { - }; + if ( p === MinEquation ) return extension.MIN_EXT; + if ( p === MaxEquation ) return extension.MAX_EXT; - SpriteMaterial.prototype = Object.create( Material.prototype ); - SpriteMaterial.prototype.constructor = SpriteMaterial; + } - SpriteMaterial.prototype.copy = function ( source ) { + extension = extensions.get( 'WEBGL_depth_texture' ); - Material.prototype.copy.call( this, source ); + if ( extension !== null ){ - this.color.copy( source.color ); - this.map = source.map; + if ( p === THREE.UnsignedInt248Type ) return extension.UNSIGNED_INT_24_8_WEBGL; - this.rotation = source.rotation; + } - return this; + return 0; - }; + } - /** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - */ + }; - function Sprite( material ) { + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - Object3D.call( this ); + function FogExp2 ( color, density ) { - this.type = 'Sprite'; + this.name = ''; - this.material = ( material !== undefined ) ? material : new SpriteMaterial(); + this.color = new Color( color ); + this.density = ( density !== undefined ) ? density : 0.00025; - }; + } - Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), { + FogExp2.prototype.isFogExp2 = true; - constructor: Sprite, + FogExp2.prototype.clone = function () { - isSprite: true, + return new FogExp2( this.color.getHex(), this.density ); - raycast: ( function () { + }; - var matrixPosition = new Vector3(); + FogExp2.prototype.toJSON = function ( meta ) { - return function raycast( raycaster, intersects ) { + return { + type: 'FogExp2', + color: this.color.getHex(), + density: this.density + }; - matrixPosition.setFromMatrixPosition( this.matrixWorld ); + }; - var distanceSq = raycaster.ray.distanceSqToPoint( matrixPosition ); - var guessSizeSq = this.scale.x * this.scale.y / 4; + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - if ( distanceSq > guessSizeSq ) { + function Fog ( color, near, far ) { - return; + this.name = ''; - } + this.color = new Color( color ); - intersects.push( { + this.near = ( near !== undefined ) ? near : 1; + this.far = ( far !== undefined ) ? far : 1000; - distance: Math.sqrt( distanceSq ), - point: this.position, - face: null, - object: this + } - } ); + Fog.prototype.isFog = true; - }; + Fog.prototype.clone = function () { - }() ), + return new Fog( this.color.getHex(), this.near, this.far ); - clone: function () { + }; - return new this.constructor( this.material ).copy( this ); + Fog.prototype.toJSON = function ( meta ) { - } + return { + type: 'Fog', + color: this.color.getHex(), + near: this.near, + far: this.far + }; - } ); + }; - /** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - */ + /** + * @author mrdoob / http://mrdoob.com/ + */ - function LOD() { + function Scene () { + + Object3D.call( this ); - Object3D.call( this ); + this.type = 'Scene'; - this.type = 'LOD'; + this.background = null; + this.fog = null; + this.overrideMaterial = null; - Object.defineProperties( this, { - levels: { - enumerable: true, - value: [] - } - } ); + this.autoUpdate = true; // checked by the renderer - }; + } + Scene.prototype = Object.create( Object3D.prototype ); - LOD.prototype = Object.assign( Object.create( Object3D.prototype ), { + Scene.prototype.constructor = Scene; - constructor: LOD, + Scene.prototype.copy = function ( source, recursive ) { - copy: function ( source ) { + Object3D.prototype.copy.call( this, source, recursive ); - Object3D.prototype.copy.call( this, source, false ); + 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 levels = source.levels; + this.autoUpdate = source.autoUpdate; + this.matrixAutoUpdate = source.matrixAutoUpdate; - for ( var i = 0, l = levels.length; i < l; i ++ ) { + return this; - var level = levels[ i ]; + }; - this.addLevel( level.object.clone(), level.distance ); + Scene.prototype.toJSON = function ( meta ) { - } + var data = Object3D.prototype.toJSON.call( this, meta ); + + if ( this.fog != null ) { + + data.object.fog = this.fog.toJSON(); - return this; + } - }, + return data; - addLevel: function ( object, distance ) { + }; - if ( distance === undefined ) distance = 0; + /** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + */ - distance = Math.abs( distance ); + function LensFlare( texture, size, distance, blending, color ) { - var levels = this.levels; + Object3D.call( this ); - for ( var l = 0; l < levels.length; l ++ ) { + this.lensFlares = []; - if ( distance < levels[ l ].distance ) { + this.positionScreen = new Vector3(); + this.customUpdateCallback = undefined; - break; + if ( texture !== undefined ) { - } + this.add( texture, size, distance, blending, color ); - } + } - levels.splice( l, 0, { distance: distance, object: object } ); + }; - this.add( object ); + LensFlare.prototype = Object.assign( Object.create( Object3D.prototype ), { - }, + constructor: LensFlare, - getObjectForDistance: function ( distance ) { + isLensFlare: true, - var levels = this.levels; + copy: function ( source ) { - for ( var i = 1, l = levels.length; i < l; i ++ ) { + Object3D.prototype.copy.call( this, source ); - if ( distance < levels[ i ].distance ) { + this.positionScreen.copy( source.positionScreen ); + this.customUpdateCallback = source.customUpdateCallback; - break; + for ( var i = 0, l = source.lensFlares.length; i < l; i ++ ) { - } + this.lensFlares.push( source.lensFlares[ i ] ); - } + } - return levels[ i - 1 ].object; + return this; - }, + }, - raycast: ( function () { + add: function ( texture, size, distance, blending, color, opacity ) { - var matrixPosition = new Vector3(); + 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; - return function raycast( raycaster, intersects ) { + distance = Math.min( distance, Math.max( 0, distance ) ); - matrixPosition.setFromMatrixPosition( this.matrixWorld ); + 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 + } ); - var distance = raycaster.ray.origin.distanceTo( matrixPosition ); + }, - this.getObjectForDistance( distance ).raycast( raycaster, intersects ); + /* + * 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. + */ - }; + updateLensFlares: function () { - }() ), + var f, fl = this.lensFlares.length; + var flare; + var vecX = - this.positionScreen.x * 2; + var vecY = - this.positionScreen.y * 2; - update: function () { + for ( f = 0; f < fl; f ++ ) { - var v1 = new Vector3(); - var v2 = new Vector3(); + flare = this.lensFlares[ f ]; - return function update( camera ) { + flare.x = this.positionScreen.x + vecX * flare.distance; + flare.y = this.positionScreen.y + vecY * flare.distance; - var levels = this.levels; + flare.wantedRotation = flare.x * Math.PI * 0.25; + flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25; - if ( levels.length > 1 ) { + } - v1.setFromMatrixPosition( camera.matrixWorld ); - v2.setFromMatrixPosition( this.matrixWorld ); + } - var distance = v1.distanceTo( v2 ); + } ); - levels[ 0 ].object.visible = true; + /** + * @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 ); - levels[ i - 1 ].object.visible = false; - levels[ i ].object.visible = true; + this.type = 'SpriteMaterial'; - } else { + this.color = new Color( 0xffffff ); + this.map = null; - break; + this.rotation = 0; - } + this.fog = false; + this.lights = false; - } + this.setValues( parameters ); - for ( ; i < l; i ++ ) { + }; - levels[ i ].object.visible = false; + SpriteMaterial.prototype = Object.create( Material.prototype ); + SpriteMaterial.prototype.constructor = SpriteMaterial; - } + SpriteMaterial.prototype.copy = function ( source ) { - } + Material.prototype.copy.call( this, source ); - }; + this.color.copy( source.color ); + this.map = source.map; - }(), + this.rotation = source.rotation; - toJSON: function ( meta ) { + return this; - var data = Object3D.prototype.toJSON.call( this, meta ); + }; - data.object.levels = []; + /** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + */ - var levels = this.levels; + function Sprite( material ) { - for ( var i = 0, l = levels.length; i < l; i ++ ) { + Object3D.call( this ); - var level = levels[ i ]; + this.type = 'Sprite'; - data.object.levels.push( { - object: level.object.uuid, - distance: level.distance - } ); + this.material = ( material !== undefined ) ? material : new SpriteMaterial(); - } + }; - return data; + Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), { - } + constructor: Sprite, - } ); + isSprite: true, - /** - * @author alteredq / http://alteredqualia.com/ - */ + raycast: ( function () { - function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) { + var matrixPosition = new Vector3(); - Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); + return function raycast( raycaster, intersects ) { - this.image = { data: data, width: width, height: height }; + matrixPosition.setFromMatrixPosition( this.matrixWorld ); - this.magFilter = magFilter !== undefined ? magFilter : NearestFilter; - this.minFilter = minFilter !== undefined ? minFilter : NearestFilter; + var distanceSq = raycaster.ray.distanceSqToPoint( matrixPosition ); + var guessSizeSq = this.scale.x * this.scale.y / 4; - this.flipY = false; - this.generateMipmaps = false; + if ( distanceSq > guessSizeSq ) { - }; + return; - DataTexture.prototype = Object.create( Texture.prototype ); - DataTexture.prototype.constructor = DataTexture; + } - DataTexture.prototype.isDataTexture = true; + intersects.push( { - /** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author michael guerrero / http://realitymeltdown.com - * @author ikerr / http://verold.com - */ + distance: Math.sqrt( distanceSq ), + point: this.position, + face: null, + object: this - function Skeleton( bones, boneInverses, useVertexTexture ) { + } ); - this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true; + }; - this.identityMatrix = new Matrix4(); + }() ), - // copy the bone array + clone: function () { - bones = bones || []; + return new this.constructor( this.material ).copy( this ); - this.bones = bones.slice( 0 ); + } - // create a bone texture or an array of floats + } ); - if ( this.useVertexTexture ) { + /** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + */ - // 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) + function LOD() { + Object3D.call( this ); - 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.type = 'LOD'; - this.boneTextureWidth = size; - this.boneTextureHeight = size; + Object.defineProperties( this, { + levels: { + enumerable: true, + value: [] + } + } ); - 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 ); + }; - } else { - this.boneMatrices = new Float32Array( 16 * this.bones.length ); + LOD.prototype = Object.assign( Object.create( Object3D.prototype ), { - } + constructor: LOD, - // use the supplied bone inverses or calculate the inverses + copy: function ( source ) { - if ( boneInverses === undefined ) { + Object3D.prototype.copy.call( this, source, false ); - this.calculateInverses(); + var levels = source.levels; - } else { + for ( var i = 0, l = levels.length; i < l; i ++ ) { - if ( this.bones.length === boneInverses.length ) { + var level = levels[ i ]; - this.boneInverses = boneInverses.slice( 0 ); + this.addLevel( level.object.clone(), level.distance ); - } else { + } - console.warn( 'THREE.Skeleton bonInverses is the wrong length.' ); + return this; - this.boneInverses = []; + }, - for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { + addLevel: function ( object, distance ) { - this.boneInverses.push( new Matrix4() ); + if ( distance === undefined ) distance = 0; - } + distance = Math.abs( distance ); - } + var levels = this.levels; - } + for ( var l = 0; l < levels.length; l ++ ) { - }; + if ( distance < levels[ l ].distance ) { - Object.assign( Skeleton.prototype, { + break; - calculateInverses: function () { + } - this.boneInverses = []; + } - for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { + levels.splice( l, 0, { distance: distance, object: object } ); - var inverse = new Matrix4(); + this.add( object ); - if ( this.bones[ b ] ) { + }, - inverse.getInverse( this.bones[ b ].matrixWorld ); + getObjectForDistance: function ( distance ) { - } + var levels = this.levels; - this.boneInverses.push( inverse ); + for ( var i = 1, l = levels.length; i < l; i ++ ) { - } + if ( distance < levels[ i ].distance ) { - }, + break; - pose: function () { + } - var bone; + } - // recover the bind-time world matrices + return levels[ i - 1 ].object; - for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { + }, - bone = this.bones[ b ]; + raycast: ( function () { - if ( bone ) { + var matrixPosition = new Vector3(); - bone.matrixWorld.getInverse( this.boneInverses[ b ] ); + return function raycast( raycaster, intersects ) { - } + matrixPosition.setFromMatrixPosition( this.matrixWorld ); - } + var distance = raycaster.ray.origin.distanceTo( matrixPosition ); - // compute the local matrices, positions, rotations and scales + this.getObjectForDistance( distance ).raycast( raycaster, intersects ); - for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { + }; - bone = this.bones[ b ]; + }() ), - if ( bone ) { + update: function () { - if ( (bone.parent && bone.parent.isBone) ) { + var v1 = new Vector3(); + var v2 = new Vector3(); - bone.matrix.getInverse( bone.parent.matrixWorld ); - bone.matrix.multiply( bone.matrixWorld ); + return function update( camera ) { - } else { + var levels = this.levels; - bone.matrix.copy( bone.matrixWorld ); + if ( levels.length > 1 ) { - } + v1.setFromMatrixPosition( camera.matrixWorld ); + v2.setFromMatrixPosition( this.matrixWorld ); - bone.matrix.decompose( bone.position, bone.quaternion, bone.scale ); + var distance = v1.distanceTo( v2 ); - } + levels[ 0 ].object.visible = true; - } + for ( var i = 1, l = levels.length; i < l; i ++ ) { - }, + if ( distance >= levels[ i ].distance ) { - update: ( function () { + levels[ i - 1 ].object.visible = false; + levels[ i ].object.visible = true; - var offsetMatrix = new Matrix4(); + } else { - return function update() { + break; - // flatten bone matrices to array + } - for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { + } - // compute the offset between the current and the original transform + for ( ; i < l; i ++ ) { - var matrix = this.bones[ b ] ? this.bones[ b ].matrixWorld : this.identityMatrix; + levels[ i ].object.visible = false; - offsetMatrix.multiplyMatrices( matrix, this.boneInverses[ b ] ); - offsetMatrix.toArray( this.boneMatrices, b * 16 ); + } - } + } - if ( this.useVertexTexture ) { + }; - this.boneTexture.needsUpdate = true; + }(), - } + toJSON: function ( meta ) { - }; + var data = Object3D.prototype.toJSON.call( this, meta ); - } )(), + data.object.levels = []; - clone: function () { + var levels = this.levels; - return new Skeleton( this.bones, this.boneInverses, this.useVertexTexture ); + for ( var i = 0, l = levels.length; i < l; i ++ ) { - } + var level = levels[ i ]; - } ); + data.object.levels.push( { + object: level.object.uuid, + distance: level.distance + } ); - /** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author ikerr / http://verold.com - */ + } - function Bone( skin ) { + return data; - Object3D.call( this ); + } - this.type = 'Bone'; + } ); - this.skin = skin; + /** + * @author alteredq / http://alteredqualia.com/ + */ - }; + function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) { - Bone.prototype = Object.assign( Object.create( Object3D.prototype ), { + Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); - constructor: Bone, + this.image = { data: data, width: width, height: height }; - isBone: true, + this.magFilter = magFilter !== undefined ? magFilter : NearestFilter; + this.minFilter = minFilter !== undefined ? minFilter : NearestFilter; - copy: function ( source ) { + this.flipY = false; + this.generateMipmaps = false; - Object3D.prototype.copy.call( this, source ); + }; - this.skin = source.skin; + DataTexture.prototype = Object.create( Texture.prototype ); + DataTexture.prototype.constructor = DataTexture; - return this; + 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 + */ - } ); + function Skeleton( bones, boneInverses, useVertexTexture ) { - /** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author ikerr / http://verold.com - */ + this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true; - function SkinnedMesh( geometry, material, useVertexTexture ) { + this.identityMatrix = new Matrix4(); - Mesh.call( this, geometry, material ); + // copy the bone array - this.type = 'SkinnedMesh'; + bones = bones || []; - this.bindMode = "attached"; - this.bindMatrix = new Matrix4(); - this.bindMatrixInverse = new Matrix4(); + this.bones = bones.slice( 0 ); - // init bones + // create a bone texture or an array of floats - // TODO: remove bone creation as there is no reason (other than - // convenience) for THREE.SkinnedMesh to do this. + if ( this.useVertexTexture ) { - var bones = []; + // 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) - if ( this.geometry && this.geometry.bones !== undefined ) { - var bone, gbone; + 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 ); - for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) { + this.boneTextureWidth = size; + this.boneTextureHeight = size; - gbone = this.geometry.bones[ b ]; + 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 ); - bone = new Bone( this ); - bones.push( bone ); + } else { - bone.name = gbone.name; - bone.position.fromArray( gbone.pos ); - bone.quaternion.fromArray( gbone.rotq ); - if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl ); + this.boneMatrices = new Float32Array( 16 * this.bones.length ); - } + } - for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) { + // use the supplied bone inverses or calculate the inverses - gbone = this.geometry.bones[ b ]; + if ( boneInverses === undefined ) { - if ( gbone.parent !== - 1 && gbone.parent !== null && - bones[ gbone.parent ] !== undefined ) { + this.calculateInverses(); - bones[ gbone.parent ].add( bones[ b ] ); + } else { - } else { + if ( this.bones.length === boneInverses.length ) { - this.add( bones[ b ] ); + this.boneInverses = boneInverses.slice( 0 ); - } + } else { - } + console.warn( 'THREE.Skeleton bonInverses is the wrong length.' ); - } + this.boneInverses = []; - this.normalizeSkinWeights(); + for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { - this.updateMatrixWorld( true ); - this.bind( new Skeleton( bones, undefined, useVertexTexture ), this.matrixWorld ); + this.boneInverses.push( new Matrix4() ); - }; + } + } - SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), { + } - constructor: SkinnedMesh, + }; - isSkinnedMesh: true, + Object.assign( Skeleton.prototype, { - bind: function( skeleton, bindMatrix ) { + calculateInverses: function () { - this.skeleton = skeleton; + this.boneInverses = []; - if ( bindMatrix === undefined ) { + for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { - this.updateMatrixWorld( true ); + var inverse = new Matrix4(); - this.skeleton.calculateInverses(); + if ( this.bones[ b ] ) { - bindMatrix = this.matrixWorld; + inverse.getInverse( this.bones[ b ].matrixWorld ); - } + } - this.bindMatrix.copy( bindMatrix ); - this.bindMatrixInverse.getInverse( bindMatrix ); + this.boneInverses.push( inverse ); - }, + } - pose: function () { + }, - this.skeleton.pose(); + pose: function () { - }, + var bone; - normalizeSkinWeights: function () { + // recover the bind-time world matrices - 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 ++ ) { + bone = this.bones[ b ]; - var sw = this.geometry.skinWeights[ i ]; + if ( bone ) { - var scale = 1.0 / sw.lengthManhattan(); + bone.matrixWorld.getInverse( this.boneInverses[ b ] ); - if ( scale !== Infinity ) { + } - sw.multiplyScalar( scale ); + } - } else { + // compute the local matrices, positions, rotations and scales - sw.set( 1, 0, 0, 0 ); // do something reasonable + for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { - } + bone = this.bones[ b ]; - } + if ( bone ) { - } else if ( (this.geometry && this.geometry.isBufferGeometry) ) { + if ( (bone.parent && bone.parent.isBone) ) { - var vec = new Vector4(); + bone.matrix.getInverse( bone.parent.matrixWorld ); + bone.matrix.multiply( bone.matrixWorld ); - var skinWeight = this.geometry.attributes.skinWeight; + } else { - for ( var i = 0; i < skinWeight.count; i ++ ) { + bone.matrix.copy( bone.matrixWorld ); - vec.x = skinWeight.getX( i ); - vec.y = skinWeight.getY( i ); - vec.z = skinWeight.getZ( i ); - vec.w = skinWeight.getW( i ); + } - var scale = 1.0 / vec.lengthManhattan(); + bone.matrix.decompose( bone.position, bone.quaternion, bone.scale ); - if ( scale !== Infinity ) { + } - vec.multiplyScalar( scale ); + } - } else { + }, - vec.set( 1, 0, 0, 0 ); // do something reasonable + update: ( function () { - } + var offsetMatrix = new Matrix4(); - skinWeight.setXYZW( i, vec.x, vec.y, vec.z, vec.w ); + return function update() { - } + // flatten bone matrices to array - } + for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { - }, + // compute the offset between the current and the original transform - updateMatrixWorld: function( force ) { + var matrix = this.bones[ b ] ? this.bones[ b ].matrixWorld : this.identityMatrix; - Mesh.prototype.updateMatrixWorld.call( this, true ); + offsetMatrix.multiplyMatrices( matrix, this.boneInverses[ b ] ); + offsetMatrix.toArray( this.boneMatrices, b * 16 ); - if ( this.bindMode === "attached" ) { + } - this.bindMatrixInverse.getInverse( this.matrixWorld ); + if ( this.useVertexTexture ) { - } else if ( this.bindMode === "detached" ) { + this.boneTexture.needsUpdate = true; - this.bindMatrixInverse.getInverse( this.bindMatrix ); + } - } else { + }; - console.warn( 'THREE.SkinnedMesh unrecognized bindMode: ' + this.bindMode ); + } )(), - } + clone: function () { - }, + return new Skeleton( this.bones, this.boneInverses, this.useVertexTexture ); - clone: function() { + } - return new this.constructor( this.geometry, this.material, this.skeleton.useVertexTexture ).copy( this ); + } ); - } + /** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + * @author ikerr / http://verold.com + */ - } ); + function Bone( skin ) { - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * opacity: , - * - * linewidth: , - * linecap: "round", - * linejoin: "round" - * } - */ + Object3D.call( this ); - function LineBasicMaterial( parameters ) { + this.type = 'Bone'; - Material.call( this ); + this.skin = skin; - this.type = 'LineBasicMaterial'; + }; - this.color = new Color( 0xffffff ); + Bone.prototype = Object.assign( Object.create( Object3D.prototype ), { - this.linewidth = 1; - this.linecap = 'round'; - this.linejoin = 'round'; + constructor: Bone, - this.lights = false; + isBone: true, - this.setValues( parameters ); + copy: function ( source ) { - }; + Object3D.prototype.copy.call( this, source ); - LineBasicMaterial.prototype = Object.create( Material.prototype ); - LineBasicMaterial.prototype.constructor = LineBasicMaterial; + this.skin = source.skin; - LineBasicMaterial.prototype.isLineBasicMaterial = true; + return this; - LineBasicMaterial.prototype.copy = function ( source ) { + } - Material.prototype.copy.call( this, source ); + } ); - this.color.copy( source.color ); + /** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + * @author ikerr / http://verold.com + */ - this.linewidth = source.linewidth; - this.linecap = source.linecap; - this.linejoin = source.linejoin; + function SkinnedMesh( geometry, material, useVertexTexture ) { - return this; + Mesh.call( this, geometry, material ); - }; + this.type = 'SkinnedMesh'; - /** - * @author mrdoob / http://mrdoob.com/ - */ + this.bindMode = "attached"; + this.bindMatrix = new Matrix4(); + this.bindMatrixInverse = new Matrix4(); - function Line( geometry, material, mode ) { + // init bones - if ( mode === 1 ) { + // TODO: remove bone creation as there is no reason (other than + // convenience) for THREE.SkinnedMesh to do this. - console.warn( 'THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.' ); - return new LineSegments( geometry, material ); + var bones = []; - } + if ( this.geometry && this.geometry.bones !== undefined ) { - Object3D.call( this ); + var bone, gbone; - this.type = 'Line'; + for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) { - this.geometry = geometry !== undefined ? geometry : new BufferGeometry(); - this.material = material !== undefined ? material : new LineBasicMaterial( { color: Math.random() * 0xffffff } ); + gbone = this.geometry.bones[ b ]; - }; + bone = new Bone( this ); + bones.push( bone ); - Line.prototype = Object.assign( Object.create( Object3D.prototype ), { + bone.name = gbone.name; + bone.position.fromArray( gbone.pos ); + bone.quaternion.fromArray( gbone.rotq ); + if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl ); - constructor: Line, + } - isLine: true, + for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) { - raycast: ( function () { + gbone = this.geometry.bones[ b ]; - var inverseMatrix = new Matrix4(); - var ray = new Ray(); - var sphere = new Sphere(); + if ( gbone.parent !== - 1 && gbone.parent !== null && + bones[ gbone.parent ] !== undefined ) { - return function raycast( raycaster, intersects ) { + bones[ gbone.parent ].add( bones[ b ] ); - var precision = raycaster.linePrecision; - var precisionSq = precision * precision; + } else { - var geometry = this.geometry; - var matrixWorld = this.matrixWorld; + this.add( bones[ b ] ); - // Checking boundingSphere distance to ray + } - if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + } - sphere.copy( geometry.boundingSphere ); - sphere.applyMatrix4( matrixWorld ); + } - if ( raycaster.ray.intersectsSphere( sphere ) === false ) return; + this.normalizeSkinWeights(); - // + this.updateMatrixWorld( true ); + this.bind( new Skeleton( bones, undefined, useVertexTexture ), this.matrixWorld ); - inverseMatrix.getInverse( matrixWorld ); - ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); + }; - var vStart = new Vector3(); - var vEnd = new Vector3(); - var interSegment = new Vector3(); - var interRay = new Vector3(); - var step = (this && this.isLineSegments) ? 2 : 1; - if ( (geometry && geometry.isBufferGeometry) ) { + SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), { - var index = geometry.index; - var attributes = geometry.attributes; - var positions = attributes.position.array; + constructor: SkinnedMesh, - if ( index !== null ) { + isSkinnedMesh: true, - var indices = index.array; + bind: function( skeleton, bindMatrix ) { - for ( var i = 0, l = indices.length - 1; i < l; i += step ) { + this.skeleton = skeleton; - var a = indices[ i ]; - var b = indices[ i + 1 ]; + if ( bindMatrix === undefined ) { - vStart.fromArray( positions, a * 3 ); - vEnd.fromArray( positions, b * 3 ); + this.updateMatrixWorld( true ); - var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); + this.skeleton.calculateInverses(); - if ( distSq > precisionSq ) continue; + bindMatrix = this.matrixWorld; - interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation + } - var distance = raycaster.ray.origin.distanceTo( interRay ); + this.bindMatrix.copy( bindMatrix ); + this.bindMatrixInverse.getInverse( bindMatrix ); - if ( distance < raycaster.near || distance > raycaster.far ) continue; + }, - intersects.push( { + pose: function () { - 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.skeleton.pose(); - } ); + }, - } + normalizeSkinWeights: function () { - } else { + if ( (this.geometry && this.geometry.isGeometry) ) { - for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) { + for ( var i = 0; i < this.geometry.skinWeights.length; i ++ ) { - vStart.fromArray( positions, 3 * i ); - vEnd.fromArray( positions, 3 * i + 3 ); + var sw = this.geometry.skinWeights[ i ]; - var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); + var scale = 1.0 / sw.lengthManhattan(); - if ( distSq > precisionSq ) continue; + if ( scale !== Infinity ) { - interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation + sw.multiplyScalar( scale ); - var distance = raycaster.ray.origin.distanceTo( interRay ); + } else { - if ( distance < raycaster.near || distance > raycaster.far ) continue; + sw.set( 1, 0, 0, 0 ); // do something reasonable - intersects.push( { + } - 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 + } - } ); + } else if ( (this.geometry && this.geometry.isBufferGeometry) ) { - } + var vec = new Vector4(); - } + var skinWeight = this.geometry.attributes.skinWeight; - } else if ( (geometry && geometry.isGeometry) ) { + for ( var i = 0; i < skinWeight.count; i ++ ) { - var vertices = geometry.vertices; - var nbVertices = vertices.length; + vec.x = skinWeight.getX( i ); + vec.y = skinWeight.getY( i ); + vec.z = skinWeight.getZ( i ); + vec.w = skinWeight.getW( i ); - for ( var i = 0; i < nbVertices - 1; i += step ) { + var scale = 1.0 / vec.lengthManhattan(); - var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment ); + if ( scale !== Infinity ) { - if ( distSq > precisionSq ) continue; + vec.multiplyScalar( scale ); - interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation + } else { - var distance = raycaster.ray.origin.distanceTo( interRay ); + vec.set( 1, 0, 0, 0 ); // do something reasonable - if ( distance < raycaster.near || distance > raycaster.far ) continue; + } - intersects.push( { + skinWeight.setXYZW( i, vec.x, vec.y, vec.z, vec.w ); - 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 + } - } ); + } - } + }, - } + updateMatrixWorld: function( force ) { - }; + Mesh.prototype.updateMatrixWorld.call( this, true ); - }() ), + if ( this.bindMode === "attached" ) { - clone: function () { + this.bindMatrixInverse.getInverse( this.matrixWorld ); - return new this.constructor( this.geometry, this.material ).copy( this ); + } else if ( this.bindMode === "detached" ) { - } + this.bindMatrixInverse.getInverse( this.bindMatrix ); - } ); + } else { - /** - * @author mrdoob / http://mrdoob.com/ - */ + console.warn( 'THREE.SkinnedMesh unrecognized bindMode: ' + this.bindMode ); - function LineSegments( geometry, material ) { + } - Line.call( this, geometry, material ); + }, - this.type = 'LineSegments'; + clone: function() { - }; + return new this.constructor( this.geometry, this.material, this.skeleton.useVertexTexture ).copy( this ); - LineSegments.prototype = Object.assign( Object.create( Line.prototype ), { + } - constructor: LineSegments, + } ); - isLineSegments: true + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * color: , + * opacity: , + * + * linewidth: , + * linecap: "round", + * linejoin: "round" + * } + */ - } ); + function LineBasicMaterial( parameters ) { - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * opacity: , - * map: new THREE.Texture( ), - * - * size: , - * sizeAttenuation: - * } - */ + Material.call( this ); - function PointsMaterial( parameters ) { + this.type = 'LineBasicMaterial'; - Material.call( this ); + this.color = new Color( 0xffffff ); - this.type = 'PointsMaterial'; + this.linewidth = 1; + this.linecap = 'round'; + this.linejoin = 'round'; - this.color = new Color( 0xffffff ); + this.lights = false; - this.map = null; + this.setValues( parameters ); - this.size = 1; - this.sizeAttenuation = true; + }; - this.lights = false; + LineBasicMaterial.prototype = Object.create( Material.prototype ); + LineBasicMaterial.prototype.constructor = LineBasicMaterial; - this.setValues( parameters ); + LineBasicMaterial.prototype.isLineBasicMaterial = true; - }; + LineBasicMaterial.prototype.copy = function ( source ) { - PointsMaterial.prototype = Object.create( Material.prototype ); - PointsMaterial.prototype.constructor = PointsMaterial; + Material.prototype.copy.call( this, source ); - PointsMaterial.prototype.isPointsMaterial = true; + this.color.copy( source.color ); - PointsMaterial.prototype.copy = function ( source ) { + this.linewidth = source.linewidth; + this.linecap = source.linecap; + this.linejoin = source.linejoin; - Material.prototype.copy.call( this, source ); + return this; - this.color.copy( source.color ); + }; - this.map = source.map; + /** + * @author mrdoob / http://mrdoob.com/ + */ - this.size = source.size; - this.sizeAttenuation = source.sizeAttenuation; + function Line( geometry, material, mode ) { - return this; + if ( mode === 1 ) { - }; + console.warn( 'THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.' ); + return new LineSegments( geometry, material ); - /** - * @author alteredq / http://alteredqualia.com/ - */ + } - function Points( geometry, material ) { + Object3D.call( this ); - Object3D.call( this ); + this.type = 'Line'; - this.type = 'Points'; + this.geometry = geometry !== undefined ? geometry : new BufferGeometry(); + this.material = material !== undefined ? material : new LineBasicMaterial( { color: Math.random() * 0xffffff } ); - this.geometry = geometry !== undefined ? geometry : new BufferGeometry(); - this.material = material !== undefined ? material : new PointsMaterial( { color: Math.random() * 0xffffff } ); + }; - }; + Line.prototype = Object.assign( Object.create( Object3D.prototype ), { - Points.prototype = Object.assign( Object.create( Object3D.prototype ), { + constructor: Line, - constructor: Points, + isLine: true, - isPoints: true, + raycast: ( function () { - raycast: ( function () { + var inverseMatrix = new Matrix4(); + var ray = new Ray(); + var sphere = new Sphere(); - var inverseMatrix = new Matrix4(); - var ray = new Ray(); - var sphere = new Sphere(); + return function raycast( raycaster, intersects ) { - return function raycast( raycaster, intersects ) { + var precision = raycaster.linePrecision; + var precisionSq = precision * precision; - var object = this; - var geometry = this.geometry; - var matrixWorld = this.matrixWorld; - var threshold = raycaster.params.Points.threshold; + var geometry = this.geometry; + var matrixWorld = this.matrixWorld; - // Checking boundingSphere distance to ray + // Checking boundingSphere distance to ray - if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); - sphere.copy( geometry.boundingSphere ); - sphere.applyMatrix4( matrixWorld ); + sphere.copy( geometry.boundingSphere ); + sphere.applyMatrix4( matrixWorld ); - if ( raycaster.ray.intersectsSphere( sphere ) === false ) return; + if ( raycaster.ray.intersectsSphere( sphere ) === false ) return; - // + // - inverseMatrix.getInverse( matrixWorld ); - ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); + inverseMatrix.getInverse( matrixWorld ); + ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); - var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 ); - var localThresholdSq = localThreshold * localThreshold; - var position = new Vector3(); + var vStart = new Vector3(); + var vEnd = new Vector3(); + var interSegment = new Vector3(); + var interRay = new Vector3(); + var step = (this && this.isLineSegments) ? 2 : 1; - function testPoint( point, index ) { + if ( (geometry && geometry.isBufferGeometry) ) { - var rayPointDistanceSq = ray.distanceSqToPoint( point ); + var index = geometry.index; + var attributes = geometry.attributes; + var positions = attributes.position.array; - if ( rayPointDistanceSq < localThresholdSq ) { + if ( index !== null ) { - var intersectPoint = ray.closestPointToPoint( point ); - intersectPoint.applyMatrix4( matrixWorld ); + var indices = index.array; - var distance = raycaster.ray.origin.distanceTo( intersectPoint ); + for ( var i = 0, l = indices.length - 1; i < l; i += step ) { - if ( distance < raycaster.near || distance > raycaster.far ) return; + var a = indices[ i ]; + var b = indices[ i + 1 ]; - intersects.push( { + vStart.fromArray( positions, a * 3 ); + vEnd.fromArray( positions, b * 3 ); - distance: distance, - distanceToRay: Math.sqrt( rayPointDistanceSq ), - point: intersectPoint.clone(), - index: index, - face: null, - object: object + var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); - } ); + if ( distSq > precisionSq ) continue; - } + interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation - } + var distance = raycaster.ray.origin.distanceTo( interRay ); - if ( (geometry && geometry.isBufferGeometry) ) { + if ( distance < raycaster.near || distance > raycaster.far ) continue; - var index = geometry.index; - var attributes = geometry.attributes; - var positions = attributes.position.array; + intersects.push( { - if ( index !== null ) { + 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 indices = index.array; + } ); - for ( var i = 0, il = indices.length; i < il; i ++ ) { + } - var a = indices[ i ]; + } else { - position.fromArray( positions, a * 3 ); + for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) { - testPoint( position, a ); + vStart.fromArray( positions, 3 * i ); + vEnd.fromArray( positions, 3 * i + 3 ); - } + var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); - } else { + if ( distSq > precisionSq ) continue; - for ( var i = 0, l = positions.length / 3; i < l; i ++ ) { + interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation - position.fromArray( positions, i * 3 ); + var distance = raycaster.ray.origin.distanceTo( interRay ); - testPoint( position, i ); + if ( distance < raycaster.near || distance > raycaster.far ) continue; - } + intersects.push( { - } + 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 - } else { + } ); - var vertices = geometry.vertices; + } - for ( var i = 0, l = vertices.length; i < l; i ++ ) { + } - testPoint( vertices[ i ], i ); + } else if ( (geometry && geometry.isGeometry) ) { - } + 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; - clone: function () { + interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation - return new this.constructor( this.geometry, this.material ).copy( this ); + var distance = raycaster.ray.origin.distanceTo( interRay ); - } + if ( distance < raycaster.near || distance > raycaster.far ) continue; - } ); + intersects.push( { - /** - * @author mrdoob / http://mrdoob.com/ - */ + 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 - function Group() { + } ); - Object3D.call( this ); + } - this.type = 'Group'; + } - }; + }; - Group.prototype = Object.assign( Object.create( Object3D.prototype ), { + }() ), - constructor: Group + clone: function () { - } ); + return new this.constructor( this.geometry, this.material ).copy( this ); - /** - * @author mrdoob / http://mrdoob.com/ - */ + } - function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { + } ); - Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + /** + * @author mrdoob / http://mrdoob.com/ + */ - this.generateMipmaps = false; + function LineSegments( geometry, material ) { - var scope = this; + Line.call( this, geometry, material ); - function update() { + this.type = 'LineSegments'; - requestAnimationFrame( update ); + }; - if ( video.readyState >= video.HAVE_CURRENT_DATA ) { + LineSegments.prototype = Object.assign( Object.create( Line.prototype ), { - scope.needsUpdate = true; + constructor: LineSegments, - } + isLineSegments: true - } + } ); - update(); + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * color: , + * opacity: , + * map: new THREE.Texture( ), + * + * size: , + * sizeAttenuation: + * } + */ - }; + function PointsMaterial( parameters ) { - VideoTexture.prototype = Object.create( Texture.prototype ); - VideoTexture.prototype.constructor = VideoTexture; + Material.call( this ); - /** - * @author alteredq / http://alteredqualia.com/ - */ + this.type = 'PointsMaterial'; - function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) { + this.color = new Color( 0xffffff ); - Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); + this.map = null; - this.image = { width: width, height: height }; - this.mipmaps = mipmaps; + this.size = 1; + this.sizeAttenuation = true; - // no flipping for cube textures - // (also flipping doesn't work for compressed textures ) + this.lights = false; - this.flipY = false; + this.setValues( parameters ); - // can't generate mipmaps for compressed textures - // mips must be embedded in DDS files + }; - this.generateMipmaps = false; + PointsMaterial.prototype = Object.create( Material.prototype ); + PointsMaterial.prototype.constructor = PointsMaterial; - }; + PointsMaterial.prototype.isPointsMaterial = true; - CompressedTexture.prototype = Object.create( Texture.prototype ); - CompressedTexture.prototype.constructor = CompressedTexture; + PointsMaterial.prototype.copy = function ( source ) { - CompressedTexture.prototype.isCompressedTexture = true; + Material.prototype.copy.call( this, source ); - /** - * @author mrdoob / http://mrdoob.com/ - */ + this.color.copy( source.color ); - function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { + this.map = source.map; - Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + this.size = source.size; + this.sizeAttenuation = source.sizeAttenuation; - this.needsUpdate = true; + return this; - }; + }; - CanvasTexture.prototype = Object.create( Texture.prototype ); - CanvasTexture.prototype.constructor = CanvasTexture; + /** + * @author alteredq / http://alteredqualia.com/ + */ - /** - * @author Matt DesLauriers / @mattdesl - * @author atix / arthursilber.de - */ + function Points( geometry, material ) { - function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) { + Object3D.call( this ); - format = format !== undefined ? format : DepthFormat; + this.type = 'Points'; - if ( format !== DepthFormat && format !== DepthStencilFormat ) { + this.geometry = geometry !== undefined ? geometry : new BufferGeometry(); + this.material = material !== undefined ? material : new PointsMaterial( { color: Math.random() * 0xffffff } ); - throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' ) + }; - } + Points.prototype = Object.assign( Object.create( Object3D.prototype ), { - Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + constructor: Points, - this.image = { width: width, height: height }; + isPoints: true, - this.type = type !== undefined ? type : UnsignedShortType; + raycast: ( function () { - this.magFilter = magFilter !== undefined ? magFilter : NearestFilter; - this.minFilter = minFilter !== undefined ? minFilter : NearestFilter; + var inverseMatrix = new Matrix4(); + var ray = new Ray(); + var sphere = new Sphere(); - this.flipY = false; - this.generateMipmaps = false; + return function raycast( raycaster, intersects ) { - }; + var object = this; + var geometry = this.geometry; + var matrixWorld = this.matrixWorld; + var threshold = raycaster.params.Points.threshold; - DepthTexture.prototype = Object.create( Texture.prototype ); - DepthTexture.prototype.constructor = DepthTexture; - DepthTexture.prototype.isDepthTexture = true; + // Checking boundingSphere distance to ray - /** - * @author mrdoob / http://mrdoob.com/ - */ + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); - function ShadowMaterial() { + sphere.copy( geometry.boundingSphere ); + sphere.applyMatrix4( matrixWorld ); - ShaderMaterial.call( this, { - uniforms: exports.UniformsUtils.merge( [ - exports.UniformsLib[ "lights" ], - { - opacity: { value: 1.0 } - } - ] ), - vertexShader: ShaderChunk[ 'shadow_vert' ], - fragmentShader: ShaderChunk[ 'shadow_frag' ] - } ); + if ( raycaster.ray.intersectsSphere( sphere ) === false ) return; - 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; - } - } - } ); + inverseMatrix.getInverse( matrixWorld ); + ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); - }; + var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 ); + var localThresholdSq = localThreshold * localThreshold; + var position = new Vector3(); - ShadowMaterial.prototype = Object.create( ShaderMaterial.prototype ); - ShadowMaterial.prototype.constructor = ShadowMaterial; + function testPoint( point, index ) { - ShadowMaterial.prototype.isShadowMaterial = true; + var rayPointDistanceSq = ray.distanceSqToPoint( point ); - /** - * @author mrdoob / http://mrdoob.com/ - */ + if ( rayPointDistanceSq < localThresholdSq ) { - function RawShaderMaterial( parameters ) { + var intersectPoint = ray.closestPointToPoint( point ); + intersectPoint.applyMatrix4( matrixWorld ); - ShaderMaterial.call( this, parameters ); + var distance = raycaster.ray.origin.distanceTo( intersectPoint ); - this.type = 'RawShaderMaterial'; + if ( distance < raycaster.near || distance > raycaster.far ) return; - }; + intersects.push( { - RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype ); - RawShaderMaterial.prototype.constructor = RawShaderMaterial; + distance: distance, + distanceToRay: Math.sqrt( rayPointDistanceSq ), + point: intersectPoint.clone(), + index: index, + face: null, + object: object - RawShaderMaterial.prototype.isRawShaderMaterial = true; + } ); - /** - * @author mrdoob / http://mrdoob.com/ - */ + } - function MultiMaterial( materials ) { + } - this.uuid = exports.Math.generateUUID(); + if ( (geometry && geometry.isBufferGeometry) ) { - this.type = 'MultiMaterial'; + var index = geometry.index; + var attributes = geometry.attributes; + var positions = attributes.position.array; - this.materials = materials instanceof Array ? materials : []; + if ( index !== null ) { - this.visible = true; + var indices = index.array; - }; + for ( var i = 0, il = indices.length; i < il; i ++ ) { - MultiMaterial.prototype = { + var a = indices[ i ]; - constructor: MultiMaterial, + position.fromArray( positions, a * 3 ); - isMultiMaterial: true, + testPoint( position, a ); - toJSON: function ( meta ) { + } - var output = { - metadata: { - version: 4.2, - type: 'material', - generator: 'MaterialExporter' - }, - uuid: this.uuid, - type: this.type, - materials: [] - }; + } else { - var materials = this.materials; + for ( var i = 0, l = positions.length / 3; i < l; i ++ ) { - for ( var i = 0, l = materials.length; i < l; i ++ ) { + position.fromArray( positions, i * 3 ); - var material = materials[ i ].toJSON( meta ); - delete material.metadata; + testPoint( position, i ); - output.materials.push( material ); + } - } + } - output.visible = this.visible; + } else { - return output; + var vertices = geometry.vertices; - }, + for ( var i = 0, l = vertices.length; i < l; i ++ ) { - clone: function () { + testPoint( vertices[ i ], i ); - var material = new this.constructor(); + } - for ( var i = 0; i < this.materials.length; i ++ ) { + } - material.materials.push( this.materials[ i ].clone() ); + }; - } + }() ), - material.visible = this.visible; + clone: function () { - return material; + return new this.constructor( this.geometry, this.material ).copy( this ); - } + } - }; + } ); - /** - * @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: - * } - */ + /** + * @author mrdoob / http://mrdoob.com/ + */ - function MeshStandardMaterial( parameters ) { + function Group() { - Material.call( this ); + Object3D.call( this ); - this.defines = { 'STANDARD': '' }; + this.type = 'Group'; - this.type = 'MeshStandardMaterial'; + }; - this.color = new Color( 0xffffff ); // diffuse - this.roughness = 0.5; - this.metalness = 0.5; + Group.prototype = Object.assign( Object.create( Object3D.prototype ), { - this.map = null; + constructor: Group - this.lightMap = null; - this.lightMapIntensity = 1.0; + } ); - this.aoMap = null; - this.aoMapIntensity = 1.0; + /** + * @author mrdoob / http://mrdoob.com/ + */ - this.emissive = new Color( 0x000000 ); - this.emissiveIntensity = 1.0; - this.emissiveMap = null; + function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { - this.bumpMap = null; - this.bumpScale = 1; + Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); - this.normalMap = null; - this.normalScale = new Vector2( 1, 1 ); + this.generateMipmaps = false; - this.displacementMap = null; - this.displacementScale = 1; - this.displacementBias = 0; + var scope = this; - this.roughnessMap = null; + function update() { - this.metalnessMap = null; + requestAnimationFrame( update ); - this.alphaMap = null; + if ( video.readyState >= video.HAVE_CURRENT_DATA ) { - this.envMap = null; - this.envMapIntensity = 1.0; + scope.needsUpdate = true; - 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; + update(); - this.setValues( parameters ); + }; - }; + VideoTexture.prototype = Object.create( Texture.prototype ); + VideoTexture.prototype.constructor = VideoTexture; - MeshStandardMaterial.prototype = Object.create( Material.prototype ); - MeshStandardMaterial.prototype.constructor = MeshStandardMaterial; + /** + * @author alteredq / http://alteredqualia.com/ + */ - MeshStandardMaterial.prototype.isMeshStandardMaterial = true; + function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) { - MeshStandardMaterial.prototype.copy = function ( source ) { + Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); - Material.prototype.copy.call( this, source ); + 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.color.copy( source.color ); - this.roughness = source.roughness; - this.metalness = source.metalness; + this.flipY = false; - this.map = source.map; + // can't generate mipmaps for compressed textures + // mips must be embedded in DDS files - this.lightMap = source.lightMap; - this.lightMapIntensity = source.lightMapIntensity; + this.generateMipmaps = false; - this.aoMap = source.aoMap; - this.aoMapIntensity = source.aoMapIntensity; + }; - this.emissive.copy( source.emissive ); - this.emissiveMap = source.emissiveMap; - this.emissiveIntensity = source.emissiveIntensity; + CompressedTexture.prototype = Object.create( Texture.prototype ); + CompressedTexture.prototype.constructor = CompressedTexture; - this.bumpMap = source.bumpMap; - this.bumpScale = source.bumpScale; + CompressedTexture.prototype.isCompressedTexture = 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 CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { - this.roughnessMap = source.roughnessMap; + Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); - this.metalnessMap = source.metalnessMap; + this.needsUpdate = true; - this.alphaMap = source.alphaMap; + }; - this.envMap = source.envMap; - this.envMapIntensity = source.envMapIntensity; + CanvasTexture.prototype = Object.create( Texture.prototype ); + CanvasTexture.prototype.constructor = CanvasTexture; - this.refractionRatio = source.refractionRatio; + /** + * @author Matt DesLauriers / @mattdesl + * @author atix / arthursilber.de + */ - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; - this.wireframeLinecap = source.wireframeLinecap; - this.wireframeLinejoin = source.wireframeLinejoin; + function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) { - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; - this.morphNormals = source.morphNormals; + format = format !== undefined ? format : DepthFormat; - return this; + if ( format !== DepthFormat && format !== DepthStencilFormat ) { - }; + throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' ) - /** - * @author WestLangley / http://github.com/WestLangley - * - * parameters = { - * reflectivity: - * } - */ + } - function MeshPhysicalMaterial( parameters ) { + Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); - MeshStandardMaterial.call( this ); + this.image = { width: width, height: height }; - this.defines = { 'PHYSICAL': '' }; + this.type = type !== undefined ? type : UnsignedShortType; - this.type = 'MeshPhysicalMaterial'; + this.magFilter = magFilter !== undefined ? magFilter : NearestFilter; + this.minFilter = minFilter !== undefined ? minFilter : NearestFilter; - this.reflectivity = 0.5; // maps to F0 = 0.04 + this.flipY = false; + this.generateMipmaps = false; - this.clearCoat = 0.0; - this.clearCoatRoughness = 0.0; + }; - this.setValues( parameters ); + 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.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; + } + } + } ); - MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype ); - MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial; + }; - MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true; + ShadowMaterial.prototype = Object.create( ShaderMaterial.prototype ); + ShadowMaterial.prototype.constructor = ShadowMaterial; - MeshPhysicalMaterial.prototype.copy = function ( source ) { + ShadowMaterial.prototype.isShadowMaterial = true; - MeshStandardMaterial.prototype.copy.call( this, source ); + /** + * @author mrdoob / http://mrdoob.com/ + */ - this.defines = { 'PHYSICAL': '' }; + function RawShaderMaterial( parameters ) { - this.reflectivity = source.reflectivity; + ShaderMaterial.call( this, parameters ); - this.clearCoat = source.clearCoat; - this.clearCoatRoughness = source.clearCoatRoughness; + this.type = 'RawShaderMaterial'; - return this; + }; - }; + RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype ); + RawShaderMaterial.prototype.constructor = RawShaderMaterial; - /** - * @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: - * } - */ + RawShaderMaterial.prototype.isRawShaderMaterial = true; - function MeshPhongMaterial( parameters ) { + /** + * @author mrdoob / http://mrdoob.com/ + */ - Material.call( this ); + function MultiMaterial( materials ) { - this.type = 'MeshPhongMaterial'; + this.uuid = exports.Math.generateUUID(); - this.color = new Color( 0xffffff ); // diffuse - this.specular = new Color( 0x111111 ); - this.shininess = 30; + this.type = 'MultiMaterial'; - this.map = null; + this.materials = materials instanceof Array ? materials : []; - this.lightMap = null; - this.lightMapIntensity = 1.0; + this.visible = true; - this.aoMap = null; - this.aoMapIntensity = 1.0; + }; - this.emissive = new Color( 0x000000 ); - this.emissiveIntensity = 1.0; - this.emissiveMap = null; + MultiMaterial.prototype = { - this.bumpMap = null; - this.bumpScale = 1; + constructor: MultiMaterial, - this.normalMap = null; - this.normalScale = new Vector2( 1, 1 ); + isMultiMaterial: true, - this.displacementMap = null; - this.displacementScale = 1; - this.displacementBias = 0; + toJSON: function ( meta ) { - this.specularMap = null; + var output = { + metadata: { + version: 4.2, + type: 'material', + generator: 'MaterialExporter' + }, + uuid: this.uuid, + type: this.type, + materials: [] + }; - this.alphaMap = null; + var materials = this.materials; - this.envMap = null; - this.combine = MultiplyOperation; - this.reflectivity = 1; - this.refractionRatio = 0.98; + for ( var i = 0, l = materials.length; i < l; i ++ ) { - this.wireframe = false; - this.wireframeLinewidth = 1; - this.wireframeLinecap = 'round'; - this.wireframeLinejoin = 'round'; + var material = materials[ i ].toJSON( meta ); + delete material.metadata; - this.skinning = false; - this.morphTargets = false; - this.morphNormals = false; + output.materials.push( material ); - this.setValues( parameters ); + } - }; + output.visible = this.visible; - MeshPhongMaterial.prototype = Object.create( Material.prototype ); - MeshPhongMaterial.prototype.constructor = MeshPhongMaterial; + return output; - MeshPhongMaterial.prototype.isMeshPhongMaterial = true; + }, - MeshPhongMaterial.prototype.copy = function ( source ) { + clone: function () { - Material.prototype.copy.call( this, source ); + var material = new this.constructor(); - this.color.copy( source.color ); - this.specular.copy( source.specular ); - this.shininess = source.shininess; + for ( var i = 0; i < this.materials.length; i ++ ) { - this.map = source.map; + material.materials.push( this.materials[ i ].clone() ); - this.lightMap = source.lightMap; - this.lightMapIntensity = source.lightMapIntensity; + } - this.aoMap = source.aoMap; - this.aoMapIntensity = source.aoMapIntensity; + material.visible = this.visible; - this.emissive.copy( source.emissive ); - this.emissiveMap = source.emissiveMap; - this.emissiveIntensity = source.emissiveIntensity; + return material; - this.bumpMap = source.bumpMap; - this.bumpScale = source.bumpScale; + } - this.normalMap = source.normalMap; - this.normalScale.copy( source.normalScale ); + }; - this.displacementMap = source.displacementMap; - this.displacementScale = source.displacementScale; - this.displacementBias = source.displacementBias; + /** + * @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.specularMap = source.specularMap; + }; - this.alphaMap = source.alphaMap; + MeshStandardMaterial.prototype = Object.create( Material.prototype ); + MeshStandardMaterial.prototype.constructor = MeshStandardMaterial; - this.envMap = source.envMap; - this.combine = source.combine; - this.reflectivity = source.reflectivity; - this.refractionRatio = source.refractionRatio; + MeshStandardMaterial.prototype.isMeshStandardMaterial = true; - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; - this.wireframeLinecap = source.wireframeLinecap; - this.wireframeLinejoin = source.wireframeLinejoin; + MeshStandardMaterial.prototype.copy = function ( source ) { - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; - this.morphNormals = source.morphNormals; + Material.prototype.copy.call( this, source ); - return this; + this.defines = { 'STANDARD': '' }; - }; + this.color.copy( source.color ); + this.roughness = source.roughness; + this.metalness = source.metalness; - /** - * @author mrdoob / http://mrdoob.com/ - * - * parameters = { - * opacity: , - * - * wireframe: , - * wireframeLinewidth: - * } - */ + this.map = source.map; - function MeshNormalMaterial( parameters ) { + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; - Material.call( this, parameters ); + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; - this.type = 'MeshNormalMaterial'; + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; - this.wireframe = false; - this.wireframeLinewidth = 1; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; - this.fog = false; - this.lights = false; - this.morphTargets = false; + this.normalMap = source.normalMap; + this.normalScale.copy( source.normalScale ); - this.setValues( parameters ); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; - }; + this.roughnessMap = source.roughnessMap; - MeshNormalMaterial.prototype = Object.create( Material.prototype ); - MeshNormalMaterial.prototype.constructor = MeshNormalMaterial; + this.metalnessMap = source.metalnessMap; - MeshNormalMaterial.prototype.isMeshNormalMaterial = true; + this.alphaMap = source.alphaMap; - MeshNormalMaterial.prototype.copy = function ( source ) { + this.envMap = source.envMap; + this.envMapIntensity = source.envMapIntensity; - Material.prototype.copy.call( this, source ); + this.refractionRatio = source.refractionRatio; - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; - return this; + this.skinning = source.skinning; + this.morphTargets = source.morphTargets; + this.morphNormals = source.morphNormals; - }; + return this; - /** - * @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 ) { + /** + * @author WestLangley / http://github.com/WestLangley + * + * parameters = { + * reflectivity: + * } + */ - Material.call( this ); + function MeshPhysicalMaterial( parameters ) { - this.type = 'MeshLambertMaterial'; + MeshStandardMaterial.call( this ); - this.color = new Color( 0xffffff ); // diffuse + this.defines = { 'PHYSICAL': '' }; - this.map = null; + this.type = 'MeshPhysicalMaterial'; - this.lightMap = null; - this.lightMapIntensity = 1.0; + this.reflectivity = 0.5; // maps to F0 = 0.04 - this.aoMap = null; - this.aoMapIntensity = 1.0; + this.clearCoat = 0.0; + this.clearCoatRoughness = 0.0; - this.emissive = new Color( 0x000000 ); - this.emissiveIntensity = 1.0; - this.emissiveMap = null; + this.setValues( parameters ); - this.specularMap = null; + }; - this.alphaMap = null; + MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype ); + MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial; - this.envMap = null; - this.combine = MultiplyOperation; - this.reflectivity = 1; - this.refractionRatio = 0.98; + MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true; - this.wireframe = false; - this.wireframeLinewidth = 1; - this.wireframeLinecap = 'round'; - this.wireframeLinejoin = 'round'; + MeshPhysicalMaterial.prototype.copy = function ( source ) { - this.skinning = false; - this.morphTargets = false; - this.morphNormals = false; + MeshStandardMaterial.prototype.copy.call( this, source ); - this.setValues( parameters ); + this.defines = { 'PHYSICAL': '' }; - }; + this.reflectivity = source.reflectivity; - MeshLambertMaterial.prototype = Object.create( Material.prototype ); - MeshLambertMaterial.prototype.constructor = MeshLambertMaterial; + this.clearCoat = source.clearCoat; + this.clearCoatRoughness = source.clearCoatRoughness; - MeshLambertMaterial.prototype.isMeshLambertMaterial = true; + return this; - MeshLambertMaterial.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.color.copy( source.color ); + }; - this.map = source.map; + MeshPhongMaterial.prototype = Object.create( Material.prototype ); + MeshPhongMaterial.prototype.constructor = MeshPhongMaterial; - this.lightMap = source.lightMap; - this.lightMapIntensity = source.lightMapIntensity; + MeshPhongMaterial.prototype.isMeshPhongMaterial = true; - this.aoMap = source.aoMap; - this.aoMapIntensity = source.aoMapIntensity; + MeshPhongMaterial.prototype.copy = function ( source ) { - this.emissive.copy( source.emissive ); - this.emissiveMap = source.emissiveMap; - this.emissiveIntensity = source.emissiveIntensity; + Material.prototype.copy.call( this, source ); - this.specularMap = source.specularMap; + this.color.copy( source.color ); + this.specular.copy( source.specular ); + this.shininess = source.shininess; - this.alphaMap = source.alphaMap; + this.map = source.map; - this.envMap = source.envMap; - this.combine = source.combine; - this.reflectivity = source.reflectivity; - this.refractionRatio = source.refractionRatio; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; - this.wireframeLinecap = source.wireframeLinecap; - this.wireframeLinejoin = source.wireframeLinejoin; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; - this.morphNormals = source.morphNormals; + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; - return this; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; - }; + this.normalMap = source.normalMap; + this.normalScale.copy( source.normalScale ); - /** - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * opacity: , - * - * linewidth: , - * - * scale: , - * dashSize: , - * gapSize: - * } - */ + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; - function LineDashedMaterial( parameters ) { + this.specularMap = source.specularMap; - Material.call( this ); + this.alphaMap = source.alphaMap; - this.type = 'LineDashedMaterial'; + this.envMap = source.envMap; + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; - this.color = new Color( 0xffffff ); + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; - this.linewidth = 1; + this.skinning = source.skinning; + this.morphTargets = source.morphTargets; + this.morphNormals = source.morphNormals; - this.scale = 1; - this.dashSize = 3; - this.gapSize = 1; + return this; - this.lights = false; + }; - this.setValues( parameters ); + /** + * @author mrdoob / http://mrdoob.com/ + * + * parameters = { + * opacity: , + * + * wireframe: , + * wireframeLinewidth: + * } + */ - }; + function MeshNormalMaterial( parameters ) { - LineDashedMaterial.prototype = Object.create( Material.prototype ); - LineDashedMaterial.prototype.constructor = LineDashedMaterial; + Material.call( this, parameters ); - LineDashedMaterial.prototype.isLineDashedMaterial = true; + this.type = 'MeshNormalMaterial'; - LineDashedMaterial.prototype.copy = function ( source ) { + this.wireframe = false; + this.wireframeLinewidth = 1; - Material.prototype.copy.call( this, source ); + this.fog = false; + this.lights = false; + this.morphTargets = false; - this.color.copy( source.color ); + this.setValues( parameters ); - this.linewidth = source.linewidth; + }; - this.scale = source.scale; - this.dashSize = source.dashSize; - this.gapSize = source.gapSize; + MeshNormalMaterial.prototype = Object.create( Material.prototype ); + MeshNormalMaterial.prototype.constructor = MeshNormalMaterial; - return this; + MeshNormalMaterial.prototype.isMeshNormalMaterial = true; - }; + MeshNormalMaterial.prototype.copy = function ( source ) { - /** - * @author mrdoob / http://mrdoob.com/ - */ + Material.prototype.copy.call( this, source ); - exports.Cache = { + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; - enabled: false, + return this; - files: {}, + }; - add: function ( key, file ) { + /** + * @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 ); - if ( this.enabled === false ) return; + }; - // console.log( 'THREE.Cache', 'Adding key:', key ); + MeshLambertMaterial.prototype = Object.create( Material.prototype ); + MeshLambertMaterial.prototype.constructor = MeshLambertMaterial; - this.files[ key ] = file; + MeshLambertMaterial.prototype.isMeshLambertMaterial = true; - }, + MeshLambertMaterial.prototype.copy = function ( source ) { - get: function ( key ) { + Material.prototype.copy.call( this, source ); - if ( this.enabled === false ) return; + this.color.copy( source.color ); - // console.log( 'THREE.Cache', 'Checking key:', key ); + this.map = source.map; - return this.files[ key ]; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; - }, + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; - remove: function ( key ) { + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; - delete this.files[ key ]; + this.specularMap = source.specularMap; - }, + this.alphaMap = source.alphaMap; - clear: function () { + this.envMap = source.envMap; + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; - this.files = {}; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; - } + this.skinning = source.skinning; + this.morphTargets = source.morphTargets; + this.morphNormals = source.morphNormals; - }; + return this; - /** - * @author mrdoob / http://mrdoob.com/ - */ + }; - function LoadingManager( onLoad, onProgress, onError ) { + /** + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * color: , + * opacity: , + * + * linewidth: , + * + * scale: , + * dashSize: , + * gapSize: + * } + */ - var scope = this; + function LineDashedMaterial( parameters ) { - var isLoading = false, itemsLoaded = 0, itemsTotal = 0; + Material.call( this ); - this.onStart = undefined; - this.onLoad = onLoad; - this.onProgress = onProgress; - this.onError = onError; + this.type = 'LineDashedMaterial'; - this.itemStart = function ( url ) { + this.color = new Color( 0xffffff ); - itemsTotal ++; + this.linewidth = 1; - if ( isLoading === false ) { + this.scale = 1; + this.dashSize = 3; + this.gapSize = 1; - if ( scope.onStart !== undefined ) { + this.lights = false; - scope.onStart( url, itemsLoaded, itemsTotal ); + this.setValues( parameters ); - } + }; - } + LineDashedMaterial.prototype = Object.create( Material.prototype ); + LineDashedMaterial.prototype.constructor = LineDashedMaterial; - isLoading = true; + LineDashedMaterial.prototype.isLineDashedMaterial = true; - }; + LineDashedMaterial.prototype.copy = function ( source ) { - this.itemEnd = function ( url ) { + Material.prototype.copy.call( this, source ); - itemsLoaded ++; + this.color.copy( source.color ); - if ( scope.onProgress !== undefined ) { + this.linewidth = source.linewidth; - scope.onProgress( url, itemsLoaded, itemsTotal ); + this.scale = source.scale; + this.dashSize = source.dashSize; + this.gapSize = source.gapSize; - } + return this; - if ( itemsLoaded === itemsTotal ) { + }; - isLoading = false; + /** + * @author mrdoob / http://mrdoob.com/ + */ - if ( scope.onLoad !== undefined ) { + exports.Cache = { - scope.onLoad(); + enabled: false, - } + files: {}, - } + add: function ( key, file ) { - }; + if ( this.enabled === false ) return; - this.itemError = function ( url ) { + // console.log( 'THREE.Cache', 'Adding key:', key ); - if ( scope.onError !== undefined ) { + this.files[ key ] = file; - scope.onError( url ); + }, - } + get: function ( key ) { - }; + if ( this.enabled === false ) return; - }; + // console.log( 'THREE.Cache', 'Checking key:', key ); - exports.DefaultLoadingManager = new LoadingManager(); + return this.files[ key ]; - /** - * @author mrdoob / http://mrdoob.com/ - */ + }, - function XHRLoader( manager ) { + remove: function ( key ) { - this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; + delete this.files[ key ]; - }; + }, - Object.assign( XHRLoader.prototype, { + clear: function () { - load: function ( url, onLoad, onProgress, onError ) { + this.files = {}; - if ( this.path !== undefined ) url = this.path + url; + } - var scope = this; + }; - var cached = exports.Cache.get( url ); + /** + * @author mrdoob / http://mrdoob.com/ + */ - if ( cached !== undefined ) { + function LoadingManager( onLoad, onProgress, onError ) { - scope.manager.itemStart( url ); + var scope = this; - setTimeout( function () { + var isLoading = false, itemsLoaded = 0, itemsTotal = 0; - if ( onLoad ) onLoad( cached ); + this.onStart = undefined; + this.onLoad = onLoad; + this.onProgress = onProgress; + this.onError = onError; - scope.manager.itemEnd( url ); + this.itemStart = function ( url ) { - }, 0 ); + itemsTotal ++; - return cached; + if ( isLoading === false ) { - } + if ( scope.onStart !== undefined ) { - var request = new XMLHttpRequest(); - request.overrideMimeType( 'text/plain' ); - request.open( 'GET', url, true ); + scope.onStart( url, itemsLoaded, itemsTotal ); - request.addEventListener( 'load', function ( event ) { + } - var response = event.target.response; + } - exports.Cache.add( url, response ); + isLoading = true; - if ( this.status === 200 ) { + }; - if ( onLoad ) onLoad( response ); + this.itemEnd = function ( url ) { - scope.manager.itemEnd( url ); + itemsLoaded ++; - } else if ( this.status === 0 ) { + if ( scope.onProgress !== undefined ) { - // Some browsers return HTTP Status 0 when using non-http protocol - // e.g. 'file://' or 'data://'. Handle as success. + scope.onProgress( url, itemsLoaded, itemsTotal ); - console.warn( 'THREE.XHRLoader: HTTP Status 0 received.' ); + } - if ( onLoad ) onLoad( response ); + if ( itemsLoaded === itemsTotal ) { - scope.manager.itemEnd( url ); + isLoading = false; - } else { + if ( scope.onLoad !== undefined ) { - if ( onError ) onError( event ); + scope.onLoad(); - scope.manager.itemError( url ); + } - } + } - }, false ); + }; - if ( onProgress !== undefined ) { + this.itemError = function ( url ) { - request.addEventListener( 'progress', function ( event ) { + if ( scope.onError !== undefined ) { - onProgress( event ); + scope.onError( url ); - }, false ); + } - } + }; - request.addEventListener( 'error', function ( event ) { + }; - if ( onError ) onError( event ); + exports.DefaultLoadingManager = new LoadingManager(); - scope.manager.itemError( url ); + /** + * @author mrdoob / http://mrdoob.com/ + */ - }, false ); + function XHRLoader( manager ) { - if ( this.responseType !== undefined ) request.responseType = this.responseType; - if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials; + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; - request.send( null ); + }; - scope.manager.itemStart( url ); + Object.assign( XHRLoader.prototype, { - return request; + load: function ( url, onLoad, onProgress, onError ) { - }, + if ( this.path !== undefined ) url = this.path + url; - setPath: function ( value ) { + var scope = this; - this.path = value; - return this; + var cached = exports.Cache.get( url ); - }, + if ( cached !== undefined ) { - setResponseType: function ( value ) { + scope.manager.itemStart( url ); - this.responseType = value; - return this; + setTimeout( function () { - }, + if ( onLoad ) onLoad( cached ); - setWithCredentials: function ( value ) { + scope.manager.itemEnd( url ); - this.withCredentials = value; - return this; + }, 0 ); - } + return cached; - } ); + } - /** - * @author mrdoob / http://mrdoob.com/ - * - * Abstract Base class to block based textures loader (dds, pvr, ...) - */ + var request = new XMLHttpRequest(); + request.overrideMimeType( 'text/plain' ); + request.open( 'GET', url, true ); - function CompressedTextureLoader( manager ) { + request.addEventListener( 'load', function ( event ) { - this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; + var response = event.target.response; - // override in sub classes - this._parser = null; + exports.Cache.add( url, response ); - }; + if ( this.status === 200 ) { - Object.assign( CompressedTextureLoader.prototype, { + if ( onLoad ) onLoad( response ); - load: function ( url, onLoad, onProgress, onError ) { + scope.manager.itemEnd( url ); - var scope = this; + } else if ( this.status === 0 ) { - var images = []; + // Some browsers return HTTP Status 0 when using non-http protocol + // e.g. 'file://' or 'data://'. Handle as success. - var texture = new CompressedTexture(); - texture.image = images; + console.warn( 'THREE.XHRLoader: HTTP Status 0 received.' ); - var loader = new XHRLoader( this.manager ); - loader.setPath( this.path ); - loader.setResponseType( 'arraybuffer' ); + if ( onLoad ) onLoad( response ); - function loadTexture( i ) { + scope.manager.itemEnd( url ); - loader.load( url[ i ], function ( buffer ) { + } else { - var texDatas = scope._parser( buffer, true ); + if ( onError ) onError( event ); - images[ i ] = { - width: texDatas.width, - height: texDatas.height, - format: texDatas.format, - mipmaps: texDatas.mipmaps - }; + scope.manager.itemError( url ); - loaded += 1; + } - if ( loaded === 6 ) { + }, false ); - if ( texDatas.mipmapCount === 1 ) - texture.minFilter = LinearFilter; + if ( onProgress !== undefined ) { - texture.format = texDatas.format; - texture.needsUpdate = true; + request.addEventListener( 'progress', function ( event ) { - if ( onLoad ) onLoad( texture ); + onProgress( event ); - } + }, false ); - }, onProgress, onError ); + } - } + request.addEventListener( 'error', function ( event ) { - if ( Array.isArray( url ) ) { + if ( onError ) onError( event ); - var loaded = 0; + scope.manager.itemError( url ); - for ( var i = 0, il = url.length; i < il; ++ i ) { + }, false ); - loadTexture( i ); + if ( this.responseType !== undefined ) request.responseType = this.responseType; + if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials; - } + request.send( null ); - } else { + scope.manager.itemStart( url ); - // compressed cubemap texture stored in a single DDS file + return request; - loader.load( url, function ( buffer ) { + }, - var texDatas = scope._parser( buffer, true ); + setPath: function ( value ) { - if ( texDatas.isCubemap ) { + this.path = value; + return this; - var faces = texDatas.mipmaps.length / texDatas.mipmapCount; + }, - for ( var f = 0; f < faces; f ++ ) { + setResponseType: function ( value ) { - images[ f ] = { mipmaps : [] }; + this.responseType = value; + return this; - for ( var i = 0; i < texDatas.mipmapCount; i ++ ) { + }, - 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; + setWithCredentials: function ( value ) { - } + this.withCredentials = value; + return this; - } + } - } else { + } ); - texture.image.width = texDatas.width; - texture.image.height = texDatas.height; - texture.mipmaps = texDatas.mipmaps; + /** + * @author mrdoob / http://mrdoob.com/ + * + * Abstract Base class to block based textures loader (dds, pvr, ...) + */ - } + function CompressedTextureLoader( manager ) { - if ( texDatas.mipmapCount === 1 ) { + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; - texture.minFilter = LinearFilter; + // override in sub classes + this._parser = null; - } + }; - texture.format = texDatas.format; - texture.needsUpdate = true; + Object.assign( CompressedTextureLoader.prototype, { - if ( onLoad ) onLoad( texture ); + load: function ( url, onLoad, onProgress, onError ) { - }, onProgress, onError ); + var scope = this; - } + var images = []; - return texture; + var texture = new CompressedTexture(); + texture.image = images; - }, + var loader = new XHRLoader( this.manager ); + loader.setPath( this.path ); + loader.setResponseType( 'arraybuffer' ); - setPath: function ( value ) { + function loadTexture( i ) { - this.path = value; - return this; + loader.load( url[ i ], function ( buffer ) { - } + var texDatas = scope._parser( buffer, true ); - } ); + images[ i ] = { + width: texDatas.width, + height: texDatas.height, + format: texDatas.format, + mipmaps: texDatas.mipmaps + }; - /** - * @author Nikos M. / https://github.com/foo123/ - * - * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...) - */ + loaded += 1; - var DataTextureLoader = BinaryTextureLoader; - function BinaryTextureLoader( manager ) { + if ( loaded === 6 ) { - this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; + if ( texDatas.mipmapCount === 1 ) + texture.minFilter = LinearFilter; - // override in sub classes - this._parser = null; + texture.format = texDatas.format; + texture.needsUpdate = true; - }; + if ( onLoad ) onLoad( texture ); - Object.assign( BinaryTextureLoader.prototype, { + } - load: function ( url, onLoad, onProgress, onError ) { + }, onProgress, onError ); - var scope = this; + } - var texture = new DataTexture(); + if ( Array.isArray( url ) ) { - var loader = new XHRLoader( this.manager ); - loader.setResponseType( 'arraybuffer' ); + var loaded = 0; - loader.load( url, function ( buffer ) { + for ( var i = 0, il = url.length; i < il; ++ i ) { - var texData = scope._parser( buffer ); + loadTexture( i ); - if ( ! texData ) return; + } - if ( undefined !== texData.image ) { + } else { - texture.image = texData.image; + // compressed cubemap texture stored in a single DDS file - } else if ( undefined !== texData.data ) { + loader.load( url, function ( buffer ) { - texture.image.width = texData.width; - texture.image.height = texData.height; - texture.image.data = texData.data; + var texDatas = scope._parser( buffer, true ); - } + if ( texDatas.isCubemap ) { - texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : ClampToEdgeWrapping; - texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : ClampToEdgeWrapping; + var faces = texDatas.mipmaps.length / texDatas.mipmapCount; - texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : LinearFilter; - texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : LinearMipMapLinearFilter; + for ( var f = 0; f < faces; f ++ ) { - texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1; + images[ f ] = { mipmaps : [] }; - if ( undefined !== texData.format ) { + for ( var i = 0; i < texDatas.mipmapCount; i ++ ) { - texture.format = texData.format; + 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; - } - if ( undefined !== texData.type ) { + } - texture.type = texData.type; + } - } + } else { - if ( undefined !== texData.mipmaps ) { + texture.image.width = texDatas.width; + texture.image.height = texDatas.height; + texture.mipmaps = texDatas.mipmaps; - texture.mipmaps = texData.mipmaps; + } - } + if ( texDatas.mipmapCount === 1 ) { - if ( 1 === texData.mipmapCount ) { + texture.minFilter = LinearFilter; - texture.minFilter = LinearFilter; + } - } + texture.format = texDatas.format; + texture.needsUpdate = true; - texture.needsUpdate = true; + if ( onLoad ) onLoad( texture ); - if ( onLoad ) onLoad( texture, texData ); + }, onProgress, onError ); - }, onProgress, onError ); + } + return texture; - return texture; + }, - } + setPath: function ( value ) { - } ); + this.path = value; + return this; - /** - * @author mrdoob / http://mrdoob.com/ - */ + } - function ImageLoader( manager ) { + } ); - this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; + /** + * @author Nikos M. / https://github.com/foo123/ + * + * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...) + */ - }; + var DataTextureLoader = BinaryTextureLoader; + function BinaryTextureLoader( manager ) { - Object.assign( ImageLoader.prototype, { + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; - load: function ( url, onLoad, onProgress, onError ) { + // override in sub classes + this._parser = null; - var scope = this; + }; - var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' ); - image.onload = function () { + Object.assign( BinaryTextureLoader.prototype, { - URL.revokeObjectURL( image.src ); + load: function ( url, onLoad, onProgress, onError ) { - if ( onLoad ) onLoad( image ); + var scope = this; - scope.manager.itemEnd( url ); + var texture = new DataTexture(); - }; + var loader = new XHRLoader( this.manager ); + loader.setResponseType( 'arraybuffer' ); - if ( url.indexOf( 'data:' ) === 0 ) { + loader.load( url, function ( buffer ) { - image.src = url; + var texData = scope._parser( buffer ); - } else { + if ( ! texData ) return; - var loader = new XHRLoader(); - loader.setPath( this.path ); - loader.setResponseType( 'blob' ); - loader.setWithCredentials( this.withCredentials ); - loader.load( url, function ( blob ) { + if ( undefined !== texData.image ) { - image.src = URL.createObjectURL( blob ); + 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; - scope.manager.itemStart( url ); + } - return image; + 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; - setCrossOrigin: function ( value ) { + texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1; - this.crossOrigin = value; - return this; + if ( undefined !== texData.format ) { - }, + texture.format = texData.format; - setWithCredentials: function ( value ) { + } + if ( undefined !== texData.type ) { - this.withCredentials = value; - return this; + texture.type = texData.type; - }, + } - setPath: function ( value ) { + if ( undefined !== texData.mipmaps ) { - this.path = value; - return this; + texture.mipmaps = texData.mipmaps; - } + } - } ); + if ( 1 === texData.mipmapCount ) { - /** - * @author mrdoob / http://mrdoob.com/ - */ + texture.minFilter = LinearFilter; - function CubeTextureLoader( manager ) { + } - this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; + texture.needsUpdate = true; - }; + if ( onLoad ) onLoad( texture, texData ); - Object.assign( CubeTextureLoader.prototype, { + }, onProgress, onError ); - load: function ( urls, onLoad, onProgress, onError ) { - var texture = new CubeTexture(); + return texture; - var loader = new ImageLoader( this.manager ); - loader.setCrossOrigin( this.crossOrigin ); - loader.setPath( this.path ); + } - var loaded = 0; + } ); - function loadTexture( i ) { + /** + * @author mrdoob / http://mrdoob.com/ + */ - loader.load( urls[ i ], function ( image ) { + function ImageLoader( manager ) { - texture.images[ i ] = image; + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; - loaded ++; + }; - if ( loaded === 6 ) { + Object.assign( ImageLoader.prototype, { - texture.needsUpdate = true; + load: function ( url, onLoad, onProgress, onError ) { - if ( onLoad ) onLoad( texture ); + var scope = this; - } + var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' ); + image.onload = function () { - }, undefined, onError ); + URL.revokeObjectURL( image.src ); - } + if ( onLoad ) onLoad( image ); - for ( var i = 0; i < urls.length; ++ i ) { + scope.manager.itemEnd( url ); - loadTexture( i ); + }; - } + if ( url.indexOf( 'data:' ) === 0 ) { - return texture; + image.src = url; - }, + } else { - setCrossOrigin: function ( value ) { + var loader = new XHRLoader(); + loader.setPath( this.path ); + loader.setResponseType( 'blob' ); + loader.setWithCredentials( this.withCredentials ); + loader.load( url, function ( blob ) { - this.crossOrigin = value; - return this; + image.src = URL.createObjectURL( blob ); - }, + }, onProgress, onError ); - setPath: function ( value ) { + } - this.path = value; - return this; + scope.manager.itemStart( url ); - } + return image; - } ); + }, - /** - * @author mrdoob / http://mrdoob.com/ - */ + setCrossOrigin: function ( value ) { - function TextureLoader( manager ) { + this.crossOrigin = value; + return this; - this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; + }, - }; + setWithCredentials: function ( value ) { - Object.assign( TextureLoader.prototype, { + this.withCredentials = value; + return this; - load: function ( url, onLoad, onProgress, onError ) { + }, - var texture = new Texture(); + setPath: function ( value ) { - var loader = new ImageLoader( this.manager ); - loader.setCrossOrigin( this.crossOrigin ); - loader.setWithCredentials( this.withCredentials ); - loader.setPath( this.path ); - loader.load( url, function ( image ) { + this.path = value; + return this; - // 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; + } - texture.format = isJPEG ? RGBFormat : RGBAFormat; - texture.image = image; - texture.needsUpdate = true; + } ); - if ( onLoad !== undefined ) { + /** + * @author mrdoob / http://mrdoob.com/ + */ - onLoad( texture ); + function CubeTextureLoader( manager ) { - } + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; - }, onProgress, onError ); + }; - return texture; + Object.assign( CubeTextureLoader.prototype, { - }, + load: function ( urls, onLoad, onProgress, onError ) { - setCrossOrigin: function ( value ) { + var texture = new CubeTexture(); - this.crossOrigin = value; - return this; + var loader = new ImageLoader( this.manager ); + loader.setCrossOrigin( this.crossOrigin ); + loader.setPath( this.path ); - }, + var loaded = 0; - setWithCredentials: function ( value ) { + function loadTexture( i ) { - this.withCredentials = value; - return this; + loader.load( urls[ i ], function ( image ) { - }, + texture.images[ i ] = image; - setPath: function ( value ) { + loaded ++; - this.path = value; - return this; + if ( loaded === 6 ) { - } + texture.needsUpdate = true; + if ( onLoad ) onLoad( texture ); + } - } ); + }, undefined, onError ); - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + } - function Light( color, intensity ) { + for ( var i = 0; i < urls.length; ++ i ) { - Object3D.call( this ); + loadTexture( i ); - this.type = 'Light'; + } - this.color = new Color( color ); - this.intensity = intensity !== undefined ? intensity : 1; + return texture; - this.receiveShadow = undefined; + }, - }; + setCrossOrigin: function ( value ) { - Light.prototype = Object.assign( Object.create( Object3D.prototype ), { + this.crossOrigin = value; + return this; - constructor: Light, + }, - isLight: true, + setPath: function ( value ) { - copy: function ( source ) { + this.path = value; + return this; - Object3D.prototype.copy.call( this, source ); + } - this.color.copy( source.color ); - this.intensity = source.intensity; + } ); - return this; + /** + * @author mrdoob / http://mrdoob.com/ + */ - }, + function TextureLoader( manager ) { - toJSON: function ( meta ) { + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; - var data = Object3D.prototype.toJSON.call( this, meta ); + }; - data.object.color = this.color.getHex(); - data.object.intensity = this.intensity; + Object.assign( TextureLoader.prototype, { - if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex(); + load: function ( url, onLoad, onProgress, onError ) { - 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; + var texture = new Texture(); - return data; + 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; - } ); + texture.format = isJPEG ? RGBFormat : RGBAFormat; + texture.image = image; + texture.needsUpdate = true; - /** - * @author alteredq / http://alteredqualia.com/ - */ + if ( onLoad !== undefined ) { - function HemisphereLight( skyColor, groundColor, intensity ) { + onLoad( texture ); - Light.call( this, skyColor, intensity ); + } - this.type = 'HemisphereLight'; + }, onProgress, onError ); - this.castShadow = undefined; + return texture; - this.position.copy( Object3D.DefaultUp ); - this.updateMatrix(); + }, - this.groundColor = new Color( groundColor ); + setCrossOrigin: function ( value ) { - }; + this.crossOrigin = value; + return this; - HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), { + }, - constructor: HemisphereLight, + setWithCredentials: function ( value ) { - isHemisphereLight: true, + this.withCredentials = value; + return this; - copy: function ( source ) { + }, - Light.prototype.copy.call( this, source ); + setPath: function ( value ) { - this.groundColor.copy( source.groundColor ); + this.path = value; + return this; - return this; + } - } - } ); - /** - * @author mrdoob / http://mrdoob.com/ - */ + } ); - function LightShadow( camera ) { + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - this.camera = camera; + function Light( color, intensity ) { - this.bias = 0; - this.radius = 1; + Object3D.call( this ); - this.mapSize = new Vector2( 512, 512 ); + this.type = 'Light'; - this.map = null; - this.matrix = new Matrix4(); + this.color = new Color( color ); + this.intensity = intensity !== undefined ? intensity : 1; - }; + this.receiveShadow = undefined; - Object.assign( LightShadow.prototype, { + }; - copy: function ( source ) { + Light.prototype = Object.assign( Object.create( Object3D.prototype ), { - this.camera = source.camera.clone(); + constructor: Light, - this.bias = source.bias; - this.radius = source.radius; + isLight: true, - this.mapSize.copy( source.mapSize ); + copy: function ( source ) { - return this; + Object3D.prototype.copy.call( this, source ); - }, + this.color.copy( source.color ); + this.intensity = source.intensity; - clone: function () { + return this; - return new this.constructor().copy( this ); + }, - } + toJSON: function ( meta ) { - } ); + var data = Object3D.prototype.toJSON.call( this, meta ); - /** - * @author mrdoob / http://mrdoob.com/ - */ + data.object.color = this.color.getHex(); + data.object.intensity = this.intensity; - function SpotLightShadow() { + if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex(); - LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) ); + 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; - }; + return data; - SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), { + } - constructor: SpotLightShadow, + } ); - isSpotLightShadow: true, + /** + * @author alteredq / http://alteredqualia.com/ + */ - update: function ( light ) { + function HemisphereLight( skyColor, groundColor, intensity ) { - var fov = exports.Math.RAD2DEG * 2 * light.angle; - var aspect = this.mapSize.width / this.mapSize.height; - var far = light.distance || 500; + Light.call( this, skyColor, intensity ); - var camera = this.camera; + this.type = 'HemisphereLight'; - if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) { + this.castShadow = undefined; - camera.fov = fov; - camera.aspect = aspect; - camera.far = far; - camera.updateProjectionMatrix(); + this.position.copy( Object3D.DefaultUp ); + this.updateMatrix(); - } + this.groundColor = new Color( groundColor ); - } + }; - } ); + HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), { - /** - * @author alteredq / http://alteredqualia.com/ - */ + constructor: HemisphereLight, - function SpotLight( color, intensity, distance, angle, penumbra, decay ) { + isHemisphereLight: true, - Light.call( this, color, intensity ); + copy: function ( source ) { - this.type = 'SpotLight'; + Light.prototype.copy.call( this, source ); - this.position.copy( Object3D.DefaultUp ); - this.updateMatrix(); + this.groundColor.copy( source.groundColor ); - this.target = new Object3D(); + return this; - 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; - } - } ); + } - 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. + } ); - this.shadow = new SpotLightShadow(); + /** + * @author mrdoob / http://mrdoob.com/ + */ - }; + function LightShadow( camera ) { - SpotLight.prototype = Object.assign( Object.create( Light.prototype ), { + this.camera = camera; - constructor: SpotLight, + this.bias = 0; + this.radius = 1; - isSpotLight: true, + this.mapSize = new Vector2( 512, 512 ); - copy: function ( source ) { + this.map = null; + this.matrix = new Matrix4(); - Light.prototype.copy.call( this, source ); + }; - this.distance = source.distance; - this.angle = source.angle; - this.penumbra = source.penumbra; - this.decay = source.decay; + Object.assign( LightShadow.prototype, { - this.target = source.target.clone(); + copy: function ( source ) { - this.shadow = source.shadow.clone(); + this.camera = source.camera.clone(); - return this; + this.bias = source.bias; + this.radius = source.radius; - } + this.mapSize.copy( source.mapSize ); - } ); + return this; - /** - * @author mrdoob / http://mrdoob.com/ - */ + }, + clone: function () { - function PointLight( color, intensity, distance, decay ) { + return new this.constructor().copy( this ); - 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 mrdoob / http://mrdoob.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 SpotLightShadow() { - this.distance = ( distance !== undefined ) ? distance : 0; - this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2. + LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) ); - this.shadow = new LightShadow( new PerspectiveCamera( 90, 1, 0.5, 500 ) ); + }; - }; + SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), { - PointLight.prototype = Object.assign( Object.create( Light.prototype ), { + constructor: SpotLightShadow, - constructor: PointLight, + isSpotLightShadow: true, - isPointLight: true, + update: function ( light ) { - copy: function ( source ) { + var fov = exports.Math.RAD2DEG * 2 * light.angle; + var aspect = this.mapSize.width / this.mapSize.height; + var far = light.distance || 500; - Light.prototype.copy.call( this, source ); + var camera = this.camera; - this.distance = source.distance; - this.decay = source.decay; + if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) { - this.shadow = source.shadow.clone(); + camera.fov = fov; + camera.aspect = aspect; + camera.far = far; + camera.updateProjectionMatrix(); - return this; + } - } + } - } ); + } ); - /** - * @author mrdoob / http://mrdoob.com/ - */ + /** + * @author alteredq / http://alteredqualia.com/ + */ - function DirectionalLightShadow( light ) { + function SpotLight( color, intensity, distance, angle, penumbra, decay ) { - LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) ); + Light.call( this, color, intensity ); - }; + this.type = 'SpotLight'; - DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), { + this.position.copy( Object3D.DefaultUp ); + this.updateMatrix(); - constructor: DirectionalLightShadow + this.target = new Object3D(); - } ); + 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; + } + } ); - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + 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. - function DirectionalLight( color, intensity ) { + this.shadow = new SpotLightShadow(); - Light.call( this, color, intensity ); + }; - this.type = 'DirectionalLight'; + SpotLight.prototype = Object.assign( Object.create( Light.prototype ), { - this.position.copy( Object3D.DefaultUp ); - this.updateMatrix(); + constructor: SpotLight, - this.target = new Object3D(); + isSpotLight: true, - this.shadow = new DirectionalLightShadow(); + copy: function ( source ) { - }; + Light.prototype.copy.call( this, source ); - DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), { + this.distance = source.distance; + this.angle = source.angle; + this.penumbra = source.penumbra; + this.decay = source.decay; - constructor: DirectionalLight, + this.target = source.target.clone(); - isDirectionalLight: true, + this.shadow = source.shadow.clone(); - copy: function ( source ) { + return this; - Light.prototype.copy.call( this, source ); + } - this.target = source.target.clone(); + } ); - this.shadow = source.shadow.clone(); + /** + * @author mrdoob / http://mrdoob.com/ + */ - return this; - } + function PointLight( color, intensity, distance, decay ) { - } ); + Light.call( this, color, intensity ); - /** - * @author mrdoob / http://mrdoob.com/ - */ + this.type = 'PointLight'; - function AmbientLight( color, intensity ) { + 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; - Light.call( this, color, intensity ); + }, + 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.type = 'AmbientLight'; + this.distance = ( distance !== undefined ) ? distance : 0; + this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2. - this.castShadow = undefined; + this.shadow = new LightShadow( new PerspectiveCamera( 90, 1, 0.5, 500 ) ); - }; + }; - AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), { + PointLight.prototype = Object.assign( Object.create( Light.prototype ), { - constructor: AmbientLight, + constructor: PointLight, - isAmbientLight: true, + isPointLight: true, - } ); + copy: function ( source ) { - /** - * @author tschw - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - */ + Light.prototype.copy.call( this, source ); - exports.AnimationUtils = { + this.distance = source.distance; + this.decay = source.decay; - // same as Array.prototype.slice, but also works on typed arrays - arraySlice: function( array, from, to ) { + this.shadow = source.shadow.clone(); - if ( exports.AnimationUtils.isTypedArray( array ) ) { + return this; - return new array.constructor( array.subarray( from, to ) ); + } - } + } ); - return array.slice( from, to ); + /** + * @author mrdoob / http://mrdoob.com/ + */ - }, + function DirectionalLightShadow( light ) { - // converts an array to a specific type - convertArray: function( array, type, forceClone ) { + LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) ); - if ( ! array || // let 'undefined' and 'null' pass - ! forceClone && array.constructor === type ) return array; + }; - if ( typeof type.BYTES_PER_ELEMENT === 'number' ) { + DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), { - return new type( array ); // create typed array + constructor: DirectionalLightShadow - } + } ); - return Array.prototype.slice.call( array ); // create Array + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - }, + function DirectionalLight( color, intensity ) { - isTypedArray: function( object ) { + Light.call( this, color, intensity ); - return ArrayBuffer.isView( object ) && - ! ( object instanceof DataView ); + this.type = 'DirectionalLight'; - }, + this.position.copy( Object3D.DefaultUp ); + this.updateMatrix(); - // returns an array by which times and values can be sorted - getKeyframeOrder: function( times ) { + this.target = new Object3D(); - function compareTime( i, j ) { + this.shadow = new DirectionalLightShadow(); - return times[ i ] - times[ j ]; + }; - } + DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), { - var n = times.length; - var result = new Array( n ); - for ( var i = 0; i !== n; ++ i ) result[ i ] = i; + constructor: DirectionalLight, - result.sort( compareTime ); + isDirectionalLight: true, - return result; + copy: function ( source ) { - }, + Light.prototype.copy.call( this, source ); - // uses the array previously returned by 'getKeyframeOrder' to sort data - sortedArray: function( values, stride, order ) { + this.target = source.target.clone(); - var nValues = values.length; - var result = new values.constructor( nValues ); + this.shadow = source.shadow.clone(); - for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) { + return this; - var srcOffset = order[ i ] * stride; + } - for ( var j = 0; j !== stride; ++ j ) { + } ); - result[ dstOffset ++ ] = values[ srcOffset + j ]; + /** + * @author mrdoob / http://mrdoob.com/ + */ - } + function AmbientLight( color, intensity ) { - } + Light.call( this, color, intensity ); - return result; + this.type = 'AmbientLight'; - }, + this.castShadow = undefined; - // function for parsing AOS keyframe formats - flattenJSON: function( jsonKeys, times, values, valuePropertyName ) { + }; - var i = 1, key = jsonKeys[ 0 ]; + AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), { - while ( key !== undefined && key[ valuePropertyName ] === undefined ) { + constructor: AmbientLight, - key = jsonKeys[ i ++ ]; + isAmbientLight: true, - } + } ); - if ( key === undefined ) return; // no data + /** + * @author tschw + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + */ - var value = key[ valuePropertyName ]; - if ( value === undefined ) return; // no data + exports.AnimationUtils = { - if ( Array.isArray( value ) ) { + // same as Array.prototype.slice, but also works on typed arrays + arraySlice: function( array, from, to ) { - do { + if ( exports.AnimationUtils.isTypedArray( array ) ) { - value = key[ valuePropertyName ]; + return new array.constructor( array.subarray( from, to ) ); - if ( value !== undefined ) { + } - times.push( key.time ); - values.push.apply( values, value ); // push all elements + return array.slice( from, to ); - } + }, - key = jsonKeys[ i ++ ]; + // converts an array to a specific type + convertArray: function( array, type, forceClone ) { - } while ( key !== undefined ); + if ( ! array || // let 'undefined' and 'null' pass + ! forceClone && array.constructor === type ) return array; - } else if ( value.toArray !== undefined ) { - // ...assume THREE.Math-ish + if ( typeof type.BYTES_PER_ELEMENT === 'number' ) { - do { + return new type( array ); // create typed array - value = key[ valuePropertyName ]; + } - if ( value !== undefined ) { + return Array.prototype.slice.call( array ); // create Array - times.push( key.time ); - value.toArray( values, values.length ); + }, - } + isTypedArray: function( object ) { - key = jsonKeys[ i ++ ]; + return ArrayBuffer.isView( object ) && + ! ( object instanceof DataView ); - } while ( key !== undefined ); + }, - } else { - // otherwise push as-is + // returns an array by which times and values can be sorted + getKeyframeOrder: function( times ) { - do { + function compareTime( i, j ) { - value = key[ valuePropertyName ]; + return times[ i ] - times[ j ]; - if ( value !== undefined ) { + } - times.push( key.time ); - values.push( value ); + var n = times.length; + var result = new Array( n ); + for ( var i = 0; i !== n; ++ i ) result[ i ] = i; - } + result.sort( compareTime ); - key = jsonKeys[ i ++ ]; + return result; - } while ( key !== undefined ); + }, - } + // uses the array previously returned by 'getKeyframeOrder' to sort data + sortedArray: function( values, stride, order ) { - } + var nValues = values.length; + var result = new values.constructor( nValues ); - }; + for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) { - /** - * 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 - */ + var srcOffset = order[ i ] * stride; - function Interpolant( - parameterPositions, sampleValues, sampleSize, resultBuffer ) { + for ( var j = 0; j !== stride; ++ j ) { - this.parameterPositions = parameterPositions; - this._cachedIndex = 0; + result[ dstOffset ++ ] = values[ srcOffset + j ]; - this.resultBuffer = resultBuffer !== undefined ? - resultBuffer : new sampleValues.constructor( sampleSize ); - this.sampleValues = sampleValues; - this.valueSize = sampleSize; + } - }; + } - Interpolant.prototype = { + return result; - constructor: Interpolant, + }, - evaluate: function( t ) { + // function for parsing AOS keyframe formats + flattenJSON: function( jsonKeys, times, values, valuePropertyName ) { - var pp = this.parameterPositions, - i1 = this._cachedIndex, + var i = 1, key = jsonKeys[ 0 ]; - t1 = pp[ i1 ], - t0 = pp[ i1 - 1 ]; + while ( key !== undefined && key[ valuePropertyName ] === undefined ) { - validate_interval: { + key = jsonKeys[ i ++ ]; - seek: { + } - var right; + if ( key === undefined ) return; // no data - linear_scan: { - //- See http://jsperf.com/comparison-to-undefined/3 - //- slower code: - //- - //- if ( t >= t1 || t1 === undefined ) { - forward_scan: if ( ! ( t < t1 ) ) { + var value = key[ valuePropertyName ]; + if ( value === undefined ) return; // no data - for ( var giveUpAt = i1 + 2; ;) { + if ( Array.isArray( value ) ) { - if ( t1 === undefined ) { + do { - if ( t < t0 ) break forward_scan; + value = key[ valuePropertyName ]; - // after end + if ( value !== undefined ) { - i1 = pp.length; - this._cachedIndex = i1; - return this.afterEnd_( i1 - 1, t, t0 ); + times.push( key.time ); + values.push.apply( values, value ); // push all elements - } + } - if ( i1 === giveUpAt ) break; // this loop + key = jsonKeys[ i ++ ]; - t0 = t1; - t1 = pp[ ++ i1 ]; + } while ( key !== undefined ); - if ( t < t1 ) { + } else if ( value.toArray !== undefined ) { + // ...assume THREE.Math-ish - // we have arrived at the sought interval - break seek; + do { - } + value = key[ valuePropertyName ]; - } + if ( value !== undefined ) { - // prepare binary search on the right side of the index - right = pp.length; - break linear_scan; + times.push( key.time ); + value.toArray( values, values.length ); - } + } - //- slower code: - //- if ( t < t0 || t0 === undefined ) { - if ( ! ( t >= t0 ) ) { + key = jsonKeys[ i ++ ]; - // looping? + } while ( key !== undefined ); - var t1global = pp[ 1 ]; + } else { + // otherwise push as-is - if ( t < t1global ) { + do { - i1 = 2; // + 1, using the scan for the details - t0 = t1global; + value = key[ valuePropertyName ]; - } + if ( value !== undefined ) { - // linear reverse scan + times.push( key.time ); + values.push( value ); - for ( var giveUpAt = i1 - 2; ;) { + } - if ( t0 === undefined ) { + key = jsonKeys[ i ++ ]; - // before start + } while ( key !== undefined ); - this._cachedIndex = 0; - return this.beforeStart_( 0, t, t1 ); + } - } + } - if ( i1 === giveUpAt ) break; // this loop + }; - t1 = t0; - t0 = pp[ -- i1 - 1 ]; + /** + * 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; - if ( t >= t0 ) { + }; - // we have arrived at the sought interval - break seek; + Interpolant.prototype = { - } + constructor: Interpolant, - } + evaluate: function( t ) { - // prepare binary search on the left side of the index - right = i1; - i1 = 0; - break linear_scan; + var pp = this.parameterPositions, + i1 = this._cachedIndex, - } + t1 = pp[ i1 ], + t0 = pp[ i1 - 1 ]; - // the interval is valid + validate_interval: { - break validate_interval; + seek: { - } // linear scan + var right; - // binary search + linear_scan: { + //- See http://jsperf.com/comparison-to-undefined/3 + //- slower code: + //- + //- if ( t >= t1 || t1 === undefined ) { + forward_scan: if ( ! ( t < t1 ) ) { - while ( i1 < right ) { + for ( var giveUpAt = i1 + 2; ;) { - var mid = ( i1 + right ) >>> 1; + if ( t1 === undefined ) { - if ( t < pp[ mid ] ) { + if ( t < t0 ) break forward_scan; - right = mid; + // after end - } else { + i1 = pp.length; + this._cachedIndex = i1; + return this.afterEnd_( i1 - 1, t, t0 ); - i1 = mid + 1; + } - } + if ( i1 === giveUpAt ) break; // this loop - } + t0 = t1; + t1 = pp[ ++ i1 ]; - t1 = pp[ i1 ]; - t0 = pp[ i1 - 1 ]; + if ( t < t1 ) { - // check boundary cases, again + // we have arrived at the sought interval + break seek; - if ( t0 === undefined ) { + } - this._cachedIndex = 0; - return this.beforeStart_( 0, t, t1 ); + } - } + // prepare binary search on the right side of the index + right = pp.length; + break linear_scan; - if ( t1 === undefined ) { + } - i1 = pp.length; - this._cachedIndex = i1; - return this.afterEnd_( i1 - 1, t0, t ); + //- slower code: + //- if ( t < t0 || t0 === undefined ) { + if ( ! ( t >= t0 ) ) { - } + // looping? - } // seek + var t1global = pp[ 1 ]; - this._cachedIndex = i1; + if ( t < t1global ) { - this.intervalChanged_( i1, t0, t1 ); + i1 = 2; // + 1, using the scan for the details + t0 = t1global; - } // validate_interval + } - return this.interpolate_( i1, t0, t, t1 ); + // linear reverse scan - }, + for ( var giveUpAt = i1 - 2; ;) { - settings: null, // optional, subclass-specific settings structure - // Note: The indirection allows central control of many interpolants. + if ( t0 === undefined ) { - // --- Protected interface + // before start - DefaultSettings_: {}, + this._cachedIndex = 0; + return this.beforeStart_( 0, t, t1 ); - getSettings_: function() { + } - return this.settings || this.DefaultSettings_; + if ( i1 === giveUpAt ) break; // this loop - }, + t1 = t0; + t0 = pp[ -- i1 - 1 ]; - copySampleValue_: function( index ) { + if ( t >= t0 ) { - // copies a sample value to the result buffer + // we have arrived at the sought interval + break seek; - var result = this.resultBuffer, - values = this.sampleValues, - stride = this.valueSize, - offset = index * stride; + } - for ( var i = 0; i !== stride; ++ i ) { + } - result[ i ] = values[ offset + i ]; + // prepare binary search on the left side of the index + right = i1; + i1 = 0; + break linear_scan; - } + } - return result; + // the interval is valid - }, + break validate_interval; - // Template methods for derived classes: + } // linear scan - interpolate_: function( i1, t0, t, t1 ) { + // binary search - throw new Error( "call to abstract method" ); - // implementations shall return this.resultBuffer + while ( i1 < right ) { - }, + var mid = ( i1 + right ) >>> 1; - intervalChanged_: function( i1, t0, t1 ) { + if ( t < pp[ mid ] ) { - // empty + right = mid; - } + } else { - }; + i1 = mid + 1; - Object.assign( Interpolant.prototype, { + } - beforeStart_: //( 0, t, t0 ), returns this.resultBuffer - Interpolant.prototype.copySampleValue_, + } - afterEnd_: //( N-1, tN-1, t ), returns this.resultBuffer - Interpolant.prototype.copySampleValue_ + t1 = pp[ i1 ]; + t0 = pp[ i1 - 1 ]; - } ); + // check boundary cases, again - /** - * 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 - */ + if ( t0 === undefined ) { - function CubicInterpolant( - parameterPositions, sampleValues, sampleSize, resultBuffer ) { + this._cachedIndex = 0; + return this.beforeStart_( 0, t, t1 ); - Interpolant.call( - this, parameterPositions, sampleValues, sampleSize, resultBuffer ); + } - this._weightPrev = -0; - this._offsetPrev = -0; - this._weightNext = -0; - this._offsetNext = -0; + if ( t1 === undefined ) { - }; + i1 = pp.length; + this._cachedIndex = i1; + return this.afterEnd_( i1 - 1, t0, t ); - CubicInterpolant.prototype = - Object.assign( Object.create( Interpolant.prototype ), { + } - constructor: CubicInterpolant, + } // seek - DefaultSettings_: { + this._cachedIndex = i1; - endingStart: ZeroCurvatureEnding, - endingEnd: ZeroCurvatureEnding + this.intervalChanged_( i1, t0, t1 ); - }, + } // validate_interval - intervalChanged_: function( i1, t0, t1 ) { + return this.interpolate_( i1, t0, t, t1 ); - var pp = this.parameterPositions, - iPrev = i1 - 2, - iNext = i1 + 1, + }, - tPrev = pp[ iPrev ], - tNext = pp[ iNext ]; + settings: null, // optional, subclass-specific settings structure + // Note: The indirection allows central control of many interpolants. - if ( tPrev === undefined ) { + // --- Protected interface - switch ( this.getSettings_().endingStart ) { + DefaultSettings_: {}, - case ZeroSlopeEnding: + getSettings_: function() { - // f'(t0) = 0 - iPrev = i1; - tPrev = 2 * t0 - t1; + return this.settings || this.DefaultSettings_; - break; + }, - case WrapAroundEnding: + copySampleValue_: function( index ) { - // use the other end of the curve - iPrev = pp.length - 2; - tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ]; + // copies a sample value to the result buffer - break; + var result = this.resultBuffer, + values = this.sampleValues, + stride = this.valueSize, + offset = index * stride; - default: // ZeroCurvatureEnding + for ( var i = 0; i !== stride; ++ i ) { - // f''(t0) = 0 a.k.a. Natural Spline - iPrev = i1; - tPrev = t1; + result[ i ] = values[ offset + i ]; - } + } - } + return result; - if ( tNext === undefined ) { + }, - switch ( this.getSettings_().endingEnd ) { + // Template methods for derived classes: - case ZeroSlopeEnding: + interpolate_: function( i1, t0, t, t1 ) { - // f'(tN) = 0 - iNext = i1; - tNext = 2 * t1 - t0; + throw new Error( "call to abstract method" ); + // implementations shall return this.resultBuffer - break; + }, - case WrapAroundEnding: + intervalChanged_: function( i1, t0, t1 ) { - // use the other end of the curve - iNext = 1; - tNext = t1 + pp[ 1 ] - pp[ 0 ]; + // empty - break; + } - default: // ZeroCurvatureEnding + }; - // f''(tN) = 0, a.k.a. Natural Spline - iNext = i1 - 1; - tNext = t0; + Object.assign( Interpolant.prototype, { - } + beforeStart_: //( 0, t, t0 ), returns this.resultBuffer + Interpolant.prototype.copySampleValue_, - } + afterEnd_: //( N-1, tN-1, t ), returns this.resultBuffer + Interpolant.prototype.copySampleValue_ - var halfDt = ( t1 - t0 ) * 0.5, - stride = this.valueSize; + } ); - this._weightPrev = halfDt / ( t0 - tPrev ); - this._weightNext = halfDt / ( tNext - t1 ); - this._offsetPrev = iPrev * stride; - this._offsetNext = iNext * stride; + /** + * 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 ) { - interpolate_: function( i1, t0, t, t1 ) { + Interpolant.call( + this, parameterPositions, sampleValues, sampleSize, resultBuffer ); - var result = this.resultBuffer, - values = this.sampleValues, - stride = this.valueSize, + this._weightPrev = -0; + this._offsetPrev = -0; + this._weightNext = -0; + this._offsetNext = -0; - o1 = i1 * stride, o0 = o1 - stride, - oP = this._offsetPrev, oN = this._offsetNext, - wP = this._weightPrev, wN = this._weightNext, + }; - p = ( t - t0 ) / ( t1 - t0 ), - pp = p * p, - ppp = pp * p; + CubicInterpolant.prototype = + Object.assign( Object.create( Interpolant.prototype ), { - // evaluate polynomials + constructor: CubicInterpolant, - 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; + DefaultSettings_: { - // combine data linearly + endingStart: ZeroCurvatureEnding, + endingEnd: ZeroCurvatureEnding - 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 ]; + intervalChanged_: function( i1, t0, t1 ) { - } + var pp = this.parameterPositions, + iPrev = i1 - 2, + iNext = i1 + 1, - return result; + tPrev = pp[ iPrev ], + tNext = pp[ iNext ]; - } + if ( tPrev === undefined ) { - } ); + switch ( this.getSettings_().endingStart ) { - /** - * @author tschw - */ + case ZeroSlopeEnding: - function LinearInterpolant( - parameterPositions, sampleValues, sampleSize, resultBuffer ) { + // f'(t0) = 0 + iPrev = i1; + tPrev = 2 * t0 - t1; - Interpolant.call( - this, parameterPositions, sampleValues, sampleSize, resultBuffer ); + break; - }; + case WrapAroundEnding: - LinearInterpolant.prototype = - Object.assign( Object.create( Interpolant.prototype ), { + // use the other end of the curve + iPrev = pp.length - 2; + tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ]; - constructor: LinearInterpolant, + break; - interpolate_: function( i1, t0, t, t1 ) { + default: // ZeroCurvatureEnding - var result = this.resultBuffer, - values = this.sampleValues, - stride = this.valueSize, + // f''(t0) = 0 a.k.a. Natural Spline + iPrev = i1; + tPrev = t1; - offset1 = i1 * stride, - offset0 = offset1 - stride, + } - weight1 = ( t - t0 ) / ( t1 - t0 ), - weight0 = 1 - weight1; + } - for ( var i = 0; i !== stride; ++ i ) { + if ( tNext === undefined ) { - result[ i ] = - values[ offset0 + i ] * weight0 + - values[ offset1 + i ] * weight1; + switch ( this.getSettings_().endingEnd ) { - } + case ZeroSlopeEnding: - return result; + // f'(tN) = 0 + iNext = i1; + tNext = 2 * t1 - t0; - } + break; - } ); + case WrapAroundEnding: - /** - * - * Interpolant that evaluates to the sample value at the position preceeding - * the parameter. - * - * @author tschw - */ + // use the other end of the curve + iNext = 1; + tNext = t1 + pp[ 1 ] - pp[ 0 ]; - function DiscreteInterpolant( - parameterPositions, sampleValues, sampleSize, resultBuffer ) { + break; - Interpolant.call( - this, parameterPositions, sampleValues, sampleSize, resultBuffer ); + default: // ZeroCurvatureEnding - }; + // f''(tN) = 0, a.k.a. Natural Spline + iNext = i1 - 1; + tNext = t0; - DiscreteInterpolant.prototype = - Object.assign( Object.create( Interpolant.prototype ), { + } - constructor: DiscreteInterpolant, + } - interpolate_: function( i1, t0, t, t1 ) { + var halfDt = ( t1 - t0 ) * 0.5, + stride = this.valueSize; - return this.copySampleValue_( i1 - 1 ); + this._weightPrev = halfDt / ( t0 - tPrev ); + this._weightNext = halfDt / ( tNext - t1 ); + this._offsetPrev = iPrev * stride; + this._offsetNext = iNext * stride; - } + }, - } ); + interpolate_: function( i1, t0, t, t1 ) { - var KeyframeTrackPrototype; + var result = this.resultBuffer, + values = this.sampleValues, + stride = this.valueSize, - KeyframeTrackPrototype = { + o1 = i1 * stride, o0 = o1 - stride, + oP = this._offsetPrev, oN = this._offsetNext, + wP = this._weightPrev, wN = this._weightNext, - TimeBufferType: Float32Array, - ValueBufferType: Float32Array, + p = ( t - t0 ) / ( t1 - t0 ), + pp = p * p, + ppp = pp * p; - DefaultInterpolation: InterpolateLinear, + // evaluate polynomials - InterpolantFactoryMethodDiscrete: function( result ) { + 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; - return new DiscreteInterpolant( - this.times, this.values, this.getValueSize(), result ); + // combine data linearly - }, + for ( var i = 0; i !== stride; ++ i ) { - InterpolantFactoryMethodLinear: function( result ) { + result[ i ] = + sP * values[ oP + i ] + + s0 * values[ o0 + i ] + + s1 * values[ o1 + i ] + + sN * values[ oN + i ]; - return new LinearInterpolant( - this.times, this.values, this.getValueSize(), result ); + } - }, + return result; - InterpolantFactoryMethodSmooth: function( result ) { + } - return new CubicInterpolant( - this.times, this.values, this.getValueSize(), result ); + } ); - }, + /** + * @author tschw + */ - setInterpolation: function( interpolation ) { + function LinearInterpolant( + parameterPositions, sampleValues, sampleSize, resultBuffer ) { - var factoryMethod; + Interpolant.call( + this, parameterPositions, sampleValues, sampleSize, resultBuffer ); - switch ( interpolation ) { + }; - case InterpolateDiscrete: + LinearInterpolant.prototype = + Object.assign( Object.create( Interpolant.prototype ), { - factoryMethod = this.InterpolantFactoryMethodDiscrete; + constructor: LinearInterpolant, - break; + interpolate_: function( i1, t0, t, t1 ) { - case InterpolateLinear: + var result = this.resultBuffer, + values = this.sampleValues, + stride = this.valueSize, - factoryMethod = this.InterpolantFactoryMethodLinear; + offset1 = i1 * stride, + offset0 = offset1 - stride, - break; + weight1 = ( t - t0 ) / ( t1 - t0 ), + weight0 = 1 - weight1; - case InterpolateSmooth: + for ( var i = 0; i !== stride; ++ i ) { - factoryMethod = this.InterpolantFactoryMethodSmooth; + result[ i ] = + values[ offset0 + i ] * weight0 + + values[ offset1 + i ] * weight1; - break; + } - } + return result; - if ( factoryMethod === undefined ) { + } - var message = "unsupported interpolation for " + - this.ValueTypeName + " keyframe track named " + this.name; + } ); - if ( this.createInterpolant === undefined ) { + /** + * + * Interpolant that evaluates to the sample value at the position preceeding + * the parameter. + * + * @author tschw + */ - // fall back to default, unless the default itself is messed up - if ( interpolation !== this.DefaultInterpolation ) { + function DiscreteInterpolant( + parameterPositions, sampleValues, sampleSize, resultBuffer ) { - this.setInterpolation( this.DefaultInterpolation ); + Interpolant.call( + this, parameterPositions, sampleValues, sampleSize, resultBuffer ); - } else { + }; - throw new Error( message ); // fatal, in this case + DiscreteInterpolant.prototype = + Object.assign( Object.create( Interpolant.prototype ), { - } + constructor: DiscreteInterpolant, - } + interpolate_: function( i1, t0, t, t1 ) { - console.warn( message ); - return; + return this.copySampleValue_( i1 - 1 ); - } + } - this.createInterpolant = factoryMethod; + } ); - }, + var KeyframeTrackPrototype; - getInterpolation: function() { + KeyframeTrackPrototype = { - switch ( this.createInterpolant ) { + TimeBufferType: Float32Array, + ValueBufferType: Float32Array, - case this.InterpolantFactoryMethodDiscrete: + DefaultInterpolation: InterpolateLinear, - return InterpolateDiscrete; + InterpolantFactoryMethodDiscrete: function( result ) { - case this.InterpolantFactoryMethodLinear: + return new DiscreteInterpolant( + this.times, this.values, this.getValueSize(), result ); - return InterpolateLinear; + }, - case this.InterpolantFactoryMethodSmooth: + InterpolantFactoryMethodLinear: function( result ) { - return InterpolateSmooth; + return new LinearInterpolant( + this.times, this.values, this.getValueSize(), result ); - } + }, - }, + InterpolantFactoryMethodSmooth: function( result ) { - getValueSize: function() { + return new CubicInterpolant( + this.times, this.values, this.getValueSize(), result ); - return this.values.length / this.times.length; + }, - }, + setInterpolation: function( interpolation ) { - // move all keyframes either forwards or backwards in time - shift: function( timeOffset ) { + var factoryMethod; - if( timeOffset !== 0.0 ) { + switch ( interpolation ) { - var times = this.times; + case InterpolateDiscrete: - for( var i = 0, n = times.length; i !== n; ++ i ) { + factoryMethod = this.InterpolantFactoryMethodDiscrete; - times[ i ] += timeOffset; + break; - } + case InterpolateLinear: - } + factoryMethod = this.InterpolantFactoryMethodLinear; - return this; + break; - }, + case InterpolateSmooth: - // scale all keyframe times by a factor (useful for frame <-> seconds conversions) - scale: function( timeScale ) { + factoryMethod = this.InterpolantFactoryMethodSmooth; - if( timeScale !== 1.0 ) { + break; - var times = this.times; + } - for( var i = 0, n = times.length; i !== n; ++ i ) { + if ( factoryMethod === undefined ) { - times[ i ] *= timeScale; + var message = "unsupported interpolation for " + + this.ValueTypeName + " keyframe track named " + this.name; - } + if ( this.createInterpolant === undefined ) { - } + // fall back to default, unless the default itself is messed up + if ( interpolation !== this.DefaultInterpolation ) { - return this; + this.setInterpolation( this.DefaultInterpolation ); - }, + } else { - // 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 ) { + throw new Error( message ); // fatal, in this case - 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; + } - ++ to; // inclusive -> exclusive bound + console.warn( message ); + return; - 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; + this.createInterpolant = factoryMethod; - var stride = this.getValueSize(); - this.times = exports.AnimationUtils.arraySlice( times, from, to ); - this.values = exports.AnimationUtils. - arraySlice( this.values, from * stride, to * stride ); + }, - } + getInterpolation: function() { - return this; + switch ( this.createInterpolant ) { - }, + case this.InterpolantFactoryMethodDiscrete: - // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable - validate: function() { + return InterpolateDiscrete; - var valid = true; + case this.InterpolantFactoryMethodLinear: - var valueSize = this.getValueSize(); - if ( valueSize - Math.floor( valueSize ) !== 0 ) { + return InterpolateLinear; - console.error( "invalid value size in track", this ); - valid = false; + case this.InterpolantFactoryMethodSmooth: - } + return InterpolateSmooth; - var times = this.times, - values = this.values, + } - nKeys = times.length; + }, - if( nKeys === 0 ) { + getValueSize: function() { - console.error( "track is empty", this ); - valid = false; + return this.values.length / this.times.length; - } + }, - var prevTime = null; + // move all keyframes either forwards or backwards in time + shift: function( timeOffset ) { - for( var i = 0; i !== nKeys; i ++ ) { + if( timeOffset !== 0.0 ) { - var currTime = times[ i ]; + var times = this.times; - if ( typeof currTime === 'number' && isNaN( currTime ) ) { + for( var i = 0, n = times.length; i !== n; ++ i ) { - console.error( "time is not a valid number", this, i, currTime ); - valid = false; - break; + times[ i ] += timeOffset; - } + } - if( prevTime !== null && prevTime > currTime ) { + } - console.error( "out of order keys", this, i, currTime, prevTime ); - valid = false; - break; + return this; - } + }, - prevTime = currTime; + // scale all keyframe times by a factor (useful for frame <-> seconds conversions) + scale: function( timeScale ) { - } + if( timeScale !== 1.0 ) { - if ( values !== undefined ) { + var times = this.times; - if ( exports.AnimationUtils.isTypedArray( values ) ) { + for( var i = 0, n = times.length; i !== n; ++ i ) { - for ( var i = 0, n = values.length; i !== n; ++ i ) { + times[ i ] *= timeScale; - var value = values[ i ]; + } - if ( isNaN( value ) ) { + } - console.error( "value is not a valid number", this, i, value ); - valid = false; - break; + return this; - } + }, - } + // 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; - return valid; + ++ to; // inclusive -> exclusive bound - }, + if( from !== 0 || to !== nKeys ) { - // 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() { + // empty tracks are forbidden, so keep at least one keyframe + if ( from >= to ) to = Math.max( to , 1 ), from = to - 1; - var times = this.times, - values = this.values, - stride = this.getValueSize(), + var stride = this.getValueSize(); + this.times = exports.AnimationUtils.arraySlice( times, from, to ); + this.values = exports.AnimationUtils. + arraySlice( this.values, from * stride, to * stride ); - writeIndex = 1; + } - for( var i = 1, n = times.length - 1; i <= n; ++ i ) { + return this; - var keep = false; + }, - var time = times[ i ]; - var timeNext = times[ i + 1 ]; + // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable + validate: function() { - // remove adjacent keyframes scheduled at the same time + var valid = true; - if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) { + var valueSize = this.getValueSize(); + if ( valueSize - Math.floor( valueSize ) !== 0 ) { - // remove unnecessary keyframes same as their neighbors - var offset = i * stride, - offsetP = offset - stride, - offsetN = offset + stride; + console.error( "invalid value size in track", this ); + valid = false; - for ( var j = 0; j !== stride; ++ j ) { + } - var value = values[ offset + j ]; + var times = this.times, + values = this.values, - if ( value !== values[ offsetP + j ] || - value !== values[ offsetN + j ] ) { + nKeys = times.length; - keep = true; - break; + if( nKeys === 0 ) { - } + console.error( "track is empty", this ); + valid = false; - } + } - } + var prevTime = null; - // in-place compaction + for( var i = 0; i !== nKeys; i ++ ) { - if ( keep ) { + var currTime = times[ i ]; - if ( i !== writeIndex ) { + if ( typeof currTime === 'number' && isNaN( currTime ) ) { - times[ writeIndex ] = times[ i ]; + console.error( "time is not a valid number", this, i, currTime ); + valid = false; + break; - var readOffset = i * stride, - writeOffset = writeIndex * stride; + } - for ( var j = 0; j !== stride; ++ j ) { + if( prevTime !== null && prevTime > currTime ) { - values[ writeOffset + j ] = values[ readOffset + j ]; + console.error( "out of order keys", this, i, currTime, prevTime ); + valid = false; + break; - } + } + prevTime = currTime; - } + } - ++ writeIndex; + if ( values !== undefined ) { - } + if ( exports.AnimationUtils.isTypedArray( values ) ) { - } + for ( var i = 0, n = values.length; i !== n; ++ i ) { - if ( writeIndex !== times.length ) { + var value = values[ i ]; - this.times = exports.AnimationUtils.arraySlice( times, 0, writeIndex ); - this.values = exports.AnimationUtils.arraySlice( values, 0, writeIndex * stride ); + if ( isNaN( value ) ) { - } + console.error( "value is not a valid number", this, i, value ); + valid = false; + break; - return this; + } - } + } - } + } - function KeyframeTrackConstructor( name, times, values, interpolation ) { + } - if( name === undefined ) throw new Error( "track name is undefined" ); + return valid; - if( times === undefined || times.length === 0 ) { + }, - throw new Error( "no keyframes in track named " + name ); + // 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(), - this.name = name; + writeIndex = 1; - this.times = exports.AnimationUtils.convertArray( times, this.TimeBufferType ); - this.values = exports.AnimationUtils.convertArray( values, this.ValueBufferType ); + for( var i = 1, n = times.length - 1; i <= n; ++ i ) { - this.setInterpolation( interpolation || this.DefaultInterpolation ); + var keep = false; - this.validate(); - this.optimize(); + var time = times[ i ]; + var timeNext = times[ i + 1 ]; - } + // remove adjacent keyframes scheduled at the same time - /** - * - * A Track of vectored keyframe values. - * - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) { - function VectorKeyframeTrack( name, times, values, interpolation ) { + // remove unnecessary keyframes same as their neighbors + var offset = i * stride, + offsetP = offset - stride, + offsetN = offset + stride; - KeyframeTrackConstructor.call( this, name, times, values, interpolation ); + for ( var j = 0; j !== stride; ++ j ) { - }; + var value = values[ offset + j ]; - VectorKeyframeTrack.prototype = - Object.assign( Object.create( KeyframeTrackPrototype ), { + if ( value !== values[ offsetP + j ] || + value !== values[ offsetN + j ] ) { - constructor: VectorKeyframeTrack, + keep = true; + break; - ValueTypeName: 'vector' + } - // ValueBufferType is inherited + } - // DefaultInterpolation is inherited + } - } ); + // in-place compaction - /** - * Spherical linear unit quaternion interpolant. - * - * @author tschw - */ + if ( keep ) { - function QuaternionLinearInterpolant( - parameterPositions, sampleValues, sampleSize, resultBuffer ) { + if ( i !== writeIndex ) { - Interpolant.call( - this, parameterPositions, sampleValues, sampleSize, resultBuffer ); + times[ writeIndex ] = times[ i ]; - }; + var readOffset = i * stride, + writeOffset = writeIndex * stride; - QuaternionLinearInterpolant.prototype = - Object.assign( Object.create( Interpolant.prototype ), { + for ( var j = 0; j !== stride; ++ j ) { - constructor: QuaternionLinearInterpolant, + values[ writeOffset + j ] = values[ readOffset + j ]; - interpolate_: function( i1, t0, t, t1 ) { + } - var result = this.resultBuffer, - values = this.sampleValues, - stride = this.valueSize, - offset = i1 * stride, + } - alpha = ( t - t0 ) / ( t1 - t0 ); + ++ writeIndex; - for ( var end = offset + stride; offset !== end; offset += 4 ) { + } - Quaternion.slerpFlat( result, 0, - values, offset - stride, values, offset, alpha ); + } - } + if ( writeIndex !== times.length ) { - return result; + this.times = exports.AnimationUtils.arraySlice( times, 0, writeIndex ); + this.values = exports.AnimationUtils.arraySlice( values, 0, writeIndex * stride ); - } + } - } ); + return this; - /** - * - * 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 ) { + } - KeyframeTrackConstructor.call( this, name, times, values, interpolation ); + function KeyframeTrackConstructor( name, times, values, interpolation ) { - }; + if( name === undefined ) throw new Error( "track name is undefined" ); - QuaternionKeyframeTrack.prototype = - Object.assign( Object.create( KeyframeTrackPrototype ), { + if( times === undefined || times.length === 0 ) { - constructor: QuaternionKeyframeTrack, + throw new Error( "no keyframes in track named " + name ); - ValueTypeName: 'quaternion', + } - // ValueBufferType is inherited + this.name = name; - DefaultInterpolation: InterpolateLinear, + this.times = exports.AnimationUtils.convertArray( times, this.TimeBufferType ); + this.values = exports.AnimationUtils.convertArray( values, this.ValueBufferType ); - InterpolantFactoryMethodLinear: function( result ) { + this.setInterpolation( interpolation || this.DefaultInterpolation ); - return new QuaternionLinearInterpolant( - this.times, this.values, this.getValueSize(), result ); + this.validate(); + this.optimize(); - }, + } - InterpolantFactoryMethodSmooth: undefined // not yet implemented + /** + * + * 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 ) { - /** - * - * A Track of numeric keyframe values. - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + KeyframeTrackConstructor.call( this, name, times, values, interpolation ); - function NumberKeyframeTrack( name, times, values, interpolation ) { + }; - KeyframeTrackConstructor.call( this, name, times, values, interpolation ); + VectorKeyframeTrack.prototype = + Object.assign( Object.create( KeyframeTrackPrototype ), { - }; + constructor: VectorKeyframeTrack, - NumberKeyframeTrack.prototype = - Object.assign( Object.create( KeyframeTrackPrototype ), { + ValueTypeName: 'vector' - constructor: NumberKeyframeTrack, + // ValueBufferType is inherited - ValueTypeName: 'number', + // DefaultInterpolation is inherited - // ValueBufferType is inherited + } ); - // DefaultInterpolation is inherited + /** + * Spherical linear unit quaternion interpolant. + * + * @author tschw + */ - } ); + function QuaternionLinearInterpolant( + parameterPositions, sampleValues, sampleSize, resultBuffer ) { - /** - * - * A Track that interpolates Strings - * - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + Interpolant.call( + this, parameterPositions, sampleValues, sampleSize, resultBuffer ); - function StringKeyframeTrack( name, times, values, interpolation ) { + }; - KeyframeTrackConstructor.call( this, name, times, values, interpolation ); + QuaternionLinearInterpolant.prototype = + Object.assign( Object.create( Interpolant.prototype ), { - }; + constructor: QuaternionLinearInterpolant, - StringKeyframeTrack.prototype = - Object.assign( Object.create( KeyframeTrackPrototype ), { + interpolate_: function( i1, t0, t, t1 ) { - constructor: StringKeyframeTrack, + var result = this.resultBuffer, + values = this.sampleValues, + stride = this.valueSize, - ValueTypeName: 'string', - ValueBufferType: Array, + offset = i1 * stride, - DefaultInterpolation: InterpolateDiscrete, + alpha = ( t - t0 ) / ( t1 - t0 ); - InterpolantFactoryMethodLinear: undefined, + for ( var end = offset + stride; offset !== end; offset += 4 ) { - InterpolantFactoryMethodSmooth: undefined + Quaternion.slerpFlat( result, 0, + values, offset - stride, values, offset, alpha ); - } ); + } - /** - * - * A Track of Boolean keyframe values. - * - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + return result; - function BooleanKeyframeTrack( name, times, values ) { + } - KeyframeTrackConstructor.call( this, name, times, values ); + } ); - }; + /** + * + * A Track of quaternion keyframe values. + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - BooleanKeyframeTrack.prototype = - Object.assign( Object.create( KeyframeTrackPrototype ), { + function QuaternionKeyframeTrack( name, times, values, interpolation ) { - constructor: BooleanKeyframeTrack, + KeyframeTrackConstructor.call( this, name, times, values, interpolation ); - ValueTypeName: 'bool', - ValueBufferType: Array, + }; - DefaultInterpolation: InterpolateDiscrete, + QuaternionKeyframeTrack.prototype = + Object.assign( Object.create( KeyframeTrackPrototype ), { - InterpolantFactoryMethodLinear: undefined, - InterpolantFactoryMethodSmooth: undefined + constructor: QuaternionKeyframeTrack, - // Note: Actually this track could have a optimized / compressed - // representation of a single value and a custom interpolant that - // computes "firstValue ^ isOdd( index )". + ValueTypeName: 'quaternion', - } ); + // ValueBufferType is inherited - /** - * - * A Track of keyframe values that represent color. - * - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + DefaultInterpolation: InterpolateLinear, - function ColorKeyframeTrack( name, times, values, interpolation ) { + InterpolantFactoryMethodLinear: function( result ) { - KeyframeTrackConstructor.call( this, name, times, values, interpolation ); + return new QuaternionLinearInterpolant( + this.times, this.values, this.getValueSize(), result ); - }; + }, - ColorKeyframeTrack.prototype = - Object.assign( Object.create( KeyframeTrackPrototype ), { + InterpolantFactoryMethodSmooth: undefined // not yet implemented - constructor: ColorKeyframeTrack, + } ); - ValueTypeName: 'color' + /** + * + * A Track of numeric keyframe values. + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - // ValueBufferType is inherited + function NumberKeyframeTrack( name, times, values, interpolation ) { - // DefaultInterpolation is inherited + KeyframeTrackConstructor.call( this, name, times, values, interpolation ); + }; - // Note: Very basic implementation and nothing special yet. - // However, this is the place for color space parameterization. + NumberKeyframeTrack.prototype = + Object.assign( Object.create( KeyframeTrackPrototype ), { - } ); + constructor: NumberKeyframeTrack, - /** - * - * A timed sequence of keyframes for a specific property. - * - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + ValueTypeName: 'number', - function KeyframeTrack( name, times, values, interpolation ) { - KeyframeTrackConstructor.apply( this, arguments ); - }; + // ValueBufferType is inherited - KeyframeTrack.prototype = KeyframeTrackPrototype; - KeyframeTrackPrototype.constructor = KeyframeTrack; + // DefaultInterpolation is inherited - // Static methods: + } ); - Object.assign( KeyframeTrack, { + /** + * + * A Track that interpolates Strings + * + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - // Serialization (in static context, because of constructor invocation - // and automatic invocation of .toJSON): + function StringKeyframeTrack( name, times, values, interpolation ) { - parse: function( json ) { + KeyframeTrackConstructor.call( this, name, times, values, interpolation ); - if( json.type === undefined ) { + }; - throw new Error( "track type undefined, can not parse" ); + StringKeyframeTrack.prototype = + Object.assign( Object.create( KeyframeTrackPrototype ), { - } + constructor: StringKeyframeTrack, - var trackType = KeyframeTrack._getTrackTypeForValueTypeName( json.type ); + ValueTypeName: 'string', + ValueBufferType: Array, - if ( json.times === undefined ) { + DefaultInterpolation: InterpolateDiscrete, - var times = [], values = []; + InterpolantFactoryMethodLinear: undefined, - exports.AnimationUtils.flattenJSON( json.keys, times, values, 'value' ); + InterpolantFactoryMethodSmooth: undefined - json.times = times; - json.values = values; + } ); - } + /** + * + * A Track of Boolean keyframe values. + * + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - // derived classes can define a static parse method - if ( trackType.parse !== undefined ) { + function BooleanKeyframeTrack( name, times, values ) { - return trackType.parse( json ); + KeyframeTrackConstructor.call( this, name, times, values ); - } else { + }; - // by default, we asssume a constructor compatible with the base - return new trackType( - json.name, json.times, json.values, json.interpolation ); + BooleanKeyframeTrack.prototype = + Object.assign( Object.create( KeyframeTrackPrototype ), { - } + constructor: BooleanKeyframeTrack, - }, + ValueTypeName: 'bool', + ValueBufferType: Array, - toJSON: function( track ) { + DefaultInterpolation: InterpolateDiscrete, - var trackType = track.constructor; + InterpolantFactoryMethodLinear: undefined, + InterpolantFactoryMethodSmooth: undefined - var json; + // Note: Actually this track could have a optimized / compressed + // representation of a single value and a custom interpolant that + // computes "firstValue ^ isOdd( index )". - // derived classes can define a static toJSON method - if ( trackType.toJSON !== undefined ) { + } ); - json = trackType.toJSON( track ); + /** + * + * A Track of keyframe values that represent color. + * + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - } else { + function ColorKeyframeTrack( name, times, values, interpolation ) { - // by default, we assume the data can be serialized as-is - json = { + KeyframeTrackConstructor.call( this, name, times, values, interpolation ); - 'name': track.name, - 'times': exports.AnimationUtils.convertArray( track.times, Array ), - 'values': exports.AnimationUtils.convertArray( track.values, Array ) + }; - }; + ColorKeyframeTrack.prototype = + Object.assign( Object.create( KeyframeTrackPrototype ), { - var interpolation = track.getInterpolation(); + constructor: ColorKeyframeTrack, - if ( interpolation !== track.DefaultInterpolation ) { + ValueTypeName: 'color' - json.interpolation = interpolation; + // ValueBufferType is inherited - } + // DefaultInterpolation is inherited - } - json.type = track.ValueTypeName; // mandatory + // Note: Very basic implementation and nothing special yet. + // However, this is the place for color space parameterization. - return json; + } ); - }, + /** + * + * A timed sequence of keyframes for a specific property. + * + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - _getTrackTypeForValueTypeName: function( typeName ) { + function KeyframeTrack( name, times, values, interpolation ) { + KeyframeTrackConstructor.apply( this, arguments ); + }; - switch( typeName.toLowerCase() ) { + KeyframeTrack.prototype = KeyframeTrackPrototype; + KeyframeTrackPrototype.constructor = KeyframeTrack; - case "scalar": - case "double": - case "float": - case "number": - case "integer": + // Static methods: - return NumberKeyframeTrack; + Object.assign( KeyframeTrack, { - case "vector": - case "vector2": - case "vector3": - case "vector4": + // Serialization (in static context, because of constructor invocation + // and automatic invocation of .toJSON): - return VectorKeyframeTrack; + parse: function( json ) { - case "color": + if( json.type === undefined ) { - return ColorKeyframeTrack; + throw new Error( "track type undefined, can not parse" ); - case "quaternion": + } - return QuaternionKeyframeTrack; + var trackType = KeyframeTrack._getTrackTypeForValueTypeName( json.type ); - case "bool": - case "boolean": + if ( json.times === undefined ) { - return BooleanKeyframeTrack; + var times = [], values = []; - case "string": + exports.AnimationUtils.flattenJSON( json.keys, times, values, 'value' ); - return StringKeyframeTrack; + json.times = times; + json.values = values; - } + } - throw new Error( "Unsupported typeName: " + typeName ); + // derived classes can define a static parse method + if ( trackType.parse !== undefined ) { - } + return trackType.parse( json ); - } ); + } else { - /** - * - * Reusable set of Tracks that represent an animation. - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - */ + // by default, we asssume a constructor compatible with the base + return new trackType( + json.name, json.times, json.values, json.interpolation ); - function AnimationClip( name, duration, tracks ) { + } - this.name = name; - this.tracks = tracks; - this.duration = ( duration !== undefined ) ? duration : -1; + }, - this.uuid = exports.Math.generateUUID(); + toJSON: function( track ) { - // this means it should figure out its duration by scanning the tracks - if ( this.duration < 0 ) { + var trackType = track.constructor; - this.resetDuration(); + var json; - } + // derived classes can define a static toJSON method + if ( trackType.toJSON !== undefined ) { - // 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(); + json = trackType.toJSON( track ); - }; + } else { - AnimationClip.prototype = { + // by default, we assume the data can be serialized as-is + json = { - constructor: AnimationClip, + 'name': track.name, + 'times': exports.AnimationUtils.convertArray( track.times, Array ), + 'values': exports.AnimationUtils.convertArray( track.values, Array ) - resetDuration: function() { + }; - var tracks = this.tracks, - duration = 0; + var interpolation = track.getInterpolation(); - for ( var i = 0, n = tracks.length; i !== n; ++ i ) { + if ( interpolation !== track.DefaultInterpolation ) { - var track = this.tracks[ i ]; + json.interpolation = interpolation; - duration = Math.max( - duration, track.times[ track.times.length - 1 ] ); + } - } + } - this.duration = duration; + json.type = track.ValueTypeName; // mandatory - }, + return json; - trim: function() { + }, - for ( var i = 0; i < this.tracks.length; i ++ ) { + _getTrackTypeForValueTypeName: function( typeName ) { - this.tracks[ i ].trim( 0, this.duration ); + switch( typeName.toLowerCase() ) { - } + case "scalar": + case "double": + case "float": + case "number": + case "integer": - return this; + return NumberKeyframeTrack; - }, + case "vector": + case "vector2": + case "vector3": + case "vector4": - optimize: function() { + return VectorKeyframeTrack; - for ( var i = 0; i < this.tracks.length; i ++ ) { + case "color": - this.tracks[ i ].optimize(); + return ColorKeyframeTrack; - } + case "quaternion": - return this; + return QuaternionKeyframeTrack; - } + case "bool": + case "boolean": - }; + return BooleanKeyframeTrack; - // Static methods: + case "string": - Object.assign( AnimationClip, { + return StringKeyframeTrack; - parse: function( json ) { + } - var tracks = [], - jsonTracks = json.tracks, - frameTime = 1.0 / ( json.fps || 1.0 ); + throw new Error( "Unsupported typeName: " + typeName ); - for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) { + } - tracks.push( KeyframeTrack.parse( jsonTracks[ i ] ).scale( frameTime ) ); + } ); - } + /** + * + * Reusable set of Tracks that represent an animation. + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + */ - return new AnimationClip( json.name, json.duration, tracks ); + function AnimationClip( name, duration, tracks ) { - }, + this.name = name; + this.tracks = tracks; + this.duration = ( duration !== undefined ) ? duration : -1; + this.uuid = exports.Math.generateUUID(); - toJSON: function( clip ) { + // this means it should figure out its duration by scanning the tracks + if ( this.duration < 0 ) { - var tracks = [], - clipTracks = clip.tracks; + this.resetDuration(); - var json = { + } - 'name': clip.name, - 'duration': clip.duration, - 'tracks': tracks + // 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(); - }; + }; - for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) { + AnimationClip.prototype = { - tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) ); + constructor: AnimationClip, - } + resetDuration: function() { - return json; + var tracks = this.tracks, + duration = 0; - }, + for ( var i = 0, n = tracks.length; i !== n; ++ i ) { + var track = this.tracks[ i ]; - CreateFromMorphTargetSequence: function( name, morphTargetSequence, fps, noLoop ) { + duration = Math.max( + duration, track.times[ track.times.length - 1 ] ); - var numMorphTargets = morphTargetSequence.length; - var tracks = []; + } - for ( var i = 0; i < numMorphTargets; i ++ ) { + this.duration = duration; - var times = []; - var values = []; + }, - times.push( - ( i + numMorphTargets - 1 ) % numMorphTargets, - i, - ( i + 1 ) % numMorphTargets ); + trim: function() { - values.push( 0, 1, 0 ); + for ( var i = 0; i < this.tracks.length; i ++ ) { - var order = exports.AnimationUtils.getKeyframeOrder( times ); - times = exports.AnimationUtils.sortedArray( times, 1, order ); - values = exports.AnimationUtils.sortedArray( values, 1, order ); + this.tracks[ i ].trim( 0, this.duration ); - // 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 ] ); + return this; - } + }, - tracks.push( - new NumberKeyframeTrack( - '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']', - times, values - ).scale( 1.0 / fps ) ); - } + optimize: function() { - return new AnimationClip( name, -1, tracks ); + for ( var i = 0; i < this.tracks.length; i ++ ) { - }, + this.tracks[ i ].optimize(); - findByName: function( objectOrClipArray, name ) { + } - var clipArray = objectOrClipArray; + return this; - if ( ! Array.isArray( objectOrClipArray ) ) { + } - var o = objectOrClipArray; - clipArray = o.geometry && o.geometry.animations || o.animations; + }; - } + // Static methods: - for ( var i = 0; i < clipArray.length; i ++ ) { + Object.assign( AnimationClip, { - if ( clipArray[ i ].name === name ) { + parse: function( json ) { - return clipArray[ i ]; + var tracks = [], + jsonTracks = json.tracks, + frameTime = 1.0 / ( json.fps || 1.0 ); - } - } + for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) { - return null; + tracks.push( KeyframeTrack.parse( jsonTracks[ i ] ).scale( frameTime ) ); - }, + } - CreateClipsFromMorphTargetSequences: function( morphTargets, fps, noLoop ) { + return new AnimationClip( json.name, json.duration, tracks ); - var animationToMorphTargets = {}; + }, - // tested with https://regex101.com/ on trick sequences - // such flamingo_flyA_003, flamingo_run1_003, crdeath0059 - var pattern = /^([\w-]*?)([\d]+)$/; - // 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 ++ ) { + toJSON: function( clip ) { - var morphTarget = morphTargets[ i ]; - var parts = morphTarget.name.match( pattern ); + var tracks = [], + clipTracks = clip.tracks; - if ( parts && parts.length > 1 ) { + var json = { - var name = parts[ 1 ]; + 'name': clip.name, + 'duration': clip.duration, + 'tracks': tracks - var animationMorphTargets = animationToMorphTargets[ name ]; - if ( ! animationMorphTargets ) { + }; - animationToMorphTargets[ name ] = animationMorphTargets = []; + for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) { - } + tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) ); - animationMorphTargets.push( morphTarget ); + } - } + return json; - } + }, - var clips = []; - for ( var name in animationToMorphTargets ) { + CreateFromMorphTargetSequence: function( name, morphTargetSequence, fps, noLoop ) { - clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) ); + var numMorphTargets = morphTargetSequence.length; + var tracks = []; - } + for ( var i = 0; i < numMorphTargets; i ++ ) { - return clips; + var times = []; + var values = []; - }, + times.push( + ( i + numMorphTargets - 1 ) % numMorphTargets, + i, + ( i + 1 ) % numMorphTargets ); - // parse the animation.hierarchy format - parseAnimation: function( animation, bones, nodeName ) { + values.push( 0, 1, 0 ); - if ( ! animation ) { + var order = exports.AnimationUtils.getKeyframeOrder( times ); + times = exports.AnimationUtils.sortedArray( times, 1, order ); + values = exports.AnimationUtils.sortedArray( values, 1, order ); - console.error( " no animation in JSONLoader data" ); - return null; + // 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 ] ); - var addNonemptyTrack = function( - trackType, trackName, animationKeys, propertyName, destTracks ) { + } - // only return track if there are actually keys. - if ( animationKeys.length !== 0 ) { + tracks.push( + new NumberKeyframeTrack( + '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']', + times, values + ).scale( 1.0 / fps ) ); + } - var times = []; - var values = []; + return new AnimationClip( name, -1, tracks ); - exports.AnimationUtils.flattenJSON( - animationKeys, times, values, propertyName ); + }, - // empty keys are filtered out, so check again - if ( times.length !== 0 ) { + findByName: function( objectOrClipArray, name ) { - destTracks.push( new trackType( trackName, times, values ) ); + var clipArray = objectOrClipArray; - } + if ( ! Array.isArray( objectOrClipArray ) ) { - } + var o = objectOrClipArray; + clipArray = o.geometry && o.geometry.animations || o.animations; - }; + } - var tracks = []; + for ( var i = 0; i < clipArray.length; i ++ ) { - var clipName = animation.name || 'default'; - // automatic length determination in AnimationClip. - var duration = animation.length || -1; - var fps = animation.fps || 30; + if ( clipArray[ i ].name === name ) { - var hierarchyTracks = animation.hierarchy || []; + return clipArray[ i ]; - for ( var h = 0; h < hierarchyTracks.length; h ++ ) { + } + } - 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 ) { + CreateClipsFromMorphTargetSequences: function( morphTargets, fps, noLoop ) { - // figure out all morph targets used in this track - var morphTargetNames = {}; - for ( var k = 0; k < animationKeys.length; k ++ ) { + var animationToMorphTargets = {}; - if ( animationKeys[k].morphTargets ) { + // tested with https://regex101.com/ on trick sequences + // such flamingo_flyA_003, flamingo_run1_003, crdeath0059 + var pattern = /^([\w-]*?)([\d]+)$/; - for ( var m = 0; m < animationKeys[k].morphTargets.length; m ++ ) { + // 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 ++ ) { - morphTargetNames[ animationKeys[k].morphTargets[m] ] = -1; - } + var morphTarget = morphTargets[ i ]; + var parts = morphTarget.name.match( pattern ); - } + if ( parts && parts.length > 1 ) { - } + var name = parts[ 1 ]; - // 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 animationMorphTargets = animationToMorphTargets[ name ]; + if ( ! animationMorphTargets ) { - var times = []; - var values = []; + animationToMorphTargets[ name ] = animationMorphTargets = []; - for ( var m = 0; - m !== animationKeys[k].morphTargets.length; ++ m ) { + } - var animationKey = animationKeys[k]; + animationMorphTargets.push( morphTarget ); - times.push( animationKey.time ); - values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 ); + } - } + } - tracks.push( new NumberKeyframeTrack( - '.morphTargetInfluence[' + morphTargetName + ']', times, values ) ); + var clips = []; - } + for ( var name in animationToMorphTargets ) { - duration = morphTargetNames.length * ( fps || 1.0 ); + clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) ); - } else { - // ...assume skeletal animation + } - var boneName = '.bones[' + bones[ h ].name + ']'; + return clips; - addNonemptyTrack( - VectorKeyframeTrack, boneName + '.position', - animationKeys, 'pos', tracks ); + }, - addNonemptyTrack( - QuaternionKeyframeTrack, boneName + '.quaternion', - animationKeys, 'rot', tracks ); + // parse the animation.hierarchy format + parseAnimation: function( animation, bones, nodeName ) { - addNonemptyTrack( - VectorKeyframeTrack, boneName + '.scale', - animationKeys, 'scl', tracks ); + if ( ! animation ) { - } + console.error( " no animation in JSONLoader data" ); + return null; - } + } - if ( tracks.length === 0 ) { + 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 = []; - var clip = new AnimationClip( clipName, duration, tracks ); + exports.AnimationUtils.flattenJSON( + animationKeys, times, values, propertyName ); - return clip; + // empty keys are filtered out, so check again + if ( times.length !== 0 ) { - } + destTracks.push( new trackType( trackName, times, values ) ); - } ); + } - /** - * @author mrdoob / http://mrdoob.com/ - */ + } - function MaterialLoader( manager ) { + }; - this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; - this.textures = {}; + var tracks = []; - }; + var clipName = animation.name || 'default'; + // automatic length determination in AnimationClip. + var duration = animation.length || -1; + var fps = animation.fps || 30; - Object.assign( MaterialLoader.prototype, { + var hierarchyTracks = animation.hierarchy || []; - load: function ( url, onLoad, onProgress, onError ) { + for ( var h = 0; h < hierarchyTracks.length; h ++ ) { - var scope = this; + var animationKeys = hierarchyTracks[ h ].keys; - var loader = new XHRLoader( scope.manager ); - loader.load( url, function ( text ) { + // skip empty tracks + if ( ! animationKeys || animationKeys.length === 0 ) continue; - onLoad( scope.parse( JSON.parse( text ) ) ); + // process morph targets in a way exactly compatible + // with AnimationHandler.init( animation ) + if ( animationKeys[0].morphTargets ) { - }, onProgress, onError ); + // figure out all morph targets used in this track + var morphTargetNames = {}; + for ( var k = 0; k < animationKeys.length; k ++ ) { - }, + if ( animationKeys[k].morphTargets ) { - setTextures: function ( value ) { + for ( var m = 0; m < animationKeys[k].morphTargets.length; m ++ ) { - this.textures = value; + morphTargetNames[ animationKeys[k].morphTargets[m] ] = -1; + } - }, + } - getTexture: function ( name ) { + } - var textures = 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 ) { - if ( textures[ name ] === undefined ) { + var times = []; + var values = []; - console.warn( 'THREE.MaterialLoader: Undefined texture', name ); + for ( var m = 0; + m !== animationKeys[k].morphTargets.length; ++ m ) { - } + var animationKey = animationKeys[k]; - return textures[ name ]; + times.push( animationKey.time ); + values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 ); - }, + } - parse: function ( json ) { + tracks.push( new NumberKeyframeTrack( + '.morphTargetInfluence[' + morphTargetName + ']', times, values ) ); - var material = new THREE[ json.type ]; + } - 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; + duration = morphTargetNames.length * ( fps || 1.0 ); - // for PointsMaterial - if ( json.size !== undefined ) material.size = json.size; - if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation; + } else { + // ...assume skeletal animation - // maps + var boneName = '.bones[' + bones[ h ].name + ']'; - if ( json.map !== undefined ) material.map = this.getTexture( json.map ); + addNonemptyTrack( + VectorKeyframeTrack, boneName + '.position', + animationKeys, 'pos', tracks ); - if ( json.alphaMap !== undefined ) { + addNonemptyTrack( + QuaternionKeyframeTrack, boneName + '.quaternion', + animationKeys, 'rot', tracks ); - material.alphaMap = this.getTexture( json.alphaMap ); - material.transparent = true; + addNonemptyTrack( + VectorKeyframeTrack, boneName + '.scale', + animationKeys, 'scl', tracks ); - } + } - if ( json.bumpMap !== undefined ) material.bumpMap = this.getTexture( json.bumpMap ); - if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale; + } - if ( json.normalMap !== undefined ) material.normalMap = this.getTexture( json.normalMap ); - if ( json.normalScale !== undefined ) { + if ( tracks.length === 0 ) { - var normalScale = json.normalScale; + return null; - if ( Array.isArray( normalScale ) === false ) { + } - // Blender exporter used to export a scalar. See #7459 + var clip = new AnimationClip( clipName, duration, tracks ); - normalScale = [ normalScale, normalScale ]; + return clip; - } + } - material.normalScale = new Vector2().fromArray( normalScale ); + } ); - } + /** + * @author mrdoob / http://mrdoob.com/ + */ - 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; + function MaterialLoader( manager ) { - if ( json.roughnessMap !== undefined ) material.roughnessMap = this.getTexture( json.roughnessMap ); - if ( json.metalnessMap !== undefined ) material.metalnessMap = this.getTexture( json.metalnessMap ); + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; + this.textures = {}; - if ( json.emissiveMap !== undefined ) material.emissiveMap = this.getTexture( json.emissiveMap ); - if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity; + }; - if ( json.specularMap !== undefined ) material.specularMap = this.getTexture( json.specularMap ); + Object.assign( MaterialLoader.prototype, { - if ( json.envMap !== undefined ) { + load: function ( url, onLoad, onProgress, onError ) { - material.envMap = this.getTexture( json.envMap ); - material.combine = MultiplyOperation; + var scope = this; - } + var loader = new XHRLoader( scope.manager ); + loader.load( url, function ( text ) { - if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity; + onLoad( scope.parse( JSON.parse( text ) ) ); - if ( json.lightMap !== undefined ) material.lightMap = this.getTexture( json.lightMap ); - if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity; + }, onProgress, onError ); - if ( json.aoMap !== undefined ) material.aoMap = this.getTexture( json.aoMap ); - if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity; + }, - // MultiMaterial + setTextures: function ( value ) { - if ( json.materials !== undefined ) { + this.textures = value; - for ( var i = 0, l = json.materials.length; i < l; i ++ ) { + }, - material.materials.push( this.parse( json.materials[ i ] ) ); + getTexture: function ( name ) { - } + var textures = this.textures; - } + if ( textures[ name ] === undefined ) { - return material; + console.warn( 'THREE.MaterialLoader: Undefined texture', name ); - } + } - } ); + return textures[ name ]; - /** - * @author mrdoob / http://mrdoob.com/ - */ + }, - function BufferGeometryLoader( manager ) { + parse: function ( json ) { - this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; + var material = new THREE[ json.type ]; - }; + 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; - Object.assign( BufferGeometryLoader.prototype, { + // for PointsMaterial + if ( json.size !== undefined ) material.size = json.size; + if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation; - load: function ( url, onLoad, onProgress, onError ) { + // maps - var scope = this; + if ( json.map !== undefined ) material.map = this.getTexture( json.map ); - var loader = new XHRLoader( scope.manager ); - loader.load( url, function ( text ) { + if ( json.alphaMap !== undefined ) { - onLoad( scope.parse( JSON.parse( text ) ) ); + material.alphaMap = this.getTexture( json.alphaMap ); + material.transparent = true; - }, onProgress, onError ); + } - }, + if ( json.bumpMap !== undefined ) material.bumpMap = this.getTexture( json.bumpMap ); + if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale; - parse: function ( json ) { + if ( json.normalMap !== undefined ) material.normalMap = this.getTexture( json.normalMap ); + if ( json.normalScale !== undefined ) { - var geometry = new BufferGeometry(); + var normalScale = json.normalScale; - var index = json.data.index; + if ( Array.isArray( normalScale ) === false ) { - var TYPED_ARRAYS = { - 'Int8Array': Int8Array, - 'Uint8Array': Uint8Array, - 'Uint8ClampedArray': Uint8ClampedArray, - 'Int16Array': Int16Array, - 'Uint16Array': Uint16Array, - 'Int32Array': Int32Array, - 'Uint32Array': Uint32Array, - 'Float32Array': Float32Array, - 'Float64Array': Float64Array - }; + // Blender exporter used to export a scalar. See #7459 - if ( index !== undefined ) { + normalScale = [ normalScale, normalScale ]; - var typedArray = new TYPED_ARRAYS[ index.type ]( index.array ); - geometry.setIndex( new BufferAttribute( typedArray, 1 ) ); + } - } + material.normalScale = new Vector2().fromArray( normalScale ); - var attributes = json.data.attributes; + } - for ( var key in attributes ) { + 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; - var attribute = attributes[ key ]; - var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array ); + if ( json.roughnessMap !== undefined ) material.roughnessMap = this.getTexture( json.roughnessMap ); + if ( json.metalnessMap !== undefined ) material.metalnessMap = this.getTexture( json.metalnessMap ); - geometry.addAttribute( key, new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ) ); + if ( json.emissiveMap !== undefined ) material.emissiveMap = this.getTexture( json.emissiveMap ); + if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity; - } + if ( json.specularMap !== undefined ) material.specularMap = this.getTexture( json.specularMap ); - var groups = json.data.groups || json.data.drawcalls || json.data.offsets; + if ( json.envMap !== undefined ) { - if ( groups !== undefined ) { + material.envMap = this.getTexture( json.envMap ); + material.combine = MultiplyOperation; - for ( var i = 0, n = groups.length; i !== n; ++ i ) { + } - var group = groups[ i ]; + if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity; - geometry.addGroup( group.start, group.count, group.materialIndex ); + if ( json.lightMap !== undefined ) material.lightMap = this.getTexture( json.lightMap ); + if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity; - } + if ( json.aoMap !== undefined ) material.aoMap = this.getTexture( json.aoMap ); + if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity; - } + // MultiMaterial - var boundingSphere = json.data.boundingSphere; + if ( json.materials !== undefined ) { - if ( boundingSphere !== undefined ) { + for ( var i = 0, l = json.materials.length; i < l; i ++ ) { - var center = new Vector3(); + material.materials.push( this.parse( json.materials[ i ] ) ); - if ( boundingSphere.center !== undefined ) { + } - center.fromArray( boundingSphere.center ); + } - } + return material; - geometry.boundingSphere = new Sphere( center, boundingSphere.radius ); + } - } + } ); - return geometry; + /** + * @author mrdoob / http://mrdoob.com/ + */ - } + function BufferGeometryLoader( manager ) { - } ); + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; - /** - * @author alteredq / http://alteredqualia.com/ - */ + }; - function Loader() { + Object.assign( BufferGeometryLoader.prototype, { - this.onLoadStart = function () {}; - this.onLoadProgress = function () {}; - this.onLoadComplete = function () {}; + load: function ( url, onLoad, onProgress, onError ) { - }; + var scope = this; - Loader.prototype = { + var loader = new XHRLoader( scope.manager ); + loader.load( url, function ( text ) { - constructor: Loader, + onLoad( scope.parse( JSON.parse( text ) ) ); - crossOrigin: undefined, + }, onProgress, onError ); - extractUrlBase: function ( url ) { + }, - var parts = url.split( '/' ); + parse: function ( json ) { - if ( parts.length === 1 ) return './'; + var geometry = new BufferGeometry(); - parts.pop(); + var index = json.data.index; - return parts.join( '/' ) + '/'; + var TYPED_ARRAYS = { + 'Int8Array': Int8Array, + 'Uint8Array': Uint8Array, + 'Uint8ClampedArray': Uint8ClampedArray, + 'Int16Array': Int16Array, + 'Uint16Array': Uint16Array, + 'Int32Array': Int32Array, + 'Uint32Array': Uint32Array, + 'Float32Array': Float32Array, + 'Float64Array': Float64Array + }; - }, + if ( index !== undefined ) { - initMaterials: function ( materials, texturePath, crossOrigin ) { + var typedArray = new TYPED_ARRAYS[ index.type ]( index.array ); + geometry.setIndex( new BufferAttribute( typedArray, 1 ) ); - var array = []; + } - for ( var i = 0; i < materials.length; ++ i ) { + var attributes = json.data.attributes; - array[ i ] = this.createMaterial( materials[ i ], texturePath, crossOrigin ); + for ( var key in attributes ) { - } + var attribute = attributes[ key ]; + var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array ); - return array; + geometry.addAttribute( key, new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ) ); - }, + } - createMaterial: ( function () { + var groups = json.data.groups || json.data.drawcalls || json.data.offsets; - var color, textureLoader, materialLoader; + if ( groups !== undefined ) { - return function createMaterial( m, texturePath, crossOrigin ) { + for ( var i = 0, n = groups.length; i !== n; ++ i ) { - if ( color === undefined ) color = new Color(); - if ( textureLoader === undefined ) textureLoader = new TextureLoader(); - if ( materialLoader === undefined ) materialLoader = new MaterialLoader(); + var group = groups[ i ]; - // convert from old material format + geometry.addGroup( group.start, group.count, group.materialIndex ); - var textures = {}; + } - function loadTexture( path, repeat, offset, wrap, anisotropy ) { + } - var fullPath = texturePath + path; - var loader = Loader.Handlers.get( fullPath ); + var boundingSphere = json.data.boundingSphere; - var texture; + if ( boundingSphere !== undefined ) { - if ( loader !== null ) { + var center = new Vector3(); - texture = loader.load( fullPath ); + if ( boundingSphere.center !== undefined ) { - } else { + center.fromArray( boundingSphere.center ); - textureLoader.setCrossOrigin( crossOrigin ); - texture = textureLoader.load( fullPath ); + } - } + geometry.boundingSphere = new Sphere( center, boundingSphere.radius ); - if ( repeat !== undefined ) { + } - texture.repeat.fromArray( repeat ); + return geometry; - if ( repeat[ 0 ] !== 1 ) texture.wrapS = RepeatWrapping; - if ( repeat[ 1 ] !== 1 ) texture.wrapT = RepeatWrapping; + } - } + } ); - if ( offset !== undefined ) { + /** + * @author alteredq / http://alteredqualia.com/ + */ - texture.offset.fromArray( offset ); + function Loader() { - } + this.onLoadStart = function () {}; + this.onLoadProgress = function () {}; + this.onLoadComplete = function () {}; - if ( wrap !== undefined ) { + }; - if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = RepeatWrapping; - if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = MirroredRepeatWrapping; + Loader.prototype = { - if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = RepeatWrapping; - if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = MirroredRepeatWrapping; + constructor: Loader, - } + crossOrigin: undefined, - if ( anisotropy !== undefined ) { + extractUrlBase: function ( url ) { - texture.anisotropy = anisotropy; + var parts = url.split( '/' ); - } + if ( parts.length === 1 ) return './'; - var uuid = exports.Math.generateUUID(); + parts.pop(); - textures[ uuid ] = texture; + return parts.join( '/' ) + '/'; - return uuid; + }, - } + initMaterials: function ( materials, texturePath, crossOrigin ) { - // + var array = []; - 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 ); + for ( var i = 0; i < materials.length; ++ i ) { - return materialLoader.parse( json ); + array[ i ] = this.createMaterial( materials[ i ], texturePath, crossOrigin ); - }; + } - } )() + return array; - }; + }, - Loader.Handlers = { + createMaterial: ( function () { - handlers: [], + var color, textureLoader, materialLoader; - add: function ( regex, loader ) { + return function createMaterial( m, texturePath, crossOrigin ) { - this.handlers.push( regex, loader ); + if ( color === undefined ) color = new Color(); + if ( textureLoader === undefined ) textureLoader = new TextureLoader(); + if ( materialLoader === undefined ) materialLoader = new MaterialLoader(); - }, + // convert from old material format - get: function ( file ) { + var textures = {}; - var handlers = this.handlers; + function loadTexture( path, repeat, offset, wrap, anisotropy ) { - for ( var i = 0, l = handlers.length; i < l; i += 2 ) { + var fullPath = texturePath + path; + var loader = Loader.Handlers.get( fullPath ); - var regex = handlers[ i ]; - var loader = handlers[ i + 1 ]; + var texture; - if ( regex.test( file ) ) { + if ( loader !== null ) { - return loader; + texture = loader.load( fullPath ); - } + } else { - } + textureLoader.setCrossOrigin( crossOrigin ); + texture = textureLoader.load( fullPath ); - return null; + } - } + if ( repeat !== undefined ) { - }; + texture.repeat.fromArray( repeat ); - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + if ( repeat[ 0 ] !== 1 ) texture.wrapS = RepeatWrapping; + if ( repeat[ 1 ] !== 1 ) texture.wrapT = RepeatWrapping; - function JSONLoader( manager ) { + } - if ( typeof manager === 'boolean' ) { + if ( offset !== undefined ) { - console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' ); - manager = undefined; + texture.offset.fromArray( offset ); - } + } - this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; + if ( wrap !== undefined ) { - this.withCredentials = false; + 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 ); + + }; + + } )() - }; + }; - Object.assign( JSONLoader.prototype, { + Loader.Handlers = { - load: function( url, onLoad, onProgress, onError ) { + handlers: [], - var scope = this; + add: function ( regex, loader ) { - var texturePath = this.texturePath && ( typeof this.texturePath === "string" ) ? this.texturePath : Loader.prototype.extractUrlBase( url ); + this.handlers.push( regex, loader ); - var loader = new XHRLoader( this.manager ); - loader.setWithCredentials( this.withCredentials ); - loader.load( url, function ( text ) { + }, - var json = JSON.parse( text ); - var metadata = json.metadata; + get: function ( file ) { - if ( metadata !== undefined ) { + var handlers = this.handlers; - var type = metadata.type; + for ( var i = 0, l = handlers.length; i < l; i += 2 ) { - if ( type !== undefined ) { + var regex = handlers[ i ]; + var loader = handlers[ i + 1 ]; - if ( type.toLowerCase() === 'object' ) { + if ( regex.test( file ) ) { - console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' ); - return; + return loader; - } + } - if ( type.toLowerCase() === 'scene' ) { + } - console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.SceneLoader instead.' ); - return; + return null; - } + } - } + }; - } + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - var object = scope.parse( json, texturePath ); - onLoad( object.geometry, object.materials ); + function JSONLoader( manager ) { - }, onProgress, onError ); + if ( typeof manager === 'boolean' ) { - }, + console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' ); + manager = undefined; - setTexturePath: function ( value ) { + } - this.texturePath = value; + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; - }, + this.withCredentials = false; - parse: function ( json, texturePath ) { + }; - var geometry = new Geometry(), - scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0; + Object.assign( JSONLoader.prototype, { - parseModel( scale ); + load: function( url, onLoad, onProgress, onError ) { - parseSkin(); - parseMorphing( scale ); - parseAnimations(); + var scope = this; - geometry.computeFaceNormals(); - geometry.computeBoundingSphere(); + var texturePath = this.texturePath && ( typeof this.texturePath === "string" ) ? this.texturePath : Loader.prototype.extractUrlBase( url ); - function parseModel( scale ) { + var loader = new XHRLoader( this.manager ); + loader.setWithCredentials( this.withCredentials ); + loader.load( url, function ( text ) { - function isBitSet( value, position ) { + var json = JSON.parse( text ); + var metadata = json.metadata; - return value & ( 1 << position ); + if ( metadata !== undefined ) { - } + var type = metadata.type; - var i, j, fi, + if ( type !== undefined ) { - offset, zLength, + if ( type.toLowerCase() === 'object' ) { - colorIndex, normalIndex, uvIndex, materialIndex, + console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' ); + return; - type, - isQuad, - hasMaterial, - hasFaceVertexUv, - hasFaceNormal, hasFaceVertexNormal, - hasFaceColor, hasFaceVertexColor, + } - vertex, face, faceA, faceB, hex, normal, + if ( type.toLowerCase() === 'scene' ) { - uvLayer, uv, u, v, + console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.SceneLoader instead.' ); + return; - faces = json.faces, - vertices = json.vertices, - normals = json.normals, - colors = json.colors, + } - nUvLayers = 0; + } - if ( json.uvs !== undefined ) { + } - // disregard empty arrays + var object = scope.parse( json, texturePath ); + onLoad( object.geometry, object.materials ); - for ( i = 0; i < json.uvs.length; i ++ ) { + }, onProgress, onError ); - if ( json.uvs[ i ].length ) nUvLayers ++; + }, - } + setTexturePath: function ( value ) { - for ( i = 0; i < nUvLayers; i ++ ) { + this.texturePath = value; - geometry.faceVertexUvs[ i ] = []; + }, - } + parse: function ( json, texturePath ) { - } + var geometry = new Geometry(), + scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0; - offset = 0; - zLength = vertices.length; + parseModel( scale ); - while ( offset < zLength ) { + parseSkin(); + parseMorphing( scale ); + parseAnimations(); - vertex = new Vector3(); + geometry.computeFaceNormals(); + geometry.computeBoundingSphere(); - vertex.x = vertices[ offset ++ ] * scale; - vertex.y = vertices[ offset ++ ] * scale; - vertex.z = vertices[ offset ++ ] * scale; + function parseModel( scale ) { - geometry.vertices.push( vertex ); + function isBitSet( value, position ) { - } + return value & ( 1 << position ); - offset = 0; - zLength = faces.length; + } - while ( offset < zLength ) { + var i, j, fi, - type = faces[ offset ++ ]; + offset, zLength, + colorIndex, normalIndex, uvIndex, materialIndex, - 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 ); + type, + isQuad, + hasMaterial, + hasFaceVertexUv, + hasFaceNormal, hasFaceVertexNormal, + hasFaceColor, hasFaceVertexColor, - // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor); + vertex, face, faceA, faceB, hex, normal, - if ( isQuad ) { + uvLayer, uv, u, v, - faceA = new Face3(); - faceA.a = faces[ offset ]; - faceA.b = faces[ offset + 1 ]; - faceA.c = faces[ offset + 3 ]; + faces = json.faces, + vertices = json.vertices, + normals = json.normals, + colors = json.colors, - faceB = new Face3(); - faceB.a = faces[ offset + 1 ]; - faceB.b = faces[ offset + 2 ]; - faceB.c = faces[ offset + 3 ]; + nUvLayers = 0; - offset += 4; + if ( json.uvs !== undefined ) { - if ( hasMaterial ) { + // disregard empty arrays - materialIndex = faces[ offset ++ ]; - faceA.materialIndex = materialIndex; - faceB.materialIndex = materialIndex; + for ( i = 0; i < json.uvs.length; i ++ ) { - } + if ( json.uvs[ i ].length ) nUvLayers ++; - // to get face <=> uv index correspondence + } - fi = geometry.faces.length; + for ( i = 0; i < nUvLayers; i ++ ) { - if ( hasFaceVertexUv ) { + geometry.faceVertexUvs[ i ] = []; - for ( i = 0; i < nUvLayers; i ++ ) { + } - uvLayer = json.uvs[ i ]; + } - geometry.faceVertexUvs[ i ][ fi ] = []; - geometry.faceVertexUvs[ i ][ fi + 1 ] = []; + offset = 0; + zLength = vertices.length; - for ( j = 0; j < 4; j ++ ) { + while ( offset < zLength ) { - uvIndex = faces[ offset ++ ]; + vertex = new Vector3(); - u = uvLayer[ uvIndex * 2 ]; - v = uvLayer[ uvIndex * 2 + 1 ]; + vertex.x = vertices[ offset ++ ] * scale; + vertex.y = vertices[ offset ++ ] * scale; + vertex.z = vertices[ offset ++ ] * scale; - uv = new Vector2( u, v ); + geometry.vertices.push( vertex ); - if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv ); - if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv ); + } - } + offset = 0; + zLength = faces.length; - } + while ( offset < zLength ) { - } + type = faces[ offset ++ ]; - if ( hasFaceNormal ) { - normalIndex = faces[ offset ++ ] * 3; + 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 ); - faceA.normal.set( - normals[ normalIndex ++ ], - normals[ normalIndex ++ ], - normals[ normalIndex ] - ); + // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor); - faceB.normal.copy( faceA.normal ); + if ( isQuad ) { - } + faceA = new Face3(); + faceA.a = faces[ offset ]; + faceA.b = faces[ offset + 1 ]; + faceA.c = faces[ offset + 3 ]; - if ( hasFaceVertexNormal ) { + faceB = new Face3(); + faceB.a = faces[ offset + 1 ]; + faceB.b = faces[ offset + 2 ]; + faceB.c = faces[ offset + 3 ]; - for ( i = 0; i < 4; i ++ ) { + offset += 4; - normalIndex = faces[ offset ++ ] * 3; + if ( hasMaterial ) { - normal = new Vector3( - normals[ normalIndex ++ ], - normals[ normalIndex ++ ], - normals[ normalIndex ] - ); + materialIndex = faces[ offset ++ ]; + faceA.materialIndex = materialIndex; + faceB.materialIndex = materialIndex; + } - if ( i !== 2 ) faceA.vertexNormals.push( normal ); - if ( i !== 0 ) faceB.vertexNormals.push( normal ); + // to get face <=> uv index correspondence - } + fi = geometry.faces.length; - } + if ( hasFaceVertexUv ) { + for ( i = 0; i < nUvLayers; i ++ ) { - if ( hasFaceColor ) { + uvLayer = json.uvs[ i ]; - colorIndex = faces[ offset ++ ]; - hex = colors[ colorIndex ]; + geometry.faceVertexUvs[ i ][ fi ] = []; + geometry.faceVertexUvs[ i ][ fi + 1 ] = []; - faceA.color.setHex( hex ); - faceB.color.setHex( hex ); + for ( j = 0; j < 4; j ++ ) { - } + uvIndex = faces[ offset ++ ]; + u = uvLayer[ uvIndex * 2 ]; + v = uvLayer[ uvIndex * 2 + 1 ]; - if ( hasFaceVertexColor ) { + 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 ); - 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 ( hasFaceNormal ) { - geometry.faces.push( faceA ); - geometry.faces.push( faceB ); + normalIndex = faces[ offset ++ ] * 3; - } else { + faceA.normal.set( + normals[ normalIndex ++ ], + normals[ normalIndex ++ ], + normals[ normalIndex ] + ); - face = new Face3(); - face.a = faces[ offset ++ ]; - face.b = faces[ offset ++ ]; - face.c = faces[ offset ++ ]; + faceB.normal.copy( faceA.normal ); - if ( hasMaterial ) { + } - materialIndex = faces[ offset ++ ]; - face.materialIndex = materialIndex; + if ( hasFaceVertexNormal ) { - } + for ( i = 0; i < 4; i ++ ) { - // to get face <=> uv index correspondence + normalIndex = faces[ offset ++ ] * 3; - fi = geometry.faces.length; + normal = new Vector3( + normals[ normalIndex ++ ], + normals[ normalIndex ++ ], + normals[ normalIndex ] + ); - if ( hasFaceVertexUv ) { - for ( i = 0; i < nUvLayers; i ++ ) { + if ( i !== 2 ) faceA.vertexNormals.push( normal ); + if ( i !== 0 ) faceB.vertexNormals.push( normal ); - uvLayer = json.uvs[ i ]; + } - geometry.faceVertexUvs[ i ][ fi ] = []; + } - for ( j = 0; j < 3; j ++ ) { - uvIndex = faces[ offset ++ ]; + if ( hasFaceColor ) { - u = uvLayer[ uvIndex * 2 ]; - v = uvLayer[ uvIndex * 2 + 1 ]; + colorIndex = faces[ offset ++ ]; + hex = colors[ colorIndex ]; - uv = new Vector2( u, v ); + faceA.color.setHex( hex ); + faceB.color.setHex( hex ); - geometry.faceVertexUvs[ i ][ fi ].push( uv ); + } - } - } + if ( hasFaceVertexColor ) { - } + for ( i = 0; i < 4; i ++ ) { - if ( hasFaceNormal ) { + colorIndex = faces[ offset ++ ]; + hex = colors[ colorIndex ]; - normalIndex = faces[ offset ++ ] * 3; + if ( i !== 2 ) faceA.vertexColors.push( new Color( hex ) ); + if ( i !== 0 ) faceB.vertexColors.push( new Color( hex ) ); - face.normal.set( - normals[ normalIndex ++ ], - normals[ normalIndex ++ ], - normals[ normalIndex ] - ); + } - } + } - if ( hasFaceVertexNormal ) { + geometry.faces.push( faceA ); + geometry.faces.push( faceB ); - for ( i = 0; i < 3; i ++ ) { + } else { - normalIndex = faces[ offset ++ ] * 3; + face = new Face3(); + face.a = faces[ offset ++ ]; + face.b = faces[ offset ++ ]; + face.c = faces[ offset ++ ]; - normal = new Vector3( - normals[ normalIndex ++ ], - normals[ normalIndex ++ ], - normals[ normalIndex ] - ); + if ( hasMaterial ) { - face.vertexNormals.push( normal ); + materialIndex = faces[ offset ++ ]; + face.materialIndex = materialIndex; - } + } - } + // to get face <=> uv index correspondence + fi = geometry.faces.length; - if ( hasFaceColor ) { + if ( hasFaceVertexUv ) { - colorIndex = faces[ offset ++ ]; - face.color.setHex( colors[ colorIndex ] ); + for ( i = 0; i < nUvLayers; i ++ ) { - } + uvLayer = json.uvs[ i ]; + geometry.faceVertexUvs[ i ][ fi ] = []; - if ( hasFaceVertexColor ) { + for ( j = 0; j < 3; j ++ ) { - for ( i = 0; i < 3; i ++ ) { + uvIndex = faces[ offset ++ ]; - colorIndex = faces[ offset ++ ]; - face.vertexColors.push( new Color( colors[ colorIndex ] ) ); + u = uvLayer[ uvIndex * 2 ]; + v = uvLayer[ uvIndex * 2 + 1 ]; - } + uv = new Vector2( u, v ); - } + geometry.faceVertexUvs[ i ][ fi ].push( uv ); - geometry.faces.push( face ); + } - } + } - } + } - } + if ( hasFaceNormal ) { - function parseSkin() { + normalIndex = faces[ offset ++ ] * 3; - var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2; + face.normal.set( + normals[ normalIndex ++ ], + normals[ normalIndex ++ ], + normals[ normalIndex ] + ); - if ( json.skinWeights ) { + } - for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) { + if ( hasFaceVertexNormal ) { - 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; + for ( i = 0; i < 3; i ++ ) { - geometry.skinWeights.push( new Vector4( x, y, z, w ) ); + normalIndex = faces[ offset ++ ] * 3; - } + normal = new Vector3( + normals[ normalIndex ++ ], + normals[ normalIndex ++ ], + normals[ normalIndex ] + ); - } + face.vertexNormals.push( normal ); - 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; - geometry.skinIndices.push( new Vector4( a, b, c, d ) ); + if ( hasFaceColor ) { - } + colorIndex = faces[ offset ++ ]; + face.color.setHex( colors[ colorIndex ] ); - } + } - geometry.bones = json.bones; - if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) { + if ( hasFaceVertexColor ) { - console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' + - geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' ); + for ( i = 0; i < 3; i ++ ) { - } + colorIndex = faces[ offset ++ ]; + face.vertexColors.push( new Color( colors[ colorIndex ] ) ); - } + } - function parseMorphing( scale ) { + } - if ( json.morphTargets !== undefined ) { + geometry.faces.push( face ); - for ( var i = 0, l = json.morphTargets.length; i < l; i ++ ) { + } - 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 ) { + function parseSkin() { - var vertex = new Vector3(); - vertex.x = srcVertices[ v ] * scale; - vertex.y = srcVertices[ v + 1 ] * scale; - vertex.z = srcVertices[ v + 2 ] * scale; + var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2; - dstVertices.push( vertex ); + if ( json.skinWeights ) { - } + for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) { - } + 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 ) ); - if ( json.morphColors !== undefined && json.morphColors.length > 0 ) { + } - console.warn( 'THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.' ); + } - var faces = geometry.faces; - var morphColors = json.morphColors[ 0 ].colors; + if ( json.skinIndices ) { - for ( var i = 0, l = faces.length; i < l; i ++ ) { + for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) { - faces[ i ].color.fromArray( morphColors, i * 3 ); + 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; - } + geometry.skinIndices.push( new Vector4( a, b, c, d ) ); - } + } - } + } - function parseAnimations() { + geometry.bones = json.bones; - var outputAnimations = []; + if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) { - // parse old style Bone/Hierarchy animations - var animations = []; + console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' + + geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' ); - if ( json.animation !== undefined ) { + } - animations.push( json.animation ); + } - } + function parseMorphing( scale ) { - if ( json.animations !== undefined ) { + if ( json.morphTargets !== undefined ) { - if ( json.animations.length ) { + for ( var i = 0, l = json.morphTargets.length; i < l; i ++ ) { - animations = animations.concat( json.animations ); + geometry.morphTargets[ i ] = {}; + geometry.morphTargets[ i ].name = json.morphTargets[ i ].name; + geometry.morphTargets[ i ].vertices = []; - } else { + var dstVertices = geometry.morphTargets[ i ].vertices; + var srcVertices = json.morphTargets[ i ].vertices; - animations.push( json.animations ); + 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 ); - for ( var i = 0; i < animations.length; i ++ ) { + } - var clip = AnimationClip.parseAnimation( animations[ i ], geometry.bones ); - if ( clip ) outputAnimations.push( clip ); + } - } + } - // parse implicit morph animations - if ( geometry.morphTargets ) { + if ( json.morphColors !== undefined && json.morphColors.length > 0 ) { - // 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 ); + console.warn( 'THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.' ); - } + var faces = geometry.faces; + var morphColors = json.morphColors[ 0 ].colors; - if ( outputAnimations.length > 0 ) geometry.animations = outputAnimations; + for ( var i = 0, l = faces.length; i < l; i ++ ) { - } + faces[ i ].color.fromArray( morphColors, i * 3 ); - if ( json.materials === undefined || json.materials.length === 0 ) { + } - return { geometry: geometry }; + } - } else { + } - var materials = Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin ); + function parseAnimations() { - return { geometry: geometry, materials: materials }; + var outputAnimations = []; - } + // parse old style Bone/Hierarchy animations + var animations = []; - } + if ( json.animation !== undefined ) { - } ); + animations.push( json.animation ); - /** - * @author mrdoob / http://mrdoob.com/ - */ + } - function ObjectLoader ( manager ) { + if ( json.animations !== undefined ) { - this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; - this.texturePath = ''; + if ( json.animations.length ) { - } + animations = animations.concat( json.animations ); - Object.assign( ObjectLoader.prototype, { + } else { - load: function ( url, onLoad, onProgress, onError ) { + animations.push( json.animations ); - if ( this.texturePath === '' ) { + } - this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 ); + } - } + for ( var i = 0; i < animations.length; i ++ ) { - var scope = this; + var clip = AnimationClip.parseAnimation( animations[ i ], geometry.bones ); + if ( clip ) outputAnimations.push( clip ); - var loader = new XHRLoader( scope.manager ); - loader.load( url, function ( text ) { + } - scope.parse( JSON.parse( text ), onLoad ); + // parse implicit morph animations + if ( geometry.morphTargets ) { - }, onProgress, onError ); + // 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 ); - }, + } - setTexturePath: function ( value ) { + if ( outputAnimations.length > 0 ) geometry.animations = outputAnimations; - this.texturePath = value; + } - }, + if ( json.materials === undefined || json.materials.length === 0 ) { - setCrossOrigin: function ( value ) { + return { geometry: geometry }; - this.crossOrigin = value; + } else { - }, + var materials = Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin ); - parse: function ( json, onLoad ) { + return { geometry: geometry, materials: materials }; - var geometries = this.parseGeometries( json.geometries ); + } - var images = this.parseImages( json.images, function () { + } - if ( onLoad !== undefined ) onLoad( object ); + } ); - } ); + /** + * @author mrdoob / http://mrdoob.com/ + */ - var textures = this.parseTextures( json.textures, images ); - var materials = this.parseMaterials( json.materials, textures ); + function ObjectLoader ( manager ) { - var object = this.parseObject( json.object, geometries, materials ); + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; + this.texturePath = ''; - if ( json.animations ) { + } - object.animations = this.parseAnimations( json.animations ); + Object.assign( ObjectLoader.prototype, { - } + load: function ( url, onLoad, onProgress, onError ) { - if ( json.images === undefined || json.images.length === 0 ) { + if ( this.texturePath === '' ) { - if ( onLoad !== undefined ) onLoad( object ); + this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 ); - } + } - return object; + var scope = this; - }, + var loader = new XHRLoader( scope.manager ); + loader.load( url, function ( text ) { - parseGeometries: function ( json ) { + scope.parse( JSON.parse( text ), onLoad ); - var geometries = {}; + }, onProgress, onError ); - if ( json !== undefined ) { + }, - var geometryLoader = new JSONLoader(); - var bufferGeometryLoader = new BufferGeometryLoader(); + setTexturePath: function ( value ) { - for ( var i = 0, l = json.length; i < l; i ++ ) { + this.texturePath = value; - var geometry; - var data = json[ i ]; + }, - switch ( data.type ) { + setCrossOrigin: function ( value ) { - case 'PlaneGeometry': - case 'PlaneBufferGeometry': + this.crossOrigin = value; - geometry = new THREE[ data.type ]( - data.width, - data.height, - data.widthSegments, - data.heightSegments - ); + }, - break; + parse: function ( json, onLoad ) { - case 'BoxGeometry': - case 'BoxBufferGeometry': - case 'CubeGeometry': // backwards compatible + var geometries = this.parseGeometries( json.geometries ); - geometry = new THREE[ data.type ]( - data.width, - data.height, - data.depth, - data.widthSegments, - data.heightSegments, - data.depthSegments - ); + var images = this.parseImages( json.images, function () { - break; + if ( onLoad !== undefined ) onLoad( object ); - case 'CircleGeometry': - case 'CircleBufferGeometry': + } ); - geometry = new THREE[ data.type ]( - data.radius, - data.segments, - data.thetaStart, - data.thetaLength - ); + var textures = this.parseTextures( json.textures, images ); + var materials = this.parseMaterials( json.materials, textures ); - break; + var object = this.parseObject( json.object, geometries, materials ); - case 'CylinderGeometry': - case 'CylinderBufferGeometry': + if ( json.animations ) { - geometry = new THREE[ data.type ]( - data.radiusTop, - data.radiusBottom, - data.height, - data.radialSegments, - data.heightSegments, - data.openEnded, - data.thetaStart, - data.thetaLength - ); + object.animations = this.parseAnimations( json.animations ); - break; + } - case 'ConeGeometry': - case 'ConeBufferGeometry': + if ( json.images === undefined || json.images.length === 0 ) { - geometry = new THREE [ data.type ]( - data.radius, - data.height, - data.radialSegments, - data.heightSegments, - data.openEnded, - data.thetaStart, - data.thetaLength - ); + if ( onLoad !== undefined ) onLoad( object ); - break; + } - case 'SphereGeometry': - case 'SphereBufferGeometry': + return object; - geometry = new THREE[ data.type ]( - data.radius, - data.widthSegments, - data.heightSegments, - data.phiStart, - data.phiLength, - data.thetaStart, - data.thetaLength - ); + }, - break; + parseGeometries: function ( json ) { - case 'DodecahedronGeometry': - case 'IcosahedronGeometry': - case 'OctahedronGeometry': - case 'TetrahedronGeometry': + var geometries = {}; - geometry = new THREE[ data.type ]( - data.radius, - data.detail - ); + if ( json !== undefined ) { - break; + var geometryLoader = new JSONLoader(); + var bufferGeometryLoader = new BufferGeometryLoader(); - case 'RingGeometry': - case 'RingBufferGeometry': + for ( var i = 0, l = json.length; i < l; i ++ ) { - geometry = new THREE[ data.type ]( - data.innerRadius, - data.outerRadius, - data.thetaSegments, - data.phiSegments, - data.thetaStart, - data.thetaLength - ); + var geometry; + var data = json[ i ]; - break; + switch ( data.type ) { - case 'TorusGeometry': - case 'TorusBufferGeometry': + case 'PlaneGeometry': + case 'PlaneBufferGeometry': - geometry = new THREE[ data.type ]( - data.radius, - data.tube, - data.radialSegments, - data.tubularSegments, - data.arc - ); + geometry = new THREE[ data.type ]( + data.width, + data.height, + data.widthSegments, + data.heightSegments + ); - break; + break; - case 'TorusKnotGeometry': - case 'TorusKnotBufferGeometry': + case 'BoxGeometry': + case 'BoxBufferGeometry': + case 'CubeGeometry': // backwards compatible - geometry = new THREE[ data.type ]( - data.radius, - data.tube, - data.tubularSegments, - data.radialSegments, - data.p, - data.q - ); + geometry = new THREE[ data.type ]( + data.width, + data.height, + data.depth, + data.widthSegments, + data.heightSegments, + data.depthSegments + ); - break; + break; - case 'LatheGeometry': - case 'LatheBufferGeometry': + case 'CircleGeometry': + case 'CircleBufferGeometry': - geometry = new THREE[ data.type ]( - data.points, - data.segments, - data.phiStart, - data.phiLength - ); + geometry = new THREE[ data.type ]( + data.radius, + data.segments, + data.thetaStart, + data.thetaLength + ); + + break; + + case 'CylinderGeometry': + case 'CylinderBufferGeometry': - break; + geometry = new THREE[ data.type ]( + data.radiusTop, + data.radiusBottom, + data.height, + data.radialSegments, + data.heightSegments, + data.openEnded, + data.thetaStart, + data.thetaLength + ); - case 'BufferGeometry': + break; - geometry = bufferGeometryLoader.parse( data ); + 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 'Geometry': + break; - geometry = geometryLoader.parse( data.data, this.texturePath ).geometry; + case 'SphereGeometry': + case 'SphereBufferGeometry': - break; + geometry = new THREE[ data.type ]( + data.radius, + data.widthSegments, + data.heightSegments, + data.phiStart, + data.phiLength, + data.thetaStart, + data.thetaLength + ); - default: + break; - console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' ); + case 'DodecahedronGeometry': + case 'IcosahedronGeometry': + case 'OctahedronGeometry': + case 'TetrahedronGeometry': - continue; + geometry = new THREE[ data.type ]( + data.radius, + data.detail + ); - } + break; - geometry.uuid = data.uuid; + case 'RingGeometry': + case 'RingBufferGeometry': - if ( data.name !== undefined ) geometry.name = data.name; + geometry = new THREE[ data.type ]( + data.innerRadius, + data.outerRadius, + data.thetaSegments, + data.phiSegments, + data.thetaStart, + data.thetaLength + ); - geometries[ data.uuid ] = geometry; + break; - } + case 'TorusGeometry': + case 'TorusBufferGeometry': - } + geometry = new THREE[ data.type ]( + data.radius, + data.tube, + data.radialSegments, + data.tubularSegments, + data.arc + ); - return geometries; + break; - }, + case 'TorusKnotGeometry': + case 'TorusKnotBufferGeometry': - parseMaterials: function ( json, textures ) { + geometry = new THREE[ data.type ]( + data.radius, + data.tube, + data.tubularSegments, + data.radialSegments, + data.p, + data.q + ); - var materials = {}; + break; - if ( json !== undefined ) { + case 'LatheGeometry': + case 'LatheBufferGeometry': - var loader = new MaterialLoader(); - loader.setTextures( textures ); + geometry = new THREE[ data.type ]( + data.points, + data.segments, + data.phiStart, + data.phiLength + ); - for ( var i = 0, l = json.length; i < l; i ++ ) { + break; - var material = loader.parse( json[ i ] ); - materials[ material.uuid ] = material; + case 'BufferGeometry': - } + geometry = bufferGeometryLoader.parse( data ); - } + break; - return materials; + case 'Geometry': - }, + geometry = geometryLoader.parse( data.data, this.texturePath ).geometry; - parseAnimations: function ( json ) { + break; - var animations = []; + default: - for ( var i = 0; i < json.length; i ++ ) { + console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' ); - var clip = AnimationClip.parse( json[ i ] ); + continue; - animations.push( clip ); + } - } + geometry.uuid = data.uuid; - return animations; + if ( data.name !== undefined ) geometry.name = data.name; - }, + geometries[ data.uuid ] = geometry; - parseImages: function ( json, onLoad ) { + } - var scope = this; - var images = {}; + } - function loadImage( url ) { + return geometries; - scope.manager.itemStart( url ); + }, - return loader.load( url, function () { + parseMaterials: function ( json, textures ) { - scope.manager.itemEnd( url ); + var materials = {}; - } ); + if ( json !== undefined ) { - } + var loader = new MaterialLoader(); + loader.setTextures( textures ); - if ( json !== undefined && json.length > 0 ) { + for ( var i = 0, l = json.length; i < l; i ++ ) { - var manager = new LoadingManager( onLoad ); + var material = loader.parse( json[ i ] ); + materials[ material.uuid ] = material; - var loader = new ImageLoader( manager ); - loader.setCrossOrigin( this.crossOrigin ); + } - for ( var i = 0, l = json.length; i < l; i ++ ) { + } - var image = json[ i ]; - var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url; + return materials; - images[ image.uuid ] = loadImage( path ); + }, - } + parseAnimations: function ( json ) { - } + var animations = []; - return images; + for ( var i = 0; i < json.length; i ++ ) { - }, + var clip = AnimationClip.parse( json[ i ] ); - parseTextures: function ( json, images ) { + animations.push( clip ); - function parseConstant( value ) { + } - if ( typeof( value ) === 'number' ) return value; + return animations; - console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value ); + }, - return THREE[ value ]; + parseImages: function ( json, onLoad ) { - } + var scope = this; + var images = {}; - var textures = {}; + function loadImage( url ) { - if ( json !== undefined ) { + scope.manager.itemStart( url ); - for ( var i = 0, l = json.length; i < l; i ++ ) { + return loader.load( url, function () { - var data = json[ i ]; + scope.manager.itemEnd( url ); - if ( data.image === undefined ) { + } ); - console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid ); + } - } + if ( json !== undefined && json.length > 0 ) { - if ( images[ data.image ] === undefined ) { + var manager = new LoadingManager( onLoad ); - console.warn( 'THREE.ObjectLoader: Undefined image', data.image ); + var loader = new ImageLoader( manager ); + loader.setCrossOrigin( this.crossOrigin ); - } + for ( var i = 0, l = json.length; i < l; i ++ ) { - var texture = new Texture( images[ data.image ] ); - texture.needsUpdate = true; + var image = json[ i ]; + var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url; - texture.uuid = data.uuid; + images[ image.uuid ] = loadImage( path ); - if ( data.name !== undefined ) texture.name = data.name; + } - if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping ); + } - if ( data.offset !== undefined ) texture.offset.fromArray( data.offset ); - if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat ); - if ( data.wrap !== undefined ) { + return images; - texture.wrapS = parseConstant( data.wrap[ 0 ] ); - texture.wrapT = parseConstant( data.wrap[ 1 ] ); + }, - } + parseTextures: function ( json, images ) { - 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 parseConstant( value ) { - if ( data.flipY !== undefined ) texture.flipY = data.flipY; + if ( typeof( value ) === 'number' ) return value; - textures[ data.uuid ] = texture; + console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value ); - } + return THREE[ value ]; - } + } - return textures; + var textures = {}; - }, + if ( json !== undefined ) { - parseObject: function () { + for ( var i = 0, l = json.length; i < l; i ++ ) { - var matrix = new Matrix4(); + var data = json[ i ]; - return function parseObject( data, geometries, materials ) { + if ( data.image === undefined ) { - var object; + console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid ); - function getGeometry( name ) { + } - if ( geometries[ name ] === undefined ) { + if ( images[ data.image ] === undefined ) { - console.warn( 'THREE.ObjectLoader: Undefined geometry', name ); + console.warn( 'THREE.ObjectLoader: Undefined image', data.image ); - } + } - return geometries[ name ]; + var texture = new Texture( images[ data.image ] ); + texture.needsUpdate = true; - } + texture.uuid = data.uuid; - function getMaterial( name ) { + if ( data.name !== undefined ) texture.name = data.name; - if ( name === undefined ) return undefined; + if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping ); - if ( materials[ name ] === undefined ) { + if ( data.offset !== undefined ) texture.offset.fromArray( data.offset ); + if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat ); + if ( data.wrap !== undefined ) { - console.warn( 'THREE.ObjectLoader: Undefined material', name ); + texture.wrapS = parseConstant( data.wrap[ 0 ] ); + texture.wrapT = parseConstant( data.wrap[ 1 ] ); - } + } - return materials[ name ]; + 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 ( data.flipY !== undefined ) texture.flipY = data.flipY; - switch ( data.type ) { + textures[ data.uuid ] = texture; - case 'Scene': + } - 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); - - } - } + return textures; - break; + }, - case 'PerspectiveCamera': + parseObject: function () { - object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far ); + var matrix = new Matrix4(); - 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 ); + return function parseObject( data, geometries, materials ) { - break; + var object; - case 'OrthographicCamera': + function getGeometry( name ) { - object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far ); + if ( geometries[ name ] === undefined ) { - break; + console.warn( 'THREE.ObjectLoader: Undefined geometry', name ); - case 'AmbientLight': + } - object = new AmbientLight( data.color, data.intensity ); + return geometries[ name ]; - break; + } - case 'DirectionalLight': + function getMaterial( name ) { - object = new DirectionalLight( data.color, data.intensity ); + if ( name === undefined ) return undefined; - break; + if ( materials[ name ] === undefined ) { - case 'PointLight': + console.warn( 'THREE.ObjectLoader: Undefined material', name ); - object = new PointLight( data.color, data.intensity, data.distance, data.decay ); + } - break; + return materials[ name ]; - case 'SpotLight': + } - object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay ); + switch ( data.type ) { - break; + case 'Scene': - case 'HemisphereLight': + object = new Scene(); - object = new HemisphereLight( data.color, data.groundColor, data.intensity ); + + 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); + + } + } - break; + break; - case 'Mesh': + case 'PerspectiveCamera': - var geometry = getGeometry( data.geometry ); - var material = getMaterial( data.material ); + object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far ); - if ( geometry.bones && geometry.bones.length > 0 ) { + 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 ); - object = new SkinnedMesh( geometry, material ); + break; - } else { + case 'OrthographicCamera': - object = new Mesh( geometry, material ); + object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far ); - } + break; - break; + case 'AmbientLight': - case 'LOD': + object = new AmbientLight( data.color, data.intensity ); - object = new LOD(); + break; - break; + case 'DirectionalLight': - case 'Line': + object = new DirectionalLight( data.color, data.intensity ); - object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode ); + break; - break; + case 'PointLight': - case 'LineSegments': + object = new PointLight( data.color, data.intensity, data.distance, data.decay ); - object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) ); + break; - break; + case 'SpotLight': - case 'PointCloud': - case 'Points': + object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay ); - object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) ); + break; - break; + case 'HemisphereLight': - case 'Sprite': + object = new HemisphereLight( data.color, data.groundColor, data.intensity ); - object = new Sprite( getMaterial( data.material ) ); + break; - break; + case 'Mesh': - case 'Group': + var geometry = getGeometry( data.geometry ); + var material = getMaterial( data.material ); - object = new Group(); + if ( geometry.bones && geometry.bones.length > 0 ) { - break; + object = new SkinnedMesh( geometry, material ); - default: + } else { - object = new Object3D(); + object = new Mesh( geometry, material ); - } + } - object.uuid = data.uuid; + break; - if ( data.name !== undefined ) object.name = data.name; - if ( data.matrix !== undefined ) { + case 'LOD': - matrix.fromArray( data.matrix ); - matrix.decompose( object.position, object.quaternion, object.scale ); + object = new LOD(); - } else { + break; - 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 ); + case 'Line': - } + object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode ); - if ( data.castShadow !== undefined ) object.castShadow = data.castShadow; - if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow; + break; - if ( data.visible !== undefined ) object.visible = data.visible; - if ( data.userData !== undefined ) object.userData = data.userData; + case 'LineSegments': - if ( data.children !== undefined ) { + object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) ); - for ( var child in data.children ) { + break; - object.add( this.parseObject( data.children[ child ], geometries, materials ) ); + case 'PointCloud': + case 'Points': - } + object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) ); - } + break; - if ( data.type === 'LOD' ) { + case 'Sprite': - var levels = data.levels; + object = new Sprite( getMaterial( data.material ) ); - for ( var l = 0; l < levels.length; l ++ ) { + break; - var level = levels[ l ]; - var child = object.getObjectByProperty( 'uuid', level.object ); + case 'Group': - if ( child !== undefined ) { + object = new Group(); - object.addLevel( child, level.distance ); + break; - } + default: - } + object = new Object3D(); - } + } - return object; + object.uuid = data.uuid; - }; + 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 { - /** - * @author zz85 / http://www.lab4games.net/zz85/blog - */ + 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 ); - exports.ShapeUtils = { + } - // calculate area of the contour polygon + if ( data.castShadow !== undefined ) object.castShadow = data.castShadow; + if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow; - area: function ( contour ) { + if ( data.visible !== undefined ) object.visible = data.visible; + if ( data.userData !== undefined ) object.userData = data.userData; - var n = contour.length; - var a = 0.0; + if ( data.children !== undefined ) { - for ( var p = n - 1, q = 0; q < n; p = q ++ ) { + for ( var child in data.children ) { - a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y; + object.add( this.parseObject( data.children[ child ], geometries, materials ) ); - } + } - return a * 0.5; + } - }, + if ( data.type === 'LOD' ) { - triangulate: ( function () { + var levels = data.levels; - /** - * 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 - * - */ + for ( var l = 0; l < levels.length; l ++ ) { - function snip( contour, u, v, w, n, verts ) { + var level = levels[ l ]; + var child = object.getObjectByProperty( 'uuid', level.object ); - var p; - var ax, ay, bx, by; - var cx, cy, px, py; + if ( child !== undefined ) { - ax = contour[ verts[ u ] ].x; - ay = contour[ verts[ u ] ].y; + object.addLevel( child, level.distance ); - bx = contour[ verts[ v ] ].x; - by = contour[ verts[ v ] ].y; + } - cx = contour[ verts[ w ] ].x; - cy = contour[ verts[ w ] ].y; + } - 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; + return object; - aX = cx - bx; aY = cy - by; - bX = ax - cx; bY = ay - cy; - cX = bx - ax; cY = by - ay; + }; - for ( p = 0; p < n; p ++ ) { + }() - px = contour[ verts[ p ] ].x; - py = contour[ verts[ p ] ].y; + } ); - if ( ( ( px === ax ) && ( py === ay ) ) || - ( ( px === bx ) && ( py === by ) ) || - ( ( px === cx ) && ( py === cy ) ) ) continue; + /** + * @author zz85 / http://www.lab4games.net/zz85/blog + */ - apx = px - ax; apy = py - ay; - bpx = px - bx; bpy = py - by; - cpx = px - cx; cpy = py - cy; + exports.ShapeUtils = { - // see if p is inside triangle abc + // calculate area of the contour polygon - aCROSSbp = aX * bpy - aY * bpx; - cCROSSap = cX * apy - cY * apx; - bCROSScp = bX * cpy - bY * cpx; + area: function ( contour ) { - if ( ( aCROSSbp >= - Number.EPSILON ) && ( bCROSScp >= - Number.EPSILON ) && ( cCROSSap >= - Number.EPSILON ) ) return false; + var n = contour.length; + var a = 0.0; - } + for ( var p = n - 1, q = 0; q < n; p = q ++ ) { - return true; + a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y; - } + } - // takes in an contour array and returns + return a * 0.5; - return function triangulate( contour, indices ) { + }, - var n = contour.length; + triangulate: ( function () { - if ( n < 3 ) return null; + /** + * 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 result = [], - verts = [], - vertIndices = []; + function snip( contour, u, v, w, n, verts ) { - /* we want a counter-clockwise polygon in verts */ + var p; + var ax, ay, bx, by; + var cx, cy, px, py; - var u, v, w; + ax = contour[ verts[ u ] ].x; + ay = contour[ verts[ u ] ].y; - if ( exports.ShapeUtils.area( contour ) > 0.0 ) { + bx = contour[ verts[ v ] ].x; + by = contour[ verts[ v ] ].y; - for ( v = 0; v < n; v ++ ) verts[ v ] = v; + cx = contour[ verts[ w ] ].x; + cy = contour[ verts[ w ] ].y; - } else { + if ( Number.EPSILON > ( ( ( bx - ax ) * ( cy - ay ) ) - ( ( by - ay ) * ( cx - ax ) ) ) ) return false; - for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v; + 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; - var nv = n; + for ( p = 0; p < n; p ++ ) { - /* remove nv - 2 vertices, creating 1 triangle every time */ + px = contour[ verts[ p ] ].x; + py = contour[ verts[ p ] ].y; - var count = 2 * nv; /* error detection */ + if ( ( ( px === ax ) && ( py === ay ) ) || + ( ( px === bx ) && ( py === by ) ) || + ( ( px === cx ) && ( py === cy ) ) ) continue; - for ( v = nv - 1; nv > 2; ) { + apx = px - ax; apy = py - ay; + bpx = px - bx; bpy = py - by; + cpx = px - cx; cpy = py - cy; - /* if we loop, it is probably a non-simple polygon */ + // see if p is inside triangle abc - if ( ( count -- ) <= 0 ) { + aCROSSbp = aX * bpy - aY * bpx; + cCROSSap = cX * apy - cY * apx; + bCROSScp = bX * cpy - bY * cpx; - //** Triangulate: ERROR - probable bad polygon! + if ( ( aCROSSbp >= - Number.EPSILON ) && ( bCROSScp >= - Number.EPSILON ) && ( cCROSSap >= - Number.EPSILON ) ) return false; - //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()' ); + } - if ( indices ) return vertIndices; - return result; + return true; - } + } - /* three consecutive vertices in current polygon, */ + // takes in an contour array and returns - 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 */ + return function triangulate( contour, indices ) { - if ( snip( contour, u, v, w, nv, verts ) ) { + var n = contour.length; - var a, b, c, s, t; + if ( n < 3 ) return null; - /* true names of the vertices */ + var result = [], + verts = [], + vertIndices = []; - a = verts[ u ]; - b = verts[ v ]; - c = verts[ w ]; + /* we want a counter-clockwise polygon in verts */ - /* output Triangle */ + var u, v, w; - result.push( [ contour[ a ], - contour[ b ], - contour[ c ] ] ); + if ( exports.ShapeUtils.area( contour ) > 0.0 ) { + for ( v = 0; v < n; v ++ ) verts[ v ] = v; - vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] ); + } else { - /* remove v from the remaining polygon */ + for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v; - for ( s = v, t = v + 1; t < nv; s ++, t ++ ) { + } - verts[ s ] = verts[ t ]; + var nv = n; - } + /* remove nv - 2 vertices, creating 1 triangle every time */ - nv --; + var count = 2 * nv; /* error detection */ - /* reset error detection counter */ + for ( v = nv - 1; nv > 2; ) { - count = 2 * nv; + /* if we loop, it is probably a non-simple polygon */ - } + if ( ( count -- ) <= 0 ) { - } + //** Triangulate: ERROR - probable bad polygon! - if ( indices ) return vertIndices; - return result; + //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()' ); - } + if ( indices ) return vertIndices; + return result; - } )(), + } - triangulateShape: function ( contour, holes ) { + /* three consecutive vertices in current polygon, */ - function removeDupEndPts(points) { + 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 */ - var l = points.length; + if ( snip( contour, u, v, w, nv, verts ) ) { - if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) { + var a, b, c, s, t; - points.pop(); + /* true names of the vertices */ - } + a = verts[ u ]; + b = verts[ v ]; + c = verts[ w ]; - } + /* output Triangle */ - removeDupEndPts( contour ); - holes.forEach( removeDupEndPts ); + result.push( [ contour[ a ], + contour[ b ], + contour[ c ] ] ); - function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) { - // inOtherPt needs to be collinear to the inSegment - if ( inSegPt1.x !== inSegPt2.x ) { + vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] ); - if ( inSegPt1.x < inSegPt2.x ) { + /* remove v from the remaining polygon */ - return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) ); + for ( s = v, t = v + 1; t < nv; s ++, t ++ ) { - } else { + verts[ s ] = verts[ t ]; - return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) ); + } - } + nv --; - } else { + /* reset error detection counter */ - if ( inSegPt1.y < inSegPt2.y ) { + count = 2 * nv; - return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) ); + } - } else { + } - return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) ); + if ( indices ) return vertIndices; + return result; - } + } - } + } )(), - } + triangulateShape: function ( contour, holes ) { - function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) { + function removeDupEndPts(points) { - var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y; - var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y; + var l = points.length; - var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x; - var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y; + if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) { - var limit = seg1dy * seg2dx - seg1dx * seg2dy; - var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy; + points.pop(); - if ( Math.abs( limit ) > Number.EPSILON ) { + } - // not parallel + } - var perpSeg2; - if ( limit > 0 ) { + 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 ) { - } else { + // inOtherPt needs to be collinear to the inSegment + if ( inSegPt1.x !== inSegPt2.x ) { - if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return []; - perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy; - if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return []; + if ( inSegPt1.x < inSegPt2.x ) { - } + return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.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 ]; + return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) ); - } - if ( perpSeg2 === limit ) { + } - 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 ]; + if ( inSegPt1.y < inSegPt2.y ) { - // return real intersection point - var factorSeg1 = perpSeg2 / limit; - return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx, - y: inSeg1Pt1.y + factorSeg1 * seg1dy } ]; + return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) ); - } else { + } else { - // parallel or collinear - if ( ( perpSeg1 !== 0 ) || - ( seg2dy * seg1seg2dx !== seg2dx * seg1seg2dy ) ) return []; + return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.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 ) { + } - 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 ( ! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2 - return [ inSeg1Pt1 ]; + function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) { - } - // segment#2 is a single point - if ( seg2Pt ) { + var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y; + var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y; - if ( ! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1 - return [ inSeg2Pt1 ]; + var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x; + var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y; - } + var limit = seg1dy * seg2dx - seg1dx * seg2dy; + var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy; - // they are collinear segments, which might overlap - var seg1min, seg1max, seg1minVal, seg1maxVal; - var seg2min, seg2max, seg2minVal, seg2maxVal; - if ( seg1dx !== 0 ) { + if ( Math.abs( limit ) > Number.EPSILON ) { - // the segments are NOT on a vertical line - if ( inSeg1Pt1.x < inSeg1Pt2.x ) { + // not parallel - seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x; - seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x; + var perpSeg2; + if ( limit > 0 ) { - } else { + if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return []; + perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy; + if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return []; - seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x; - seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x; + } else { - } - 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 { + // i.e. to reduce rounding errors + // intersection at endpoint of segment#1? + if ( perpSeg2 === 0 ) { - seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x; - seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x; + if ( ( inExcludeAdjacentSegs ) && + ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return []; + return [ inSeg1Pt1 ]; - } + } + if ( perpSeg2 === limit ) { - } else { + if ( ( inExcludeAdjacentSegs ) && + ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return []; + return [ inSeg1Pt2 ]; - // the segments are on a vertical line - if ( inSeg1Pt1.y < inSeg1Pt2.y ) { + } + // intersection at endpoint of segment#2? + if ( perpSeg1 === 0 ) return [ inSeg2Pt1 ]; + if ( perpSeg1 === limit ) return [ inSeg2Pt2 ]; - seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y; - seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y; + // return real intersection point + var factorSeg1 = perpSeg2 / limit; + return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx, + y: inSeg1Pt1.y + factorSeg1 * seg1dy } ]; - } else { + } else { - seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y; - seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y; + // parallel or collinear + if ( ( perpSeg1 !== 0 ) || + ( seg2dy * seg1seg2dx !== seg2dx * seg1seg2dy ) ) return []; - } - if ( inSeg2Pt1.y < inSeg2Pt2.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 ) { - seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y; - seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y; + if ( ( inSeg1Pt1.x !== inSeg2Pt1.x ) || + ( inSeg1Pt1.y !== inSeg2Pt1.y ) ) return []; // they are distinct points + return [ inSeg1Pt1 ]; // they are the same point - } else { + } + // segment#1 is a single point + if ( seg1Pt ) { - seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y; - seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y; + 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 ( seg1minVal <= seg2minVal ) { + if ( ! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1 + return [ inSeg2Pt1 ]; - if ( seg1maxVal < seg2minVal ) return []; - if ( seg1maxVal === seg2minVal ) { + } - if ( inExcludeAdjacentSegs ) return []; - return [ seg2min ]; + // they are collinear segments, which might overlap + var seg1min, seg1max, seg1minVal, seg1maxVal; + var seg2min, seg2max, seg2minVal, seg2maxVal; + if ( seg1dx !== 0 ) { - } - if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ]; - return [ seg2min, seg2max ]; + // the segments are NOT on a vertical line + if ( inSeg1Pt1.x < inSeg1Pt2.x ) { - } else { + seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x; + seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x; - if ( seg1minVal > seg2maxVal ) return []; - if ( seg1minVal === seg2maxVal ) { + } else { - if ( inExcludeAdjacentSegs ) return []; - return [ seg1min ]; + seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x; + seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x; - } - if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ]; - return [ seg1min, seg2max ]; + } + if ( inSeg2Pt1.x < inSeg2Pt2.x ) { - } + seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x; + seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x; - } + } else { - } + seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x; + seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x; - function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) { + } - // The order of legs is important + } else { - // 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; + // the segments are on a vertical line + if ( inSeg1Pt1.y < inSeg1Pt2.y ) { - // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg. - var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX; - var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX; + seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y; + seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y; - if ( Math.abs( from2toAngle ) > Number.EPSILON ) { + } else { - // angle != 180 deg. + seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y; + seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y; - var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX; - // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle ); + } + if ( inSeg2Pt1.y < inSeg2Pt2.y ) { - if ( from2toAngle > 0 ) { + seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y; + seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y; - // main angle < 180 deg. - return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) ); + } else { - } else { + seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y; + seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y; - // main angle > 180 deg. - return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) ); + } - } + } + if ( seg1minVal <= seg2minVal ) { - } else { + if ( seg1maxVal < seg2minVal ) return []; + if ( seg1maxVal === seg2minVal ) { - // angle == 180 deg. - // console.log( "from2to: 180 deg., from2other: " + from2otherAngle ); - return ( from2otherAngle > 0 ); + if ( inExcludeAdjacentSegs ) return []; + return [ seg2min ]; - } + } + if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ]; + return [ seg2min, seg2max ]; - } + } else { + if ( seg1minVal > seg2maxVal ) return []; + if ( seg1minVal === seg2maxVal ) { - function removeHoles( contour, holes ) { + if ( inExcludeAdjacentSegs ) return []; + return [ seg1min ]; - var shape = contour.concat(); // work on this shape - var hole; + } + if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ]; + return [ seg1min, seg2max ]; - function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) { + } - // Check if hole point lies within angle around shape point - var lastShapeIdx = shape.length - 1; + } - var prevShapeIdx = inShapeIdx - 1; - if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx; + } - var nextShapeIdx = inShapeIdx + 1; - if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0; + function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) { - var insideAngle = isPointInsideAngle( shape[ inShapeIdx ], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[ inHoleIdx ] ); - if ( ! insideAngle ) { + // The order of legs is important - // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y ); - return false; + // 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; - // Check if shape point lies within angle around hole point - var lastHoleIdx = hole.length - 1; + if ( Math.abs( from2toAngle ) > Number.EPSILON ) { - var prevHoleIdx = inHoleIdx - 1; - if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx; + // angle != 180 deg. - var nextHoleIdx = inHoleIdx + 1; - if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0; + var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX; + // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle ); - insideAngle = isPointInsideAngle( hole[ inHoleIdx ], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[ inShapeIdx ] ); - if ( ! insideAngle ) { + if ( from2toAngle > 0 ) { - // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y ); - return false; + // main angle < 180 deg. + return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) ); - } + } else { - return true; + // main angle > 180 deg. + return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) ); - } + } - function intersectsShapeEdge( inShapePt, inHolePt ) { + } else { - // checks for intersections with shape edges - var sIdx, nextIdx, intersection; - for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) { + // angle == 180 deg. + // console.log( "from2to: 180 deg., from2other: " + from2otherAngle ); + return ( from2otherAngle > 0 ); - nextIdx = sIdx + 1; nextIdx %= shape.length; - intersection = intersect_segments_2D( inShapePt, inHolePt, shape[ sIdx ], shape[ nextIdx ], true ); - if ( intersection.length > 0 ) return true; + } - } + } - return false; - } + function removeHoles( contour, holes ) { - var indepHoles = []; + var shape = contour.concat(); // work on this shape + var hole; - function intersectsHoleEdge( inShapePt, inHolePt ) { + function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) { - // checks for intersections with hole edges - var ihIdx, chkHole, - hIdx, nextIdx, intersection; - for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) { + // Check if hole point lies within angle around shape point + var lastShapeIdx = shape.length - 1; - chkHole = holes[ indepHoles[ ihIdx ]]; - for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) { + var prevShapeIdx = inShapeIdx - 1; + if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx; - nextIdx = hIdx + 1; nextIdx %= chkHole.length; - intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[ hIdx ], chkHole[ nextIdx ], true ); - if ( intersection.length > 0 ) return true; + var nextShapeIdx = inShapeIdx + 1; + if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0; - } + var insideAngle = isPointInsideAngle( shape[ inShapeIdx ], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[ inHoleIdx ] ); + if ( ! insideAngle ) { - } - return false; + // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y ); + return false; - } + } - var holeIndex, shapeIndex, - shapePt, holePt, - holeIdx, cutKey, failedCuts = [], - tmpShape1, tmpShape2, - tmpHole1, tmpHole2; + // Check if shape point lies within angle around hole point + var lastHoleIdx = hole.length - 1; - for ( var h = 0, hl = holes.length; h < hl; h ++ ) { + var prevHoleIdx = inHoleIdx - 1; + if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx; - indepHoles.push( h ); + var nextHoleIdx = inHoleIdx + 1; + if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0; - } + insideAngle = isPointInsideAngle( hole[ inHoleIdx ], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[ inShapeIdx ] ); + if ( ! insideAngle ) { - var minShapeIndex = 0; - var counter = indepHoles.length * 2; - while ( indepHoles.length > 0 ) { + // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y ); + return false; - counter --; - if ( counter < 0 ) { + } - console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" ); - break; + return true; - } + } - // search for shape-vertex and hole-vertex, - // which can be connected without intersections - for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) { + function intersectsShapeEdge( inShapePt, inHolePt ) { - shapePt = shape[ shapeIndex ]; - holeIndex = - 1; + // checks for intersections with shape edges + var sIdx, nextIdx, intersection; + for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) { - // search for hole which can be reached without intersections - for ( var h = 0; h < indepHoles.length; h ++ ) { + nextIdx = sIdx + 1; nextIdx %= shape.length; + intersection = intersect_segments_2D( inShapePt, inHolePt, shape[ sIdx ], shape[ nextIdx ], true ); + if ( intersection.length > 0 ) return true; - holeIdx = indepHoles[ h ]; + } - // prevent multiple checks - cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx; - if ( failedCuts[ cutKey ] !== undefined ) continue; + return false; - 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; + var indepHoles = []; - holeIndex = h2; - indepHoles.splice( h, 1 ); + function intersectsHoleEdge( inShapePt, inHolePt ) { - tmpShape1 = shape.slice( 0, shapeIndex + 1 ); - tmpShape2 = shape.slice( shapeIndex ); - tmpHole1 = hole.slice( holeIndex ); - tmpHole2 = hole.slice( 0, holeIndex + 1 ); + // checks for intersections with hole edges + var ihIdx, chkHole, + hIdx, nextIdx, intersection; + for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) { - shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 ); + chkHole = holes[ indepHoles[ ihIdx ]]; + for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) { - minShapeIndex = shapeIndex; + nextIdx = hIdx + 1; nextIdx %= chkHole.length; + intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[ hIdx ], chkHole[ nextIdx ], true ); + if ( intersection.length > 0 ) return true; - // Debug only, to show the selected cuts - // glob_CutLines.push( [ shapePt, holePt ] ); + } - break; + } + return false; - } - if ( holeIndex >= 0 ) break; // hole-vertex found + } - failedCuts[ cutKey ] = true; // remember failure + var holeIndex, shapeIndex, + shapePt, holePt, + holeIdx, cutKey, failedCuts = [], + tmpShape1, tmpShape2, + tmpHole1, tmpHole2; - } - if ( holeIndex >= 0 ) break; // hole-vertex found + for ( var h = 0, hl = holes.length; h < hl; h ++ ) { - } + indepHoles.push( h ); - } + } - return shape; /* shape with no holes */ + var minShapeIndex = 0; + var counter = indepHoles.length * 2; + while ( indepHoles.length > 0 ) { - } + counter --; + if ( counter < 0 ) { + console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" ); + break; - 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. + // search for shape-vertex and hole-vertex, + // which can be connected without intersections + for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) { - var allpoints = contour.concat(); + shapePt = shape[ shapeIndex ]; + holeIndex = - 1; - for ( var h = 0, hl = holes.length; h < hl; h ++ ) { + // search for hole which can be reached without intersections + for ( var h = 0; h < indepHoles.length; h ++ ) { - Array.prototype.push.apply( allpoints, holes[ h ] ); + holeIdx = indepHoles[ h ]; - } + // prevent multiple checks + cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx; + if ( failedCuts[ cutKey ] !== undefined ) continue; - //console.log( "allpoints",allpoints, allpoints.length ); + hole = holes[ holeIdx ]; + for ( var h2 = 0; h2 < hole.length; h2 ++ ) { - // prepare all points map + holePt = hole[ h2 ]; + if ( ! isCutLineInsideAngles( shapeIndex, h2 ) ) continue; + if ( intersectsShapeEdge( shapePt, holePt ) ) continue; + if ( intersectsHoleEdge( shapePt, holePt ) ) continue; - for ( i = 0, il = allpoints.length; i < il; i ++ ) { + holeIndex = h2; + indepHoles.splice( h, 1 ); - key = allpoints[ i ].x + ":" + allpoints[ i ].y; + tmpShape1 = shape.slice( 0, shapeIndex + 1 ); + tmpShape2 = shape.slice( shapeIndex ); + tmpHole1 = hole.slice( holeIndex ); + tmpHole2 = hole.slice( 0, holeIndex + 1 ); - if ( allPointsMap[ key ] !== undefined ) { + shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 ); - console.warn( "THREE.ShapeUtils: Duplicate point", key, i ); + minShapeIndex = shapeIndex; - } + // Debug only, to show the selected cuts + // glob_CutLines.push( [ shapePt, holePt ] ); - allPointsMap[ key ] = i; + break; - } + } + if ( holeIndex >= 0 ) break; // hole-vertex found - // remove holes by cutting paths to holes and adding them to the shape - var shapeWithoutHoles = removeHoles( contour, holes ); + failedCuts[ cutKey ] = true; // remember failure - 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 + } - for ( i = 0, il = triangles.length; i < il; i ++ ) { + } - face = triangles[ i ]; + return shape; /* shape with no holes */ - for ( f = 0; f < 3; f ++ ) { + } - key = face[ f ].x + ":" + face[ f ].y; - index = allPointsMap[ key ]; + var i, il, f, face, + key, index, + allPointsMap = {}; - if ( index !== undefined ) { + // 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. - face[ f ] = index; + var allpoints = contour.concat(); - } + for ( var h = 0, hl = holes.length; h < hl; h ++ ) { - } + Array.prototype.push.apply( allpoints, holes[ h ] ); - } + } - return triangles.concat(); + //console.log( "allpoints",allpoints, allpoints.length ); - }, + // prepare all points map - isClockWise: function ( pts ) { + for ( i = 0, il = allpoints.length; i < il; i ++ ) { - return exports.ShapeUtils.area( pts ) < 0; + key = allpoints[ i ].x + ":" + allpoints[ i ].y; - }, + if ( allPointsMap[ key ] !== undefined ) { - // Bezier Curves formulas obtained from - // http://en.wikipedia.org/wiki/B%C3%A9zier_curve + console.warn( "THREE.ShapeUtils: Duplicate point", key, i ); - // Quad Bezier Functions + } - b2: ( function () { + allPointsMap[ key ] = i; - function b2p0( t, p ) { + } - var k = 1 - t; - return k * k * p; + // remove holes by cutting paths to holes and adding them to the shape + var shapeWithoutHoles = removeHoles( contour, holes ); - } + var triangles = exports.ShapeUtils.triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape + //console.log( "triangles",triangles, triangles.length ); - function b2p1( t, p ) { + // check all face vertices against all points map - return 2 * ( 1 - t ) * t * p; + for ( i = 0, il = triangles.length; i < il; i ++ ) { - } + face = triangles[ i ]; - function b2p2( t, p ) { + for ( f = 0; f < 3; f ++ ) { - return t * t * p; + key = face[ f ].x + ":" + face[ f ].y; - } + index = allPointsMap[ key ]; - return function b2( t, p0, p1, p2 ) { + if ( index !== undefined ) { - return b2p0( t, p0 ) + b2p1( t, p1 ) + b2p2( t, p2 ); + face[ f ] = index; - }; + } - } )(), + } - // Cubic Bezier Functions + } - b3: ( function () { + return triangles.concat(); - function b3p0( t, p ) { + }, - var k = 1 - t; - return k * k * k * p; + isClockWise: function ( pts ) { - } + return exports.ShapeUtils.area( pts ) < 0; - function b3p1( t, p ) { + }, - var k = 1 - t; - return 3 * k * k * t * p; + // Bezier Curves formulas obtained from + // http://en.wikipedia.org/wiki/B%C3%A9zier_curve - } + // Quad Bezier Functions - function b3p2( t, p ) { + b2: ( function () { - var k = 1 - t; - return 3 * k * t * t * p; + function b2p0( t, p ) { - } + var k = 1 - t; + return k * k * p; - function b3p3( t, p ) { + } - return t * t * t * p; + function b2p1( t, p ) { - } + return 2 * ( 1 - t ) * t * p; - return function b3( t, p0, p1, p2, p3 ) { + } - return b3p0( t, p0 ) + b3p1( t, p1 ) + b3p2( t, p2 ) + b3p3( t, p3 ); + function b2p2( t, p ) { - }; + return t * t * p; - } )() + } - }; + return function b2( t, p0, p1, p2 ) { - /** - * @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 - * - **/ + return b2p0( t, p0 ) + b2p1( t, p1 ) + b2p2( t, p2 ); - /************************************************************** - * Abstract Curve base class - **************************************************************/ + }; - function Curve() {} + } )(), - Curve.prototype = { + // Cubic Bezier Functions - constructor: Curve, + b3: ( function () { - // Virtual base class method to overwrite and implement in subclasses - // - t [0 .. 1] + function b3p0( t, p ) { - getPoint: function ( t ) { + var k = 1 - t; + return k * k * k * p; - console.warn( "THREE.Curve: Warning, getPoint() not implemented!" ); - return null; + } - }, + function b3p1( t, p ) { - // Get point at relative position in curve according to arc length - // - u [0 .. 1] + var k = 1 - t; + return 3 * k * k * t * p; - getPointAt: function ( u ) { + } - var t = this.getUtoTmapping( u ); - return this.getPoint( t ); + function b3p2( t, p ) { - }, + var k = 1 - t; + return 3 * k * t * t * p; - // Get sequence of points using getPoint( t ) + } - getPoints: function ( divisions ) { + function b3p3( t, p ) { - if ( ! divisions ) divisions = 5; + return t * t * t * p; - var points = []; + } - for ( var d = 0; d <= divisions; d ++ ) { + return function b3( t, p0, p1, p2, p3 ) { - points.push( this.getPoint( d / divisions ) ); + return b3p0( t, p0 ) + b3p1( t, p1 ) + b3p2( t, p2 ) + b3p3( t, p3 ); - } + }; - return points; + } )() - }, + }; - // Get sequence of points using getPointAt( u ) + /** + * @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; - getSpacedPoints: function ( divisions ) { + }, - if ( ! divisions ) divisions = 5; + // Get point at relative position in curve according to arc length + // - u [0 .. 1] - var points = []; + getPointAt: function ( u ) { - for ( var d = 0; d <= divisions; d ++ ) { + var t = this.getUtoTmapping( u ); + return this.getPoint( t ); - points.push( this.getPointAt( d / divisions ) ); + }, - } + // Get sequence of points using getPoint( t ) - return points; + getPoints: function ( divisions ) { - }, + if ( ! divisions ) divisions = 5; - // Get total curve arc length + var points = []; - getLength: function () { + for ( var d = 0; d <= divisions; d ++ ) { - var lengths = this.getLengths(); - return lengths[ lengths.length - 1 ]; + points.push( this.getPoint( d / divisions ) ); - }, + } - // Get list of cumulative segment lengths + return points; - getLengths: function ( divisions ) { + }, - if ( ! divisions ) divisions = ( this.__arcLengthDivisions ) ? ( this.__arcLengthDivisions ) : 200; + // Get sequence of points using getPointAt( u ) - if ( this.cacheArcLengths - && ( this.cacheArcLengths.length === divisions + 1 ) - && ! this.needsUpdate ) { + getSpacedPoints: function ( divisions ) { - //console.log( "cached", this.cacheArcLengths ); - return this.cacheArcLengths; + if ( ! divisions ) divisions = 5; - } + var points = []; - this.needsUpdate = false; + for ( var d = 0; d <= divisions; d ++ ) { - var cache = []; - var current, last = this.getPoint( 0 ); - var p, sum = 0; + points.push( this.getPointAt( d / divisions ) ); - cache.push( 0 ); + } - for ( p = 1; p <= divisions; p ++ ) { + return points; - current = this.getPoint ( p / divisions ); - sum += current.distanceTo( last ); - cache.push( sum ); - last = current; + }, - } + // Get total curve arc length - this.cacheArcLengths = cache; + getLength: function () { - return cache; // { sums: cache, sum:sum }; Sum is in the last element. + var lengths = this.getLengths(); + return lengths[ lengths.length - 1 ]; - }, + }, - updateArcLengths: function() { + // Get list of cumulative segment lengths - this.needsUpdate = true; - this.getLengths(); + getLengths: function ( divisions ) { - }, + if ( ! divisions ) divisions = ( this.__arcLengthDivisions ) ? ( this.__arcLengthDivisions ) : 200; - // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant + if ( this.cacheArcLengths + && ( this.cacheArcLengths.length === divisions + 1 ) + && ! this.needsUpdate ) { - getUtoTmapping: function ( u, distance ) { + //console.log( "cached", this.cacheArcLengths ); + return this.cacheArcLengths; - var arcLengths = this.getLengths(); + } - var i = 0, il = arcLengths.length; + this.needsUpdate = false; - var targetArcLength; // The targeted u distance value to get + var cache = []; + var current, last = this.getPoint( 0 ); + var p, sum = 0; - if ( distance ) { + cache.push( 0 ); - targetArcLength = distance; + for ( p = 1; p <= divisions; p ++ ) { - } else { + current = this.getPoint ( p / divisions ); + sum += current.distanceTo( last ); + cache.push( sum ); + last = current; - targetArcLength = u * arcLengths[ il - 1 ]; + } - } + this.cacheArcLengths = cache; - //var time = Date.now(); + return cache; // { sums: cache, sum:sum }; Sum is in the last element. - // binary search for the index with largest value smaller than target u distance + }, - var low = 0, high = il - 1, comparison; + updateArcLengths: function() { - while ( low <= high ) { + this.needsUpdate = true; + this.getLengths(); - 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 + }, - comparison = arcLengths[ i ] - targetArcLength; + // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant - if ( comparison < 0 ) { + getUtoTmapping: function ( u, distance ) { - low = i + 1; + var arcLengths = this.getLengths(); - } else if ( comparison > 0 ) { + var i = 0, il = arcLengths.length; - high = i - 1; + var targetArcLength; // The targeted u distance value to get - } else { + if ( distance ) { - high = i; - break; + targetArcLength = distance; - // DONE + } else { - } + targetArcLength = u * arcLengths[ il - 1 ]; - } + } - i = high; + //var time = Date.now(); - //console.log('b' , i, low, high, Date.now()- time); + // binary search for the index with largest value smaller than target u distance - if ( arcLengths[ i ] === targetArcLength ) { + var low = 0, high = il - 1, comparison; - var t = i / ( il - 1 ); - return t; + 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 - // we could get finer grain at lengths, or use simple interpolation between two points + comparison = arcLengths[ i ] - targetArcLength; - var lengthBefore = arcLengths[ i ]; - var lengthAfter = arcLengths[ i + 1 ]; + if ( comparison < 0 ) { - var segmentLength = lengthAfter - lengthBefore; + low = i + 1; - // determine where we are between the 'before' and 'after' points + } else if ( comparison > 0 ) { - var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength; + high = i - 1; - // add that fractional amount to t + } else { - var t = ( i + segmentFraction ) / ( il - 1 ); + high = i; + break; - return t; + // DONE - }, + } - // 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 ) { + i = high; - var delta = 0.0001; - var t1 = t - delta; - var t2 = t + delta; + //console.log('b' , i, low, high, Date.now()- time); - // Capping in case of danger + if ( arcLengths[ i ] === targetArcLength ) { - if ( t1 < 0 ) t1 = 0; - if ( t2 > 1 ) t2 = 1; + var t = i / ( il - 1 ); + return t; - var pt1 = this.getPoint( t1 ); - var pt2 = this.getPoint( t2 ); + } - var vec = pt2.clone().sub( pt1 ); - return vec.normalize(); + // we could get finer grain at lengths, or use simple interpolation between two points - }, + var lengthBefore = arcLengths[ i ]; + var lengthAfter = arcLengths[ i + 1 ]; - getTangentAt: function ( u ) { + var segmentLength = lengthAfter - lengthBefore; - var t = this.getUtoTmapping( u ); - return this.getTangent( t ); + // determine where we are between the 'before' and 'after' points - } + var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength; - }; + // add that fractional amount to t - // TODO: Transformation for Curves? + var t = ( i + segmentFraction ) / ( il - 1 ); - /************************************************************** - * 3D Curves - **************************************************************/ + return t; - // A Factory method for creating new curve subclasses + }, - Curve.create = function ( constructor, getPointFunc ) { + // 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 - constructor.prototype = Object.create( Curve.prototype ); - constructor.prototype.constructor = constructor; - constructor.prototype.getPoint = getPointFunc; + getTangent: function( t ) { - return constructor; + var delta = 0.0001; + var t1 = t - delta; + var t2 = t + delta; - }; + // Capping in case of danger - /************************************************************** - * Line - **************************************************************/ + if ( t1 < 0 ) t1 = 0; + if ( t2 > 1 ) t2 = 1; - function LineCurve( v1, v2 ) { + var pt1 = this.getPoint( t1 ); + var pt2 = this.getPoint( t2 ); - this.v1 = v1; - this.v2 = v2; + var vec = pt2.clone().sub( pt1 ); + return vec.normalize(); - }; + }, - LineCurve.prototype = Object.create( Curve.prototype ); - LineCurve.prototype.constructor = LineCurve; + getTangentAt: function ( u ) { - LineCurve.prototype.isLineCurve = true; + var t = this.getUtoTmapping( u ); + return this.getTangent( t ); - LineCurve.prototype.getPoint = function ( t ) { + } - if ( t === 1 ) { + }; - return this.v2.clone(); + // TODO: Transformation for Curves? - } + /************************************************************** + * 3D Curves + **************************************************************/ - var point = this.v2.clone().sub( this.v1 ); - point.multiplyScalar( t ).add( this.v1 ); + // A Factory method for creating new curve subclasses - return point; + Curve.create = function ( constructor, getPointFunc ) { - }; + constructor.prototype = Object.create( Curve.prototype ); + constructor.prototype.constructor = constructor; + constructor.prototype.getPoint = getPointFunc; - // Line curve is linear, so we can overwrite default getPointAt + return constructor; - LineCurve.prototype.getPointAt = function ( u ) { + }; - return this.getPoint( u ); + /************************************************************** + * Line + **************************************************************/ - }; + function LineCurve( v1, v2 ) { - LineCurve.prototype.getTangent = function( t ) { + this.v1 = v1; + this.v2 = v2; - var tangent = this.v2.clone().sub( this.v1 ); + }; - return tangent.normalize(); + LineCurve.prototype = Object.create( Curve.prototype ); + LineCurve.prototype.constructor = LineCurve; - }; + LineCurve.prototype.isLineCurve = true; - /** - * @author zz85 / http://www.lab4games.net/zz85/blog - * - **/ + LineCurve.prototype.getPoint = function ( t ) { - /************************************************************** - * Curved Path - a curve path is simply a array of connected - * curves, but retains the api of a curve - **************************************************************/ + if ( t === 1 ) { - function CurvePath() { + return this.v2.clone(); - this.curves = []; + } - this.autoClose = false; // Automatically closes the path + var point = this.v2.clone().sub( this.v1 ); + point.multiplyScalar( t ).add( this.v1 ); - }; + return point; - CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), { + }; - constructor: CurvePath, + // Line curve is linear, so we can overwrite default getPointAt - add: function ( curve ) { + LineCurve.prototype.getPointAt = function ( u ) { - this.curves.push( curve ); + return this.getPoint( u ); - }, + }; - closePath: function () { + LineCurve.prototype.getTangent = function( t ) { - // 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 ); + var tangent = this.v2.clone().sub( this.v1 ); - if ( ! startPoint.equals( endPoint ) ) { + return tangent.normalize(); - this.curves.push( new LineCurve( endPoint, startPoint ) ); + }; - } + /** + * @author zz85 / http://www.lab4games.net/zz85/blog + * + **/ - }, + /************************************************************** + * Curved Path - a curve path is simply a array of connected + * curves, but retains the api of a curve + **************************************************************/ - // To get accurate point with reference to - // entire path distance at time t, - // following has to be done: + function CurvePath() { - // 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') + this.curves = []; - getPoint: function ( t ) { + this.autoClose = false; // Automatically closes the path - var d = t * this.getLength(); - var curveLengths = this.getCurveLengths(); - var i = 0; + }; - // To think about boundaries points. + CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), { - while ( i < curveLengths.length ) { + constructor: CurvePath, - if ( curveLengths[ i ] >= d ) { + add: function ( curve ) { - var diff = curveLengths[ i ] - d; - var curve = this.curves[ i ]; + this.curves.push( curve ); - var segmentLength = curve.getLength(); - var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength; + }, - return curve.getPointAt( u ); + 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 ); - i ++; + if ( ! startPoint.equals( endPoint ) ) { - } + this.curves.push( new LineCurve( endPoint, startPoint ) ); - return null; + } - // loop where sum != 0, sum > d , sum+1 = d ) { - }, + var diff = curveLengths[ i ] - d; + var curve = this.curves[ i ]; - // Compute lengths and cache them - // We cannot overwrite getLengths() because UtoT mapping uses it. + var segmentLength = curve.getLength(); + var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength; - getCurveLengths: function () { + return curve.getPointAt( u ); - // We use cache values if curves and cache array are same length + } - if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) { + i ++; - return this.cacheLengths; + } - } + return null; - // Get length of sub-curve - // Push sums into cached array + // loop where sum != 0, sum > d , sum+1 1 && !points[ points.length - 1 ].equals( points[ 0 ] ) ) { + } - points.push( points[ 0 ] ); + return points; - } + }, - return points; + getPoints: function ( divisions ) { - }, + divisions = divisions || 12; - /************************************************************** - * Create Geometries Helpers - **************************************************************/ + var points = [], last; - /// Generate geometry from path points (for Line or Points objects) + for ( var i = 0, curves = this.curves; i < curves.length; i ++ ) { - createPointsGeometry: function ( divisions ) { + var curve = curves[ i ]; + var resolution = (curve && curve.isEllipseCurve) ? divisions * 2 + : (curve && curve.isLineCurve) ? 1 + : (curve && curve.isSplineCurve) ? divisions * curve.points.length + : divisions; - var pts = this.getPoints( divisions ); - return this.createGeometry( pts ); + var pts = curve.getPoints( resolution ); - }, + for ( var j = 0; j < pts.length; j++ ) { - // Generate geometry from equidistant sampling along the path + var point = pts[ j ]; - createSpacedPointsGeometry: function ( divisions ) { + if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates - var pts = this.getSpacedPoints( divisions ); - return this.createGeometry( pts ); + points.push( point ); + last = point; - }, + } - createGeometry: function ( points ) { + } - var geometry = new Geometry(); + if ( this.autoClose && points.length > 1 && !points[ points.length - 1 ].equals( points[ 0 ] ) ) { - for ( var i = 0, l = points.length; i < l; i ++ ) { + points.push( points[ 0 ] ); - var point = points[ i ]; - geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) ); + } - } + return points; - return geometry; + }, - } + /************************************************************** + * Create Geometries Helpers + **************************************************************/ - } ); + /// Generate geometry from path points (for Line or Points objects) - /************************************************************** - * Ellipse curve - **************************************************************/ + createPointsGeometry: function ( divisions ) { - function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { + var pts = this.getPoints( divisions ); + return this.createGeometry( pts ); - this.aX = aX; - this.aY = aY; + }, - this.xRadius = xRadius; - this.yRadius = yRadius; + // Generate geometry from equidistant sampling along the path - this.aStartAngle = aStartAngle; - this.aEndAngle = aEndAngle; + createSpacedPointsGeometry: function ( divisions ) { - this.aClockwise = aClockwise; + var pts = this.getSpacedPoints( divisions ); + return this.createGeometry( pts ); - this.aRotation = aRotation || 0; + }, - }; + createGeometry: function ( points ) { - EllipseCurve.prototype = Object.create( Curve.prototype ); - EllipseCurve.prototype.constructor = EllipseCurve; + var geometry = new Geometry(); - EllipseCurve.prototype.isEllipseCurve = true; + for ( var i = 0, l = points.length; i < l; i ++ ) { - EllipseCurve.prototype.getPoint = function( t ) { + var point = points[ i ]; + geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) ); - var twoPi = Math.PI * 2; - var deltaAngle = this.aEndAngle - this.aStartAngle; - var samePoints = Math.abs( deltaAngle ) < Number.EPSILON; + } - // ensures that deltaAngle is 0 .. 2 PI - while ( deltaAngle < 0 ) deltaAngle += twoPi; - while ( deltaAngle > twoPi ) deltaAngle -= twoPi; + return geometry; - if ( deltaAngle < Number.EPSILON ) { + } - if ( samePoints ) { + } ); - deltaAngle = 0; + /************************************************************** + * Ellipse curve + **************************************************************/ - } else { + function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { - deltaAngle = twoPi; + this.aX = aX; + this.aY = aY; - } + this.xRadius = xRadius; + this.yRadius = yRadius; - } + this.aStartAngle = aStartAngle; + this.aEndAngle = aEndAngle; - if ( this.aClockwise === true && ! samePoints ) { + this.aClockwise = aClockwise; - if ( deltaAngle === twoPi ) { + this.aRotation = aRotation || 0; - deltaAngle = - twoPi; + }; - } else { + EllipseCurve.prototype = Object.create( Curve.prototype ); + EllipseCurve.prototype.constructor = EllipseCurve; - deltaAngle = deltaAngle - twoPi; + EllipseCurve.prototype.isEllipseCurve = true; - } + EllipseCurve.prototype.getPoint = function( t ) { - } + var twoPi = Math.PI * 2; + var deltaAngle = this.aEndAngle - this.aStartAngle; + var samePoints = Math.abs( deltaAngle ) < Number.EPSILON; - var angle = this.aStartAngle + t * deltaAngle; - var x = this.aX + this.xRadius * Math.cos( angle ); - var y = this.aY + this.yRadius * Math.sin( angle ); + // ensures that deltaAngle is 0 .. 2 PI + while ( deltaAngle < 0 ) deltaAngle += twoPi; + while ( deltaAngle > twoPi ) deltaAngle -= twoPi; - if ( this.aRotation !== 0 ) { + if ( deltaAngle < Number.EPSILON ) { - var cos = Math.cos( this.aRotation ); - var sin = Math.sin( this.aRotation ); + if ( samePoints ) { - var tx = x - this.aX; - var ty = y - this.aY; + deltaAngle = 0; - // Rotate the point about the center of the ellipse. - x = tx * cos - ty * sin + this.aX; - y = tx * sin + ty * cos + this.aY; + } else { - } + deltaAngle = twoPi; - return new Vector2( x, y ); + } - }; + } - /** - * @author zz85 / http://www.lab4games.net/zz85/blog - */ + if ( this.aClockwise === true && ! samePoints ) { - exports.CurveUtils = { + if ( deltaAngle === twoPi ) { - tangentQuadraticBezier: function ( t, p0, p1, p2 ) { + deltaAngle = - twoPi; - return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 ); + } else { - }, + deltaAngle = deltaAngle - twoPi; - // Puay Bing, thanks for helping with this derivative! + } - tangentCubicBezier: function ( t, p0, p1, p2, p3 ) { + } - 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; + var angle = this.aStartAngle + t * deltaAngle; + var x = this.aX + this.xRadius * Math.cos( angle ); + var y = this.aY + this.yRadius * Math.sin( angle ); - }, + if ( this.aRotation !== 0 ) { - tangentSpline: function ( t, p0, p1, p2, p3 ) { + var cos = Math.cos( this.aRotation ); + var sin = Math.sin( this.aRotation ); - // To check if my formulas are correct + var tx = x - this.aX; + var ty = y - this.aY; - 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 + // Rotate the point about the center of the ellipse. + x = tx * cos - ty * sin + this.aX; + y = tx * sin + ty * cos + this.aY; - return h00 + h10 + h01 + h11; + } - }, + return new Vector2( x, y ); - // Catmull-Rom + }; - interpolate: function( p0, p1, p2, p3, t ) { + /** + * @author zz85 / http://www.lab4games.net/zz85/blog + */ - 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; + exports.CurveUtils = { - } + tangentQuadraticBezier: function ( t, p0, p1, p2 ) { - }; + return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 ); - /************************************************************** - * Spline curve - **************************************************************/ + }, - function SplineCurve( points /* array of Vector2 */ ) { + // Puay Bing, thanks for helping with this derivative! - this.points = ( points == undefined ) ? [] : points; + tangentCubicBezier: function ( t, p0, p1, p2, p3 ) { - }; + 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 = Object.create( Curve.prototype ); - SplineCurve.prototype.constructor = SplineCurve; + }, - SplineCurve.prototype.isSplineCurve = true; + tangentSpline: function ( t, p0, p1, p2, p3 ) { - SplineCurve.prototype.getPoint = function ( t ) { + // To check if my formulas are correct - var points = this.points; - var point = ( points.length - 1 ) * t; + 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 intPoint = Math.floor( point ); - var weight = point - intPoint; + return h00 + h10 + h01 + h11; - 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; + // Catmull-Rom - return new Vector2( - interpolate( point0.x, point1.x, point2.x, point3.x, weight ), - interpolate( point0.y, point1.y, point2.y, point3.y, weight ) - ); + interpolate: function( p0, p1, p2, p3, t ) { - }; + 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; - /************************************************************** - * Cubic Bezier curve - **************************************************************/ + } - function CubicBezierCurve( v0, v1, v2, v3 ) { + }; - this.v0 = v0; - this.v1 = v1; - this.v2 = v2; - this.v3 = v3; + /************************************************************** + * Spline curve + **************************************************************/ - }; + function SplineCurve( points /* array of Vector2 */ ) { - CubicBezierCurve.prototype = Object.create( Curve.prototype ); - CubicBezierCurve.prototype.constructor = CubicBezierCurve; + this.points = ( points == undefined ) ? [] : points; - CubicBezierCurve.prototype.getPoint = function ( t ) { + }; - var b3 = exports.ShapeUtils.b3; + SplineCurve.prototype = Object.create( Curve.prototype ); + SplineCurve.prototype.constructor = SplineCurve; - 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.isSplineCurve = true; - }; + SplineCurve.prototype.getPoint = function ( t ) { - CubicBezierCurve.prototype.getTangent = function( t ) { + var points = this.points; + var point = ( points.length - 1 ) * t; - var tangentCubicBezier = exports.CurveUtils.tangentCubicBezier; + var intPoint = Math.floor( point ); + var weight = point - intPoint; - 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 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; - /************************************************************** - * Quadratic Bezier curve - **************************************************************/ + return new Vector2( + interpolate( point0.x, point1.x, point2.x, point3.x, weight ), + interpolate( point0.y, point1.y, point2.y, point3.y, weight ) + ); + }; - function QuadraticBezierCurve( v0, v1, v2 ) { + /************************************************************** + * Cubic Bezier curve + **************************************************************/ - this.v0 = v0; - this.v1 = v1; - this.v2 = v2; + function CubicBezierCurve( v0, v1, v2, v3 ) { - }; + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + this.v3 = v3; - QuadraticBezierCurve.prototype = Object.create( Curve.prototype ); - QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve; + }; + CubicBezierCurve.prototype = Object.create( Curve.prototype ); + CubicBezierCurve.prototype.constructor = CubicBezierCurve; - QuadraticBezierCurve.prototype.getPoint = function ( t ) { + CubicBezierCurve.prototype.getPoint = function ( t ) { - var b2 = exports.ShapeUtils.b2; + var b3 = exports.ShapeUtils.b3; - 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 ) - ); + 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 ) + ); - }; + }; + CubicBezierCurve.prototype.getTangent = function( t ) { - QuadraticBezierCurve.prototype.getTangent = function( t ) { + var tangentCubicBezier = exports.CurveUtils.tangentCubicBezier; - var tangentQuadraticBezier = exports.CurveUtils.tangentQuadraticBezier; + 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(); - 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(); + }; - }; + /************************************************************** + * Quadratic Bezier curve + **************************************************************/ - var PathPrototype = Object.assign( Object.create( CurvePath.prototype ), { - fromPoints: function ( vectors ) { + function QuadraticBezierCurve( v0, v1, v2 ) { - this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y ); + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; - for ( var i = 1, l = vectors.length; i < l; i ++ ) { + }; - this.lineTo( vectors[ i ].x, vectors[ i ].y ); + QuadraticBezierCurve.prototype = Object.create( Curve.prototype ); + QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve; - } - }, + QuadraticBezierCurve.prototype.getPoint = function ( t ) { - moveTo: function ( x, y ) { + var b2 = exports.ShapeUtils.b2; - this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying? + 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 ) + ); - }, + }; - lineTo: function ( x, y ) { - var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) ); - this.curves.push( curve ); + QuadraticBezierCurve.prototype.getTangent = function( t ) { - this.currentPoint.set( x, y ); + var tangentQuadraticBezier = exports.CurveUtils.tangentQuadraticBezier; - }, + 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(); - quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) { + }; - var curve = new QuadraticBezierCurve( - this.currentPoint.clone(), - new Vector2( aCPx, aCPy ), - new Vector2( aX, aY ) - ); + var PathPrototype = Object.assign( Object.create( CurvePath.prototype ), { - this.curves.push( curve ); + fromPoints: function ( vectors ) { - this.currentPoint.set( aX, aY ); + this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y ); - }, + for ( var i = 1, l = vectors.length; i < l; i ++ ) { - bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) { + this.lineTo( vectors[ i ].x, vectors[ i ].y ); - var curve = new CubicBezierCurve( - this.currentPoint.clone(), - new Vector2( aCP1x, aCP1y ), - new Vector2( aCP2x, aCP2y ), - new Vector2( aX, aY ) - ); + } - this.curves.push( curve ); + }, - this.currentPoint.set( aX, aY ); + moveTo: function ( x, y ) { - }, + this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying? - splineThru: function ( pts /*Array of Vector*/ ) { + }, - var npts = [ this.currentPoint.clone() ].concat( pts ); + lineTo: function ( x, y ) { - var curve = new SplineCurve( npts ); - this.curves.push( curve ); + var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) ); + this.curves.push( curve ); - this.currentPoint.copy( pts[ pts.length - 1 ] ); + this.currentPoint.set( x, y ); - }, + }, - arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { + quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) { - var x0 = this.currentPoint.x; - var y0 = this.currentPoint.y; + var curve = new QuadraticBezierCurve( + this.currentPoint.clone(), + new Vector2( aCPx, aCPy ), + new Vector2( aX, aY ) + ); - this.absarc( aX + x0, aY + y0, aRadius, - aStartAngle, aEndAngle, aClockwise ); + this.curves.push( curve ); - }, + this.currentPoint.set( aX, aY ); - absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { + }, - this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); + bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) { - }, + var curve = new CubicBezierCurve( + this.currentPoint.clone(), + new Vector2( aCP1x, aCP1y ), + new Vector2( aCP2x, aCP2y ), + new Vector2( aX, aY ) + ); - ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { + this.curves.push( curve ); - var x0 = this.currentPoint.x; - var y0 = this.currentPoint.y; + this.currentPoint.set( aX, aY ); - this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); + }, - }, + splineThru: function ( pts /*Array of Vector*/ ) { - absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { + var npts = [ this.currentPoint.clone() ].concat( pts ); - var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); + var curve = new SplineCurve( npts ); + this.curves.push( curve ); - if ( this.curves.length > 0 ) { + this.currentPoint.copy( pts[ pts.length - 1 ] ); - // if a previous curve is present, attempt to join - var firstPoint = curve.getPoint( 0 ); + }, - if ( ! firstPoint.equals( this.currentPoint ) ) { + arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { - this.lineTo( firstPoint.x, firstPoint.y ); + var x0 = this.currentPoint.x; + var y0 = this.currentPoint.y; - } + this.absarc( aX + x0, aY + y0, aRadius, + aStartAngle, aEndAngle, aClockwise ); - } + }, - this.curves.push( curve ); + absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { - var lastPoint = curve.getPoint( 1 ); - this.currentPoint.copy( lastPoint ); + this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); - } + }, - } ) + ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { - /** - * @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 - */ + var x0 = this.currentPoint.x; + var y0 = this.currentPoint.y; - function TubeGeometry( path, segments, radius, radialSegments, closed, taper ) { + this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); - Geometry.call( this ); + }, - this.type = 'TubeGeometry'; + absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { - this.parameters = { - path: path, - segments: segments, - radius: radius, - radialSegments: radialSegments, - closed: closed, - taper: taper - }; + var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); - segments = segments || 64; - radius = radius || 1; - radialSegments = radialSegments || 8; - closed = closed || false; - taper = taper || TubeGeometry.NoTaper; + if ( this.curves.length > 0 ) { - var grid = []; + // if a previous curve is present, attempt to join + var firstPoint = curve.getPoint( 0 ); - var scope = this, + if ( ! firstPoint.equals( this.currentPoint ) ) { - tangent, - normal, - binormal, + this.lineTo( firstPoint.x, firstPoint.y ); - numpoints = segments + 1, + } - u, v, r, + } - cx, cy, - pos, pos2 = new Vector3(), - i, j, - ip, jp, - a, b, c, d, - uva, uvb, uvc, uvd; + this.curves.push( curve ); - var frames = new TubeGeometry.FrenetFrames( path, segments, closed ), - tangents = frames.tangents, - normals = frames.normals, - binormals = frames.binormals; + var lastPoint = curve.getPoint( 1 ); + this.currentPoint.copy( lastPoint ); - // proxy internals - this.tangents = tangents; - this.normals = normals; - this.binormals = binormals; + } - function vert( x, y, z ) { + } ) - return scope.vertices.push( new Vector3( x, y, z ) ) - 1; + /** + * @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 ) { - // construct the grid + Geometry.call( this ); - for ( i = 0; i < numpoints; i ++ ) { + this.type = 'TubeGeometry'; - grid[ i ] = []; + this.parameters = { + path: path, + segments: segments, + radius: radius, + radialSegments: radialSegments, + closed: closed, + taper: taper + }; - u = i / ( numpoints - 1 ); + segments = segments || 64; + radius = radius || 1; + radialSegments = radialSegments || 8; + closed = closed || false; + taper = taper || TubeGeometry.NoTaper; - pos = path.getPointAt( u ); + var grid = []; - tangent = tangents[ i ]; - normal = normals[ i ]; - binormal = binormals[ i ]; + var scope = this, - r = radius * taper( u ); + tangent, + normal, + binormal, - for ( j = 0; j < radialSegments; j ++ ) { + numpoints = segments + 1, - v = j / radialSegments * 2 * Math.PI; + u, v, r, - cx = - r * Math.cos( v ); // TODO: Hack: Negating it so it faces outside. - cy = r * Math.sin( v ); + cx, cy, + pos, pos2 = new Vector3(), + i, j, + ip, jp, + a, b, c, d, + uva, uvb, uvc, uvd; - 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; + var frames = new TubeGeometry.FrenetFrames( path, segments, closed ), + tangents = frames.tangents, + normals = frames.normals, + binormals = frames.binormals; - grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z ); + // proxy internals + this.tangents = tangents; + this.normals = normals; + this.binormals = binormals; - } + function vert( x, y, z ) { - } + return scope.vertices.push( new Vector3( x, y, z ) ) - 1; + } - // construct the mesh + // construct the grid - for ( i = 0; i < segments; i ++ ) { + for ( i = 0; i < numpoints; i ++ ) { - for ( j = 0; j < radialSegments; j ++ ) { + grid[ i ] = []; - ip = ( closed ) ? ( i + 1 ) % segments : i + 1; - jp = ( j + 1 ) % radialSegments; + u = i / ( numpoints - 1 ); - a = grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! *** - b = grid[ ip ][ j ]; - c = grid[ ip ][ jp ]; - d = grid[ i ][ jp ]; + pos = path.getPointAt( u ); - 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 ); + tangent = tangents[ i ]; + normal = normals[ i ]; + binormal = binormals[ i ]; - this.faces.push( new Face3( a, b, d ) ); - this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] ); + r = radius * taper( u ); - this.faces.push( new Face3( b, c, d ) ); - this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] ); + for ( j = 0; j < radialSegments; j ++ ) { - } + v = j / radialSegments * 2 * Math.PI; - } + cx = - r * Math.cos( v ); // TODO: Hack: Negating it so it faces outside. + cy = r * Math.sin( v ); - this.computeFaceNormals(); - this.computeVertexNormals(); + 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; - }; + grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z ); - TubeGeometry.prototype = Object.create( Geometry.prototype ); - TubeGeometry.prototype.constructor = TubeGeometry; + } - TubeGeometry.NoTaper = function ( u ) { + } - return 1; - }; + // construct the mesh - TubeGeometry.SinusoidalTaper = function ( u ) { + for ( i = 0; i < segments; i ++ ) { - return Math.sin( Math.PI * u ); + for ( j = 0; j < radialSegments; j ++ ) { - }; + ip = ( closed ) ? ( i + 1 ) % segments : i + 1; + jp = ( j + 1 ) % radialSegments; - // For computing of Frenet frames, exposing the tangents, normals and binormals the spline - TubeGeometry.FrenetFrames = function ( path, segments, closed ) { + a = grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! *** + b = grid[ ip ][ j ]; + c = grid[ ip ][ jp ]; + d = grid[ i ][ jp ]; - var normal = new Vector3(), + 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 ); - tangents = [], - normals = [], - binormals = [], + this.faces.push( new Face3( a, b, d ) ); + this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] ); - vec = new Vector3(), - mat = new Matrix4(), + this.faces.push( new Face3( b, c, d ) ); + this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] ); - numpoints = segments + 1, - theta, - smallest, + } - tx, ty, tz, - i, u; + } + this.computeFaceNormals(); + this.computeVertexNormals(); - // expose internals - this.tangents = tangents; - this.normals = normals; - this.binormals = binormals; + }; - // compute the tangent vectors for each segment on the path + TubeGeometry.prototype = Object.create( Geometry.prototype ); + TubeGeometry.prototype.constructor = TubeGeometry; - for ( i = 0; i < numpoints; i ++ ) { + TubeGeometry.NoTaper = function ( u ) { - u = i / ( numpoints - 1 ); + return 1; - tangents[ i ] = path.getTangentAt( u ); - tangents[ i ].normalize(); + }; - } + TubeGeometry.SinusoidalTaper = function ( u ) { - initialNormal3(); + return Math.sin( Math.PI * u ); - /* - 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(); - } + }; - function initialNormal2() { + // For computing of Frenet frames, exposing the tangents, normals and binormals the spline + TubeGeometry.FrenetFrames = function ( path, segments, closed ) { - // This uses the Frenet-Serret formula for deriving binormal - var t2 = path.getTangentAt( epsilon ); + var normal = new Vector3(), - normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize(); - binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] ); + tangents = [], + normals = [], + binormals = [], - normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent - binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize(); + vec = new Vector3(), + mat = new Matrix4(), - } - */ + numpoints = segments + 1, + theta, + smallest, - function initialNormal3() { + tx, ty, tz, + i, u; - // select an initial normal vector perpendicular to the first tangent vector, - // and in the direction of the smallest tangent xyz component - 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 ); + // expose internals + this.tangents = tangents; + this.normals = normals; + this.binormals = binormals; - if ( tx <= smallest ) { + // compute the tangent vectors for each segment on the path - smallest = tx; - normal.set( 1, 0, 0 ); + for ( i = 0; i < numpoints; i ++ ) { - } + u = i / ( numpoints - 1 ); - if ( ty <= smallest ) { + tangents[ i ] = path.getTangentAt( u ); + tangents[ i ].normalize(); - smallest = ty; - normal.set( 0, 1, 0 ); + } - } + initialNormal3(); - if ( tz <= smallest ) { + /* + 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(); + } - normal.set( 0, 0, 1 ); + function initialNormal2() { - } + // This uses the Frenet-Serret formula for deriving binormal + var t2 = path.getTangentAt( epsilon ); - vec.crossVectors( tangents[ 0 ], normal ).normalize(); + normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize(); + binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] ); - normals[ 0 ].crossVectors( tangents[ 0 ], vec ); - binormals[ 0 ].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(); - } + } + */ + function initialNormal3() { - // compute the slowly-varying normal and binormal vectors for each segment on the path + // select an initial normal vector perpendicular to the first tangent vector, + // and in the direction of the smallest tangent xyz component - for ( i = 1; i < numpoints; i ++ ) { + 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 ); - normals[ i ] = normals[ i - 1 ].clone(); + if ( tx <= smallest ) { - binormals[ i ] = binormals[ i - 1 ].clone(); + smallest = tx; + normal.set( 1, 0, 0 ); - vec.crossVectors( tangents[ i - 1 ], tangents[ i ] ); + } - if ( vec.length() > Number.EPSILON ) { + if ( ty <= smallest ) { - vec.normalize(); + smallest = ty; + normal.set( 0, 1, 0 ); - theta = Math.acos( exports.Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors + } - normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) ); + if ( tz <= smallest ) { - } + normal.set( 0, 0, 1 ); - binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); + } - } + vec.crossVectors( tangents[ 0 ], normal ).normalize(); + normals[ 0 ].crossVectors( tangents[ 0 ], vec ); + binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ); - // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same + } - if ( closed ) { - theta = Math.acos( exports.Math.clamp( normals[ 0 ].dot( normals[ numpoints - 1 ] ), - 1, 1 ) ); - theta /= ( numpoints - 1 ); + // compute the slowly-varying normal and binormal vectors for each segment on the path - if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints - 1 ] ) ) > 0 ) { + for ( i = 1; i < numpoints; i ++ ) { - theta = - theta; + normals[ i ] = normals[ i - 1 ].clone(); - } + binormals[ i ] = binormals[ i - 1 ].clone(); - for ( i = 1; i < numpoints; i ++ ) { + vec.crossVectors( tangents[ i - 1 ], tangents[ i ] ); - // twist a little... - normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) ); - binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); + if ( vec.length() > Number.EPSILON ) { - } + vec.normalize(); - } + theta = Math.acos( exports.Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors - }; + normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) ); - /** - * @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 ) { + binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); - if ( typeof( shapes ) === "undefined" ) { + } - shapes = []; - return; - } + // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same - Geometry.call( this ); + if ( closed ) { - this.type = 'ExtrudeGeometry'; + theta = Math.acos( exports.Math.clamp( normals[ 0 ].dot( normals[ numpoints - 1 ] ), - 1, 1 ) ); + theta /= ( numpoints - 1 ); - shapes = Array.isArray( shapes ) ? shapes : [ shapes ]; + if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints - 1 ] ) ) > 0 ) { - this.addShapeList( shapes, options ); + theta = - theta; - this.computeFaceNormals(); + } - // can't really use automatic vertex normals - // as then front and back sides get smoothed too - // should do separate smoothing just for sides + for ( i = 1; i < numpoints; i ++ ) { - //this.computeVertexNormals(); + // twist a little... + normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) ); + binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); - //console.log( "took", ( Date.now() - startTime ) ); + } - }; + } - ExtrudeGeometry.prototype = Object.create( Geometry.prototype ); - ExtrudeGeometry.prototype.constructor = ExtrudeGeometry; + }; - ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) { + /** + * @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 sl = shapes.length; + } - for ( var s = 0; s < sl; s ++ ) { + Geometry.call( this ); - var shape = shapes[ s ]; - this.addShape( shape, options ); + this.type = 'ExtrudeGeometry'; - } + shapes = Array.isArray( shapes ) ? shapes : [ shapes ]; - }; + this.addShapeList( shapes, options ); - ExtrudeGeometry.prototype.addShape = function ( shape, options ) { + this.computeFaceNormals(); - var amount = options.amount !== undefined ? options.amount : 100; + // can't really use automatic vertex normals + // as then front and back sides get smoothed too + // should do separate smoothing just for sides - 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.computeVertexNormals(); - var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false + //console.log( "took", ( Date.now() - startTime ) ); - var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12; + }; - var steps = options.steps !== undefined ? options.steps : 1; + ExtrudeGeometry.prototype = Object.create( Geometry.prototype ); + ExtrudeGeometry.prototype.constructor = ExtrudeGeometry; - var extrudePath = options.extrudePath; - var extrudePts, extrudeByPath = false; + ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) { - // Use default WorldUVGenerator if no UV generators are specified. - var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : ExtrudeGeometry.WorldUVGenerator; + var sl = shapes.length; - var splineTube, binormal, normal, position2; - if ( extrudePath ) { + for ( var s = 0; s < sl; s ++ ) { - extrudePts = extrudePath.getSpacedPoints( steps ); + var shape = shapes[ s ]; + this.addShape( shape, options ); - extrudeByPath = true; - bevelEnabled = false; // bevels not supported for path extrusion + } - // SETUP TNB variables + }; - // Reuse TNB from TubeGeomtry for now. - // TODO1 - have a .isClosed in spline? + ExtrudeGeometry.prototype.addShape = function ( shape, options ) { - splineTube = options.frames !== undefined ? options.frames : new TubeGeometry.FrenetFrames( extrudePath, steps, false ); + var amount = options.amount !== undefined ? options.amount : 100; - // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length); + 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; - binormal = new Vector3(); - normal = new Vector3(); - position2 = new Vector3(); + var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false - } + var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12; - // Safeguards if bevels are not enabled + var steps = options.steps !== undefined ? options.steps : 1; - if ( ! bevelEnabled ) { + var extrudePath = options.extrudePath; + var extrudePts, extrudeByPath = false; - bevelSegments = 0; - bevelThickness = 0; - bevelSize = 0; + // Use default WorldUVGenerator if no UV generators are specified. + var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : ExtrudeGeometry.WorldUVGenerator; - } + var splineTube, binormal, normal, position2; + if ( extrudePath ) { - // Variables initialization + extrudePts = extrudePath.getSpacedPoints( steps ); - var ahole, h, hl; // looping of holes - var scope = this; + extrudeByPath = true; + bevelEnabled = false; // bevels not supported for path extrusion - var shapesOffset = this.vertices.length; + // SETUP TNB variables - var shapePoints = shape.extractPoints( curveSegments ); + // Reuse TNB from TubeGeomtry for now. + // TODO1 - have a .isClosed in spline? - var vertices = shapePoints.shape; - var holes = shapePoints.holes; + splineTube = options.frames !== undefined ? options.frames : new TubeGeometry.FrenetFrames( extrudePath, steps, false ); - var reverse = ! exports.ShapeUtils.isClockWise( vertices ); + // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length); - if ( reverse ) { + binormal = new Vector3(); + normal = new Vector3(); + position2 = new Vector3(); - vertices = vertices.reverse(); + } - // Maybe we should also check if holes are in the opposite direction, just to be safe ... + // Safeguards if bevels are not enabled - for ( h = 0, hl = holes.length; h < hl; h ++ ) { + if ( ! bevelEnabled ) { - ahole = holes[ h ]; + bevelSegments = 0; + bevelThickness = 0; + bevelSize = 0; - if ( exports.ShapeUtils.isClockWise( ahole ) ) { + } - holes[ h ] = ahole.reverse(); + // Variables initialization - } + var ahole, h, hl; // looping of holes + var scope = this; - } + var shapesOffset = this.vertices.length; - reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)! + var shapePoints = shape.extractPoints( curveSegments ); - } + var vertices = shapePoints.shape; + var holes = shapePoints.holes; + var reverse = ! exports.ShapeUtils.isClockWise( vertices ); - var faces = exports.ShapeUtils.triangulateShape( vertices, holes ); + if ( reverse ) { - /* Vertices */ + vertices = vertices.reverse(); - var contour = vertices; // vertices has all points but contour has only points of circumference + // Maybe we should also check if holes are in the opposite direction, just to be safe ... - for ( h = 0, hl = holes.length; h < hl; h ++ ) { + for ( h = 0, hl = holes.length; h < hl; h ++ ) { - ahole = holes[ h ]; + ahole = holes[ h ]; - vertices = vertices.concat( ahole ); + if ( exports.ShapeUtils.isClockWise( ahole ) ) { - } + holes[ h ] = ahole.reverse(); + } - function scalePt2( pt, vec, size ) { + } - if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" ); + reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)! - return vec.clone().multiplyScalar( size ).add( pt ); + } - } - var b, bs, t, z, - vert, vlen = vertices.length, - face, flen = faces.length; + var faces = exports.ShapeUtils.triangulateShape( vertices, holes ); + /* Vertices */ - // Find directions for point movement + var contour = vertices; // vertices has all points but contour has only points of circumference + for ( h = 0, hl = holes.length; h < hl; h ++ ) { - function getBevelVec( inPt, inPrev, inNext ) { + ahole = holes[ h ]; - // 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. + vertices = vertices.concat( ahole ); - var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt + } - // good reading for geometry algorithms (here: line-line intersection) - // http://geomalgorithms.com/a05-_intersect-1.html - 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; + function scalePt2( pt, vec, size ) { - var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y ); + if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" ); - // check for collinear edges - var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x ); + return vec.clone().multiplyScalar( size ).add( pt ); - if ( Math.abs( collinear0 ) > Number.EPSILON ) { + } - // not collinear + var b, bs, t, z, + vert, vlen = vertices.length, + face, flen = faces.length; - // 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 ); + // Find directions for point movement - // 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 ); + function getBevelVec( inPt, inPrev, inNext ) { - var ptNextShift_x = ( inNext.x - v_next_y / v_next_len ); - var ptNextShift_y = ( inNext.y + v_next_x / v_next_len ); + // 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. - // scaling factor for v_prev to intersection point + var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt - 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 ); + // good reading for geometry algorithms (here: line-line intersection) + // http://geomalgorithms.com/a05-_intersect-1.html - // vector from inPt to intersection point + 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; - v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x ); - v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y ); + var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y ); - // 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 ) { + // check for collinear edges + var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x ); - return new Vector2( v_trans_x, v_trans_y ); + if ( Math.abs( collinear0 ) > Number.EPSILON ) { - } else { + // not collinear - shrink_by = Math.sqrt( v_trans_lensq / 2 ); + // 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 ); - } else { + // shift adjacent points by unit vectors to the left - // handle special case of collinear edges + var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len ); + var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len ); - var direction_eq = false; // assumes: opposite - if ( v_prev_x > Number.EPSILON ) { + var ptNextShift_x = ( inNext.x - v_next_y / v_next_len ); + var ptNextShift_y = ( inNext.y + v_next_x / v_next_len ); - if ( v_next_x > Number.EPSILON ) { + // scaling factor for v_prev to intersection point - direction_eq = true; + 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 ); - } + // vector from inPt to intersection point - } else { + v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x ); + v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y ); - if ( v_prev_x < - Number.EPSILON ) { + // 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 ) { - if ( v_next_x < - Number.EPSILON ) { + return new Vector2( v_trans_x, v_trans_y ); - direction_eq = true; + } else { - } + shrink_by = Math.sqrt( v_trans_lensq / 2 ); - } else { + } - if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) { + } else { - direction_eq = true; + // handle special case of collinear edges - } + var direction_eq = false; // assumes: opposite + if ( v_prev_x > Number.EPSILON ) { - } + if ( v_next_x > Number.EPSILON ) { - } + direction_eq = true; - if ( direction_eq ) { + } - // 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 ); + } else { - } else { + if ( v_prev_x < - Number.EPSILON ) { - // 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 ); + if ( v_next_x < - Number.EPSILON ) { - } + direction_eq = true; - } + } - return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by ); + } else { - } + if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) { + direction_eq = true; - 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; + } - // (j)---(i)---(k) - // console.log('i,j,k', i, j , k) + if ( direction_eq ) { - contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] ); + // 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 ); - } + } else { - var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat(); + // 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 ); - for ( h = 0, hl = holes.length; h < hl; h ++ ) { + } - ahole = holes[ h ]; + } - oneHoleMovements = []; + return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by ); - 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; - // (j)---(i)---(k) - oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] ); + var contourMovements = []; - } + for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) { - holesMovements.push( oneHoleMovements ); - verticesMovements = verticesMovements.concat( oneHoleMovements ); + 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 ] ); - // Loop bevelSegments, 1 for the front, 1 for the back + } - for ( b = 0; b < bevelSegments; b ++ ) { + var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat(); - //for ( b = bevelSegments; b > 0; b -- ) { + for ( h = 0, hl = holes.length; h < hl; h ++ ) { - t = b / bevelSegments; - z = bevelThickness * Math.cos( t * Math.PI / 2 ); - bs = bevelSize * Math.sin( t * Math.PI / 2 ); + ahole = holes[ h ]; - // contract shape + oneHoleMovements = []; - for ( i = 0, il = contour.length; i < il; i ++ ) { + for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) { - vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); + if ( j === il ) j = 0; + if ( k === il ) k = 0; - v( vert.x, vert.y, - z ); + // (j)---(i)---(k) + oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] ); - } + } - // expand holes + holesMovements.push( oneHoleMovements ); + verticesMovements = verticesMovements.concat( oneHoleMovements ); - for ( h = 0, hl = holes.length; h < hl; h ++ ) { + } - ahole = holes[ h ]; - oneHoleMovements = holesMovements[ h ]; - for ( i = 0, il = ahole.length; i < il; i ++ ) { + // Loop bevelSegments, 1 for the front, 1 for the back - vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); + for ( b = 0; b < bevelSegments; b ++ ) { - v( vert.x, vert.y, - z ); + //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 ); - } + // contract shape - } + for ( i = 0, il = contour.length; i < il; i ++ ) { - bs = bevelSize; + vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); - // Back facing vertices + v( vert.x, vert.y, - z ); - for ( i = 0; i < vlen; i ++ ) { + } - vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; + // expand holes - if ( ! extrudeByPath ) { + for ( h = 0, hl = holes.length; h < hl; h ++ ) { - v( vert.x, vert.y, 0 ); + ahole = holes[ h ]; + oneHoleMovements = holesMovements[ h ]; - } else { + for ( i = 0, il = ahole.length; i < il; i ++ ) { - // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x ); + vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); - normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x ); - binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y ); + v( vert.x, vert.y, - z ); - position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal ); + } - v( position2.x, position2.y, position2.z ); + } - } + } - } + bs = bevelSize; - // Add stepped vertices... - // Including front facing vertices + // Back facing vertices - var s; + for ( i = 0; i < vlen; i ++ ) { - for ( s = 1; s <= steps; s ++ ) { + vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; - for ( i = 0; i < vlen; i ++ ) { + if ( ! extrudeByPath ) { - vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; + v( vert.x, vert.y, 0 ); - if ( ! extrudeByPath ) { + } else { - v( vert.x, vert.y, amount / steps * s ); + // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x ); - } else { + normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x ); + binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y ); - // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x ); + position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal ); - normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x ); - binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y ); + v( position2.x, position2.y, position2.z ); - position2.copy( extrudePts[ s ] ).add( normal ).add( binormal ); + } - v( position2.x, position2.y, position2.z ); + } - } + // Add stepped vertices... + // Including front facing vertices - } + var s; - } + for ( s = 1; s <= steps; s ++ ) { + for ( i = 0; i < vlen; i ++ ) { - // Add bevel segments planes + vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; - //for ( b = 1; b <= bevelSegments; b ++ ) { - for ( b = bevelSegments - 1; b >= 0; b -- ) { + if ( ! extrudeByPath ) { - t = b / bevelSegments; - z = bevelThickness * Math.cos ( t * Math.PI / 2 ); - bs = bevelSize * Math.sin( t * Math.PI / 2 ); + v( vert.x, vert.y, amount / steps * s ); - // contract shape + } else { - for ( i = 0, il = contour.length; i < il; i ++ ) { + // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x ); - vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); - v( vert.x, vert.y, amount + z ); + normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x ); + binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y ); - } + position2.copy( extrudePts[ s ] ).add( normal ).add( binormal ); - // expand holes + v( position2.x, position2.y, position2.z ); - for ( h = 0, hl = holes.length; h < hl; h ++ ) { + } - ahole = holes[ h ]; - oneHoleMovements = holesMovements[ h ]; + } - for ( i = 0, il = ahole.length; i < il; i ++ ) { + } - vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); - if ( ! extrudeByPath ) { + // Add bevel segments planes - v( vert.x, vert.y, amount + z ); + //for ( b = 1; b <= bevelSegments; b ++ ) { + for ( b = bevelSegments - 1; b >= 0; b -- ) { - } else { + t = b / bevelSegments; + z = bevelThickness * Math.cos ( t * Math.PI / 2 ); + bs = bevelSize * Math.sin( t * Math.PI / 2 ); - v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z ); + // 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 ); - } + } - } + // expand holes - /* Faces */ + for ( h = 0, hl = holes.length; h < hl; h ++ ) { - // Top and bottom faces + ahole = holes[ h ]; + oneHoleMovements = holesMovements[ h ]; - buildLidFaces(); + for ( i = 0, il = ahole.length; i < il; i ++ ) { - // Sides faces + vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); - buildSideFaces(); + if ( ! extrudeByPath ) { + v( vert.x, vert.y, amount + z ); - ///// Internal functions + } else { - function buildLidFaces() { + v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z ); - if ( bevelEnabled ) { + } - var layer = 0; // steps + 1 - var offset = vlen * layer; + } - // Bottom faces + } - for ( i = 0; i < flen; i ++ ) { + } - face = faces[ i ]; - f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset ); + /* Faces */ - } + // Top and bottom faces - layer = steps + bevelSegments * 2; - offset = vlen * layer; + buildLidFaces(); - // Top faces + // Sides faces - for ( i = 0; i < flen; i ++ ) { + buildSideFaces(); - face = faces[ i ]; - f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset ); - } + ///// Internal functions - } else { + function buildLidFaces() { - // Bottom faces + if ( bevelEnabled ) { - for ( i = 0; i < flen; i ++ ) { + var layer = 0; // steps + 1 + var offset = vlen * layer; - face = faces[ i ]; - f3( face[ 2 ], face[ 1 ], face[ 0 ] ); + // Bottom faces - } + for ( i = 0; i < flen; i ++ ) { - // Top faces + face = faces[ i ]; + f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset ); - for ( i = 0; i < flen; i ++ ) { + } - face = faces[ i ]; - f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps ); + layer = steps + bevelSegments * 2; + offset = vlen * layer; - } + // Top faces - } + for ( i = 0; i < flen; i ++ ) { - } + face = faces[ i ]; + f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset ); - // Create faces for the z-sides of the shape + } - function buildSideFaces() { + } else { - var layeroffset = 0; - sidewalls( contour, layeroffset ); - layeroffset += contour.length; + // Bottom faces - for ( h = 0, hl = holes.length; h < hl; h ++ ) { + for ( i = 0; i < flen; i ++ ) { - ahole = holes[ h ]; - sidewalls( ahole, layeroffset ); + face = faces[ i ]; + f3( face[ 2 ], face[ 1 ], face[ 0 ] ); - //, true - layeroffset += ahole.length; + } - } + // Top faces - } + for ( i = 0; i < flen; i ++ ) { - function sidewalls( contour, layeroffset ) { + face = faces[ i ]; + f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps ); - var j, k; - i = contour.length; + } - while ( -- i >= 0 ) { + } - j = i; - k = i - 1; - if ( k < 0 ) k = contour.length - 1; + } - //console.log('b', i,j, i-1, k,vertices.length); + // Create faces for the z-sides of the shape - var s = 0, sl = steps + bevelSegments * 2; + function buildSideFaces() { - for ( s = 0; s < sl; s ++ ) { + var layeroffset = 0; + sidewalls( contour, layeroffset ); + layeroffset += contour.length; - var slen1 = vlen * s; - var slen2 = vlen * ( s + 1 ); + for ( h = 0, hl = holes.length; h < hl; h ++ ) { - var a = layeroffset + j + slen1, - b = layeroffset + k + slen1, - c = layeroffset + k + slen2, - d = layeroffset + j + slen2; + ahole = holes[ h ]; + sidewalls( ahole, layeroffset ); - f4( a, b, c, d, contour, s, sl, j, k ); + //, true + layeroffset += ahole.length; - } + } - } + } - } + function sidewalls( contour, layeroffset ) { + var j, k; + i = contour.length; - function v( x, y, z ) { + while ( -- i >= 0 ) { - scope.vertices.push( new Vector3( x, y, z ) ); + j = i; + k = i - 1; + if ( k < 0 ) k = contour.length - 1; - } + //console.log('b', i,j, i-1, k,vertices.length); - function f3( a, b, c ) { + var s = 0, sl = steps + bevelSegments * 2; - a += shapesOffset; - b += shapesOffset; - c += shapesOffset; + for ( s = 0; s < sl; s ++ ) { - scope.faces.push( new Face3( a, b, c, null, null, 0 ) ); + var slen1 = vlen * s; + var slen2 = vlen * ( s + 1 ); - var uvs = uvgen.generateTopUV( scope, a, b, c ); + var a = layeroffset + j + slen1, + b = layeroffset + k + slen1, + c = layeroffset + k + slen2, + d = layeroffset + j + slen2; - scope.faceVertexUvs[ 0 ].push( uvs ); + f4( a, b, c, d, contour, s, sl, j, k ); - } + } - function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) { + } - 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 ); + function v( x, y, z ) { - scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] ); - scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] ); + scope.vertices.push( new Vector3( x, y, z ) ); - } + } - }; + function f3( a, b, c ) { - ExtrudeGeometry.WorldUVGenerator = { + a += shapesOffset; + b += shapesOffset; + c += shapesOffset; - generateTopUV: function ( geometry, indexA, indexB, indexC ) { + scope.faces.push( new Face3( a, b, c, null, null, 0 ) ); - var vertices = geometry.vertices; + var uvs = uvgen.generateTopUV( scope, a, b, c ); - var a = vertices[ indexA ]; - var b = vertices[ indexB ]; - var c = vertices[ indexC ]; + scope.faceVertexUvs[ 0 ].push( uvs ); - return [ - new Vector2( a.x, a.y ), - new Vector2( b.x, b.y ), - new Vector2( c.x, c.y ) - ]; + } - }, + function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) { - generateSideWallUV: function ( geometry, indexA, indexB, indexC, indexD ) { + a += shapesOffset; + b += shapesOffset; + c += shapesOffset; + d += shapesOffset; - var vertices = geometry.vertices; + scope.faces.push( new Face3( a, b, d, null, null, 1 ) ); + scope.faces.push( new Face3( b, c, d, null, null, 1 ) ); - var a = vertices[ indexA ]; - var b = vertices[ indexB ]; - var c = vertices[ indexC ]; - var d = vertices[ indexD ]; + var uvs = uvgen.generateSideWallUV( scope, a, b, c, d ); - if ( Math.abs( a.y - b.y ) < 0.01 ) { + scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] ); + scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] ); - 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 ) - ]; + } - } else { + }; - 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 = { - } + generateTopUV: function ( geometry, indexA, indexB, indexC ) { - } - }; + var vertices = geometry.vertices; - /** - * @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 - * - * } - **/ + var a = vertices[ indexA ]; + var b = vertices[ indexB ]; + var c = vertices[ indexC ]; - function ShapeGeometry( shapes, options ) { + return [ + new Vector2( a.x, a.y ), + new Vector2( b.x, b.y ), + new Vector2( c.x, c.y ) + ]; - Geometry.call( this ); + }, - this.type = 'ShapeGeometry'; + generateSideWallUV: function ( geometry, indexA, indexB, indexC, indexD ) { - if ( Array.isArray( shapes ) === false ) shapes = [ shapes ]; + var vertices = geometry.vertices; - this.addShapeList( shapes, options ); + var a = vertices[ indexA ]; + var b = vertices[ indexB ]; + var c = vertices[ indexC ]; + var d = vertices[ indexD ]; - this.computeFaceNormals(); + if ( Math.abs( a.y - b.y ) < 0.01 ) { - }; + 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 ) + ]; - ShapeGeometry.prototype = Object.create( Geometry.prototype ); - ShapeGeometry.prototype.constructor = ShapeGeometry; + } else { - /** - * Add an array of shapes to THREE.ShapeGeometry. - */ - ShapeGeometry.prototype.addShapeList = function ( shapes, 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 ) + ]; - for ( var i = 0, l = shapes.length; i < l; i ++ ) { + } - this.addShape( shapes[ i ], options ); + } + }; - } + /** + * @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 + * + * } + **/ - return this; + function ShapeGeometry( shapes, options ) { - }; + Geometry.call( this ); - /** - * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry. - */ - ShapeGeometry.prototype.addShape = function ( shape, options ) { + this.type = 'ShapeGeometry'; - if ( options === undefined ) options = {}; - var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12; + if ( Array.isArray( shapes ) === false ) shapes = [ shapes ]; - var material = options.material; - var uvgen = options.UVGenerator === undefined ? ExtrudeGeometry.WorldUVGenerator : options.UVGenerator; + this.addShapeList( shapes, options ); - // + this.computeFaceNormals(); - var i, l, hole; + }; - var shapesOffset = this.vertices.length; - var shapePoints = shape.extractPoints( curveSegments ); + ShapeGeometry.prototype = Object.create( Geometry.prototype ); + ShapeGeometry.prototype.constructor = ShapeGeometry; - var vertices = shapePoints.shape; - var holes = shapePoints.holes; + /** + * Add an array of shapes to THREE.ShapeGeometry. + */ + ShapeGeometry.prototype.addShapeList = function ( shapes, options ) { - var reverse = ! exports.ShapeUtils.isClockWise( vertices ); + for ( var i = 0, l = shapes.length; i < l; i ++ ) { - if ( reverse ) { + this.addShape( shapes[ i ], options ); - vertices = vertices.reverse(); + } - // Maybe we should also check if holes are in the opposite direction, just to be safe... + return this; - for ( i = 0, l = holes.length; i < l; i ++ ) { + }; - hole = holes[ i ]; + /** + * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry. + */ + ShapeGeometry.prototype.addShape = function ( shape, options ) { - if ( exports.ShapeUtils.isClockWise( hole ) ) { + if ( options === undefined ) options = {}; + var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12; - holes[ i ] = hole.reverse(); + var material = options.material; + var uvgen = options.UVGenerator === undefined ? ExtrudeGeometry.WorldUVGenerator : options.UVGenerator; - } + // - } + var i, l, hole; - reverse = false; + var shapesOffset = this.vertices.length; + var shapePoints = shape.extractPoints( curveSegments ); - } + var vertices = shapePoints.shape; + var holes = shapePoints.holes; - var faces = exports.ShapeUtils.triangulateShape( vertices, holes ); + var reverse = ! exports.ShapeUtils.isClockWise( vertices ); - // Vertices + if ( reverse ) { - for ( i = 0, l = holes.length; i < l; i ++ ) { + vertices = vertices.reverse(); - hole = holes[ i ]; - vertices = vertices.concat( hole ); + // Maybe we should also check if holes are in the opposite direction, just to be safe... - } + for ( i = 0, l = holes.length; i < l; i ++ ) { - // + hole = holes[ i ]; - var vert, vlen = vertices.length; - var face, flen = faces.length; + if ( exports.ShapeUtils.isClockWise( hole ) ) { - for ( i = 0; i < vlen; i ++ ) { + holes[ i ] = hole.reverse(); - vert = vertices[ i ]; + } - this.vertices.push( new Vector3( vert.x, vert.y, 0 ) ); + } - } + reverse = false; - for ( i = 0; i < flen; i ++ ) { + } - face = faces[ i ]; + var faces = exports.ShapeUtils.triangulateShape( vertices, holes ); - var a = face[ 0 ] + shapesOffset; - var b = face[ 1 ] + shapesOffset; - var c = face[ 2 ] + shapesOffset; + // Vertices - this.faces.push( new Face3( a, b, c, null, null, material ) ); - this.faceVertexUvs[ 0 ].push( uvgen.generateTopUV( this, a, b, c ) ); + for ( i = 0, l = holes.length; i < l; i ++ ) { - } + hole = holes[ i ]; + vertices = vertices.concat( hole ); - }; + } - /** - * @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. + var vert, vlen = vertices.length; + var face, flen = faces.length; - function Shape() { + for ( i = 0; i < vlen; i ++ ) { - Path.apply( this, arguments ); + vert = vertices[ i ]; - this.holes = []; + this.vertices.push( new Vector3( vert.x, vert.y, 0 ) ); - }; + } - Shape.prototype = Object.assign( Object.create( PathPrototype ), { + for ( i = 0; i < flen; i ++ ) { - constructor: Shape, + face = faces[ i ]; - // Convenience method to return ExtrudeGeometry + var a = face[ 0 ] + shapesOffset; + var b = face[ 1 ] + shapesOffset; + var c = face[ 2 ] + shapesOffset; - extrude: function ( options ) { + this.faces.push( new Face3( a, b, c, null, null, material ) ); + this.faceVertexUvs[ 0 ].push( uvgen.generateTopUV( this, a, b, c ) ); - return new ExtrudeGeometry( this, options ); + } - }, + }; - // Convenience method to return ShapeGeometry + /** + * @author zz85 / http://www.lab4games.net/zz85/blog + * Defines a 2d shape plane using paths. + **/ - makeGeometry: function ( options ) { + // 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. - return new ShapeGeometry( this, options ); + function Shape() { - }, + Path.apply( this, arguments ); - getPointsHoles: function ( divisions ) { + this.holes = []; - var holesPts = []; + }; - for ( var i = 0, l = this.holes.length; i < l; i ++ ) { + Shape.prototype = Object.assign( Object.create( PathPrototype ), { - holesPts[ i ] = this.holes[ i ].getPoints( divisions ); + constructor: Shape, - } + // Convenience method to return ExtrudeGeometry - return holesPts; + extrude: function ( options ) { - }, + return new ExtrudeGeometry( this, options ); - // Get points of shape and holes (keypoints based on segments parameter) + }, - extractAllPoints: function ( divisions ) { + // Convenience method to return ShapeGeometry - return { + makeGeometry: function ( options ) { - shape: this.getPoints( divisions ), - holes: this.getPointsHoles( divisions ) + return new ShapeGeometry( this, options ); - }; + }, - }, + getPointsHoles: function ( divisions ) { - extractPoints: function ( divisions ) { + var holesPts = []; - return this.extractAllPoints( divisions ); + for ( var i = 0, l = this.holes.length; i < l; i ++ ) { - } + holesPts[ i ] = this.holes[ i ].getPoints( divisions ); - } ); + } - /** - * @author zz85 / http://www.lab4games.net/zz85/blog - * Creates free form 2d path using series of points, lines or curves. - * - **/ + return holesPts; - function Path( points ) { + }, - CurvePath.call( this ); - this.currentPoint = new Vector2(); + // Get points of shape and holes (keypoints based on segments parameter) - if ( points ) { + extractAllPoints: function ( divisions ) { - this.fromPoints( points ); + return { - } + shape: this.getPoints( divisions ), + holes: this.getPointsHoles( divisions ) - }; + }; - Path.prototype = PathPrototype; - PathPrototype.constructor = Path; + }, + extractPoints: function ( divisions ) { - // minimal class for proxing functions to Path. Replaces old "extractSubpaths()" - function ShapePath() { - this.subPaths = []; - this.currentPath = null; - } + return this.extractAllPoints( divisions ); - 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 ); - }, + } - toShapes: function ( isCCW, noHoles ) { + } ); - function toShapesNoHoles( inSubpaths ) { + /** + * @author zz85 / http://www.lab4games.net/zz85/blog + * Creates free form 2d path using series of points, lines or curves. + * + **/ - var shapes = []; + function Path( points ) { - for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) { + CurvePath.call( this ); + this.currentPoint = new Vector2(); - var tmpPath = inSubpaths[ i ]; + if ( points ) { - var tmpShape = new Shape(); - tmpShape.curves = tmpPath.curves; + this.fromPoints( points ); - shapes.push( tmpShape ); + } - } + }; - return shapes; + Path.prototype = PathPrototype; + PathPrototype.constructor = Path; - } - function isPointInsidePolygon( inPt, inPolygon ) { + // minimal class for proxing functions to Path. Replaces old "extractSubpaths()" + function ShapePath() { + this.subPaths = []; + this.currentPath = null; + } - var polyLen = inPolygon.length; + 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 ); + }, - // 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 ++ ) { + toShapes: function ( isCCW, noHoles ) { - var edgeLowPt = inPolygon[ p ]; - var edgeHighPt = inPolygon[ q ]; + function toShapesNoHoles( inSubpaths ) { - var edgeDx = edgeHighPt.x - edgeLowPt.x; - var edgeDy = edgeHighPt.y - edgeLowPt.y; + var shapes = []; - if ( Math.abs( edgeDy ) > Number.EPSILON ) { + for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) { - // not parallel - if ( edgeDy < 0 ) { + var tmpPath = inSubpaths[ i ]; - edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx; - edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy; + var tmpShape = new Shape(); + tmpShape.curves = tmpPath.curves; - } - if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue; + shapes.push( tmpShape ); - if ( inPt.y === edgeLowPt.y ) { + } - if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ? - // continue; // no intersection or edgeLowPt => doesn't count !!! + return shapes; - } 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 + function isPointInsidePolygon( inPt, inPolygon ) { - } + var polyLen = inPolygon.length; - } else { + // 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 ++ ) { - // 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 edgeLowPt = inPolygon[ p ]; + var edgeHighPt = inPolygon[ q ]; - } + var edgeDx = edgeHighPt.x - edgeLowPt.x; + var edgeDy = edgeHighPt.y - edgeLowPt.y; - } + if ( Math.abs( edgeDy ) > Number.EPSILON ) { - return inside; + // not parallel + if ( edgeDy < 0 ) { - } + edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx; + edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy; - var isClockWise = exports.ShapeUtils.isClockWise; + } + if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue; - var subPaths = this.subPaths; - if ( subPaths.length === 0 ) return []; + if ( inPt.y === edgeLowPt.y ) { - if ( noHoles === true ) return toShapesNoHoles( subPaths ); + if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ? + // continue; // no intersection or edgeLowPt => doesn't count !!! + } else { - var solid, tmpPath, tmpShape, 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 - if ( subPaths.length === 1 ) { + } - tmpPath = subPaths[ 0 ]; - tmpShape = new Shape(); - tmpShape.curves = tmpPath.curves; - shapes.push( tmpShape ); - return shapes; + } else { - } + // 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 holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() ); - holesFirst = isCCW ? ! holesFirst : holesFirst; + } - // console.log("Holes first", holesFirst); + } - var betterShapeHoles = []; - var newShapes = []; - var newShapeHoles = []; - var mainIdx = 0; - var tmpPoints; + return inside; - newShapes[ mainIdx ] = undefined; - newShapeHoles[ mainIdx ] = []; + } - for ( var i = 0, l = subPaths.length; i < l; i ++ ) { + var isClockWise = exports.ShapeUtils.isClockWise; - tmpPath = subPaths[ i ]; - tmpPoints = tmpPath.getPoints(); - solid = isClockWise( tmpPoints ); - solid = isCCW ? ! solid : solid; + var subPaths = this.subPaths; + if ( subPaths.length === 0 ) return []; - if ( solid ) { + if ( noHoles === true ) return toShapesNoHoles( subPaths ); - if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++; - newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints }; - newShapes[ mainIdx ].s.curves = tmpPath.curves; + var solid, tmpPath, tmpShape, shapes = []; - if ( holesFirst ) mainIdx ++; - newShapeHoles[ mainIdx ] = []; + if ( subPaths.length === 1 ) { - //console.log('cw', i); + tmpPath = subPaths[ 0 ]; + tmpShape = new Shape(); + tmpShape.curves = tmpPath.curves; + shapes.push( tmpShape ); + return shapes; - } else { + } - newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } ); + var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() ); + holesFirst = isCCW ? ! holesFirst : holesFirst; - //console.log('ccw', i); + // console.log("Holes first", holesFirst); - } + var betterShapeHoles = []; + var newShapes = []; + var newShapeHoles = []; + var mainIdx = 0; + var tmpPoints; - } + newShapes[ mainIdx ] = undefined; + newShapeHoles[ mainIdx ] = []; - // only Holes? -> probably all Shapes with wrong orientation - if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths ); + for ( var i = 0, l = subPaths.length; i < l; i ++ ) { + tmpPath = subPaths[ i ]; + tmpPoints = tmpPath.getPoints(); + solid = isClockWise( tmpPoints ); + solid = isCCW ? ! solid : solid; - if ( newShapes.length > 1 ) { + if ( solid ) { - var ambiguous = false; - var toChange = []; + if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++; - for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) { + newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints }; + newShapes[ mainIdx ].s.curves = tmpPath.curves; - betterShapeHoles[ sIdx ] = []; + if ( holesFirst ) mainIdx ++; + newShapeHoles[ mainIdx ] = []; - } + //console.log('cw', i); - for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) { + } else { - var sho = newShapeHoles[ sIdx ]; + newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } ); - for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) { + //console.log('ccw', i); - var ho = sho[ hIdx ]; - var hole_unassigned = true; + } - for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) { + } - if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) { + // only Holes? -> probably all Shapes with wrong orientation + if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths ); - if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } ); - if ( hole_unassigned ) { - hole_unassigned = false; - betterShapeHoles[ s2Idx ].push( ho ); + if ( newShapes.length > 1 ) { - } else { + var ambiguous = false; + var toChange = []; - ambiguous = true; + for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) { - } + betterShapeHoles[ sIdx ] = []; - } + } - } - if ( hole_unassigned ) { + for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) { - betterShapeHoles[ sIdx ].push( ho ); + var sho = newShapeHoles[ sIdx ]; - } + for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) { - } + var ho = sho[ hIdx ]; + var hole_unassigned = true; - } - // console.log("ambiguous: ", ambiguous); - if ( toChange.length > 0 ) { + for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) { - // console.log("to change: ", toChange); - if ( ! ambiguous ) newShapeHoles = betterShapeHoles; + 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 ); - var tmpHoles; + } else { - for ( var i = 0, il = newShapes.length; i < il; i ++ ) { + ambiguous = true; - tmpShape = newShapes[ i ].s; - shapes.push( tmpShape ); - tmpHoles = newShapeHoles[ i ]; + } - for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) { + } - tmpShape.holes.push( tmpHoles[ j ].h ); + } + if ( hole_unassigned ) { - } + betterShapeHoles[ sIdx ].push( ho ); - } + } - //console.log("shape", shapes); + } - return shapes; + } + // console.log("ambiguous: ", ambiguous); + if ( toChange.length > 0 ) { - } - } + // console.log("to change: ", toChange); + if ( ! ambiguous ) newShapeHoles = betterShapeHoles; - /** - * @author zz85 / http://www.lab4games.net/zz85/blog - * @author mrdoob / http://mrdoob.com/ - */ + } - function Font( data ) { + } - this.data = data; + var tmpHoles; - }; + for ( var i = 0, il = newShapes.length; i < il; i ++ ) { - Object.assign( Font.prototype, { + tmpShape = newShapes[ i ].s; + shapes.push( tmpShape ); + tmpHoles = newShapeHoles[ i ]; - isFont: true, + for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) { - generateShapes: function ( text, size, divisions ) { + tmpShape.holes.push( tmpHoles[ j ].h ); - function createPaths( text ) { + } - var chars = String( text ).split( '' ); - var scale = size / data.resolution; - var offset = 0; + } - var paths = []; + //console.log("shape", shapes); - for ( var i = 0; i < chars.length; i ++ ) { + return shapes; - var ret = createPath( chars[ i ], scale, offset ); - offset += ret.offset; + } + } - paths.push( ret.path ); + /** + * @author zz85 / http://www.lab4games.net/zz85/blog + * @author mrdoob / http://mrdoob.com/ + */ - } + function Font( data ) { - return paths; + this.data = data; - } + }; - function createPath( c, scale, offset ) { + Object.assign( Font.prototype, { - var glyph = data.glyphs[ c ] || data.glyphs[ '?' ]; + isFont: true, - if ( ! glyph ) return; + generateShapes: function ( text, size, divisions ) { - var path = new ShapePath(); + function createPaths( text ) { - var pts = [], b2 = exports.ShapeUtils.b2, b3 = exports.ShapeUtils.b3; - var x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2, laste; + var chars = String( text ).split( '' ); + var scale = size / data.resolution; + var offset = 0; - if ( glyph.o ) { + var paths = []; - var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) ); + for ( var i = 0; i < chars.length; i ++ ) { - for ( var i = 0, l = outline.length; i < l; ) { + var ret = createPath( chars[ i ], scale, offset ); + offset += ret.offset; - var action = outline[ i ++ ]; + paths.push( ret.path ); - switch ( action ) { + } - case 'm': // moveTo + return paths; - x = outline[ i ++ ] * scale + offset; - y = outline[ i ++ ] * scale; + } - path.moveTo( x, y ); + function createPath( c, scale, offset ) { - break; + var glyph = data.glyphs[ c ] || data.glyphs[ '?' ]; - case 'l': // lineTo + if ( ! glyph ) return; - x = outline[ i ++ ] * scale + offset; - y = outline[ i ++ ] * scale; + var path = new ShapePath(); - path.lineTo( x, y ); + var pts = [], b2 = exports.ShapeUtils.b2, b3 = exports.ShapeUtils.b3; + var x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2, laste; - break; + if ( glyph.o ) { - case 'q': // quadraticCurveTo + var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) ); - cpx = outline[ i ++ ] * scale + offset; - cpy = outline[ i ++ ] * scale; - cpx1 = outline[ i ++ ] * scale + offset; - cpy1 = outline[ i ++ ] * scale; + for ( var i = 0, l = outline.length; i < l; ) { - path.quadraticCurveTo( cpx1, cpy1, cpx, cpy ); + var action = outline[ i ++ ]; - laste = pts[ pts.length - 1 ]; + switch ( action ) { - if ( laste ) { + case 'm': // moveTo - cpx0 = laste.x; - cpy0 = laste.y; + x = outline[ i ++ ] * scale + offset; + y = outline[ i ++ ] * scale; - for ( var i2 = 1; i2 <= divisions; i2 ++ ) { + path.moveTo( x, y ); - var t = i2 / divisions; - b2( t, cpx0, cpx1, cpx ); - b2( t, cpy0, cpy1, cpy ); + break; - } + case 'l': // lineTo - } + x = outline[ i ++ ] * scale + offset; + y = outline[ i ++ ] * scale; - break; + path.lineTo( x, y ); - case 'b': // bezierCurveTo + break; - 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; + case 'q': // quadraticCurveTo - path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy ); + cpx = outline[ i ++ ] * scale + offset; + cpy = outline[ i ++ ] * scale; + cpx1 = outline[ i ++ ] * scale + offset; + cpy1 = outline[ i ++ ] * scale; - laste = pts[ pts.length - 1 ]; + path.quadraticCurveTo( cpx1, cpy1, cpx, cpy ); - if ( laste ) { + laste = pts[ pts.length - 1 ]; - cpx0 = laste.x; - cpy0 = laste.y; + if ( laste ) { - for ( var i2 = 1; i2 <= divisions; i2 ++ ) { + cpx0 = laste.x; + cpy0 = laste.y; - var t = i2 / divisions; - b3( t, cpx0, cpx1, cpx2, cpx ); - b3( t, cpy0, cpy1, cpy2, cpy ); + for ( var i2 = 1; i2 <= divisions; i2 ++ ) { - } + var t = i2 / divisions; + b2( t, cpx0, cpx1, cpx ); + b2( t, cpy0, cpy1, cpy ); - } + } - break; + } - } + break; - } + 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; - return { offset: glyph.ha * scale, path: path }; + path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy ); - } + laste = pts[ pts.length - 1 ]; - // + if ( laste ) { - if ( size === undefined ) size = 100; - if ( divisions === undefined ) divisions = 4; + cpx0 = laste.x; + cpy0 = laste.y; - var data = this.data; + for ( var i2 = 1; i2 <= divisions; i2 ++ ) { - var paths = createPaths( text ); - var shapes = []; + var t = i2 / divisions; + b3( t, cpx0, cpx1, cpx2, cpx ); + b3( t, cpy0, cpy1, cpy2, cpy ); - for ( var p = 0, pl = paths.length; p < pl; p ++ ) { + } - Array.prototype.push.apply( shapes, paths[ p ].toShapes() ); + } - } + break; - return shapes; + } - } + } - } ); + } - /** - * @author mrdoob / http://mrdoob.com/ - */ + return { offset: glyph.ha * scale, path: path }; - function FontLoader( manager ) { + } - this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; + // - }; + if ( size === undefined ) size = 100; + if ( divisions === undefined ) divisions = 4; - Object.assign( FontLoader.prototype, { + var data = this.data; - load: function ( url, onLoad, onProgress, onError ) { + var paths = createPaths( text ); + var shapes = []; - var scope = this; + for ( var p = 0, pl = paths.length; p < pl; p ++ ) { - var loader = new XHRLoader( this.manager ); - loader.load( url, function ( text ) { + Array.prototype.push.apply( shapes, paths[ p ].toShapes() ); - var json; + } - try { + return shapes; - json = JSON.parse( text ); + } - } 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 ) ); + /** + * @author mrdoob / http://mrdoob.com/ + */ - } + function FontLoader( manager ) { - var font = scope.parse( json ); + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; - if ( onLoad ) onLoad( font ); + }; - }, onProgress, onError ); + Object.assign( FontLoader.prototype, { - }, + load: function ( url, onLoad, onProgress, onError ) { - parse: function ( json ) { + var scope = this; - return new Font( json ); + var loader = new XHRLoader( this.manager ); + loader.load( url, function ( text ) { - } + var json; - } ); + try { - var context; + json = JSON.parse( text ); - function getAudioContext() { + } catch ( e ) { - if ( context === undefined ) { + console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' ); + json = JSON.parse( text.substring( 65, text.length - 2 ) ); - context = new ( window.AudioContext || window.webkitAudioContext )(); + } - } + var font = scope.parse( json ); - return context; + if ( onLoad ) onLoad( font ); - } + }, onProgress, onError ); - /** - * @author Reece Aaron Lecrivain / http://reecenotes.com/ - */ + }, - function AudioLoader( manager ) { + parse: function ( json ) { - this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; + return new Font( json ); - }; + } - Object.assign( AudioLoader.prototype, { + } ); - load: function ( url, onLoad, onProgress, onError ) { + var context; - var loader = new XHRLoader( this.manager ); - loader.setResponseType( 'arraybuffer' ); - loader.load( url, function ( buffer ) { + function getAudioContext() { - var context = getAudioContext(); + if ( context === undefined ) { - context.decodeAudioData( buffer, function ( audioBuffer ) { + context = new ( window.AudioContext || window.webkitAudioContext )(); - onLoad( audioBuffer ); + } - } ); + return context; - }, onProgress, onError ); + } - } + /** + * @author Reece Aaron Lecrivain / http://reecenotes.com/ + */ - } ); + function AudioLoader( manager ) { - /** - * @author mrdoob / http://mrdoob.com/ - */ + this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager; - function StereoCamera() { + }; - this.type = 'StereoCamera'; + Object.assign( AudioLoader.prototype, { - this.aspect = 1; + load: function ( url, onLoad, onProgress, onError ) { - this.cameraL = new PerspectiveCamera(); - this.cameraL.layers.enable( 1 ); - this.cameraL.matrixAutoUpdate = false; + var loader = new XHRLoader( this.manager ); + loader.setResponseType( 'arraybuffer' ); + loader.load( url, function ( buffer ) { - this.cameraR = new PerspectiveCamera(); - this.cameraR.layers.enable( 2 ); - this.cameraR.matrixAutoUpdate = false; + var context = getAudioContext(); - }; + context.decodeAudioData( buffer, function ( audioBuffer ) { - Object.assign( StereoCamera.prototype, { + onLoad( audioBuffer ); - update: ( function () { + } ); - var focus, fov, aspect, near, far; + }, onProgress, onError ); - var eyeRight = new Matrix4(); - var eyeLeft = new Matrix4(); + } - return function update( camera ) { + } ); - var needsUpdate = focus !== camera.focus || fov !== camera.fov || - aspect !== camera.aspect * this.aspect || near !== camera.near || - far !== camera.far; + /** + * @author mrdoob / http://mrdoob.com/ + */ - if ( needsUpdate ) { + function StereoCamera() { - focus = camera.focus; - fov = camera.fov; - aspect = camera.aspect * this.aspect; - near = camera.near; - far = camera.far; + this.type = 'StereoCamera'; - // Off-axis stereoscopic effect based on - // http://paulbourke.net/stereographics/stereorender/ + this.aspect = 1; - 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.cameraL = new PerspectiveCamera(); + this.cameraL.layers.enable( 1 ); + this.cameraL.matrixAutoUpdate = false; - // translate xOffset + this.cameraR = new PerspectiveCamera(); + this.cameraR.layers.enable( 2 ); + this.cameraR.matrixAutoUpdate = false; - eyeLeft.elements[ 12 ] = - eyeSep; - eyeRight.elements[ 12 ] = eyeSep; + }; - // for left eye + Object.assign( StereoCamera.prototype, { - xmin = - ymax * aspect + eyeSepOnProjection; - xmax = ymax * aspect + eyeSepOnProjection; + update: ( function () { - projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin ); - projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin ); + var focus, fov, aspect, near, far; - this.cameraL.projectionMatrix.copy( projectionMatrix ); + var eyeRight = new Matrix4(); + var eyeLeft = new Matrix4(); - // for right eye + return function update( camera ) { - xmin = - ymax * aspect - eyeSepOnProjection; - xmax = ymax * aspect - eyeSepOnProjection; + var needsUpdate = focus !== camera.focus || fov !== camera.fov || + aspect !== camera.aspect * this.aspect || near !== camera.near || + far !== camera.far; - projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin ); - projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin ); + if ( needsUpdate ) { - this.cameraR.projectionMatrix.copy( projectionMatrix ); + 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/ - this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( eyeLeft ); - this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( eyeRight ); + 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; - }; + // translate xOffset - } )() + eyeLeft.elements[ 12 ] = - eyeSep; + eyeRight.elements[ 12 ] = eyeSep; - } ); + // for left eye - /** - * Camera for rendering cube maps - * - renders scene into axis-aligned cube - * - * @author alteredq / http://alteredqualia.com/ - */ + xmin = - ymax * aspect + eyeSepOnProjection; + xmax = ymax * aspect + eyeSepOnProjection; - function CubeCamera( near, far, cubeResolution ) { + projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin ); + projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin ); - Object3D.call( this ); + this.cameraL.projectionMatrix.copy( projectionMatrix ); - this.type = 'CubeCamera'; + // for right eye - var fov = 90, aspect = 1; + xmin = - ymax * aspect - eyeSepOnProjection; + xmax = ymax * aspect - eyeSepOnProjection; - var cameraPX = new PerspectiveCamera( fov, aspect, near, far ); - cameraPX.up.set( 0, - 1, 0 ); - cameraPX.lookAt( new Vector3( 1, 0, 0 ) ); - this.add( cameraPX ); + projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin ); + projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin ); - var cameraNX = new PerspectiveCamera( fov, aspect, near, far ); - cameraNX.up.set( 0, - 1, 0 ); - cameraNX.lookAt( new Vector3( - 1, 0, 0 ) ); - this.add( cameraNX ); + this.cameraR.projectionMatrix.copy( projectionMatrix ); - var cameraPY = new PerspectiveCamera( fov, aspect, near, far ); - cameraPY.up.set( 0, 0, 1 ); - cameraPY.lookAt( new Vector3( 0, 1, 0 ) ); - this.add( cameraPY ); + } - var cameraNY = new PerspectiveCamera( fov, aspect, near, far ); - cameraNY.up.set( 0, 0, - 1 ); - cameraNY.lookAt( new Vector3( 0, - 1, 0 ) ); - this.add( cameraNY ); + this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( eyeLeft ); + this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( eyeRight ); - 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 }; + } ); - this.renderTarget = new WebGLRenderTargetCube( cubeResolution, cubeResolution, options ); + /** + * Camera for rendering cube maps + * - renders scene into axis-aligned cube + * + * @author alteredq / http://alteredqualia.com/ + */ - this.updateCubeMap = function ( renderer, scene ) { + function CubeCamera( near, far, cubeResolution ) { - if ( this.parent === null ) this.updateMatrixWorld(); + Object3D.call( this ); - var renderTarget = this.renderTarget; - var generateMipmaps = renderTarget.texture.generateMipmaps; + this.type = 'CubeCamera'; - renderTarget.texture.generateMipmaps = false; + var fov = 90, aspect = 1; - renderTarget.activeCubeFace = 0; - renderer.render( scene, cameraPX, 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 = 1; - renderer.render( scene, cameraNX, 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.activeCubeFace = 2; - renderer.render( scene, cameraPY, renderTarget ); + 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 = 3; - renderer.render( scene, cameraNY, 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 ); - renderTarget.activeCubeFace = 4; - renderer.render( scene, cameraPZ, renderTarget ); + var cameraPZ = new PerspectiveCamera( fov, aspect, near, far ); + cameraPZ.up.set( 0, - 1, 0 ); + cameraPZ.lookAt( new Vector3( 0, 0, 1 ) ); + this.add( cameraPZ ); - renderTarget.texture.generateMipmaps = generateMipmaps; + var cameraNZ = new PerspectiveCamera( fov, aspect, near, far ); + cameraNZ.up.set( 0, - 1, 0 ); + cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) ); + this.add( cameraNZ ); - renderTarget.activeCubeFace = 5; - renderer.render( scene, cameraNZ, renderTarget ); + var options = { format: RGBFormat, magFilter: LinearFilter, minFilter: LinearFilter }; - renderer.setRenderTarget( null ); + this.renderTarget = new WebGLRenderTargetCube( cubeResolution, cubeResolution, options ); - }; + this.updateCubeMap = function ( renderer, scene ) { - }; + if ( this.parent === null ) this.updateMatrixWorld(); - CubeCamera.prototype = Object.create( Object3D.prototype ); - CubeCamera.prototype.constructor = CubeCamera; + var renderTarget = this.renderTarget; + var generateMipmaps = renderTarget.texture.generateMipmaps; - function AudioListener() { + renderTarget.texture.generateMipmaps = false; - Object3D.call( this ); + renderTarget.activeCubeFace = 0; + renderer.render( scene, cameraPX, renderTarget ); - this.type = 'AudioListener'; + renderTarget.activeCubeFace = 1; + renderer.render( scene, cameraNX, renderTarget ); - this.context = getAudioContext(); + renderTarget.activeCubeFace = 2; + renderer.render( scene, cameraPY, renderTarget ); - this.gain = this.context.createGain(); - this.gain.connect( this.context.destination ); + renderTarget.activeCubeFace = 3; + renderer.render( scene, cameraNY, renderTarget ); - this.filter = null; + renderTarget.activeCubeFace = 4; + renderer.render( scene, cameraPZ, renderTarget ); - } + renderTarget.texture.generateMipmaps = generateMipmaps; - AudioListener.prototype = Object.assign( Object.create( Object3D.prototype ), { + renderTarget.activeCubeFace = 5; + renderer.render( scene, cameraNZ, renderTarget ); - constructor: AudioListener, + renderer.setRenderTarget( null ); - getInput: function () { + }; - return this.gain; + }; - }, + CubeCamera.prototype = Object.create( Object3D.prototype ); + CubeCamera.prototype.constructor = CubeCamera; - removeFilter: function ( ) { + function AudioListener() { - if ( this.filter !== null ) { + Object3D.call( this ); - this.gain.disconnect( this.filter ); - this.filter.disconnect( this.context.destination ); - this.gain.connect( this.context.destination ); - this.filter = null; + this.type = 'AudioListener'; - } + this.context = getAudioContext(); - }, + this.gain = this.context.createGain(); + this.gain.connect( this.context.destination ); - getFilter: function () { + this.filter = null; - return this.filter; + } - }, + AudioListener.prototype = Object.assign( Object.create( Object3D.prototype ), { - setFilter: function ( value ) { + constructor: AudioListener, - if ( this.filter !== null ) { + getInput: function () { - this.gain.disconnect( this.filter ); - this.filter.disconnect( this.context.destination ); + return this.gain; - } else { + }, - this.gain.disconnect( this.context.destination ); + removeFilter: function ( ) { - } + if ( this.filter !== null ) { - this.filter = value; - this.gain.connect( this.filter ); - this.filter.connect( this.context.destination ); + this.gain.disconnect( this.filter ); + this.filter.disconnect( this.context.destination ); + this.gain.connect( this.context.destination ); + this.filter = null; - }, + } - getMasterVolume: function () { + }, - return this.gain.gain.value; + getFilter: function () { - }, + return this.filter; - setMasterVolume: function ( value ) { + }, - this.gain.gain.value = value; + setFilter: function ( value ) { - }, + if ( this.filter !== null ) { - updateMatrixWorld: ( function () { + this.gain.disconnect( this.filter ); + this.filter.disconnect( this.context.destination ); - var position = new Vector3(); - var quaternion = new Quaternion(); - var scale = new Vector3(); + } else { - var orientation = new Vector3(); + this.gain.disconnect( this.context.destination ); - return function updateMatrixWorld( force ) { + } - Object3D.prototype.updateMatrixWorld.call( this, force ); + this.filter = value; + this.gain.connect( this.filter ); + this.filter.connect( this.context.destination ); - var listener = this.context.listener; - var up = this.up; + }, - this.matrixWorld.decompose( position, quaternion, scale ); + getMasterVolume: function () { - orientation.set( 0, 0, - 1 ).applyQuaternion( quaternion ); + return this.gain.gain.value; - listener.setPosition( position.x, position.y, position.z ); - listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z ); + }, - }; + setMasterVolume: function ( value ) { - } )() + this.gain.gain.value = value; - } ); + }, - function Audio( listener ) { + updateMatrixWorld: ( function () { - Object3D.call( this ); + var position = new Vector3(); + var quaternion = new Quaternion(); + var scale = new Vector3(); - this.type = 'Audio'; + var orientation = new Vector3(); - this.context = listener.context; - this.source = this.context.createBufferSource(); - this.source.onended = this.onEnded.bind( this ); + return function updateMatrixWorld( force ) { - this.gain = this.context.createGain(); - this.gain.connect( listener.getInput() ); + Object3D.prototype.updateMatrixWorld.call( this, force ); - this.autoplay = false; + var listener = this.context.listener; + var up = this.up; - this.startTime = 0; - this.playbackRate = 1; - this.isPlaying = false; - this.hasPlaybackControl = true; - this.sourceType = 'empty'; + this.matrixWorld.decompose( position, quaternion, scale ); - this.filters = []; + orientation.set( 0, 0, - 1 ).applyQuaternion( quaternion ); - } + listener.setPosition( position.x, position.y, position.z ); + listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z ); - Audio.prototype = Object.assign( Object.create( Object3D.prototype ), { + }; - constructor: Audio, + } )() - getOutput: function () { + } ); - return this.gain; + function Audio( listener ) { - }, + Object3D.call( this ); - setNodeSource: function ( audioNode ) { + this.type = 'Audio'; - this.hasPlaybackControl = false; - this.sourceType = 'audioNode'; - this.source = audioNode; - this.connect(); + this.context = listener.context; + this.source = this.context.createBufferSource(); + this.source.onended = this.onEnded.bind( this ); - return this; + this.gain = this.context.createGain(); + this.gain.connect( listener.getInput() ); - }, + this.autoplay = false; - setBuffer: function ( audioBuffer ) { + this.startTime = 0; + this.playbackRate = 1; + this.isPlaying = false; + this.hasPlaybackControl = true; + this.sourceType = 'empty'; - this.source.buffer = audioBuffer; - this.sourceType = 'buffer'; + this.filters = []; - if ( this.autoplay ) this.play(); + } - return this; + Audio.prototype = Object.assign( Object.create( Object3D.prototype ), { - }, + constructor: Audio, - play: function () { + getOutput: function () { - if ( this.isPlaying === true ) { + return this.gain; - console.warn( 'THREE.Audio: Audio is already playing.' ); - return; + }, - } + setNodeSource: function ( audioNode ) { - if ( this.hasPlaybackControl === false ) { + this.hasPlaybackControl = false; + this.sourceType = 'audioNode'; + this.source = audioNode; + this.connect(); - console.warn( 'THREE.Audio: this Audio has no playback control.' ); - return; + return this; - } + }, - var source = this.context.createBufferSource(); + setBuffer: function ( audioBuffer ) { - 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.buffer = audioBuffer; + this.sourceType = 'buffer'; - this.isPlaying = true; + if ( this.autoplay ) this.play(); - this.source = source; + return this; - return this.connect(); + }, - }, + play: function () { - pause: function () { + if ( this.isPlaying === true ) { - if ( this.hasPlaybackControl === false ) { + console.warn( 'THREE.Audio: Audio is already playing.' ); + return; - console.warn( 'THREE.Audio: this Audio has no playback control.' ); - return; + } - } + if ( this.hasPlaybackControl === false ) { - this.source.stop(); - this.startTime = this.context.currentTime; - this.isPlaying = false; + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; - return this; + } - }, + var source = this.context.createBufferSource(); - stop: function () { + 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; - if ( this.hasPlaybackControl === false ) { + this.isPlaying = true; - console.warn( 'THREE.Audio: this Audio has no playback control.' ); - return; + this.source = source; - } + return this.connect(); - this.source.stop(); - this.startTime = 0; - this.isPlaying = false; + }, - return this; + pause: function () { - }, + if ( this.hasPlaybackControl === false ) { - connect: function () { + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; - if ( this.filters.length > 0 ) { + } - this.source.connect( this.filters[ 0 ] ); + this.source.stop(); + this.startTime = this.context.currentTime; + this.isPlaying = false; - for ( var i = 1, l = this.filters.length; i < l; i ++ ) { + return this; - this.filters[ i - 1 ].connect( this.filters[ i ] ); + }, - } + stop: function () { - this.filters[ this.filters.length - 1 ].connect( this.getOutput() ); + if ( this.hasPlaybackControl === false ) { - } else { + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; - this.source.connect( this.getOutput() ); + } - } + this.source.stop(); + this.startTime = 0; + this.isPlaying = false; - return this; + return this; - }, + }, - disconnect: function () { + connect: function () { - if ( this.filters.length > 0 ) { + if ( this.filters.length > 0 ) { - this.source.disconnect( this.filters[ 0 ] ); + this.source.connect( this.filters[ 0 ] ); - for ( var i = 1, l = this.filters.length; i < l; i ++ ) { + for ( var i = 1, l = this.filters.length; i < l; i ++ ) { - this.filters[ i - 1 ].disconnect( this.filters[ i ] ); + this.filters[ i - 1 ].connect( this.filters[ i ] ); - } + } - this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() ); + this.filters[ this.filters.length - 1 ].connect( this.getOutput() ); - } else { + } else { - this.source.disconnect( this.getOutput() ); + this.source.connect( this.getOutput() ); - } + } - return this; + return this; - }, + }, - getFilters: function () { + disconnect: function () { - return this.filters; + if ( this.filters.length > 0 ) { - }, + this.source.disconnect( this.filters[ 0 ] ); - setFilters: function ( value ) { + for ( var i = 1, l = this.filters.length; i < l; i ++ ) { - if ( ! value ) value = []; + this.filters[ i - 1 ].disconnect( this.filters[ i ] ); - if ( this.isPlaying === true ) { + } - this.disconnect(); - this.filters = value; - this.connect(); + this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() ); - } else { + } else { - this.filters = value; + this.source.disconnect( this.getOutput() ); - } + } - return this; + return this; - }, + }, - getFilter: function () { + getFilters: function () { - return this.getFilters()[ 0 ]; + return this.filters; - }, + }, - setFilter: function ( filter ) { + setFilters: function ( value ) { - return this.setFilters( filter ? [ filter ] : [] ); + if ( ! value ) value = []; - }, + if ( this.isPlaying === true ) { - setPlaybackRate: function ( value ) { + this.disconnect(); + this.filters = value; + this.connect(); - if ( this.hasPlaybackControl === false ) { + } else { - console.warn( 'THREE.Audio: this Audio has no playback control.' ); - return; + this.filters = value; - } + } - this.playbackRate = value; + return this; - if ( this.isPlaying === true ) { + }, - this.source.playbackRate.value = this.playbackRate; + getFilter: function () { - } + return this.getFilters()[ 0 ]; - return this; + }, - }, + setFilter: function ( filter ) { - getPlaybackRate: function () { + return this.setFilters( filter ? [ filter ] : [] ); - return this.playbackRate; + }, - }, + setPlaybackRate: function ( value ) { - onEnded: function () { + if ( this.hasPlaybackControl === false ) { - this.isPlaying = false; + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; - }, + } - getLoop: function () { + this.playbackRate = value; - if ( this.hasPlaybackControl === false ) { + if ( this.isPlaying === true ) { - console.warn( 'THREE.Audio: this Audio has no playback control.' ); - return false; + this.source.playbackRate.value = this.playbackRate; - } + } - return this.source.loop; + return this; - }, + }, - setLoop: function ( value ) { + getPlaybackRate: function () { - if ( this.hasPlaybackControl === false ) { + return this.playbackRate; - console.warn( 'THREE.Audio: this Audio has no playback control.' ); - return; + }, - } + onEnded: function () { - this.source.loop = value; + this.isPlaying = false; - }, + }, - getVolume: function () { + getLoop: function () { - return this.gain.gain.value; + if ( this.hasPlaybackControl === false ) { - }, + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return false; + } - setVolume: function ( value ) { + return this.source.loop; - this.gain.gain.value = value; + }, - return this; + setLoop: function ( value ) { - } + if ( this.hasPlaybackControl === false ) { - } ); + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; - function PositionalAudio( listener ) { + } - Audio.call( this, listener ); + this.source.loop = value; - this.panner = this.context.createPanner(); - this.panner.connect( this.gain ); + }, - } + getVolume: function () { - PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), { + return this.gain.gain.value; - constructor: PositionalAudio, + }, - getOutput: function () { - return this.panner; + setVolume: function ( value ) { - }, + this.gain.gain.value = value; - getRefDistance: function () { + return this; - return this.panner.refDistance; + } - }, + } ); - setRefDistance: function ( value ) { + function PositionalAudio( listener ) { - this.panner.refDistance = value; + Audio.call( this, listener ); - }, + this.panner = this.context.createPanner(); + this.panner.connect( this.gain ); - getRolloffFactor: function () { + } - return this.panner.rolloffFactor; + PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), { - }, + constructor: PositionalAudio, - setRolloffFactor: function ( value ) { + getOutput: function () { - this.panner.rolloffFactor = value; + return this.panner; - }, + }, - getDistanceModel: function () { + getRefDistance: function () { - return this.panner.distanceModel; + return this.panner.refDistance; - }, + }, - setDistanceModel: function ( value ) { + setRefDistance: function ( value ) { - this.panner.distanceModel = value; + this.panner.refDistance = value; - }, + }, - getMaxDistance: function () { + getRolloffFactor: function () { - return this.panner.maxDistance; + return this.panner.rolloffFactor; - }, + }, - setMaxDistance: function ( value ) { + setRolloffFactor: function ( value ) { - this.panner.maxDistance = value; + this.panner.rolloffFactor = value; - }, + }, - updateMatrixWorld: ( function () { + getDistanceModel: function () { - var position = new Vector3(); + return this.panner.distanceModel; - return function updateMatrixWorld( force ) { + }, - Object3D.prototype.updateMatrixWorld.call( this, force ); + setDistanceModel: function ( value ) { - position.setFromMatrixPosition( this.matrixWorld ); + this.panner.distanceModel = value; - this.panner.setPosition( position.x, position.y, position.z ); + }, - }; + getMaxDistance: function () { - } )() + return this.panner.maxDistance; + }, - } ); + setMaxDistance: function ( value ) { - /** - * @author mrdoob / http://mrdoob.com/ - */ + this.panner.maxDistance = value; - function AudioAnalyser( audio, fftSize ) { + }, - this.analyser = audio.context.createAnalyser(); - this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048; + updateMatrixWorld: ( function () { - this.data = new Uint8Array( this.analyser.frequencyBinCount ); + var position = new Vector3(); - audio.getOutput().connect( this.analyser ); + return function updateMatrixWorld( force ) { - } + Object3D.prototype.updateMatrixWorld.call( this, force ); - Object.assign( AudioAnalyser.prototype, { + position.setFromMatrixPosition( this.matrixWorld ); - getFrequencyData: function () { + this.panner.setPosition( position.x, position.y, position.z ); - this.analyser.getByteFrequencyData( this.data ); + }; - return this.data; + } )() - }, - getAverageFrequency: function () { + } ); - var value = 0, data = this.getFrequencyData(); + /** + * @author mrdoob / http://mrdoob.com/ + */ - for ( var i = 0; i < data.length; i ++ ) { + function AudioAnalyser( audio, fftSize ) { - value += data[ i ]; + this.analyser = audio.context.createAnalyser(); + this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048; - } + this.data = new Uint8Array( this.analyser.frequencyBinCount ); - return value / data.length; + audio.getOutput().connect( this.analyser ); - } + } - } ); + Object.assign( AudioAnalyser.prototype, { - /** - * - * Buffered scene graph property that allows weighted accumulation. - * - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + getFrequencyData: function () { - function PropertyMixer( binding, typeName, valueSize ) { + this.analyser.getByteFrequencyData( this.data ); - this.binding = binding; - this.valueSize = valueSize; + return this.data; - var bufferType = Float64Array, - mixFunction; + }, - switch ( typeName ) { + getAverageFrequency: function () { - case 'quaternion': mixFunction = this._slerp; break; + var value = 0, data = this.getFrequencyData(); - case 'string': - case 'bool': + for ( var i = 0; i < data.length; i ++ ) { - bufferType = Array, mixFunction = this._select; break; + value += data[ i ]; - default: mixFunction = this._lerp; + } - } + return value / data.length; - 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 + } - this._mixBufferRegion = mixFunction; + } ); - this.cumulativeWeight = 0; + /** + * + * Buffered scene graph property that allows weighted accumulation. + * + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - this.useCount = 0; - this.referenceCount = 0; + function PropertyMixer( binding, typeName, valueSize ) { - }; + this.binding = binding; + this.valueSize = valueSize; - PropertyMixer.prototype = { + var bufferType = Float64Array, + mixFunction; - constructor: PropertyMixer, + switch ( typeName ) { - // accumulate data in the 'incoming' region into 'accu' - accumulate: function( accuIndex, weight ) { + case 'quaternion': mixFunction = this._slerp; break; - // note: happily accumulating nothing when weight = 0, the caller knows - // the weight and shouldn't have made the call in the first place + case 'string': + case 'bool': - var buffer = this.buffer, - stride = this.valueSize, - offset = accuIndex * stride + stride, + bufferType = Array, mixFunction = this._select; break; - currentWeight = this.cumulativeWeight; + default: mixFunction = this._lerp; - if ( currentWeight === 0 ) { + } - // accuN := incoming * weight + 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 - for ( var i = 0; i !== stride; ++ i ) { + this._mixBufferRegion = mixFunction; - buffer[ offset + i ] = buffer[ i ]; + this.cumulativeWeight = 0; - } + this.useCount = 0; + this.referenceCount = 0; - currentWeight = weight; + }; - } else { + PropertyMixer.prototype = { - // accuN := accuN + incoming * weight + constructor: PropertyMixer, - currentWeight += weight; - var mix = weight / currentWeight; - this._mixBufferRegion( buffer, offset, 0, mix, stride ); + // accumulate data in the 'incoming' region into 'accu' + accumulate: function( accuIndex, weight ) { - } + // note: happily accumulating nothing when weight = 0, the caller knows + // the weight and shouldn't have made the call in the first place - this.cumulativeWeight = currentWeight; + var buffer = this.buffer, + stride = this.valueSize, + offset = accuIndex * stride + stride, - }, + currentWeight = this.cumulativeWeight; - // apply the state of 'accu' to the binding when accus differ - apply: function( accuIndex ) { + if ( currentWeight === 0 ) { - var stride = this.valueSize, - buffer = this.buffer, - offset = accuIndex * stride + stride, + // accuN := incoming * weight - weight = this.cumulativeWeight, + for ( var i = 0; i !== stride; ++ i ) { - binding = this.binding; + buffer[ offset + i ] = buffer[ i ]; - this.cumulativeWeight = 0; + } - if ( weight < 1 ) { + currentWeight = weight; - // accuN := accuN + original * ( 1 - cumulativeWeight ) + } else { - var originalValueOffset = stride * 3; + // accuN := accuN + incoming * weight - this._mixBufferRegion( - buffer, offset, originalValueOffset, 1 - weight, stride ); + currentWeight += weight; + var mix = weight / currentWeight; + this._mixBufferRegion( buffer, offset, 0, mix, stride ); - } + } - for ( var i = stride, e = stride + stride; i !== e; ++ i ) { + this.cumulativeWeight = currentWeight; - if ( buffer[ i ] !== buffer[ i + stride ] ) { + }, - // value has changed -> update scene graph + // apply the state of 'accu' to the binding when accus differ + apply: function( accuIndex ) { - binding.setValue( buffer, offset ); - break; + var stride = this.valueSize, + buffer = this.buffer, + offset = accuIndex * stride + stride, - } + weight = this.cumulativeWeight, - } + binding = this.binding; - }, + this.cumulativeWeight = 0; - // remember the state of the bound property and copy it to both accus - saveOriginalState: function() { + if ( weight < 1 ) { - var binding = this.binding; + // accuN := accuN + original * ( 1 - cumulativeWeight ) - var buffer = this.buffer, - stride = this.valueSize, + var originalValueOffset = stride * 3; - originalValueOffset = stride * 3; + this._mixBufferRegion( + buffer, offset, originalValueOffset, 1 - weight, stride ); - binding.getValue( buffer, originalValueOffset ); + } - // accu[0..1] := orig -- initially detect changes against the original - for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) { + for ( var i = stride, e = stride + stride; i !== e; ++ i ) { - buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ]; + if ( buffer[ i ] !== buffer[ i + stride ] ) { - } + // value has changed -> update scene graph - this.cumulativeWeight = 0; + binding.setValue( buffer, offset ); + break; - }, + } - // apply the state previously taken via 'saveOriginalState' to the binding - restoreOriginalState: function() { + } - var originalValueOffset = this.valueSize * 3; - this.binding.setValue( this.buffer, originalValueOffset ); + }, - }, + // remember the state of the bound property and copy it to both accus + saveOriginalState: function() { + var binding = this.binding; - // mix functions + var buffer = this.buffer, + stride = this.valueSize, - _select: function( buffer, dstOffset, srcOffset, t, stride ) { + originalValueOffset = stride * 3; - if ( t >= 0.5 ) { + binding.getValue( buffer, originalValueOffset ); - for ( var i = 0; i !== stride; ++ i ) { + // accu[0..1] := orig -- initially detect changes against the original + for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) { - buffer[ dstOffset + i ] = buffer[ srcOffset + i ]; + buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ]; - } + } - } + this.cumulativeWeight = 0; - }, + }, - _slerp: function( buffer, dstOffset, srcOffset, t, stride ) { + // apply the state previously taken via 'saveOriginalState' to the binding + restoreOriginalState: function() { - Quaternion.slerpFlat( buffer, dstOffset, - buffer, dstOffset, buffer, srcOffset, t ); + var originalValueOffset = this.valueSize * 3; + this.binding.setValue( this.buffer, originalValueOffset ); - }, + }, - _lerp: function( buffer, dstOffset, srcOffset, t, stride ) { - var s = 1 - t; + // mix functions - for ( var i = 0; i !== stride; ++ i ) { + _select: function( buffer, dstOffset, srcOffset, t, stride ) { - var j = dstOffset + i; + if ( t >= 0.5 ) { - buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t; + for ( var i = 0; i !== stride; ++ i ) { - } + buffer[ dstOffset + i ] = buffer[ srcOffset + 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 - */ + }, - function PropertyBinding( rootNode, path, parsedPath ) { + _slerp: function( buffer, dstOffset, srcOffset, t, stride ) { - this.path = path; - this.parsedPath = parsedPath || - PropertyBinding.parseTrackName( path ); + Quaternion.slerpFlat( buffer, dstOffset, + buffer, dstOffset, buffer, srcOffset, t ); - this.node = PropertyBinding.findNode( - rootNode, this.parsedPath.nodeName ) || rootNode; + }, - this.rootNode = rootNode; + _lerp: function( buffer, dstOffset, srcOffset, t, stride ) { - }; + var s = 1 - t; - PropertyBinding.prototype = { + for ( var i = 0; i !== stride; ++ i ) { - constructor: PropertyBinding, + var j = dstOffset + i; - getValue: function getValue_unbound( targetArray, offset ) { + buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t; - 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. + } - }, + }; - setValue: function getValue_unbound( sourceArray, offset ) { + /** + * + * A reference to a real property in the scene graph. + * + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - this.bind(); - this.setValue( sourceArray, offset ); + function PropertyBinding( rootNode, path, parsedPath ) { - }, + this.path = path; + this.parsedPath = parsedPath || + PropertyBinding.parseTrackName( path ); - // create getter / setter pair for a property in the scene graph - bind: function() { + this.node = PropertyBinding.findNode( + rootNode, this.parsedPath.nodeName ) || rootNode; - var targetObject = this.node, - parsedPath = this.parsedPath, + this.rootNode = rootNode; - objectName = parsedPath.objectName, - propertyName = parsedPath.propertyName, - propertyIndex = parsedPath.propertyIndex; + }; - if ( ! targetObject ) { + PropertyBinding.prototype = { - targetObject = PropertyBinding.findNode( - this.rootNode, parsedPath.nodeName ) || this.rootNode; + constructor: PropertyBinding, - this.node = targetObject; + getValue: function getValue_unbound( targetArray, offset ) { - } + this.bind(); + this.getValue( targetArray, offset ); - // set fail state so we can just 'return' on error - this.getValue = this._getValue_unavailable; - this.setValue = this._setValue_unavailable; + // 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. - // ensure there is a value node - if ( ! targetObject ) { + }, - console.error( " trying to update node for track: " + this.path + " but it wasn't found." ); - return; + setValue: function getValue_unbound( sourceArray, offset ) { - } + this.bind(); + this.setValue( sourceArray, offset ); - if ( objectName ) { + }, - var objectIndex = parsedPath.objectIndex; + // create getter / setter pair for a property in the scene graph + bind: function() { - // special cases were we need to reach deeper into the hierarchy to get the face materials.... - switch ( objectName ) { + var targetObject = this.node, + parsedPath = this.parsedPath, - case 'materials': + objectName = parsedPath.objectName, + propertyName = parsedPath.propertyName, + propertyIndex = parsedPath.propertyIndex; - if ( ! targetObject.material ) { + if ( ! targetObject ) { - console.error( ' can not bind to material as node does not have a material', this ); - return; + targetObject = PropertyBinding.findNode( + this.rootNode, parsedPath.nodeName ) || this.rootNode; - } + this.node = targetObject; - if ( ! targetObject.material.materials ) { + } - console.error( ' can not bind to material.materials as node.material does not have a materials array', this ); - return; + // set fail state so we can just 'return' on error + this.getValue = this._getValue_unavailable; + this.setValue = this._setValue_unavailable; - } + // ensure there is a value node + if ( ! targetObject ) { - targetObject = targetObject.material.materials; + console.error( " trying to update node for track: " + this.path + " but it wasn't found." ); + return; - break; + } - case 'bones': + if ( objectName ) { - if ( ! targetObject.skeleton ) { + var objectIndex = parsedPath.objectIndex; - console.error( ' can not bind to bones as node does not have a skeleton', this ); - return; + // special cases were we need to reach deeper into the hierarchy to get the face materials.... + switch ( objectName ) { - } + case 'materials': - // potential future optimization: skip this if propertyIndex is already an integer - // and convert the integer string to a true integer. + if ( ! targetObject.material ) { - targetObject = targetObject.skeleton.bones; + console.error( ' can not bind to material as node does not have a material', this ); + return; - // support resolving morphTarget names into indices. - for ( var i = 0; i < targetObject.length; i ++ ) { + } - if ( targetObject[ i ].name === objectIndex ) { + if ( ! targetObject.material.materials ) { - objectIndex = i; - break; + console.error( ' can not bind to material.materials as node.material does not have a materials array', this ); + return; - } + } - } + targetObject = targetObject.material.materials; - break; + break; - default: + case 'bones': - if ( targetObject[ objectName ] === undefined ) { + if ( ! targetObject.skeleton ) { - console.error( ' can not bind to objectName of node, undefined', this ); - return; + console.error( ' can not bind to bones as node does not have a skeleton', this ); + return; - } + } - targetObject = targetObject[ objectName ]; + // potential future optimization: skip this if propertyIndex is already an integer + // and convert the integer string to a true integer. - } + targetObject = targetObject.skeleton.bones; + // support resolving morphTarget names into indices. + for ( var i = 0; i < targetObject.length; i ++ ) { - if ( objectIndex !== undefined ) { + if ( targetObject[ i ].name === objectIndex ) { - if ( targetObject[ objectIndex ] === undefined ) { + objectIndex = i; + break; - console.error( " trying to bind to objectIndex of objectName, but is undefined:", this, targetObject ); - return; + } - } + } - targetObject = targetObject[ objectIndex ]; + break; - } + default: - } + if ( targetObject[ objectName ] === undefined ) { - // resolve property - var nodeProperty = targetObject[ propertyName ]; + console.error( ' can not bind to objectName of node, undefined', this ); + return; - if ( nodeProperty === undefined ) { + } - var nodeName = parsedPath.nodeName; + targetObject = targetObject[ objectName ]; - console.error( " trying to update property for track: " + nodeName + - '.' + propertyName + " but it wasn't found.", targetObject ); - return; + } - } - // determine versioning scheme - var versioning = this.Versioning.None; + if ( objectIndex !== undefined ) { - if ( targetObject.needsUpdate !== undefined ) { // material + if ( targetObject[ objectIndex ] === undefined ) { - versioning = this.Versioning.NeedsUpdate; - this.targetObject = targetObject; + console.error( " trying to bind to objectIndex of objectName, but is undefined:", this, targetObject ); + return; - } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform + } - versioning = this.Versioning.MatrixWorldNeedsUpdate; - this.targetObject = targetObject; + targetObject = targetObject[ objectIndex ]; - } + } - // 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) + // resolve property + var nodeProperty = targetObject[ propertyName ]; - if ( propertyName === "morphTargetInfluences" ) { - // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer. + if ( nodeProperty === undefined ) { - // support resolving morphTarget names into indices. - if ( ! targetObject.geometry ) { + var nodeName = parsedPath.nodeName; - console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry', this ); - return; + console.error( " trying to update property for track: " + nodeName + + '.' + propertyName + " but it wasn't found.", targetObject ); + return; - } + } - if ( ! targetObject.geometry.morphTargets ) { + // determine versioning scheme + var versioning = this.Versioning.None; - console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry.morphTargets', this ); - return; + if ( targetObject.needsUpdate !== undefined ) { // material - } + versioning = this.Versioning.NeedsUpdate; + this.targetObject = targetObject; - for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) { + } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform - if ( targetObject.geometry.morphTargets[ i ].name === propertyIndex ) { + versioning = this.Versioning.MatrixWorldNeedsUpdate; + this.targetObject = targetObject; - propertyIndex = i; - break; + } - } + // 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) - } + 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.ArrayElement; + // support resolving morphTarget names into indices. + if ( ! targetObject.geometry ) { - this.resolvedProperty = nodeProperty; - this.propertyIndex = propertyIndex; + console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry', this ); + return; - } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) { - // must use copy for Object3D.Euler/Quaternion + } - bindingType = this.BindingType.HasFromToArray; + 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 if ( nodeProperty.length !== undefined ) { + } - bindingType = this.BindingType.EntireArray; + for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) { - this.resolvedProperty = nodeProperty; + if ( targetObject.geometry.morphTargets[ i ].name === propertyIndex ) { - } else { + propertyIndex = i; + break; - this.propertyName = propertyName; + } - } + } - // select getter / setter - this.getValue = this.GetterByBindingType[ bindingType ]; - this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ]; + } - }, + bindingType = this.BindingType.ArrayElement; - unbind: function() { + this.resolvedProperty = nodeProperty; + this.propertyIndex = propertyIndex; - this.node = null; + } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) { + // must use copy for Object3D.Euler/Quaternion - // 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.HasFromToArray; - } + this.resolvedProperty = nodeProperty; - }; + } else if ( nodeProperty.length !== undefined ) { - Object.assign( PropertyBinding.prototype, { // prototype, continued + bindingType = this.BindingType.EntireArray; - // 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 { - BindingType: { - Direct: 0, - EntireArray: 1, - ArrayElement: 2, - HasFromToArray: 3 - }, + this.propertyName = propertyName; - Versioning: { - None: 0, - NeedsUpdate: 1, - MatrixWorldNeedsUpdate: 2 - }, + } - GetterByBindingType: [ + // select getter / setter + this.getValue = this.GetterByBindingType[ bindingType ]; + this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ]; - function getValue_direct( buffer, offset ) { + }, - buffer[ offset ] = this.node[ this.propertyName ]; + unbind: function() { - }, + this.node = null; - function getValue_array( buffer, offset ) { + // 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; - var source = this.resolvedProperty; + } - for ( var i = 0, n = source.length; i !== n; ++ i ) { + }; - buffer[ offset ++ ] = source[ i ]; + Object.assign( PropertyBinding.prototype, { // prototype, continued - } + // 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_arrayElement( buffer, offset ) { + BindingType: { + Direct: 0, + EntireArray: 1, + ArrayElement: 2, + HasFromToArray: 3 + }, - buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ]; + Versioning: { + None: 0, + NeedsUpdate: 1, + MatrixWorldNeedsUpdate: 2 + }, - }, + GetterByBindingType: [ - function getValue_toArray( buffer, offset ) { + function getValue_direct( buffer, offset ) { - this.resolvedProperty.toArray( buffer, offset ); + buffer[ offset ] = this.node[ this.propertyName ]; - } + }, - ], + function getValue_array( buffer, offset ) { - SetterByBindingTypeAndVersioning: [ + var source = this.resolvedProperty; - [ - // Direct + for ( var i = 0, n = source.length; i !== n; ++ i ) { - function setValue_direct( buffer, offset ) { + buffer[ offset ++ ] = source[ i ]; - this.node[ this.propertyName ] = buffer[ offset ]; + } - }, + }, - function setValue_direct_setNeedsUpdate( buffer, offset ) { + function getValue_arrayElement( buffer, offset ) { - this.node[ this.propertyName ] = buffer[ offset ]; - this.targetObject.needsUpdate = true; + buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ]; - }, + }, - function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) { + function getValue_toArray( buffer, offset ) { - this.node[ this.propertyName ] = buffer[ offset ]; - this.targetObject.matrixWorldNeedsUpdate = true; + this.resolvedProperty.toArray( buffer, offset ); - } + } - ], [ + ], - // EntireArray + SetterByBindingTypeAndVersioning: [ - function setValue_array( buffer, offset ) { + [ + // Direct - var dest = this.resolvedProperty; + function setValue_direct( buffer, offset ) { - for ( var i = 0, n = dest.length; i !== n; ++ i ) { + this.node[ this.propertyName ] = buffer[ offset ]; - dest[ i ] = buffer[ offset ++ ]; + }, - } + function setValue_direct_setNeedsUpdate( buffer, offset ) { - }, + this.node[ this.propertyName ] = buffer[ offset ]; + this.targetObject.needsUpdate = true; - function setValue_array_setNeedsUpdate( buffer, offset ) { + }, - var dest = this.resolvedProperty; + function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) { - for ( var i = 0, n = dest.length; i !== n; ++ i ) { + this.node[ this.propertyName ] = buffer[ offset ]; + this.targetObject.matrixWorldNeedsUpdate = true; - dest[ i ] = buffer[ offset ++ ]; + } - } + ], [ - this.targetObject.needsUpdate = true; + // EntireArray - }, + function setValue_array( buffer, offset ) { - function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) { + var dest = this.resolvedProperty; - var dest = this.resolvedProperty; + for ( var i = 0, n = dest.length; i !== n; ++ i ) { - for ( var i = 0, n = dest.length; i !== n; ++ i ) { + dest[ i ] = buffer[ offset ++ ]; - dest[ i ] = buffer[ offset ++ ]; + } - } + }, - this.targetObject.matrixWorldNeedsUpdate = true; + function setValue_array_setNeedsUpdate( buffer, offset ) { - } + var dest = this.resolvedProperty; - ], [ + for ( var i = 0, n = dest.length; i !== n; ++ i ) { - // ArrayElement + dest[ i ] = buffer[ offset ++ ]; - function setValue_arrayElement( buffer, offset ) { + } - this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; + this.targetObject.needsUpdate = true; - }, + }, - function setValue_arrayElement_setNeedsUpdate( buffer, offset ) { + function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) { - this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; - this.targetObject.needsUpdate = true; + var dest = this.resolvedProperty; - }, + for ( var i = 0, n = dest.length; i !== n; ++ i ) { - function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) { + dest[ i ] = buffer[ offset ++ ]; - this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; - this.targetObject.matrixWorldNeedsUpdate = true; + } - } + this.targetObject.matrixWorldNeedsUpdate = true; - ], [ + } - // HasToFromArray + ], [ - function setValue_fromArray( buffer, offset ) { + // ArrayElement - this.resolvedProperty.fromArray( buffer, offset ); + function setValue_arrayElement( buffer, offset ) { - }, + this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; - function setValue_fromArray_setNeedsUpdate( buffer, offset ) { + }, - this.resolvedProperty.fromArray( buffer, offset ); - this.targetObject.needsUpdate = true; + function setValue_arrayElement_setNeedsUpdate( buffer, offset ) { - }, + this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; + this.targetObject.needsUpdate = true; - function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) { + }, - this.resolvedProperty.fromArray( buffer, offset ); - this.targetObject.matrixWorldNeedsUpdate = true; + function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) { - } + this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; + this.targetObject.matrixWorldNeedsUpdate = true; - ] + } - ] + ], [ - } ); + // HasToFromArray - PropertyBinding.Composite = - function( targetGroup, path, optionalParsedPath ) { + function setValue_fromArray( buffer, offset ) { - var parsedPath = optionalParsedPath || - PropertyBinding.parseTrackName( path ); + this.resolvedProperty.fromArray( buffer, offset ); - this._targetGroup = targetGroup; - this._bindings = targetGroup.subscribe_( path, parsedPath ); + }, - }; + function setValue_fromArray_setNeedsUpdate( buffer, offset ) { - PropertyBinding.Composite.prototype = { + this.resolvedProperty.fromArray( buffer, offset ); + this.targetObject.needsUpdate = true; - constructor: PropertyBinding.Composite, + }, - getValue: function( array, offset ) { + function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) { - this.bind(); // bind all binding + this.resolvedProperty.fromArray( buffer, offset ); + this.targetObject.matrixWorldNeedsUpdate = true; - var firstValidIndex = this._targetGroup.nCachedObjects_, - binding = this._bindings[ firstValidIndex ]; + } - // and only call .getValue on the first - if ( binding !== undefined ) binding.getValue( array, offset ); + ] - }, + ] - setValue: function( array, offset ) { + } ); - var bindings = this._bindings; + PropertyBinding.Composite = + function( targetGroup, path, optionalParsedPath ) { - for ( var i = this._targetGroup.nCachedObjects_, - n = bindings.length; i !== n; ++ i ) { + var parsedPath = optionalParsedPath || + PropertyBinding.parseTrackName( path ); - bindings[ i ].setValue( array, offset ); + this._targetGroup = targetGroup; + this._bindings = targetGroup.subscribe_( path, parsedPath ); - } + }; - }, + PropertyBinding.Composite.prototype = { - bind: function() { + constructor: PropertyBinding.Composite, - var bindings = this._bindings; + getValue: function( array, offset ) { - for ( var i = this._targetGroup.nCachedObjects_, - n = bindings.length; i !== n; ++ i ) { + this.bind(); // bind all binding - bindings[ i ].bind(); + var firstValidIndex = this._targetGroup.nCachedObjects_, + binding = this._bindings[ firstValidIndex ]; - } + // and only call .getValue on the first + if ( binding !== undefined ) binding.getValue( array, offset ); - }, + }, - unbind: function() { + setValue: function( array, offset ) { - var bindings = this._bindings; + var bindings = this._bindings; - for ( var i = this._targetGroup.nCachedObjects_, - n = bindings.length; i !== n; ++ i ) { + for ( var i = this._targetGroup.nCachedObjects_, + n = bindings.length; i !== n; ++ i ) { - bindings[ i ].unbind(); + bindings[ i ].setValue( array, offset ); - } + } - } + }, - }; + bind: function() { - PropertyBinding.create = function( root, path, parsedPath ) { + var bindings = this._bindings; - if ( ! ( (root && root.isAnimationObjectGroup) ) ) { + for ( var i = this._targetGroup.nCachedObjects_, + n = bindings.length; i !== n; ++ i ) { - return new PropertyBinding( root, path, parsedPath ); + bindings[ i ].bind(); - } else { + } - return new PropertyBinding.Composite( root, path, parsedPath ); + }, - } + unbind: function() { - }; + var bindings = this._bindings; - PropertyBinding.parseTrackName = function( trackName ) { + for ( var i = this._targetGroup.nCachedObjects_, + n = bindings.length; i !== n; ++ i ) { - // 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 + bindings[ i ].unbind(); - var re = /^(([\w]+\/)*)([\w-\d]+)?(\.([\w]+)(\[([\w\d\[\]\_.:\- ]+)\])?)?(\.([\w.]+)(\[([\w\d\[\]\_. ]+)\])?)$/; - var matches = re.exec( trackName ); + } - if ( ! matches ) { + } - throw new Error( "cannot parse trackName at all: " + trackName ); + }; - } + PropertyBinding.create = function( root, path, parsedPath ) { - if ( matches.index === re.lastIndex ) { + if ( ! ( (root && root.isAnimationObjectGroup) ) ) { - re.lastIndex++; + return new PropertyBinding( root, path, parsedPath ); - } + } else { - 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. - }; + return new PropertyBinding.Composite( root, path, parsedPath ); - if ( results.propertyName === null || results.propertyName.length === 0 ) { + } - throw new Error( "can not parse propertyName from trackName: " + trackName ); + }; - } + PropertyBinding.parseTrackName = function( trackName ) { - return results; + // 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 - }; + var re = /^(([\w]+\/)*)([\w-\d]+)?(\.([\w]+)(\[([\w\d\[\]\_.:\- ]+)\])?)?(\.([\w.]+)(\[([\w\d\[\]\_. ]+)\])?)$/; + var matches = re.exec( trackName ); - PropertyBinding.findNode = function( root, nodeName ) { + if ( ! matches ) { - if ( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) { + throw new Error( "cannot parse trackName at all: " + trackName ); - return root; + } - } + if ( matches.index === re.lastIndex ) { - // search into skeleton bones. - if ( root.skeleton ) { + re.lastIndex++; - var searchSkeleton = function( skeleton ) { + } - for( var i = 0; i < skeleton.bones.length; i ++ ) { + 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. + }; - 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.isBufferGeometry = 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 ); + + this.material = material; + this.render = function ( renderCallback ) {}; + + }; + + ImmediateRenderObject.prototype = Object.create( Object3D.prototype ); + ImmediateRenderObject.prototype.constructor = ImmediateRenderObject; - /** - * @author alteredq / http://alteredqualia.com/ - */ + ImmediateRenderObject.prototype.isImmediateRenderObject = true; - function ImmediateRenderObject( material ) { + /** + * @author mrdoob / http://mrdoob.com/ + */ - Object3D.call( this ); + function WireframeGeometry( geometry ) { - this.material = material; - this.render = function ( renderCallback ) {}; + BufferGeometry.call( this ); - }; + var edge = [ 0, 0 ], hash = {}; - ImmediateRenderObject.prototype = Object.create( Object3D.prototype ); - ImmediateRenderObject.prototype.constructor = ImmediateRenderObject; + function sortFunction( a, b ) { - ImmediateRenderObject.prototype.isImmediateRenderObject = true; + return a - b; + + } - /** - * @author mrdoob / http://mrdoob.com/ - */ + var keys = [ 'a', 'b', 'c' ]; - function WireframeGeometry( geometry ) { + if ( (geometry && geometry.isGeometry) ) { - BufferGeometry.call( this ); + var vertices = geometry.vertices; + var faces = geometry.faces; + var numEdges = 0; - var edge = [ 0, 0 ], hash = {}; + // allocate maximal size + var edges = new Uint32Array( 6 * faces.length ); - function sortFunction( a, b ) { + for ( var i = 0, l = faces.length; i < l; i ++ ) { - return a - b; + var face = faces[ i ]; - } + for ( var j = 0; j < 3; j ++ ) { - var keys = [ 'a', 'b', 'c' ]; + edge[ 0 ] = face[ keys[ j ] ]; + edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ]; + edge.sort( sortFunction ); - if ( (geometry && geometry.isGeometry) ) { + var key = edge.toString(); - var vertices = geometry.vertices; - var faces = geometry.faces; - var numEdges = 0; + if ( hash[ key ] === undefined ) { - // allocate maximal size - var edges = new Uint32Array( 6 * faces.length ); + edges[ 2 * numEdges ] = edge[ 0 ]; + edges[ 2 * numEdges + 1 ] = edge[ 1 ]; + hash[ key ] = true; + numEdges ++; - for ( var i = 0, l = faces.length; i < l; i ++ ) { + } - var face = faces[ i ]; + } - for ( var j = 0; j < 3; j ++ ) { + } - edge[ 0 ] = face[ keys[ j ] ]; - edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ]; - edge.sort( sortFunction ); + var coords = new Float32Array( numEdges * 2 * 3 ); - var key = edge.toString(); + for ( var i = 0, l = numEdges; i < l; i ++ ) { - if ( hash[ key ] === undefined ) { + for ( var j = 0; j < 2; j ++ ) { - edges[ 2 * numEdges ] = edge[ 0 ]; - edges[ 2 * numEdges + 1 ] = edge[ 1 ]; - hash[ key ] = true; - numEdges ++; + 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 ); + this.addAttribute( 'position', new BufferAttribute( coords, 3 ) ); - for ( var i = 0, l = numEdges; i < l; i ++ ) { + } else if ( (geometry && geometry.isBufferGeometry) ) { - for ( var j = 0; j < 2; j ++ ) { + if ( geometry.index !== null ) { - var vertex = vertices[ edges [ 2 * i + j ] ]; + // Indexed BufferGeometry - var index = 6 * i + 3 * j; - coords[ index + 0 ] = vertex.x; - coords[ index + 1 ] = vertex.y; - coords[ index + 2 ] = vertex.z; + var indices = geometry.index.array; + var vertices = geometry.attributes.position; + var groups = geometry.groups; + var numEdges = 0; - } + if ( groups.length === 0 ) { - } + geometry.addGroup( 0, indices.length ); - this.addAttribute( 'position', new BufferAttribute( coords, 3 ) ); + } - } else if ( (geometry && geometry.isBufferGeometry) ) { + // allocate maximal size + var edges = new Uint32Array( 2 * indices.length ); - if ( geometry.index !== null ) { + for ( var o = 0, ol = groups.length; o < ol; ++ o ) { - // Indexed BufferGeometry + var group = groups[ o ]; - var indices = geometry.index.array; - var vertices = geometry.attributes.position; - var groups = geometry.groups; - var numEdges = 0; + var start = group.start; + var count = group.count; - if ( groups.length === 0 ) { + for ( var i = start, il = start + count; i < il; i += 3 ) { - geometry.addGroup( 0, indices.length ); + for ( var j = 0; j < 3; j ++ ) { - } + edge[ 0 ] = indices[ i + j ]; + edge[ 1 ] = indices[ i + ( j + 1 ) % 3 ]; + edge.sort( sortFunction ); - // allocate maximal size - var edges = new Uint32Array( 2 * indices.length ); + var key = edge.toString(); - for ( var o = 0, ol = groups.length; o < ol; ++ o ) { + if ( hash[ key ] === undefined ) { - var group = groups[ o ]; + edges[ 2 * numEdges ] = edge[ 0 ]; + edges[ 2 * numEdges + 1 ] = edge[ 1 ]; + hash[ key ] = true; + numEdges ++; - var start = group.start; - var count = group.count; + } - for ( var i = start, il = start + count; i < il; i += 3 ) { + } - 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(); + var coords = new Float32Array( numEdges * 2 * 3 ); - if ( hash[ key ] === undefined ) { + for ( var i = 0, l = numEdges; i < l; i ++ ) { - edges[ 2 * numEdges ] = edge[ 0 ]; - edges[ 2 * numEdges + 1 ] = edge[ 1 ]; - hash[ key ] = true; - numEdges ++; + 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 ); + this.addAttribute( 'position', new BufferAttribute( coords, 3 ) ); - for ( var i = 0, l = numEdges; i < l; i ++ ) { + } else { - for ( var j = 0; j < 2; j ++ ) { + // non-indexed BufferGeometry - var index = 6 * i + 3 * j; - var index2 = edges[ 2 * i + j ]; + var vertices = geometry.attributes.position.array; + var numEdges = vertices.length / 3; + var numTris = numEdges / 3; - 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 = numTris; i < l; i ++ ) { - } + for ( var j = 0; j < 3; j ++ ) { - this.addAttribute( 'position', new BufferAttribute( coords, 3 ) ); + var index = 18 * i + 6 * j; - } else { + var index1 = 9 * i + 3 * j; + coords[ index + 0 ] = vertices[ index1 ]; + coords[ index + 1 ] = vertices[ index1 + 1 ]; + coords[ index + 2 ] = vertices[ index1 + 2 ]; - // non-indexed BufferGeometry + 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 ]; - var vertices = geometry.attributes.position.array; - var numEdges = vertices.length / 3; - var numTris = numEdges / 3; + } - var coords = new Float32Array( numEdges * 2 * 3 ); + } - for ( var i = 0, l = numTris; i < l; i ++ ) { + this.addAttribute( 'position', new BufferAttribute( coords, 3 ) ); - for ( var j = 0; j < 3; j ++ ) { + } - var index = 18 * i + 6 * j; + } - 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; - } + /** + * @author mrdoob / http://mrdoob.com/ + */ - } + function WireframeHelper( object, hex ) { - this.addAttribute( 'position', new BufferAttribute( coords, 3 ) ); + var color = ( hex !== undefined ) ? hex : 0xffffff; - } + LineSegments.call( this, new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: color } ) ); - } + this.matrix = object.matrixWorld; + this.matrixAutoUpdate = false; - }; + }; - WireframeGeometry.prototype = Object.create( BufferGeometry.prototype ); - WireframeGeometry.prototype.constructor = WireframeGeometry; + WireframeHelper.prototype = Object.create( LineSegments.prototype ); + WireframeHelper.prototype.constructor = WireframeHelper; - /** - * @author mrdoob / http://mrdoob.com/ - */ + /** + * @author mrdoob / http://mrdoob.com/ + * @author WestLangley / http://github.com/WestLangley + */ - function WireframeHelper( object, hex ) { + function VertexNormalsHelper( object, size, hex, linewidth ) { - var color = ( hex !== undefined ) ? hex : 0xffffff; + this.object = object; - LineSegments.call( this, new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: color } ) ); + this.size = ( size !== undefined ) ? size : 1; - this.matrix = object.matrixWorld; - this.matrixAutoUpdate = false; + var color = ( hex !== undefined ) ? hex : 0xff0000; - }; + var width = ( linewidth !== undefined ) ? linewidth : 1; - WireframeHelper.prototype = Object.create( LineSegments.prototype ); - WireframeHelper.prototype.constructor = WireframeHelper; + // - /** - * @author mrdoob / http://mrdoob.com/ - * @author WestLangley / http://github.com/WestLangley - */ + var nNormals = 0; - function VertexNormalsHelper( object, size, hex, linewidth ) { + var objGeometry = this.object.geometry; - this.object = object; + if ( (objGeometry && objGeometry.isGeometry) ) { - this.size = ( size !== undefined ) ? size : 1; + nNormals = objGeometry.faces.length * 3; - var color = ( hex !== undefined ) ? hex : 0xff0000; + } else if ( (objGeometry && objGeometry.isBufferGeometry) ) { - var width = ( linewidth !== undefined ) ? linewidth : 1; + nNormals = objGeometry.attributes.normal.count; - // + } - var nNormals = 0; + // - var objGeometry = this.object.geometry; + var geometry = new BufferGeometry(); - if ( (objGeometry && objGeometry.isGeometry) ) { + var positions = new Float32Attribute( nNormals * 2 * 3, 3 ); - nNormals = objGeometry.faces.length * 3; + geometry.addAttribute( 'position', positions ); - } else if ( (objGeometry && objGeometry.isBufferGeometry) ) { + LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) ); - nNormals = objGeometry.attributes.normal.count; + // - } + this.matrixAutoUpdate = false; - // + this.update(); - var geometry = new BufferGeometry(); + }; - var positions = new Float32Attribute( nNormals * 2 * 3, 3 ); + VertexNormalsHelper.prototype = Object.create( LineSegments.prototype ); + VertexNormalsHelper.prototype.constructor = VertexNormalsHelper; - geometry.addAttribute( 'position', positions ); + VertexNormalsHelper.prototype.update = ( function () { - LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) ); + var v1 = new Vector3(); + var v2 = new Vector3(); + var normalMatrix = new Matrix3(); - // + return function update() { - this.matrixAutoUpdate = false; + var keys = [ 'a', 'b', 'c' ]; - this.update(); + this.object.updateMatrixWorld( true ); - }; + normalMatrix.getNormalMatrix( this.object.matrixWorld ); - VertexNormalsHelper.prototype = Object.create( LineSegments.prototype ); - VertexNormalsHelper.prototype.constructor = VertexNormalsHelper; + var matrixWorld = this.object.matrixWorld; - VertexNormalsHelper.prototype.update = ( function () { + var position = this.geometry.attributes.position; - var v1 = new Vector3(); - var v2 = new Vector3(); - var normalMatrix = new Matrix3(); + // - return function update() { + var objGeometry = this.object.geometry; - var keys = [ 'a', 'b', 'c' ]; + if ( (objGeometry && objGeometry.isGeometry) ) { - this.object.updateMatrixWorld( true ); + var vertices = objGeometry.vertices; - normalMatrix.getNormalMatrix( this.object.matrixWorld ); + var faces = objGeometry.faces; - var matrixWorld = this.object.matrixWorld; + var idx = 0; - var position = this.geometry.attributes.position; + for ( var i = 0, l = faces.length; i < l; i ++ ) { - // + var face = faces[ i ]; - var objGeometry = this.object.geometry; + for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) { - if ( (objGeometry && objGeometry.isGeometry) ) { + var vertex = vertices[ face[ keys[ j ] ] ]; - var vertices = objGeometry.vertices; + var normal = face.vertexNormals[ j ]; - var faces = objGeometry.faces; + v1.copy( vertex ).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; - for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) { + position.setXYZ( idx, v2.x, v2.y, v2.z ); - var vertex = vertices[ face[ keys[ j ] ] ]; + idx = idx + 1; - var normal = face.vertexNormals[ j ]; + } - v1.copy( vertex ).applyMatrix4( matrixWorld ); + } - v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 ); + } else if ( (objGeometry && objGeometry.isBufferGeometry) ) { - position.setXYZ( idx, v1.x, v1.y, v1.z ); + var objPos = objGeometry.attributes.position; - idx = idx + 1; + var objNorm = objGeometry.attributes.normal; - position.setXYZ( idx, v2.x, v2.y, v2.z ); + var idx = 0; - idx = idx + 1; + // for simplicity, ignore index and drawcalls, and render every normal - } + for ( var j = 0, jl = objPos.count; j < jl; j ++ ) { - } + v1.set( objPos.getX( j ), objPos.getY( j ), objPos.getZ( j ) ).applyMatrix4( matrixWorld ); - } else if ( (objGeometry && objGeometry.isBufferGeometry) ) { + v2.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) ); - var objPos = objGeometry.attributes.position; + v2.applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 ); - var objNorm = objGeometry.attributes.normal; + position.setXYZ( idx, v1.x, v1.y, v1.z ); - var idx = 0; + idx = idx + 1; - // for simplicity, ignore index and drawcalls, and render every normal + position.setXYZ( idx, v2.x, v2.y, v2.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 ); + } - v2.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) ); + } - v2.applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 ); + position.needsUpdate = true; - position.setXYZ( idx, v1.x, v1.y, v1.z ); + return this; - idx = idx + 1; + }; - position.setXYZ( idx, v2.x, v2.y, v2.z ); + }() ); - idx = idx + 1; + /** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + * @author WestLangley / http://github.com/WestLangley + */ - } + function SpotLightHelper( light ) { - } + Object3D.call( this ); - position.needsUpdate = true; + this.light = light; + this.light.updateMatrixWorld(); - return this; + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; - }; + 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 + ]; - /** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - * @author WestLangley / http://github.com/WestLangley - */ + for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) { - function SpotLightHelper( light ) { + var p1 = ( i / l ) * Math.PI * 2; + var p2 = ( j / l ) * Math.PI * 2; - Object3D.call( this ); + positions.push( + Math.cos( p1 ), Math.sin( p1 ), 1, + Math.cos( p2 ), Math.sin( p2 ), 1 + ); - this.light = light; - this.light.updateMatrixWorld(); + } - this.matrix = light.matrixWorld; - this.matrixAutoUpdate = false; + geometry.addAttribute( 'position', new Float32Attribute( positions, 3 ) ); - var geometry = new BufferGeometry(); + var material = new LineBasicMaterial( { fog: false } ); - 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 - ]; + this.cone = new LineSegments( geometry, material ); + this.add( this.cone ); - for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) { + this.update(); - var p1 = ( i / l ) * Math.PI * 2; - var p2 = ( j / l ) * Math.PI * 2; + }; - positions.push( - Math.cos( p1 ), Math.sin( p1 ), 1, - Math.cos( p2 ), Math.sin( p2 ), 1 - ); + SpotLightHelper.prototype = Object.create( Object3D.prototype ); + SpotLightHelper.prototype.constructor = SpotLightHelper; - } + SpotLightHelper.prototype.dispose = function () { - geometry.addAttribute( 'position', new Float32Attribute( positions, 3 ) ); + this.cone.geometry.dispose(); + this.cone.material.dispose(); - var material = new LineBasicMaterial( { fog: false } ); + }; - this.cone = new LineSegments( geometry, material ); - this.add( this.cone ); + SpotLightHelper.prototype.update = function () { - this.update(); + var vector = new Vector3(); + var vector2 = new Vector3(); - }; + return function update() { - SpotLightHelper.prototype = Object.create( Object3D.prototype ); - SpotLightHelper.prototype.constructor = SpotLightHelper; + var coneLength = this.light.distance ? this.light.distance : 1000; + var coneWidth = coneLength * Math.tan( this.light.angle ); - SpotLightHelper.prototype.dispose = function () { + this.cone.scale.set( coneWidth, coneWidth, coneLength ); - this.cone.geometry.dispose(); - this.cone.material.dispose(); + vector.setFromMatrixPosition( this.light.matrixWorld ); + vector2.setFromMatrixPosition( this.light.target.matrixWorld ); - }; + this.cone.lookAt( vector2.sub( vector ) ); - SpotLightHelper.prototype.update = function () { + this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); - var vector = new Vector3(); - var vector2 = new Vector3(); + }; - return function update() { + }(); - var coneLength = this.light.distance ? this.light.distance : 1000; - var coneWidth = coneLength * Math.tan( this.light.angle ); + /** + * @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.scale.set( coneWidth, coneWidth, coneLength ); + function SkeletonHelper( object ) { - vector.setFromMatrixPosition( this.light.matrixWorld ); - vector2.setFromMatrixPosition( this.light.target.matrixWorld ); + this.bones = this.getBoneList( object ); - this.cone.lookAt( vector2.sub( vector ) ); + var geometry = new Geometry(); - this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); + for ( var i = 0; i < this.bones.length; i ++ ) { - }; + var bone = this.bones[ i ]; - }(); + if ( (bone.parent && bone.parent.isBone) ) { - /** - * @author Sean Griffin / http://twitter.com/sgrif - * @author Michael Guerrero / http://realitymeltdown.com - * @author mrdoob / http://mrdoob.com/ - * @author ikerr / http://verold.com - */ + 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 ) ); - function SkeletonHelper( object ) { + } - this.bones = this.getBoneList( object ); + } - var geometry = new Geometry(); + geometry.dynamic = true; - for ( var i = 0; i < this.bones.length; i ++ ) { + var material = new LineBasicMaterial( { vertexColors: VertexColors, depthTest: false, depthWrite: false, transparent: true } ); - var bone = this.bones[ i ]; + LineSegments.call( this, geometry, material ); - if ( (bone.parent && bone.parent.isBone) ) { + this.root = 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 ) ); + this.matrix = object.matrixWorld; + this.matrixAutoUpdate = false; - } + this.update(); - } + }; - geometry.dynamic = true; - var material = new LineBasicMaterial( { vertexColors: VertexColors, depthTest: false, depthWrite: false, transparent: true } ); + SkeletonHelper.prototype = Object.create( LineSegments.prototype ); + SkeletonHelper.prototype.constructor = SkeletonHelper; - LineSegments.call( this, geometry, material ); + SkeletonHelper.prototype.getBoneList = function( object ) { - this.root = object; + var boneList = []; - this.matrix = object.matrixWorld; - this.matrixAutoUpdate = false; + if ( (object && object.isBone) ) { - this.update(); + boneList.push( object ); - }; + } + for ( var i = 0; i < object.children.length; i ++ ) { - SkeletonHelper.prototype = Object.create( LineSegments.prototype ); - SkeletonHelper.prototype.constructor = SkeletonHelper; + boneList.push.apply( boneList, this.getBoneList( object.children[ i ] ) ); - SkeletonHelper.prototype.getBoneList = function( object ) { + } - var boneList = []; + return boneList; - if ( (object && object.isBone) ) { + }; - boneList.push( object ); + SkeletonHelper.prototype.update = function () { - } + var geometry = this.geometry; - for ( var i = 0; i < object.children.length; i ++ ) { + var matrixWorldInv = new Matrix4().getInverse( this.root.matrixWorld ); - boneList.push.apply( boneList, this.getBoneList( object.children[ i ] ) ); + var boneMatrix = new Matrix4(); - } + var j = 0; - return boneList; + for ( var i = 0; i < this.bones.length; i ++ ) { - }; + var bone = this.bones[ i ]; - SkeletonHelper.prototype.update = function () { + if ( (bone.parent && bone.parent.isBone) ) { - var geometry = this.geometry; + boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld ); + geometry.vertices[ j ].setFromMatrixPosition( boneMatrix ); - var matrixWorldInv = new Matrix4().getInverse( this.root.matrixWorld ); + boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld ); + geometry.vertices[ j + 1 ].setFromMatrixPosition( boneMatrix ); - var boneMatrix = new Matrix4(); + j += 2; - var j = 0; + } - for ( var i = 0; i < this.bones.length; i ++ ) { + } - var bone = this.bones[ i ]; + geometry.verticesNeedUpdate = true; - if ( (bone.parent && bone.parent.isBone) ) { + geometry.computeBoundingSphere(); - boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld ); - geometry.vertices[ j ].setFromMatrixPosition( boneMatrix ); + }; - boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld ); - geometry.vertices[ j + 1 ].setFromMatrixPosition( boneMatrix ); + /** + * @author benaadams / https://twitter.com/ben_a_adams + * based on THREE.SphereGeometry + */ - j += 2; + function SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) { - } + BufferGeometry.call( this ); - } + this.type = 'SphereBufferGeometry'; - geometry.verticesNeedUpdate = true; + this.parameters = { + radius: radius, + widthSegments: widthSegments, + heightSegments: heightSegments, + phiStart: phiStart, + phiLength: phiLength, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - geometry.computeBoundingSphere(); + radius = radius || 50; - }; + widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 ); + heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 ); - /** - * @author benaadams / https://twitter.com/ben_a_adams - * based on THREE.SphereGeometry - */ + phiStart = phiStart !== undefined ? phiStart : 0; + phiLength = phiLength !== undefined ? phiLength : Math.PI * 2; - function SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) { + thetaStart = thetaStart !== undefined ? thetaStart : 0; + thetaLength = thetaLength !== undefined ? thetaLength : Math.PI; - BufferGeometry.call( this ); + var thetaEnd = thetaStart + thetaLength; - this.type = 'SphereBufferGeometry'; + var vertexCount = ( ( widthSegments + 1 ) * ( heightSegments + 1 ) ); - this.parameters = { - radius: radius, - widthSegments: widthSegments, - heightSegments: heightSegments, - phiStart: phiStart, - phiLength: phiLength, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + 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 ); - radius = radius || 50; + var index = 0, vertices = [], normal = new Vector3(); - widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 ); - heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 ); + for ( var y = 0; y <= heightSegments; y ++ ) { - phiStart = phiStart !== undefined ? phiStart : 0; - phiLength = phiLength !== undefined ? phiLength : Math.PI * 2; + var verticesRow = []; - thetaStart = thetaStart !== undefined ? thetaStart : 0; - thetaLength = thetaLength !== undefined ? thetaLength : Math.PI; + var v = y / heightSegments; - var thetaEnd = thetaStart + thetaLength; + for ( var x = 0; x <= widthSegments; x ++ ) { - var vertexCount = ( ( widthSegments + 1 ) * ( heightSegments + 1 ) ); + var u = x / widthSegments; - 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 ); + 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 index = 0, vertices = [], normal = new Vector3(); + normal.set( px, py, pz ).normalize(); - for ( var y = 0; y <= heightSegments; y ++ ) { + positions.setXYZ( index, px, py, pz ); + normals.setXYZ( index, normal.x, normal.y, normal.z ); + uvs.setXY( index, u, 1 - v ); - var verticesRow = []; + verticesRow.push( index ); - var v = y / heightSegments; + index ++; - for ( var x = 0; x <= widthSegments; x ++ ) { + } - var u = x / widthSegments; + vertices.push( verticesRow ); - 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(); + var indices = []; - positions.setXYZ( index, px, py, pz ); - normals.setXYZ( index, normal.x, normal.y, normal.z ); - uvs.setXY( index, u, 1 - v ); + for ( var y = 0; y < heightSegments; y ++ ) { - verticesRow.push( index ); + for ( var x = 0; x < widthSegments; x ++ ) { - index ++; + 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 ); - vertices.push( verticesRow ); + } - } + } - var indices = []; + this.setIndex( new ( positions.count > 65535 ? Uint32Attribute : Uint16Attribute )( indices, 1 ) ); + this.addAttribute( 'position', positions ); + this.addAttribute( 'normal', normals ); + this.addAttribute( 'uv', uvs ); - for ( var y = 0; y < heightSegments; y ++ ) { + this.boundingSphere = new Sphere( new Vector3(), radius ); - for ( var x = 0; x < widthSegments; x ++ ) { + }; - var v1 = vertices[ y ][ x + 1 ]; - var v2 = vertices[ y ][ x ]; - var v3 = vertices[ y + 1 ][ x ]; - var v4 = vertices[ y + 1 ][ x + 1 ]; + SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + SphereBufferGeometry.prototype.constructor = SphereBufferGeometry; - if ( y !== 0 || thetaStart > 0 ) indices.push( v1, v2, v4 ); - if ( y !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( v2, v3, v4 ); + /** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + */ - } + function PointLightHelper( light, sphereSize ) { - } + this.light = light; + this.light.updateMatrixWorld(); - this.setIndex( new ( positions.count > 65535 ? Uint32Attribute : Uint16Attribute )( indices, 1 ) ); - this.addAttribute( 'position', positions ); - this.addAttribute( 'normal', normals ); - this.addAttribute( 'uv', uvs ); + 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 ); - this.boundingSphere = new Sphere( new Vector3(), radius ); + Mesh.call( this, geometry, material ); - }; + this.matrix = this.light.matrixWorld; + this.matrixAutoUpdate = false; - SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); - SphereBufferGeometry.prototype.constructor = SphereBufferGeometry; + /* + var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 ); + var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } ); - /** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - */ + this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial ); + this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial ); - function PointLightHelper( light, sphereSize ) { + var d = light.distance; - this.light = light; - this.light.updateMatrixWorld(); + if ( d === 0.0 ) { - 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 ); + this.lightDistance.visible = false; - Mesh.call( this, geometry, material ); + } else { - this.matrix = this.light.matrixWorld; - this.matrixAutoUpdate = false; + this.lightDistance.scale.set( d, d, d ); - /* - var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 ); - var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } ); + } - this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial ); - this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial ); + this.add( this.lightDistance ); + */ - var d = light.distance; + }; - if ( d === 0.0 ) { + PointLightHelper.prototype = Object.create( Mesh.prototype ); + PointLightHelper.prototype.constructor = PointLightHelper; - this.lightDistance.visible = false; + PointLightHelper.prototype.dispose = function () { - } else { + this.geometry.dispose(); + this.material.dispose(); - this.lightDistance.scale.set( d, d, d ); + }; - } + PointLightHelper.prototype.update = function () { - this.add( this.lightDistance ); - */ + this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); - }; + /* + var d = this.light.distance; - PointLightHelper.prototype = Object.create( Mesh.prototype ); - PointLightHelper.prototype.constructor = PointLightHelper; + if ( d === 0.0 ) { - PointLightHelper.prototype.dispose = function () { + this.lightDistance.visible = false; - this.geometry.dispose(); - this.material.dispose(); + } else { - }; + this.lightDistance.visible = true; + this.lightDistance.scale.set( d, d, d ); - PointLightHelper.prototype.update = function () { + } + */ - this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); + }; - /* - var d = this.light.distance; + /** + * @author mrdoob / http://mrdoob.com/ + */ - if ( d === 0.0 ) { + function SphereGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) { - this.lightDistance.visible = false; + Geometry.call( this ); - } else { + this.type = 'SphereGeometry'; - this.lightDistance.visible = true; - this.lightDistance.scale.set( d, d, d ); + this.parameters = { + radius: radius, + widthSegments: widthSegments, + heightSegments: heightSegments, + phiStart: phiStart, + phiLength: phiLength, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - } - */ + this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) ); - }; + }; - /** - * @author mrdoob / http://mrdoob.com/ - */ + SphereGeometry.prototype = Object.create( Geometry.prototype ); + SphereGeometry.prototype.constructor = SphereGeometry; - function SphereGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) { + /** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + */ - Geometry.call( this ); + function HemisphereLightHelper( light, sphereSize ) { - this.type = 'SphereGeometry'; + Object3D.call( this ); - this.parameters = { - radius: radius, - widthSegments: widthSegments, - heightSegments: heightSegments, - phiStart: phiStart, - phiLength: phiLength, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + this.light = light; + this.light.updateMatrixWorld(); - this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) ); + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; - }; + this.colors = [ new Color(), new Color() ]; - SphereGeometry.prototype = Object.create( Geometry.prototype ); - SphereGeometry.prototype.constructor = SphereGeometry; + var geometry = new SphereGeometry( sphereSize, 4, 2 ); + geometry.rotateX( - Math.PI / 2 ); - /** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - */ + for ( var i = 0, il = 8; i < il; i ++ ) { - function HemisphereLightHelper( light, sphereSize ) { + geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ]; - Object3D.call( this ); + } - this.light = light; - this.light.updateMatrixWorld(); + var material = new MeshBasicMaterial( { vertexColors: FaceColors, wireframe: true } ); - this.matrix = light.matrixWorld; - this.matrixAutoUpdate = false; + this.lightSphere = new Mesh( geometry, material ); + this.add( this.lightSphere ); - this.colors = [ new Color(), new Color() ]; + this.update(); - var geometry = new SphereGeometry( sphereSize, 4, 2 ); - geometry.rotateX( - Math.PI / 2 ); + }; - for ( var i = 0, il = 8; i < il; i ++ ) { + HemisphereLightHelper.prototype = Object.create( Object3D.prototype ); + HemisphereLightHelper.prototype.constructor = HemisphereLightHelper; - geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ]; + HemisphereLightHelper.prototype.dispose = function () { - } + this.lightSphere.geometry.dispose(); + this.lightSphere.material.dispose(); - var material = new MeshBasicMaterial( { vertexColors: FaceColors, wireframe: true } ); + }; - this.lightSphere = new Mesh( geometry, material ); - this.add( this.lightSphere ); + HemisphereLightHelper.prototype.update = function () { - this.update(); + var vector = new Vector3(); - }; + return function update() { - HemisphereLightHelper.prototype = Object.create( Object3D.prototype ); - HemisphereLightHelper.prototype.constructor = HemisphereLightHelper; + this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity ); + this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity ); - HemisphereLightHelper.prototype.dispose = function () { + this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() ); + this.lightSphere.geometry.colorsNeedUpdate = true; - this.lightSphere.geometry.dispose(); - this.lightSphere.material.dispose(); + }; - }; + }(); - HemisphereLightHelper.prototype.update = function () { + /** + * @author mrdoob / http://mrdoob.com/ + */ - var vector = new Vector3(); + function GridHelper( size, divisions, color1, color2 ) { - return function update() { + divisions = divisions || 1; + color1 = new Color( color1 !== undefined ? color1 : 0x444444 ); + color2 = new Color( color2 !== undefined ? color2 : 0x888888 ); - this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity ); - this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity ); + var center = divisions / 2; + var step = ( size * 2 ) / divisions; + var vertices = [], colors = []; - this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() ); - this.lightSphere.geometry.colorsNeedUpdate = true; + for ( var i = 0, j = 0, k = - size; i <= divisions; i ++, k += step ) { - }; + vertices.push( - size, 0, k, size, 0, k ); + vertices.push( k, 0, - size, k, 0, size ); - }(); + var color = i === center ? color1 : color2; - /** - * @author mrdoob / http://mrdoob.com/ - */ + color.toArray( colors, j ); j += 3; + color.toArray( colors, j ); j += 3; + color.toArray( colors, j ); j += 3; + color.toArray( colors, j ); j += 3; - function GridHelper( size, divisions, color1, color2 ) { + } - divisions = divisions || 1; - color1 = new Color( color1 !== undefined ? color1 : 0x444444 ); - color2 = new Color( color2 !== undefined ? color2 : 0x888888 ); + var geometry = new BufferGeometry(); + geometry.addAttribute( 'position', new Float32Attribute( vertices, 3 ) ); + geometry.addAttribute( 'color', new Float32Attribute( colors, 3 ) ); - var center = divisions / 2; - var step = ( size * 2 ) / divisions; - var vertices = [], colors = []; + var material = new LineBasicMaterial( { vertexColors: VertexColors } ); - for ( var i = 0, j = 0, k = - size; i <= divisions; i ++, k += step ) { + LineSegments.call( this, geometry, material ); - vertices.push( - size, 0, k, size, 0, k ); - vertices.push( k, 0, - size, k, 0, size ); + }; - var color = i === center ? color1 : color2; + GridHelper.prototype = Object.create( LineSegments.prototype ); + GridHelper.prototype.constructor = GridHelper; - 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.setColors = function () { - } + console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' ); - var geometry = new BufferGeometry(); - geometry.addAttribute( 'position', new Float32Attribute( vertices, 3 ) ); - geometry.addAttribute( 'color', new Float32Attribute( colors, 3 ) ); + }; - var material = new LineBasicMaterial( { vertexColors: VertexColors } ); + /** + * @author mrdoob / http://mrdoob.com/ + * @author WestLangley / http://github.com/WestLangley + */ - LineSegments.call( this, geometry, material ); + function FaceNormalsHelper( object, size, hex, linewidth ) { - }; + // FaceNormalsHelper only supports THREE.Geometry - GridHelper.prototype = Object.create( LineSegments.prototype ); - GridHelper.prototype.constructor = GridHelper; + this.object = object; - GridHelper.prototype.setColors = function () { + this.size = ( size !== undefined ) ? size : 1; - console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' ); + var color = ( hex !== undefined ) ? hex : 0xffff00; - }; + var width = ( linewidth !== undefined ) ? linewidth : 1; - /** - * @author mrdoob / http://mrdoob.com/ - * @author WestLangley / http://github.com/WestLangley - */ + // - function FaceNormalsHelper( object, size, hex, linewidth ) { + var nNormals = 0; - // FaceNormalsHelper only supports THREE.Geometry + var objGeometry = this.object.geometry; - this.object = object; + if ( (objGeometry && objGeometry.isGeometry) ) { - this.size = ( size !== undefined ) ? size : 1; + nNormals = objGeometry.faces.length; - var color = ( hex !== undefined ) ? hex : 0xffff00; + } else { - var width = ( linewidth !== undefined ) ? linewidth : 1; + console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' ); - // + } - var nNormals = 0; + // - var objGeometry = this.object.geometry; + var geometry = new BufferGeometry(); - if ( (objGeometry && objGeometry.isGeometry) ) { + var positions = new Float32Attribute( nNormals * 2 * 3, 3 ); - nNormals = objGeometry.faces.length; + geometry.addAttribute( 'position', positions ); - } else { + LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) ); - console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' ); + // - } + this.matrixAutoUpdate = false; + this.update(); - // + }; - var geometry = new BufferGeometry(); + FaceNormalsHelper.prototype = Object.create( LineSegments.prototype ); + FaceNormalsHelper.prototype.constructor = FaceNormalsHelper; - var positions = new Float32Attribute( nNormals * 2 * 3, 3 ); + FaceNormalsHelper.prototype.update = ( function () { - geometry.addAttribute( 'position', positions ); + var v1 = new Vector3(); + var v2 = new Vector3(); + var normalMatrix = new Matrix3(); - LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) ); + return function update() { - // + this.object.updateMatrixWorld( true ); - this.matrixAutoUpdate = false; - this.update(); + normalMatrix.getNormalMatrix( this.object.matrixWorld ); - }; + var matrixWorld = this.object.matrixWorld; - FaceNormalsHelper.prototype = Object.create( LineSegments.prototype ); - FaceNormalsHelper.prototype.constructor = FaceNormalsHelper; + var position = this.geometry.attributes.position; - FaceNormalsHelper.prototype.update = ( function () { + // - var v1 = new Vector3(); - var v2 = new Vector3(); - var normalMatrix = new Matrix3(); + var objGeometry = this.object.geometry; - return function update() { + var vertices = objGeometry.vertices; - this.object.updateMatrixWorld( true ); + var faces = objGeometry.faces; - normalMatrix.getNormalMatrix( this.object.matrixWorld ); + var idx = 0; - var matrixWorld = this.object.matrixWorld; + for ( var i = 0, l = faces.length; i < l; i ++ ) { - var position = this.geometry.attributes.position; + var face = faces[ i ]; - // + var normal = face.normal; - var objGeometry = this.object.geometry; + v1.copy( vertices[ face.a ] ) + .add( vertices[ face.b ] ) + .add( vertices[ face.c ] ) + .divideScalar( 3 ) + .applyMatrix4( matrixWorld ); - var vertices = objGeometry.vertices; + v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 ); - var faces = objGeometry.faces; + position.setXYZ( idx, v1.x, v1.y, v1.z ); - var idx = 0; + idx = idx + 1; - for ( var i = 0, l = faces.length; i < l; i ++ ) { + position.setXYZ( idx, v2.x, v2.y, v2.z ); - var face = faces[ i ]; + idx = idx + 1; - var normal = face.normal; + } - v1.copy( vertices[ face.a ] ) - .add( vertices[ face.b ] ) - .add( vertices[ face.c ] ) - .divideScalar( 3 ) - .applyMatrix4( matrixWorld ); + position.needsUpdate = true; - v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 ); + return this; - position.setXYZ( idx, v1.x, v1.y, v1.z ); + }; - idx = idx + 1; + }() ); - position.setXYZ( idx, v2.x, v2.y, v2.z ); + /** + * @author WestLangley / http://github.com/WestLangley + */ - idx = idx + 1; + function EdgesGeometry( geometry, thresholdAngle ) { - } + BufferGeometry.call( this ); - position.needsUpdate = true; + thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1; - return this; + var thresholdDot = Math.cos( exports.Math.DEG2RAD * thresholdAngle ); - }; + var edge = [ 0, 0 ], hash = {}; - }() ); + function sortFunction( a, b ) { - /** - * @author WestLangley / http://github.com/WestLangley - */ + return a - b; - function EdgesGeometry( geometry, thresholdAngle ) { + } - BufferGeometry.call( this ); + var keys = [ 'a', 'b', 'c' ]; - thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1; + var geometry2; - var thresholdDot = Math.cos( exports.Math.DEG2RAD * thresholdAngle ); + if ( (geometry && geometry.isBufferGeometry) ) { - var edge = [ 0, 0 ], hash = {}; + geometry2 = new Geometry(); + geometry2.fromBufferGeometry( geometry ); - function sortFunction( a, b ) { + } else { - return a - b; + geometry2 = geometry.clone(); - } + } - var keys = [ 'a', 'b', 'c' ]; + geometry2.mergeVertices(); + geometry2.computeFaceNormals(); - var geometry2; + var vertices = geometry2.vertices; + var faces = geometry2.faces; - if ( (geometry && geometry.isBufferGeometry) ) { + for ( var i = 0, l = faces.length; i < l; i ++ ) { - geometry2 = new Geometry(); - geometry2.fromBufferGeometry( geometry ); + var face = faces[ i ]; - } else { + for ( var j = 0; j < 3; j ++ ) { - geometry2 = geometry.clone(); + edge[ 0 ] = face[ keys[ j ] ]; + edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ]; + edge.sort( sortFunction ); - } + var key = edge.toString(); - geometry2.mergeVertices(); - geometry2.computeFaceNormals(); + if ( hash[ key ] === undefined ) { - var vertices = geometry2.vertices; - var faces = geometry2.faces; + hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined }; - for ( var i = 0, l = faces.length; i < l; i ++ ) { + } else { - var face = faces[ i ]; + hash[ key ].face2 = i; - 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 = []; - hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined }; + for ( var key in hash ) { - } else { + var h = hash[ key ]; - hash[ key ].face2 = i; + 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 ); - } + vertex = vertices[ h.vert2 ]; + coords.push( vertex.x ); + coords.push( vertex.y ); + coords.push( vertex.z ); - } + } - var coords = []; + } - for ( var key in hash ) { + this.addAttribute( 'position', new BufferAttribute( new Float32Array( coords ), 3 ) ); - var h = hash[ key ]; + }; - if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) <= thresholdDot ) { + EdgesGeometry.prototype = Object.create( BufferGeometry.prototype ); + EdgesGeometry.prototype.constructor = EdgesGeometry; - var vertex = vertices[ h.vert1 ]; - coords.push( vertex.x ); - coords.push( vertex.y ); - coords.push( vertex.z ); + /** + * @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. + */ - vertex = vertices[ h.vert2 ]; - coords.push( vertex.x ); - coords.push( vertex.y ); - coords.push( vertex.z ); + function EdgesHelper( object, hex, thresholdAngle ) { - } + var color = ( hex !== undefined ) ? hex : 0xffffff; - } + LineSegments.call( this, new EdgesGeometry( object.geometry, thresholdAngle ), new LineBasicMaterial( { color: color } ) ); - this.addAttribute( 'position', new BufferAttribute( new Float32Array( coords ), 3 ) ); + this.matrix = object.matrixWorld; + this.matrixAutoUpdate = false; - }; + }; - EdgesGeometry.prototype = Object.create( BufferGeometry.prototype ); - EdgesGeometry.prototype.constructor = EdgesGeometry; + EdgesHelper.prototype = Object.create( LineSegments.prototype ); + EdgesHelper.prototype.constructor = EdgesHelper; - /** - * @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. - */ + /** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + * @author WestLangley / http://github.com/WestLangley + */ - function EdgesHelper( object, hex, thresholdAngle ) { + function DirectionalLightHelper( light, size ) { - var color = ( hex !== undefined ) ? hex : 0xffffff; + Object3D.call( this ); - LineSegments.call( this, new EdgesGeometry( object.geometry, thresholdAngle ), new LineBasicMaterial( { color: color } ) ); + this.light = light; + this.light.updateMatrixWorld(); - this.matrix = object.matrixWorld; - this.matrixAutoUpdate = false; + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; - }; + if ( size === undefined ) size = 1; - EdgesHelper.prototype = Object.create( LineSegments.prototype ); - EdgesHelper.prototype.constructor = EdgesHelper; + 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 ) ); - /** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - * @author WestLangley / http://github.com/WestLangley - */ + var material = new LineBasicMaterial( { fog: false } ); - function DirectionalLightHelper( light, size ) { + this.add( new Line( geometry, material ) ); - Object3D.call( this ); + geometry = new BufferGeometry(); + geometry.addAttribute( 'position', new Float32Attribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) ); - this.light = light; - this.light.updateMatrixWorld(); + this.add( new Line( geometry, material )); - this.matrix = light.matrixWorld; - this.matrixAutoUpdate = false; + this.update(); - if ( size === undefined ) size = 1; + }; - 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 ) ); + DirectionalLightHelper.prototype = Object.create( Object3D.prototype ); + DirectionalLightHelper.prototype.constructor = DirectionalLightHelper; - var material = new LineBasicMaterial( { fog: false } ); + DirectionalLightHelper.prototype.dispose = function () { - this.add( new Line( geometry, material ) ); + var lightPlane = this.children[ 0 ]; + var targetLine = this.children[ 1 ]; - geometry = new BufferGeometry(); - geometry.addAttribute( 'position', new Float32Attribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) ); + lightPlane.geometry.dispose(); + lightPlane.material.dispose(); + targetLine.geometry.dispose(); + targetLine.material.dispose(); - this.add( new Line( geometry, material )); + }; - this.update(); + DirectionalLightHelper.prototype.update = function () { - }; + var v1 = new Vector3(); + var v2 = new Vector3(); + var v3 = new Vector3(); - DirectionalLightHelper.prototype = Object.create( Object3D.prototype ); - DirectionalLightHelper.prototype.constructor = DirectionalLightHelper; + return function update() { - DirectionalLightHelper.prototype.dispose = function () { + 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 ]; + var lightPlane = this.children[ 0 ]; + var targetLine = this.children[ 1 ]; - lightPlane.geometry.dispose(); - lightPlane.material.dispose(); - targetLine.geometry.dispose(); - targetLine.material.dispose(); + lightPlane.lookAt( v3 ); + lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); - }; + targetLine.lookAt( v3 ); + targetLine.scale.z = v3.length(); - DirectionalLightHelper.prototype.update = function () { + }; - var v1 = new Vector3(); - var v2 = new Vector3(); - var v3 = new Vector3(); + }(); - return function update() { + /** + * @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 + */ - v1.setFromMatrixPosition( this.light.matrixWorld ); - v2.setFromMatrixPosition( this.light.target.matrixWorld ); - v3.subVectors( v2, v1 ); + function CameraHelper( camera ) { - var lightPlane = this.children[ 0 ]; - var targetLine = this.children[ 1 ]; + var geometry = new Geometry(); + var material = new LineBasicMaterial( { color: 0xffffff, vertexColors: FaceColors } ); - lightPlane.lookAt( v3 ); - lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); + var pointMap = {}; - targetLine.lookAt( v3 ); - targetLine.scale.z = v3.length(); + // colors - }; + var hexFrustum = 0xffaa00; + var hexCone = 0xff0000; + var hexUp = 0x00aaff; + var hexTarget = 0xffffff; + var hexCross = 0x333333; - }(); + // near - /** - * @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 - */ + addLine( "n1", "n2", hexFrustum ); + addLine( "n2", "n4", hexFrustum ); + addLine( "n4", "n3", hexFrustum ); + addLine( "n3", "n1", hexFrustum ); - function CameraHelper( camera ) { + // far - var geometry = new Geometry(); - var material = new LineBasicMaterial( { color: 0xffffff, vertexColors: FaceColors } ); + addLine( "f1", "f2", hexFrustum ); + addLine( "f2", "f4", hexFrustum ); + addLine( "f4", "f3", hexFrustum ); + addLine( "f3", "f1", hexFrustum ); - var pointMap = {}; + // sides - // colors + addLine( "n1", "f1", hexFrustum ); + addLine( "n2", "f2", hexFrustum ); + addLine( "n3", "f3", hexFrustum ); + addLine( "n4", "f4", hexFrustum ); - var hexFrustum = 0xffaa00; - var hexCone = 0xff0000; - var hexUp = 0x00aaff; - var hexTarget = 0xffffff; - var hexCross = 0x333333; + // cone - // near + addLine( "p", "n1", hexCone ); + addLine( "p", "n2", hexCone ); + addLine( "p", "n3", hexCone ); + addLine( "p", "n4", hexCone ); - addLine( "n1", "n2", hexFrustum ); - addLine( "n2", "n4", hexFrustum ); - addLine( "n4", "n3", hexFrustum ); - addLine( "n3", "n1", hexFrustum ); + // up - // far + addLine( "u1", "u2", hexUp ); + addLine( "u2", "u3", hexUp ); + addLine( "u3", "u1", hexUp ); - addLine( "f1", "f2", hexFrustum ); - addLine( "f2", "f4", hexFrustum ); - addLine( "f4", "f3", hexFrustum ); - addLine( "f3", "f1", hexFrustum ); + // target - // sides + addLine( "c", "t", hexTarget ); + addLine( "p", "c", hexCross ); - addLine( "n1", "f1", hexFrustum ); - addLine( "n2", "f2", hexFrustum ); - addLine( "n3", "f3", hexFrustum ); - addLine( "n4", "f4", hexFrustum ); + // cross - // cone + addLine( "cn1", "cn2", hexCross ); + addLine( "cn3", "cn4", hexCross ); - addLine( "p", "n1", hexCone ); - addLine( "p", "n2", hexCone ); - addLine( "p", "n3", hexCone ); - addLine( "p", "n4", hexCone ); + addLine( "cf1", "cf2", hexCross ); + addLine( "cf3", "cf4", hexCross ); - // up + function addLine( a, b, hex ) { - addLine( "u1", "u2", hexUp ); - addLine( "u2", "u3", hexUp ); - addLine( "u3", "u1", hexUp ); + addPoint( a, hex ); + addPoint( b, hex ); - // target + } - addLine( "c", "t", hexTarget ); - addLine( "p", "c", hexCross ); + function addPoint( id, hex ) { - // cross + geometry.vertices.push( new Vector3() ); + geometry.colors.push( new Color( hex ) ); - addLine( "cn1", "cn2", hexCross ); - addLine( "cn3", "cn4", hexCross ); + if ( pointMap[ id ] === undefined ) { - addLine( "cf1", "cf2", hexCross ); - addLine( "cf3", "cf4", hexCross ); + pointMap[ id ] = []; - function addLine( a, b, hex ) { + } - addPoint( a, hex ); - addPoint( b, hex ); + pointMap[ id ].push( geometry.vertices.length - 1 ); - } + } - function addPoint( id, hex ) { + LineSegments.call( this, geometry, material ); - geometry.vertices.push( new Vector3() ); - geometry.colors.push( new Color( hex ) ); + this.camera = camera; + if( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix(); - if ( pointMap[ id ] === undefined ) { + this.matrix = camera.matrixWorld; + this.matrixAutoUpdate = false; - pointMap[ id ] = []; + this.pointMap = pointMap; - } + this.update(); - pointMap[ id ].push( geometry.vertices.length - 1 ); + }; - } + CameraHelper.prototype = Object.create( LineSegments.prototype ); + CameraHelper.prototype.constructor = CameraHelper; - LineSegments.call( this, geometry, material ); + CameraHelper.prototype.update = function () { - this.camera = camera; - if( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix(); + var geometry, pointMap; - this.matrix = camera.matrixWorld; - this.matrixAutoUpdate = false; + var vector = new Vector3(); + var camera = new Camera(); - this.pointMap = pointMap; + function setPoint( point, x, y, z ) { - this.update(); + vector.set( x, y, z ).unproject( camera ); - }; + var points = pointMap[ point ]; - CameraHelper.prototype = Object.create( LineSegments.prototype ); - CameraHelper.prototype.constructor = CameraHelper; + if ( points !== undefined ) { - CameraHelper.prototype.update = function () { + for ( var i = 0, il = points.length; i < il; i ++ ) { - var geometry, pointMap; + geometry.vertices[ points[ i ] ].copy( vector ); - var vector = new Vector3(); - var camera = new Camera(); + } - function setPoint( point, x, y, z ) { + } - vector.set( x, y, z ).unproject( camera ); + } - var points = pointMap[ point ]; + return function update() { - if ( points !== undefined ) { + geometry = this.geometry; + pointMap = this.pointMap; - for ( var i = 0, il = points.length; i < il; i ++ ) { + var w = 1, h = 1; - geometry.vertices[ points[ i ] ].copy( vector ); + // we need just camera projection matrix + // world matrix must be identity - } + camera.projectionMatrix.copy( this.camera.projectionMatrix ); - } + // center / target - } + setPoint( "c", 0, 0, - 1 ); + setPoint( "t", 0, 0, 1 ); - return function update() { + // near - geometry = this.geometry; - pointMap = this.pointMap; + setPoint( "n1", - w, - h, - 1 ); + setPoint( "n2", w, - h, - 1 ); + setPoint( "n3", - w, h, - 1 ); + setPoint( "n4", w, h, - 1 ); - var w = 1, h = 1; + // far - // we need just camera projection matrix - // world matrix must be identity + setPoint( "f1", - w, - h, 1 ); + setPoint( "f2", w, - h, 1 ); + setPoint( "f3", - w, h, 1 ); + setPoint( "f4", w, h, 1 ); - camera.projectionMatrix.copy( this.camera.projectionMatrix ); + // up - // center / target + 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( "c", 0, 0, - 1 ); - setPoint( "t", 0, 0, 1 ); + // cross - // near + setPoint( "cf1", - w, 0, 1 ); + setPoint( "cf2", w, 0, 1 ); + setPoint( "cf3", 0, - h, 1 ); + setPoint( "cf4", 0, h, 1 ); - setPoint( "n1", - w, - h, - 1 ); - setPoint( "n2", w, - h, - 1 ); - setPoint( "n3", - w, h, - 1 ); - setPoint( "n4", w, h, - 1 ); + setPoint( "cn1", - w, 0, - 1 ); + setPoint( "cn2", w, 0, - 1 ); + setPoint( "cn3", 0, - h, - 1 ); + setPoint( "cn4", 0, h, - 1 ); - // far + geometry.verticesNeedUpdate = true; - setPoint( "f1", - w, - h, 1 ); - setPoint( "f2", w, - h, 1 ); - setPoint( "f3", - w, h, 1 ); - setPoint( "f4", w, h, 1 ); + }; - // up + }(); - setPoint( "u1", w * 0.7, h * 1.1, - 1 ); - setPoint( "u2", - w * 0.7, h * 1.1, - 1 ); - setPoint( "u3", 0, h * 2, - 1 ); + /** + * @author mrdoob / http://mrdoob.com/ + * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as + */ - // cross + function BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) { - setPoint( "cf1", - w, 0, 1 ); - setPoint( "cf2", w, 0, 1 ); - setPoint( "cf3", 0, - h, 1 ); - setPoint( "cf4", 0, h, 1 ); + Geometry.call( this ); - setPoint( "cn1", - w, 0, - 1 ); - setPoint( "cn2", w, 0, - 1 ); - setPoint( "cn3", 0, - h, - 1 ); - setPoint( "cn4", 0, h, - 1 ); + this.type = 'BoxGeometry'; - geometry.verticesNeedUpdate = true; + this.parameters = { + width: width, + height: height, + depth: depth, + widthSegments: widthSegments, + heightSegments: heightSegments, + depthSegments: depthSegments + }; - }; + this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) ); + this.mergeVertices(); - }(); + }; - /** - * @author mrdoob / http://mrdoob.com/ - * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as - */ + BoxGeometry.prototype = Object.create( Geometry.prototype ); + BoxGeometry.prototype.constructor = BoxGeometry; - function BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) { + exports.CubeGeometry = BoxGeometry; - Geometry.call( this ); + /** + * @author WestLangley / http://github.com/WestLangley + */ - this.type = 'BoxGeometry'; + // a helper to show the world-axis-aligned bounding box for an object - this.parameters = { - width: width, - height: height, - depth: depth, - widthSegments: widthSegments, - heightSegments: heightSegments, - depthSegments: depthSegments - }; + function BoundingBoxHelper( object, hex ) { - this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) ); - this.mergeVertices(); + var color = ( hex !== undefined ) ? hex : 0x888888; - }; + this.object = object; - BoxGeometry.prototype = Object.create( Geometry.prototype ); - BoxGeometry.prototype.constructor = BoxGeometry; + this.box = new Box3(); - exports.CubeGeometry = BoxGeometry; + Mesh.call( this, new BoxGeometry( 1, 1, 1 ), new MeshBasicMaterial( { color: color, wireframe: true } ) ); - /** - * @author WestLangley / http://github.com/WestLangley - */ + }; - // a helper to show the world-axis-aligned bounding box for an object + BoundingBoxHelper.prototype = Object.create( Mesh.prototype ); + BoundingBoxHelper.prototype.constructor = BoundingBoxHelper; - function BoundingBoxHelper( object, hex ) { + BoundingBoxHelper.prototype.update = function () { - var color = ( hex !== undefined ) ? hex : 0x888888; + this.box.setFromObject( this.object ); - this.object = object; + this.box.size( this.scale ); - this.box = new Box3(); + this.box.center( this.position ); - Mesh.call( this, new BoxGeometry( 1, 1, 1 ), new MeshBasicMaterial( { color: color, wireframe: true } ) ); + }; - }; + /** + * @author mrdoob / http://mrdoob.com/ + */ - BoundingBoxHelper.prototype = Object.create( Mesh.prototype ); - BoundingBoxHelper.prototype.constructor = BoundingBoxHelper; + function BoxHelper( object, color ) { - BoundingBoxHelper.prototype.update = function () { + if ( color === undefined ) color = 0xffff00; - this.box.setFromObject( this.object ); + 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.size( this.scale ); + var geometry = new BufferGeometry(); + geometry.setIndex( new BufferAttribute( indices, 1 ) ); + geometry.addAttribute( 'position', new BufferAttribute( positions, 3 ) ); - this.box.center( this.position ); + LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) ); - }; + if ( object !== undefined ) { - /** - * @author mrdoob / http://mrdoob.com/ - */ + this.update( object ); - function BoxHelper( object, color ) { + } - 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 ); + BoxHelper.prototype = Object.create( LineSegments.prototype ); + BoxHelper.prototype.constructor = BoxHelper; - var geometry = new BufferGeometry(); - geometry.setIndex( new BufferAttribute( indices, 1 ) ); - geometry.addAttribute( 'position', new BufferAttribute( positions, 3 ) ); + BoxHelper.prototype.update = ( function () { - LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) ); + var box = new Box3(); - if ( object !== undefined ) { + return function update( object ) { - this.update( object ); + if ( (object && object.isBox3) ) { - } + box.copy( object ); - }; + } else { - BoxHelper.prototype = Object.create( LineSegments.prototype ); - BoxHelper.prototype.constructor = BoxHelper; + box.setFromObject( object ); - BoxHelper.prototype.update = ( function () { + } - var box = new Box3(); + if ( box.isEmpty() ) return; - return function update( object ) { + var min = box.min; + var max = box.max; - if ( (object && object.isBox3) ) { + /* + 5____4 + 1/___0/| + | 6__|_7 + 2/___3/ - box.copy( object ); + 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 + */ - } else { + var position = this.geometry.attributes.position; + var array = position.array; - box.setFromObject( object ); + 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; - } + position.needsUpdate = true; - if ( box.isEmpty() ) return; + this.geometry.computeBoundingSphere(); - var min = box.min; - var max = box.max; + }; - /* - 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 - */ + /** + * @author Mugen87 / https://github.com/Mugen87 + */ - var position = this.geometry.attributes.position; - var array = position.array; + function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { - 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; + BufferGeometry.call( this ); - position.needsUpdate = true; + this.type = 'CylinderBufferGeometry'; - this.geometry.computeBoundingSphere(); + this.parameters = { + radiusTop: radiusTop, + radiusBottom: radiusBottom, + height: height, + radialSegments: radialSegments, + heightSegments: heightSegments, + openEnded: openEnded, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - }; + var scope = this; - } )(); + radiusTop = radiusTop !== undefined ? radiusTop : 20; + radiusBottom = radiusBottom !== undefined ? radiusBottom : 20; + height = height !== undefined ? height : 100; - /** - * @author Mugen87 / https://github.com/Mugen87 - */ + radialSegments = Math.floor( radialSegments ) || 8; + heightSegments = Math.floor( heightSegments ) || 1; - function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { + openEnded = openEnded !== undefined ? openEnded : false; + thetaStart = thetaStart !== undefined ? thetaStart : 0.0; + thetaLength = thetaLength !== undefined ? thetaLength : 2.0 * Math.PI; - BufferGeometry.call( this ); + // used to calculate buffer length - this.type = 'CylinderBufferGeometry'; + var nbCap = 0; - this.parameters = { - radiusTop: radiusTop, - radiusBottom: radiusBottom, - height: height, - radialSegments: radialSegments, - heightSegments: heightSegments, - openEnded: openEnded, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + if ( openEnded === false ) { - var scope = this; + if ( radiusTop > 0 ) nbCap ++; + if ( radiusBottom > 0 ) nbCap ++; - radiusTop = radiusTop !== undefined ? radiusTop : 20; - radiusBottom = radiusBottom !== undefined ? radiusBottom : 20; - height = height !== undefined ? height : 100; + } - radialSegments = Math.floor( radialSegments ) || 8; - heightSegments = Math.floor( heightSegments ) || 1; + var vertexCount = calculateVertexCount(); + var indexCount = calculateIndexCount(); - openEnded = openEnded !== undefined ? openEnded : false; - thetaStart = thetaStart !== undefined ? thetaStart : 0.0; - thetaLength = thetaLength !== undefined ? thetaLength : 2.0 * Math.PI; + // buffers - // used to calculate buffer length + 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 ); - var nbCap = 0; + // helper variables - if ( openEnded === false ) { + var index = 0, + indexOffset = 0, + indexArray = [], + halfHeight = height / 2; - if ( radiusTop > 0 ) nbCap ++; - if ( radiusBottom > 0 ) nbCap ++; + // group variables + var groupStart = 0; - } + // generate geometry - var vertexCount = calculateVertexCount(); - var indexCount = calculateIndexCount(); + generateTorso(); - // buffers + if ( openEnded === false ) { - 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 ( radiusTop > 0 ) generateCap( true ); + if ( radiusBottom > 0 ) generateCap( false ); - // helper variables + } - var index = 0, - indexOffset = 0, - indexArray = [], - halfHeight = height / 2; + // build geometry - // group variables - var groupStart = 0; + this.setIndex( indices ); + this.addAttribute( 'position', vertices ); + this.addAttribute( 'normal', normals ); + this.addAttribute( 'uv', uvs ); - // generate geometry + // helper functions - generateTorso(); + function calculateVertexCount() { - if ( openEnded === false ) { + var count = ( radialSegments + 1 ) * ( heightSegments + 1 ); - if ( radiusTop > 0 ) generateCap( true ); - if ( radiusBottom > 0 ) generateCap( false ); + if ( openEnded === false ) { - } + count += ( ( radialSegments + 1 ) * nbCap ) + ( radialSegments * nbCap ); - // build geometry + } - this.setIndex( indices ); - this.addAttribute( 'position', vertices ); - this.addAttribute( 'normal', normals ); - this.addAttribute( 'uv', uvs ); + return count; - // helper functions + } - function calculateVertexCount() { + function calculateIndexCount() { - var count = ( radialSegments + 1 ) * ( heightSegments + 1 ); + var count = radialSegments * heightSegments * 2 * 3; - if ( openEnded === false ) { + if ( openEnded === false ) { - count += ( ( radialSegments + 1 ) * nbCap ) + ( radialSegments * nbCap ); + count += radialSegments * nbCap * 3; - } + } - return count; + return count; - } + } - function calculateIndexCount() { + function generateTorso() { - var count = radialSegments * heightSegments * 2 * 3; + var x, y; + var normal = new Vector3(); + var vertex = new Vector3(); - if ( openEnded === false ) { + var groupCount = 0; - count += radialSegments * nbCap * 3; + // this will be used to calculate the normal + var tanTheta = ( radiusBottom - radiusTop ) / height; - } + // generate vertices, normals and uvs - return count; + for ( y = 0; y <= heightSegments; y ++ ) { - } + var indexRow = []; - function generateTorso() { + var v = y / heightSegments; - var x, y; - var normal = new Vector3(); - var vertex = new Vector3(); + // calculate the radius of the current row + var radius = v * ( radiusBottom - radiusTop ) + radiusTop; - var groupCount = 0; + for ( x = 0; x <= radialSegments; x ++ ) { - // this will be used to calculate the normal - var tanTheta = ( radiusBottom - radiusTop ) / height; + var u = x / radialSegments; - // generate vertices, normals and uvs + // 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 ); - for ( y = 0; y <= heightSegments; y ++ ) { + // normal + normal.copy( vertex ); - var indexRow = []; + // handle special case if radiusTop/radiusBottom is zero - var v = y / heightSegments; + if ( ( radiusTop === 0 && y === 0 ) || ( radiusBottom === 0 && y === heightSegments ) ) { - // calculate the radius of the current row - var radius = v * ( radiusBottom - radiusTop ) + radiusTop; + normal.x = Math.sin( u * thetaLength + thetaStart ); + normal.z = Math.cos( u * thetaLength + thetaStart ); - for ( x = 0; x <= radialSegments; x ++ ) { + } - var u = x / radialSegments; + normal.setY( Math.sqrt( normal.x * normal.x + normal.z * normal.z ) * tanTheta ).normalize(); + normals.setXYZ( index, normal.x, normal.y, normal.z ); - // 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 ); + // uv + uvs.setXY( index, u, 1 - v ); - // normal - normal.copy( vertex ); + // save index of vertex in respective row + indexRow.push( index ); - // handle special case if radiusTop/radiusBottom is zero + // increase index + index ++; - if ( ( radiusTop === 0 && y === 0 ) || ( radiusBottom === 0 && y === heightSegments ) ) { + } - 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 ); + // generate indices - // uv - uvs.setXY( index, u, 1 - v ); + for ( x = 0; x < radialSegments; x ++ ) { - // save index of vertex in respective row - indexRow.push( index ); + for ( y = 0; y < heightSegments; y ++ ) { - // increase index - index ++; + // 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 ]; - } + // face one + indices.setX( indexOffset, i1 ); indexOffset ++; + indices.setX( indexOffset, i2 ); indexOffset ++; + indices.setX( indexOffset, i4 ); indexOffset ++; - // now save vertices of the row in our index array - indexArray.push( indexRow ); + // face two + indices.setX( indexOffset, i2 ); indexOffset ++; + indices.setX( indexOffset, i3 ); indexOffset ++; + indices.setX( indexOffset, i4 ); indexOffset ++; - } + // update counters + groupCount += 6; - // generate indices + } - for ( x = 0; x < radialSegments; x ++ ) { + } - for ( y = 0; y < heightSegments; y ++ ) { + // add a group to the geometry. this will ensure multi material support + scope.addGroup( groupStart, groupCount, 0 ); - // 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 ]; + // calculate new start value for groups + groupStart += groupCount; - // 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 ++; + function generateCap( top ) { - // update counters - groupCount += 6; + var x, centerIndexStart, centerIndexEnd; - } + var uv = new Vector2(); + var vertex = new Vector3(); - } + var groupCount = 0; - // add a group to the geometry. this will ensure multi material support - scope.addGroup( groupStart, groupCount, 0 ); + var radius = ( top === true ) ? radiusTop : radiusBottom; + var sign = ( top === true ) ? 1 : - 1; - // calculate new start value for groups - groupStart += groupCount; + // save the index of the first center vertex + centerIndexStart = index; - } + // 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 - function generateCap( top ) { + for ( x = 1; x <= radialSegments; x ++ ) { - var x, centerIndexStart, centerIndexEnd; + // vertex + vertices.setXYZ( index, 0, halfHeight * sign, 0 ); - var uv = new Vector2(); - var vertex = new Vector3(); + // normal + normals.setXYZ( index, 0, sign, 0 ); - var groupCount = 0; + // uv + uv.x = 0.5; + uv.y = 0.5; - var radius = ( top === true ) ? radiusTop : radiusBottom; - var sign = ( top === true ) ? 1 : - 1; + uvs.setXY( index, uv.x, uv.y ); - // save the index of the first center vertex - centerIndexStart = index; + // increase index + index ++; - // 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 + } - for ( x = 1; x <= radialSegments; x ++ ) { + // save the index of the last center vertex + centerIndexEnd = index; - // vertex - vertices.setXYZ( index, 0, halfHeight * sign, 0 ); + // now we generate the surrounding vertices, normals and uvs - // normal - normals.setXYZ( index, 0, sign, 0 ); + for ( x = 0; x <= radialSegments; x ++ ) { - // uv - uv.x = 0.5; - uv.y = 0.5; + var u = x / radialSegments; + var theta = u * thetaLength + thetaStart; - uvs.setXY( index, uv.x, uv.y ); + var cosTheta = Math.cos( theta ); + var sinTheta = Math.sin( theta ); - // increase index - index ++; + // vertex + vertex.x = radius * sinTheta; + vertex.y = halfHeight * sign; + vertex.z = radius * cosTheta; + vertices.setXYZ( index, vertex.x, vertex.y, vertex.z ); - } + // normal + normals.setXYZ( index, 0, sign, 0 ); - // save the index of the last center vertex - centerIndexEnd = index; + // uv + uv.x = ( cosTheta * 0.5 ) + 0.5; + uv.y = ( sinTheta * 0.5 * sign ) + 0.5; + uvs.setXY( index, uv.x, uv.y ); - // now we generate the surrounding vertices, normals and uvs + // increase index + index ++; - for ( x = 0; x <= radialSegments; x ++ ) { + } - var u = x / radialSegments; - var theta = u * thetaLength + thetaStart; + // generate indices - var cosTheta = Math.cos( theta ); - var sinTheta = Math.sin( theta ); + for ( x = 0; x < radialSegments; x ++ ) { - // vertex - vertex.x = radius * sinTheta; - vertex.y = halfHeight * sign; - vertex.z = radius * cosTheta; - vertices.setXYZ( index, vertex.x, vertex.y, vertex.z ); + var c = centerIndexStart + x; + var i = centerIndexEnd + x; - // normal - normals.setXYZ( index, 0, sign, 0 ); + if ( top === true ) { - // uv - uv.x = ( cosTheta * 0.5 ) + 0.5; - uv.y = ( sinTheta * 0.5 * sign ) + 0.5; - uvs.setXY( index, uv.x, uv.y ); + // face top + indices.setX( indexOffset, i ); indexOffset ++; + indices.setX( indexOffset, i + 1 ); indexOffset ++; + indices.setX( indexOffset, c ); indexOffset ++; - // increase index - index ++; + } else { - } + // face bottom + indices.setX( indexOffset, i + 1 ); indexOffset ++; + indices.setX( indexOffset, i ); indexOffset ++; + indices.setX( indexOffset, c ); indexOffset ++; - // generate indices + } - for ( x = 0; x < radialSegments; x ++ ) { + // update counters + groupCount += 3; - var c = centerIndexStart + x; - var i = centerIndexEnd + x; + } - if ( top === true ) { + // add a group to the geometry. this will ensure multi material support + scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 ); - // face top - indices.setX( indexOffset, i ); indexOffset ++; - indices.setX( indexOffset, i + 1 ); indexOffset ++; - indices.setX( indexOffset, c ); indexOffset ++; + // calculate new start value for groups + groupStart += groupCount; - } else { + } - // face bottom - indices.setX( indexOffset, i + 1 ); indexOffset ++; - indices.setX( indexOffset, i ); indexOffset ++; - indices.setX( indexOffset, c ); indexOffset ++; + }; - } + CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry; - // update counters - groupCount += 3; + /** + * @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 + */ - } + exports.ArrowHelper = ( function () { - // add a group to the geometry. this will ensure multi material support - scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 ); + var lineGeometry = new BufferGeometry(); + lineGeometry.addAttribute( 'position', new Float32Attribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) ); - // calculate new start value for groups - groupStart += groupCount; + 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 ) { - }; + // dir is assumed to be normalized - CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); - CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry; + Object3D.call( this ); - /** - * @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 - */ + if ( color === undefined ) color = 0xffff00; + if ( length === undefined ) length = 1; + if ( headLength === undefined ) headLength = 0.2 * length; + if ( headWidth === undefined ) headWidth = 0.2 * headLength; - exports.ArrowHelper = ( function () { + this.position.copy( origin ); - var lineGeometry = new BufferGeometry(); - lineGeometry.addAttribute( 'position', new Float32Attribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) ); + this.line = new Line( lineGeometry, new LineBasicMaterial( { color: color } ) ); + this.line.matrixAutoUpdate = false; + this.add( this.line ); - var coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 ); - coneGeometry.translate( 0, - 0.5, 0 ); + this.cone = new Mesh( coneGeometry, new MeshBasicMaterial( { color: color } ) ); + this.cone.matrixAutoUpdate = false; + this.add( this.cone ); - return function ArrowHelper( dir, origin, length, color, headLength, headWidth ) { + this.setDirection( dir ); + this.setLength( length, headLength, headWidth ); - // dir is assumed to be normalized + }; - 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; + exports.ArrowHelper.prototype = Object.create( Object3D.prototype ); + exports.ArrowHelper.prototype.constructor = exports.ArrowHelper; - this.position.copy( origin ); + exports.ArrowHelper.prototype.setDirection = ( function () { - this.line = new Line( lineGeometry, new LineBasicMaterial( { color: color } ) ); - this.line.matrixAutoUpdate = false; - this.add( this.line ); + var axis = new Vector3(); + var radians; - this.cone = new Mesh( coneGeometry, new MeshBasicMaterial( { color: color } ) ); - this.cone.matrixAutoUpdate = false; - this.add( this.cone ); + return function setDirection( dir ) { - this.setDirection( dir ); - this.setLength( length, headLength, headWidth ); + // dir is assumed to be normalized - }; + if ( dir.y > 0.99999 ) { - }() ); + this.quaternion.set( 0, 0, 0, 1 ); - exports.ArrowHelper.prototype = Object.create( Object3D.prototype ); - exports.ArrowHelper.prototype.constructor = exports.ArrowHelper; + } else if ( dir.y < - 0.99999 ) { - exports.ArrowHelper.prototype.setDirection = ( function () { + this.quaternion.set( 1, 0, 0, 0 ); - var axis = new Vector3(); - var radians; + } else { - return function setDirection( dir ) { + axis.set( dir.z, 0, - dir.x ).normalize(); - // dir is assumed to be normalized + radians = Math.acos( dir.y ); - if ( dir.y > 0.99999 ) { + this.quaternion.setFromAxisAngle( axis, radians ); - this.quaternion.set( 0, 0, 0, 1 ); + } - } else if ( dir.y < - 0.99999 ) { + }; - this.quaternion.set( 1, 0, 0, 0 ); + }() ); - } else { + exports.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) { - axis.set( dir.z, 0, - dir.x ).normalize(); + if ( headLength === undefined ) headLength = 0.2 * length; + if ( headWidth === undefined ) headWidth = 0.2 * headLength; - radians = Math.acos( dir.y ); + this.line.scale.set( 1, Math.max( 0, length - headLength ), 1 ); + this.line.updateMatrix(); - this.quaternion.setFromAxisAngle( axis, radians ); + this.cone.scale.set( headWidth, headLength, headWidth ); + this.cone.position.y = length; + this.cone.updateMatrix(); - } + }; - }; + exports.ArrowHelper.prototype.setColor = function ( color ) { - }() ); + this.line.material.color.copy( color ); + this.cone.material.color.copy( color ); - exports.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) { + }; - if ( headLength === undefined ) headLength = 0.2 * length; - if ( headWidth === undefined ) headWidth = 0.2 * headLength; + /** + * @author sroucheray / http://sroucheray.org/ + * @author mrdoob / http://mrdoob.com/ + */ - this.line.scale.set( 1, Math.max( 0, length - headLength ), 1 ); - this.line.updateMatrix(); + function AxisHelper( size ) { - this.cone.scale.set( headWidth, headLength, headWidth ); - this.cone.position.y = length; - this.cone.updateMatrix(); + 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 + ] ); - exports.ArrowHelper.prototype.setColor = function ( 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 + ] ); - this.line.material.color.copy( color ); - this.cone.material.color.copy( color ); + var geometry = new BufferGeometry(); + geometry.addAttribute( 'position', new BufferAttribute( vertices, 3 ) ); + geometry.addAttribute( 'color', new BufferAttribute( colors, 3 ) ); - }; + var material = new LineBasicMaterial( { vertexColors: VertexColors } ); - /** - * @author sroucheray / http://sroucheray.org/ - * @author mrdoob / http://mrdoob.com/ - */ + LineSegments.call( this, geometry, material ); - function AxisHelper( size ) { + }; - size = size || 1; + AxisHelper.prototype = Object.create( LineSegments.prototype ); + AxisHelper.prototype.constructor = AxisHelper; - var vertices = new Float32Array( [ - 0, 0, 0, size, 0, 0, - 0, 0, 0, 0, size, 0, - 0, 0, 0, 0, 0, size - ] ); + /** + * @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 colors = new Float32Array( [ - 1, 0, 0, 1, 0.6, 0, - 0, 1, 0, 0.6, 1, 0, - 0, 0, 1, 0, 0.6, 1 - ] ); + function ParametricGeometry( func, slices, stacks ) { - var geometry = new BufferGeometry(); - geometry.addAttribute( 'position', new BufferAttribute( vertices, 3 ) ); - geometry.addAttribute( 'color', new BufferAttribute( colors, 3 ) ); + Geometry.call( this ); - var material = new LineBasicMaterial( { vertexColors: VertexColors } ); + this.type = 'ParametricGeometry'; - LineSegments.call( this, geometry, material ); + this.parameters = { + func: func, + slices: slices, + stacks: stacks + }; - }; + var verts = this.vertices; + var faces = this.faces; + var uvs = this.faceVertexUvs[ 0 ]; - AxisHelper.prototype = Object.create( LineSegments.prototype ); - AxisHelper.prototype.constructor = AxisHelper; + var i, j, p; + var u, v; - /** - * @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 sliceCount = slices + 1; - function ParametricGeometry( func, slices, stacks ) { + for ( i = 0; i <= stacks; i ++ ) { - Geometry.call( this ); + v = i / stacks; - this.type = 'ParametricGeometry'; + for ( j = 0; j <= slices; j ++ ) { - this.parameters = { - func: func, - slices: slices, - stacks: stacks - }; + u = j / slices; - var verts = this.vertices; - var faces = this.faces; - var uvs = this.faceVertexUvs[ 0 ]; + p = func( u, v ); + verts.push( p ); - var i, j, p; - var u, v; + } - var sliceCount = slices + 1; + } - for ( i = 0; i <= stacks; i ++ ) { + var a, b, c, d; + var uva, uvb, uvc, uvd; - v = i / stacks; + for ( i = 0; i < stacks; i ++ ) { - for ( j = 0; j <= slices; j ++ ) { + for ( j = 0; j < slices; j ++ ) { - u = j / slices; + a = i * sliceCount + j; + b = i * sliceCount + j + 1; + c = ( i + 1 ) * sliceCount + j + 1; + d = ( i + 1 ) * sliceCount + j; - p = func( u, v ); - verts.push( p ); + 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 ] ); - } + faces.push( new Face3( b, c, d ) ); + uvs.push( [ uvb.clone(), uvc, uvd.clone() ] ); - var a, b, c, d; - var uva, uvb, uvc, uvd; + } - for ( i = 0; i < stacks; i ++ ) { + } - for ( j = 0; j < slices; j ++ ) { + // console.log(this); - a = i * sliceCount + j; - b = i * sliceCount + j + 1; - c = ( i + 1 ) * sliceCount + j + 1; - d = ( i + 1 ) * sliceCount + j; + // magic bullet + // var diff = this.mergeVertices(); + // console.log('removed ', diff, ' vertices by merging'); - 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 ); + this.computeFaceNormals(); + this.computeVertexNormals(); - faces.push( new Face3( a, b, d ) ); - uvs.push( [ uva, uvb, uvd ] ); + }; - 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 + */ - } + function PolyhedronGeometry( vertices, indices, radius, detail ) { - // console.log(this); + Geometry.call( this ); - // magic bullet - // var diff = this.mergeVertices(); - // console.log('removed ', diff, ' vertices by merging'); + this.type = 'PolyhedronGeometry'; - this.computeFaceNormals(); - this.computeVertexNormals(); + this.parameters = { + vertices: vertices, + indices: indices, + radius: radius, + detail: detail + }; - }; + radius = radius || 1; + detail = detail || 0; - ParametricGeometry.prototype = Object.create( Geometry.prototype ); - ParametricGeometry.prototype.constructor = ParametricGeometry; + var that = this; - /** - * @author clockworkgeek / https://github.com/clockworkgeek - * @author timothypratley / https://github.com/timothypratley - * @author WestLangley / http://github.com/WestLangley - */ + for ( var i = 0, l = vertices.length; i < l; i += 3 ) { - function PolyhedronGeometry( vertices, indices, radius, detail ) { + prepare( new Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) ); - Geometry.call( this ); + } - this.type = 'PolyhedronGeometry'; + var p = this.vertices; - this.parameters = { - vertices: vertices, - indices: indices, - radius: radius, - detail: detail - }; + var faces = []; - radius = radius || 1; - detail = detail || 0; + for ( var i = 0, j = 0, l = indices.length; i < l; i += 3, j ++ ) { - var that = this; + var v1 = p[ indices[ i ] ]; + var v2 = p[ indices[ i + 1 ] ]; + var v3 = p[ indices[ i + 2 ] ]; - for ( var i = 0, l = vertices.length; i < l; i += 3 ) { + faces[ j ] = new Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] ); - prepare( new Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) ); + } - } + var centroid = new Vector3(); - var p = this.vertices; + for ( var i = 0, l = faces.length; i < l; i ++ ) { - var faces = []; + subdivide( faces[ i ], detail ); - for ( var i = 0, j = 0, l = indices.length; i < l; i += 3, j ++ ) { + } - 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 - } + for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) { - var centroid = new Vector3(); + var uvs = this.faceVertexUvs[ 0 ][ i ]; - for ( var i = 0, l = faces.length; i < l; i ++ ) { + var x0 = uvs[ 0 ].x; + var x1 = uvs[ 1 ].x; + var x2 = uvs[ 2 ].x; - subdivide( faces[ i ], detail ); + var max = Math.max( x0, x1, x2 ); + var min = Math.min( x0, x1, x2 ); - } + if ( max > 0.9 && min < 0.1 ) { + // 0.9 is somewhat arbitrary - // Handle case when face straddles the seam + if ( x0 < 0.2 ) uvs[ 0 ].x += 1; + if ( x1 < 0.2 ) uvs[ 1 ].x += 1; + if ( x2 < 0.2 ) uvs[ 2 ].x += 1; - for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) { + } - 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 ); + // Apply radius - if ( max > 0.9 && min < 0.1 ) { + for ( var i = 0, l = this.vertices.length; i < l; i ++ ) { - // 0.9 is somewhat arbitrary + this.vertices[ i ].multiplyScalar( radius ); - if ( x0 < 0.2 ) uvs[ 0 ].x += 1; - if ( x1 < 0.2 ) uvs[ 1 ].x += 1; - if ( x2 < 0.2 ) uvs[ 2 ].x += 1; + } - } - } + // Merge vertices + this.mergeVertices(); - // Apply radius + this.computeFaceNormals(); - for ( var i = 0, l = this.vertices.length; i < l; i ++ ) { + this.boundingSphere = new Sphere( new Vector3(), radius ); - this.vertices[ i ].multiplyScalar( radius ); - } + // Project vector onto sphere's surface + function prepare( vector ) { - // Merge vertices + var vertex = vector.normalize().clone(); + vertex.index = that.vertices.push( vertex ) - 1; - this.mergeVertices(); + // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle. - this.computeFaceNormals(); + var u = azimuth( vector ) / 2 / Math.PI + 0.5; + var v = inclination( vector ) / Math.PI + 0.5; + vertex.uv = new Vector2( u, 1 - v ); - this.boundingSphere = new Sphere( new Vector3(), radius ); + return vertex; + } - // Project vector onto sphere's surface - function prepare( vector ) { + // Approximate a curved face with recursively sub-divided triangles. - var vertex = vector.normalize().clone(); - vertex.index = that.vertices.push( vertex ) - 1; + function make( v1, v2, v3 ) { - // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle. + var face = new Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] ); + that.faces.push( face ); - var u = azimuth( vector ) / 2 / Math.PI + 0.5; - var v = inclination( vector ) / Math.PI + 0.5; - vertex.uv = new Vector2( u, 1 - v ); + centroid.copy( v1 ).add( v2 ).add( v3 ).divideScalar( 3 ); - return vertex; + 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 ) { + // Analytically subdivide a face to the required detail level. - var face = new Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] ); - that.faces.push( face ); + function subdivide( face, detail ) { - centroid.copy( v1 ).add( v2 ).add( v3 ).divideScalar( 3 ); + 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 = []; - var azi = azimuth( centroid ); + // Construct all of the vertices for this subdivision. - that.faceVertexUvs[ 0 ].push( [ - correctUV( v1.uv, v1, azi ), - correctUV( v2.uv, v2, azi ), - correctUV( v3.uv, v3, azi ) - ] ); + for ( var i = 0 ; i <= cols; i ++ ) { - } + v[ i ] = []; + var aj = prepare( a.clone().lerp( c, i / cols ) ); + var bj = prepare( b.clone().lerp( c, i / cols ) ); + var rows = cols - i; - // Analytically subdivide a face to the required detail level. + for ( var j = 0; j <= rows; j ++ ) { - function subdivide( face, detail ) { + if ( j === 0 && i === cols ) { - 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 = []; + v[ i ][ j ] = aj; - // Construct all of the vertices for this subdivision. + } else { - for ( var i = 0 ; i <= cols; i ++ ) { + v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) ); - v[ i ] = []; + } - 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 ) { + // Construct all of the faces. - v[ i ][ j ] = aj; + for ( var i = 0; i < cols ; i ++ ) { - } else { + for ( var j = 0; j < 2 * ( cols - i ) - 1; j ++ ) { - v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) ); + var k = Math.floor( j / 2 ); - } + if ( j % 2 === 0 ) { - } + make( + v[ i ][ k + 1 ], + v[ i + 1 ][ k ], + v[ i ][ k ] + ); - } + } else { - // Construct all of the faces. + make( + v[ i ][ k + 1 ], + v[ i + 1 ][ k + 1 ], + v[ i + 1 ][ k ] + ); - for ( var i = 0; i < cols ; i ++ ) { + } - 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 { + // Angle around the Y axis, counter-clockwise when looking from above. - make( - v[ i ][ k + 1 ], - v[ i + 1 ][ k + 1 ], - v[ i + 1 ][ k ] - ); + function azimuth( vector ) { - } + return Math.atan2( vector.z, - vector.x ); - } + } - } - } + // Angle above the XZ plane. + function inclination( vector ) { - // Angle around the Y axis, counter-clockwise when looking from above. + return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) ); - function azimuth( vector ) { + } - return Math.atan2( vector.z, - vector.x ); - } + // Texture fixing helper. Spheres have some odd behaviours. + function correctUV( uv, vector, azimuth ) { - // Angle above the XZ plane. + 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(); - function inclination( vector ) { + } - 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 }); })); /**