diff --git a/dependencies/OrbitControls.js b/dependencies/OrbitControls.js index 24f82d57ab1077b026538178331cdf1339954613..544b3f60eec9cdafa003dcf0a4e175febc88e562 100644 --- a/dependencies/OrbitControls.js +++ b/dependencies/OrbitControls.js @@ -5,59 +5,33 @@ * @author WestLangley / http://github.com/WestLangley * @author erich666 / http://erichaines.com */ -/*global THREE, console */ -// This set of controls performs orbiting, dollying (zooming), and panning. It maintains -// the "up" direction as +Y, unlike the TrackballControls. Touch on tablet and phones is -// supported. +// This set of controls performs orbiting, dollying (zooming), and panning. +// Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default). // // Orbit - left mouse / touch: one finger move // Zoom - middle mouse, or mousewheel / touch: two finger spread or squish // Pan - right mouse, or arrow keys / touch: three finter swipe -// -// This is a drop-in replacement for (most) TrackballControls used in examples. -// That is, include this js file and wherever you see: -// controls = new THREE.TrackballControls( camera ); -// controls.target.z = 150; -// Simple substitute "OrbitControls" and the control should work as-is. THREE.OrbitControls = function ( object, domElement ) { this.object = object; - this.domElement = ( domElement !== undefined ) ? domElement : document; - // API + this.domElement = ( domElement !== undefined ) ? domElement : document; // Set to false to disable this control this.enabled = true; - // "target" sets the location of focus, where the control orbits around - // and where it pans with respect to. + // "target" sets the location of focus, where the object orbits around this.target = new THREE.Vector3(); - // center is old, deprecated; use "target" instead - this.center = this.target; - - // This option actually enables dollying in and out; left as "zoom" for - // backwards compatibility - this.noZoom = false; - this.zoomSpeed = 1.0; - - // Limits to how far you can dolly in and out + // How far you can dolly in and out ( PerspectiveCamera only ) this.minDistance = 0; - this.maxDistance = 600; - - // Set to true to disable this control - this.noRotate = false; - this.rotateSpeed = 1.0; + this.maxDistance = Infinity; - // Set to true to disable this control - this.noPan = false; - this.keyPanSpeed = 7.0; // pixels moved per arrow key push - - // Set to true to automatically rotate around the target - this.autoRotate = false; - this.autoRotateSpeed = 2.0; // 30 seconds per round when fps is 60 + // How far you can zoom in and out ( OrthographicCamera only ) + this.minZoom = 0; + this.maxZoom = Infinity; // How far you can orbit vertically, upper and lower limits. // Range is 0 to Math.PI radians. @@ -69,8 +43,31 @@ THREE.OrbitControls = function ( object, domElement ) { this.minAzimuthAngle = - Infinity; // radians this.maxAzimuthAngle = Infinity; // radians - // Set to true to disable use of the keys - this.noKeys = false; + // Set to true to enable damping (inertia) + // If damping is enabled, you must call controls.update() in your animation loop + this.enableDamping = false; + this.dampingFactor = 0.25; + + // This option actually enables dollying in and out; left as "zoom" for backwards compatibility. + // Set to false to disable zooming + this.enableZoom = true; + this.zoomSpeed = 1.0; + + // Set to false to disable rotating + this.enableRotate = true; + this.rotateSpeed = 1.0; + + // Set to false to disable panning + this.enablePan = true; + this.keyPanSpeed = 7.0; // pixels moved per arrow key push + + // Set to true to automatically rotate around the target + // If auto-rotate is enabled, you must call controls.update() in your animation loop + this.autoRotate = false; + this.autoRotateSpeed = 2.0; // 30 seconds per round when fps is 60 + + // Set to false to disable use of the keys + this.enableKeys = true; // The four arrow keys this.keys = { LEFT: 37, UP: 38, RIGHT: 39, BOTTOM: 40 }; @@ -78,13 +75,187 @@ THREE.OrbitControls = function ( object, domElement ) { // Mouse buttons this.mouseButtons = { ORBIT: THREE.MOUSE.LEFT, ZOOM: THREE.MOUSE.MIDDLE, PAN: THREE.MOUSE.RIGHT }; - //////////// + // for reset + this.target0 = this.target.clone(); + this.position0 = this.object.position.clone(); + this.zoom0 = this.object.zoom; + + this.setTarget = function(target){//three vector + this.target = target; + this.target0 = this.target.clone(); + }; + + // + // public methods + // + + this.getPolarAngle = function () { + + return spherical.phi; + + }; + + this.getAzimuthalAngle = function () { + + return spherical.theta; + + }; + + this.reset = function () { + + scope.target.copy( scope.target0 ); + scope.object.position.copy( scope.position0 ); + scope.object.zoom = scope.zoom0; + + scope.object.updateProjectionMatrix(); + scope.dispatchEvent( changeEvent ); + + scope.update(); + + state = STATE.NONE; + + }; + + // this method is exposed, but perhaps it would be better if we can make it private... + this.update = function() { + + var offset = new THREE.Vector3(); + + // so camera.up is the orbit axis + var quat = new THREE.Quaternion().setFromUnitVectors( object.up, new THREE.Vector3( 0, 1, 0 ) ); + var quatInverse = quat.clone().inverse(); + + var lastPosition = new THREE.Vector3(); + var lastQuaternion = new THREE.Quaternion(); + + return function update () { + + var position = scope.object.position; + + offset.copy( position ).sub( scope.target ); + + // rotate offset to "y-axis-is-up" space + offset.applyQuaternion( quat ); + + // angle from z-axis around y-axis + spherical.setFromVector3( offset ); + + if ( scope.autoRotate && state === STATE.NONE ) { + + rotateLeft( getAutoRotationAngle() ); + + } + + spherical.theta += sphericalDelta.theta; + spherical.phi += sphericalDelta.phi; + + // restrict theta to be between desired limits + spherical.theta = Math.max( scope.minAzimuthAngle, Math.min( scope.maxAzimuthAngle, spherical.theta ) ); + + // restrict phi to be between desired limits + spherical.phi = Math.max( scope.minPolarAngle, Math.min( scope.maxPolarAngle, spherical.phi ) ); + + spherical.makeSafe(); + + + spherical.radius *= scale; + + // restrict radius to be between desired limits + spherical.radius = Math.max( scope.minDistance, Math.min( scope.maxDistance, spherical.radius ) ); + + // move target to panned location + scope.target.add( panOffset ); + + offset.setFromSpherical( spherical ); + + // rotate offset back to "camera-up-vector-is-up" space + offset.applyQuaternion( quatInverse ); + + position.copy( scope.target ).add( offset ); + + scope.object.lookAt( scope.target ); + + if ( scope.enableDamping === true ) { + + sphericalDelta.theta *= ( 1 - scope.dampingFactor ); + sphericalDelta.phi *= ( 1 - scope.dampingFactor ); + + } else { + + sphericalDelta.set( 0, 0, 0 ); + + } + + scale = 1; + panOffset.set( 0, 0, 0 ); + + // update condition is: + // min(camera displacement, camera rotation in radians)^2 > EPS + // using small-angle approximation cos(x/2) = 1 - x^2 / 8 + + if ( zoomChanged || + lastPosition.distanceToSquared( scope.object.position ) > EPS || + 8 * ( 1 - lastQuaternion.dot( scope.object.quaternion ) ) > EPS ) { + + scope.dispatchEvent( changeEvent ); + + lastPosition.copy( scope.object.position ); + lastQuaternion.copy( scope.object.quaternion ); + zoomChanged = false; + + return true; + + } + + return false; + + }; + + }(); + + this.dispose = function() { + + scope.domElement.removeEventListener( 'contextmenu', onContextMenu, false ); + scope.domElement.removeEventListener( 'mousedown', onMouseDown, false ); + scope.domElement.removeEventListener( 'wheel', onMouseWheel, false ); + + scope.domElement.removeEventListener( 'touchstart', onTouchStart, false ); + scope.domElement.removeEventListener( 'touchend', onTouchEnd, false ); + scope.domElement.removeEventListener( 'touchmove', onTouchMove, false ); + + document.removeEventListener( 'mousemove', onMouseMove, false ); + document.removeEventListener( 'mouseup', onMouseUp, false ); + + window.removeEventListener( 'keydown', onKeyDown, false ); + + //scope.dispatchEvent( { type: 'dispose' } ); // should this be added here? + + }; + + // // internals + // var scope = this; + var changeEvent = { type: 'change' }; + var startEvent = { type: 'start' }; + var endEvent = { type: 'end' }; + + var STATE = { NONE : - 1, ROTATE : 0, DOLLY : 1, PAN : 2, TOUCH_ROTATE : 3, TOUCH_DOLLY : 4, TOUCH_PAN : 5 }; + + var state = STATE.NONE; + var EPS = 0.000001; + // current position in spherical coordinates + var spherical = new THREE.Spherical(); + var sphericalDelta = new THREE.Spherical(); + + var scale = 1; + var panOffset = new THREE.Vector3(); + var zoomChanged = false; + var rotateStart = new THREE.Vector2(); var rotateEnd = new THREE.Vector2(); var rotateDelta = new THREE.Vector2(); @@ -92,441 +263,505 @@ THREE.OrbitControls = function ( object, domElement ) { var panStart = new THREE.Vector2(); var panEnd = new THREE.Vector2(); var panDelta = new THREE.Vector2(); - var panOffset = new THREE.Vector3(); - - var offset = new THREE.Vector3(); var dollyStart = new THREE.Vector2(); var dollyEnd = new THREE.Vector2(); var dollyDelta = new THREE.Vector2(); - var theta; - var phi; - var phiDelta = 0; - var thetaDelta = 0; - var scale = 1; - var pan = new THREE.Vector3(); + function getAutoRotationAngle() { - var lastPosition = new THREE.Vector3(); - var lastQuaternion = new THREE.Quaternion(); + return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed; - var STATE = { NONE : -1, ROTATE : 0, DOLLY : 1, PAN : 2, TOUCH_ROTATE : 3, TOUCH_DOLLY : 4, TOUCH_PAN : 5 }; + } - var state = STATE.NONE; + function getZoomScale() { - // for reset + return Math.pow( 0.95, scope.zoomSpeed ); - this.target0 = this.target.clone(); - this.position0 = this.object.position.clone(); + } - // so camera.up is the orbit axis + function rotateLeft( angle ) { - var quat = new THREE.Quaternion().setFromUnitVectors( object.up, new THREE.Vector3( 0, 1, 0 ) ); - var quatInverse = quat.clone().inverse(); + sphericalDelta.theta -= angle; - // events + } - var changeEvent = { type: 'change' }; - var startEvent = { type: 'start'}; - var endEvent = { type: 'end'}; + function rotateUp( angle ) { - this.setTarget = function(target){//three vector - this.target = target; - this.target0 = this.target.clone(); - }; + sphericalDelta.phi -= angle; - this.rotateLeft = function ( angle ) { + } - if ( angle === undefined ) { + var panLeft = function() { - angle = getAutoRotationAngle(); + var v = new THREE.Vector3(); - } + return function panLeft( distance, objectMatrix ) { - thetaDelta -= angle; + v.setFromMatrixColumn( objectMatrix, 0 ); // get X column of objectMatrix + v.multiplyScalar( - distance ); - }; + panOffset.add( v ); - this.rotateUp = function ( angle ) { + }; - if ( angle === undefined ) { + }(); - angle = getAutoRotationAngle(); + var panUp = function() { - } + var v = new THREE.Vector3(); - phiDelta -= angle; + return function panUp( distance, objectMatrix ) { - }; + v.setFromMatrixColumn( objectMatrix, 1 ); // get Y column of objectMatrix + v.multiplyScalar( distance ); - // pass in distance in world space to move left - this.panLeft = function ( distance ) { + panOffset.add( v ); - var te = this.object.matrix.elements; + }; - // get X column of matrix - panOffset.set( te[ 0 ], te[ 1 ], te[ 2 ] ); - panOffset.multiplyScalar( - distance ); + }(); - pan.add( panOffset ); + // deltaX and deltaY are in pixels; right and down are positive + var pan = function() { - }; + var offset = new THREE.Vector3(); - // pass in distance in world space to move up - this.panUp = function ( distance ) { + return function pan ( deltaX, deltaY ) { - var te = this.object.matrix.elements; + var element = scope.domElement === document ? scope.domElement.body : scope.domElement; - // get Y column of matrix - panOffset.set( te[ 4 ], te[ 5 ], te[ 6 ] ); - panOffset.multiplyScalar( distance ); + if ( scope.object instanceof THREE.PerspectiveCamera ) { - pan.add( panOffset ); + // perspective + var position = scope.object.position; + offset.copy( position ).sub( scope.target ); + var targetDistance = offset.length(); - }; + // half of the fov is center to top of screen + targetDistance *= Math.tan( ( scope.object.fov / 2 ) * Math.PI / 180.0 ); - // pass in x,y of change desired in pixel space, - // right and down are positive - this.pan = function ( deltaX, deltaY ) { + // we actually don't use screenWidth, since perspective camera is fixed to screen height + panLeft( 2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix ); + panUp( 2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix ); - var element = scope.domElement === document ? scope.domElement.body : scope.domElement; + } else if ( scope.object instanceof THREE.OrthographicCamera ) { - if ( scope.object.fov !== undefined ) { + // orthographic + panLeft( deltaX * ( scope.object.right - scope.object.left ) / scope.object.zoom / element.clientWidth, scope.object.matrix ); + panUp( deltaY * ( scope.object.top - scope.object.bottom ) / scope.object.zoom / element.clientHeight, scope.object.matrix ); - // perspective - var position = scope.object.position; - var offset = position.clone().sub( scope.target ); - var targetDistance = offset.length(); + } else { + + // camera neither orthographic nor perspective + console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.' ); + scope.enablePan = false; + + } - // half of the fov is center to top of screen - targetDistance *= Math.tan( ( scope.object.fov / 2 ) * Math.PI / 180.0 ); + }; - // we actually don't use screenWidth, since perspective camera is fixed to screen height - scope.panLeft( 2 * deltaX * targetDistance / element.clientHeight ); - scope.panUp( 2 * deltaY * targetDistance / element.clientHeight ); + }(); - } else if ( scope.object.top !== undefined ) { + function dollyIn( dollyScale ) { - // orthographic - scope.panLeft( deltaX * (scope.object.right - scope.object.left) / element.clientWidth ); - scope.panUp( deltaY * (scope.object.top - scope.object.bottom) / element.clientHeight ); + if ( scope.object instanceof THREE.PerspectiveCamera ) { + + scale /= dollyScale; + + } else if ( scope.object instanceof THREE.OrthographicCamera ) { + + scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom * dollyScale ) ); + scope.object.updateProjectionMatrix(); + zoomChanged = true; } else { - // camera neither orthographic or perspective - console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.' ); + console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' ); + scope.enableZoom = false; } - }; + } + + function dollyOut( dollyScale ) { + + if ( scope.object instanceof THREE.PerspectiveCamera ) { - this.dollyIn = function ( dollyScale ) { + scale *= dollyScale; - if ( dollyScale === undefined ) { + } else if ( scope.object instanceof THREE.OrthographicCamera ) { - dollyScale = getZoomScale(); + scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom / dollyScale ) ); + scope.object.updateProjectionMatrix(); + zoomChanged = true; + + } else { + + console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' ); + scope.enableZoom = false; } - scale /= dollyScale; + } - }; + // + // event callbacks - update the object state + // - this.dollyOut = function ( dollyScale ) { + function handleMouseDownRotate( event ) { - if ( dollyScale === undefined ) { + //console.log( 'handleMouseDownRotate' ); - dollyScale = getZoomScale(); + rotateStart.set( event.clientX, event.clientY ); - } + } - scale *= dollyScale; + function handleMouseDownDolly( event ) { - }; + //console.log( 'handleMouseDownDolly' ); + + dollyStart.set( event.clientX, event.clientY ); + + } + + function handleMouseDownPan( event ) { + + //console.log( 'handleMouseDownPan' ); - this.update = function () { + panStart.set( event.clientX, event.clientY ); - var position = this.object.position; + } + + function handleMouseMoveRotate( event ) { - offset.copy( position ).sub( this.target ); + //console.log( 'handleMouseMoveRotate' ); - // rotate offset to "y-axis-is-up" space - offset.applyQuaternion( quat ); + rotateEnd.set( event.clientX, event.clientY ); + rotateDelta.subVectors( rotateEnd, rotateStart ); + + var element = scope.domElement === document ? scope.domElement.body : scope.domElement; - // angle from z-axis around y-axis + // rotating across whole screen goes 360 degrees around + rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientWidth * scope.rotateSpeed ); - theta = Math.atan2( offset.x, offset.z ); + // rotating up and down along whole screen attempts to go 360, but limited to 180 + rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight * scope.rotateSpeed ); - // angle from y-axis + rotateStart.copy( rotateEnd ); - phi = Math.atan2( Math.sqrt( offset.x * offset.x + offset.z * offset.z ), offset.y ); + scope.update(); + + } - if ( this.autoRotate && state === STATE.NONE ) { + function handleMouseMoveDolly( event ) { - this.rotateLeft( getAutoRotationAngle() ); + //console.log( 'handleMouseMoveDolly' ); + + dollyEnd.set( event.clientX, event.clientY ); + + dollyDelta.subVectors( dollyEnd, dollyStart ); + + if ( dollyDelta.y > 0 ) { + + dollyIn( getZoomScale() ); + + } else if ( dollyDelta.y < 0 ) { + + dollyOut( getZoomScale() ); } - theta += thetaDelta; - phi += phiDelta; + dollyStart.copy( dollyEnd ); - // restrict theta to be between desired limits - theta = Math.max( this.minAzimuthAngle, Math.min( this.maxAzimuthAngle, theta ) ); + scope.update(); - // restrict phi to be between desired limits - phi = Math.max( this.minPolarAngle, Math.min( this.maxPolarAngle, phi ) ); + } + + function handleMouseMovePan( event ) { + + //console.log( 'handleMouseMovePan' ); - // restrict phi to be betwee EPS and PI-EPS - phi = Math.max( EPS, Math.min( Math.PI - EPS, phi ) ); + panEnd.set( event.clientX, event.clientY ); - var radius = offset.length() * scale; + panDelta.subVectors( panEnd, panStart ); - // restrict radius to be between desired limits - radius = Math.max( this.minDistance, Math.min( this.maxDistance, radius ) ); + pan( panDelta.x, panDelta.y ); - // move target to panned location - this.target.add( pan ); + panStart.copy( panEnd ); - offset.x = radius * Math.sin( phi ) * Math.sin( theta ); - offset.y = radius * Math.cos( phi ); - offset.z = radius * Math.sin( phi ) * Math.cos( theta ); + scope.update(); - // rotate offset back to "camera-up-vector-is-up" space - offset.applyQuaternion( quatInverse ); + } - position.copy( this.target ).add( offset ); + function handleMouseUp( event ) { - this.object.lookAt( this.target ); + //console.log( 'handleMouseUp' ); - thetaDelta = 0; - phiDelta = 0; - scale = 1; - pan.set( 0, 0, 0 ); + } - // update condition is: - // min(camera displacement, camera rotation in radians)^2 > EPS - // using small-angle approximation cos(x/2) = 1 - x^2 / 8 + function handleMouseWheel( event ) { - if ( lastPosition.distanceToSquared( this.object.position ) > EPS - || 8 * (1 - lastQuaternion.dot(this.object.quaternion)) > EPS ) { + //console.log( 'handleMouseWheel' ); - this.dispatchEvent( changeEvent ); + if ( event.deltaY < 0 ) { - lastPosition.copy( this.object.position ); - lastQuaternion.copy (this.object.quaternion ); + dollyOut( getZoomScale() ); + + } else if ( event.deltaY > 0 ) { + + dollyIn( getZoomScale() ); } - }; + scope.update(); + } - this.reset = function () { + function handleKeyDown( event ) { - state = STATE.NONE; + //console.log( 'handleKeyDown' ); - this.target.copy( this.target0 ); - this.object.position.copy( this.position0 ); + switch ( event.keyCode ) { - this.update(); + case scope.keys.UP: + pan( 0, scope.keyPanSpeed ); + scope.update(); + break; - }; + case scope.keys.BOTTOM: + pan( 0, - scope.keyPanSpeed ); + scope.update(); + break; - this.getPolarAngle = function () { + case scope.keys.LEFT: + pan( scope.keyPanSpeed, 0 ); + scope.update(); + break; - return phi; + case scope.keys.RIGHT: + pan( - scope.keyPanSpeed, 0 ); + scope.update(); + break; - }; + } - this.getAzimuthalAngle = function () { + } - return theta + function handleTouchStartRotate( event ) { - }; + //console.log( 'handleTouchStartRotate' ); - function getAutoRotationAngle() { + rotateStart.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ); - return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed; + } + + function handleTouchStartDolly( event ) { + + //console.log( 'handleTouchStartDolly' ); + + var dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX; + var dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY; + + var distance = Math.sqrt( dx * dx + dy * dy ); + + dollyStart.set( 0, distance ); } - function getZoomScale() { + function handleTouchStartPan( event ) { - return Math.pow( 0.95, scope.zoomSpeed ); + //console.log( 'handleTouchStartPan' ); + + panStart.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ); } - function onMouseDown( event ) { + function handleTouchMoveRotate( event ) { - if ( scope.enabled === false ) return; - event.preventDefault(); + //console.log( 'handleTouchMoveRotate' ); - if ( event.button === scope.mouseButtons.ORBIT ) { - if ( scope.noRotate === true ) return; + rotateEnd.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ); + rotateDelta.subVectors( rotateEnd, rotateStart ); - state = STATE.ROTATE; + var element = scope.domElement === document ? scope.domElement.body : scope.domElement; - rotateStart.set( event.clientX, event.clientY ); + // rotating across whole screen goes 360 degrees around + rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientWidth * scope.rotateSpeed ); - } else if ( event.button === scope.mouseButtons.ZOOM ) { - if ( scope.noZoom === true ) return; + // rotating up and down along whole screen attempts to go 360, but limited to 180 + rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight * scope.rotateSpeed ); - state = STATE.DOLLY; + rotateStart.copy( rotateEnd ); - dollyStart.set( event.clientX, event.clientY ); + scope.update(); - } else if ( event.button === scope.mouseButtons.PAN ) { - if ( scope.noPan === true ) return; + } - state = STATE.PAN; + function handleTouchMoveDolly( event ) { - panStart.set( event.clientX, event.clientY ); + //console.log( 'handleTouchMoveDolly' ); - } + var dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX; + var dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY; + + var distance = Math.sqrt( dx * dx + dy * dy ); + + dollyEnd.set( 0, distance ); + + dollyDelta.subVectors( dollyEnd, dollyStart ); + + if ( dollyDelta.y > 0 ) { + + dollyOut( getZoomScale() ); + + } else if ( dollyDelta.y < 0 ) { + + dollyIn( getZoomScale() ); - if ( state !== STATE.NONE ) { - document.addEventListener( 'mousemove', onMouseMove, false ); - document.addEventListener( 'mouseup', onMouseUp, false ); - scope.dispatchEvent( startEvent ); } + dollyStart.copy( dollyEnd ); + + scope.update(); + } - function onMouseMove( event ) { + function handleTouchMovePan( event ) { - if ( scope.enabled === false ) return; + //console.log( 'handleTouchMovePan' ); - event.preventDefault(); + panEnd.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ); - var element = scope.domElement === document ? scope.domElement.body : scope.domElement; + panDelta.subVectors( panEnd, panStart ); - if ( state === STATE.ROTATE ) { + pan( panDelta.x, panDelta.y ); - if ( scope.noRotate === true ) return; + panStart.copy( panEnd ); - rotateEnd.set( event.clientX, event.clientY ); - rotateDelta.subVectors( rotateEnd, rotateStart ); + scope.update(); - // rotating across whole screen goes 360 degrees around - scope.rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientWidth * scope.rotateSpeed ); + } - // rotating up and down along whole screen attempts to go 360, but limited to 180 - scope.rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight * scope.rotateSpeed ); + function handleTouchEnd( event ) { - rotateStart.copy( rotateEnd ); + //console.log( 'handleTouchEnd' ); - } else if ( state === STATE.DOLLY ) { + } - if ( scope.noZoom === true ) return; + // + // event handlers - FSM: listen for events and reset state + // - dollyEnd.set( event.clientX, event.clientY ); - dollyDelta.subVectors( dollyEnd, dollyStart ); + function onMouseDown( event ) { - if ( dollyDelta.y > 0 ) { + if ( scope.enabled === false ) return; - scope.dollyIn(); + event.preventDefault(); - } else { + if ( event.button === scope.mouseButtons.ORBIT ) { - scope.dollyOut(); + if ( scope.enableRotate === false ) return; - } + handleMouseDownRotate( event ); - dollyStart.copy( dollyEnd ); + state = STATE.ROTATE; - } else if ( state === STATE.PAN ) { + } else if ( event.button === scope.mouseButtons.ZOOM ) { + + if ( scope.enableZoom === false ) return; + + handleMouseDownDolly( event ); + + state = STATE.DOLLY; - if ( scope.noPan === true ) return; + } else if ( event.button === scope.mouseButtons.PAN ) { - panEnd.set( event.clientX, event.clientY ); - panDelta.subVectors( panEnd, panStart ); + if ( scope.enablePan === false ) return; - scope.pan( panDelta.x, panDelta.y ); + handleMouseDownPan( event ); - panStart.copy( panEnd ); + state = STATE.PAN; } - if ( state !== STATE.NONE ) scope.update(); + if ( state !== STATE.NONE ) { + + document.addEventListener( 'mousemove', onMouseMove, false ); + document.addEventListener( 'mouseup', onMouseUp, false ); + + scope.dispatchEvent( startEvent ); + + } } - function onMouseUp( /* event */ ) { + function onMouseMove( event ) { if ( scope.enabled === false ) return; - document.removeEventListener( 'mousemove', onMouseMove, false ); - document.removeEventListener( 'mouseup', onMouseUp, false ); - scope.dispatchEvent( endEvent ); - state = STATE.NONE; + event.preventDefault(); - } + if ( state === STATE.ROTATE ) { - function onMouseWheel( event ) { + if ( scope.enableRotate === false ) return; - if ( scope.enabled === false || scope.noZoom === true || state !== STATE.NONE ) return; + handleMouseMoveRotate( event ); - event.preventDefault(); - event.stopPropagation(); + } else if ( state === STATE.DOLLY ) { - var delta = 0; + if ( scope.enableZoom === false ) return; - if ( event.wheelDelta !== undefined ) { // WebKit / Opera / Explorer 9 + handleMouseMoveDolly( event ); - delta = event.wheelDelta; + } else if ( state === STATE.PAN ) { - } else if ( event.detail !== undefined ) { // Firefox + if ( scope.enablePan === false ) return; - delta = - event.detail; + handleMouseMovePan( event ); } - if ( delta > 0 ) { + } - scope.dollyOut(); + function onMouseUp( event ) { - } else { + if ( scope.enabled === false ) return; - scope.dollyIn(); + handleMouseUp( event ); - } + document.removeEventListener( 'mousemove', onMouseMove, false ); + document.removeEventListener( 'mouseup', onMouseUp, false ); - scope.update(); - scope.dispatchEvent( startEvent ); scope.dispatchEvent( endEvent ); + state = STATE.NONE; + } - function onKeyDown( event ) { + function onMouseWheel( event ) { - if ( scope.enabled === false || scope.noKeys === true || scope.noPan === true ) return; + if ( scope.enabled === false || scope.enableZoom === false || ( state !== STATE.NONE && state !== STATE.ROTATE ) ) return; - switch ( event.keyCode ) { + event.preventDefault(); + event.stopPropagation(); - case scope.keys.UP: - scope.pan( 0, scope.keyPanSpeed ); - scope.update(); - break; + handleMouseWheel( event ); - case scope.keys.BOTTOM: - scope.pan( 0, - scope.keyPanSpeed ); - scope.update(); - break; + scope.dispatchEvent( startEvent ); // not sure why these are here... + scope.dispatchEvent( endEvent ); - case scope.keys.LEFT: - scope.pan( scope.keyPanSpeed, 0 ); - scope.update(); - break; + } - case scope.keys.RIGHT: - scope.pan( - scope.keyPanSpeed, 0 ); - scope.update(); - break; + function onKeyDown( event ) { - } + if ( scope.enabled === false || scope.enableKeys === false || scope.enablePan === false ) return; + + handleKeyDown( event ); } - function touchstart( event ) { + function onTouchStart( event ) { if ( scope.enabled === false ) return; @@ -534,32 +769,32 @@ THREE.OrbitControls = function ( object, domElement ) { case 1: // one-fingered touch: rotate - if ( scope.noRotate === true ) return; + if ( scope.enableRotate === false ) return; + + handleTouchStartRotate( event ); state = STATE.TOUCH_ROTATE; - rotateStart.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ); break; case 2: // two-fingered touch: dolly - if ( scope.noZoom === true ) return; + if ( scope.enableZoom === false ) return; + + handleTouchStartDolly( event ); state = STATE.TOUCH_DOLLY; - var dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX; - var dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY; - var distance = Math.sqrt( dx * dx + dy * dy ); - dollyStart.set( 0, distance ); break; case 3: // three-fingered touch: pan - if ( scope.noPan === true ) return; + if ( scope.enablePan === false ) return; + + handleTouchStartPan( event ); state = STATE.TOUCH_PAN; - panStart.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ); break; default: @@ -568,79 +803,48 @@ THREE.OrbitControls = function ( object, domElement ) { } - if ( state !== STATE.NONE ) scope.dispatchEvent( startEvent ); + if ( state !== STATE.NONE ) { + + scope.dispatchEvent( startEvent ); + + } } - function touchmove( event ) { + function onTouchMove( event ) { if ( scope.enabled === false ) return; event.preventDefault(); event.stopPropagation(); - var element = scope.domElement === document ? scope.domElement.body : scope.domElement; - switch ( event.touches.length ) { case 1: // one-fingered touch: rotate - if ( scope.noRotate === true ) return; - if ( state !== STATE.TOUCH_ROTATE ) return; + if ( scope.enableRotate === false ) return; + if ( state !== STATE.TOUCH_ROTATE ) return; // is this needed?... - rotateEnd.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ); - rotateDelta.subVectors( rotateEnd, rotateStart ); + handleTouchMoveRotate( event ); - // rotating across whole screen goes 360 degrees around - scope.rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientWidth * scope.rotateSpeed ); - // rotating up and down along whole screen attempts to go 360, but limited to 180 - scope.rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight * scope.rotateSpeed ); - - rotateStart.copy( rotateEnd ); - - scope.update(); break; case 2: // two-fingered touch: dolly - if ( scope.noZoom === true ) return; - if ( state !== STATE.TOUCH_DOLLY ) return; - - var dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX; - var dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY; - var distance = Math.sqrt( dx * dx + dy * dy ); - - dollyEnd.set( 0, distance ); - dollyDelta.subVectors( dollyEnd, dollyStart ); - - if ( dollyDelta.y > 0 ) { - - scope.dollyOut(); - - } else { - - scope.dollyIn(); + if ( scope.enableZoom === false ) return; + if ( state !== STATE.TOUCH_DOLLY ) return; // is this needed?... - } + handleTouchMoveDolly( event ); - dollyStart.copy( dollyEnd ); - - scope.update(); break; case 3: // three-fingered touch: pan - if ( scope.noPan === true ) return; - if ( state !== STATE.TOUCH_PAN ) return; - - panEnd.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ); - panDelta.subVectors( panEnd, panStart ); - - scope.pan( panDelta.x, panDelta.y ); + if ( scope.enablePan === false ) return; + if ( state !== STATE.TOUCH_PAN ) return; // is this needed?... - panStart.copy( panEnd ); + handleTouchMovePan( event ); - scope.update(); break; default: @@ -651,30 +855,167 @@ THREE.OrbitControls = function ( object, domElement ) { } - function touchend( /* event */ ) { + function onTouchEnd( event ) { if ( scope.enabled === false ) return; + handleTouchEnd( event ); + scope.dispatchEvent( endEvent ); + state = STATE.NONE; } - this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false ); - this.domElement.addEventListener( 'mousedown', onMouseDown, false ); - this.domElement.addEventListener( 'mousewheel', onMouseWheel, false ); - this.domElement.addEventListener( 'DOMMouseScroll', onMouseWheel, false ); // firefox + function onContextMenu( event ) { + + event.preventDefault(); + + } + + // + + scope.domElement.addEventListener( 'contextmenu', onContextMenu, false ); - this.domElement.addEventListener( 'touchstart', touchstart, false ); - this.domElement.addEventListener( 'touchend', touchend, false ); - this.domElement.addEventListener( 'touchmove', touchmove, false ); + scope.domElement.addEventListener( 'mousedown', onMouseDown, false ); + scope.domElement.addEventListener( 'wheel', onMouseWheel, false ); -// window.addEventListener( 'keydown', onKeyDown, false ); + scope.domElement.addEventListener( 'touchstart', onTouchStart, false ); + scope.domElement.addEventListener( 'touchend', onTouchEnd, false ); + scope.domElement.addEventListener( 'touchmove', onTouchMove, false ); + + window.addEventListener( 'keydown', onKeyDown, false ); // force an update at start + this.update(); }; THREE.OrbitControls.prototype = Object.create( THREE.EventDispatcher.prototype ); THREE.OrbitControls.prototype.constructor = THREE.OrbitControls; + +Object.defineProperties( THREE.OrbitControls.prototype, { + + center: { + + get: function () { + + console.warn( 'THREE.OrbitControls: .center has been renamed to .target' ); + return this.target; + + } + + }, + + // backward compatibility + + noZoom: { + + get: function () { + + console.warn( 'THREE.OrbitControls: .noZoom has been deprecated. Use .enableZoom instead.' ); + return ! this.enableZoom; + + }, + + set: function ( value ) { + + console.warn( 'THREE.OrbitControls: .noZoom has been deprecated. Use .enableZoom instead.' ); + this.enableZoom = ! value; + + } + + }, + + noRotate: { + + get: function () { + + console.warn( 'THREE.OrbitControls: .noRotate has been deprecated. Use .enableRotate instead.' ); + return ! this.enableRotate; + + }, + + set: function ( value ) { + + console.warn( 'THREE.OrbitControls: .noRotate has been deprecated. Use .enableRotate instead.' ); + this.enableRotate = ! value; + + } + + }, + + noPan: { + + get: function () { + + console.warn( 'THREE.OrbitControls: .noPan has been deprecated. Use .enablePan instead.' ); + return ! this.enablePan; + + }, + + set: function ( value ) { + + console.warn( 'THREE.OrbitControls: .noPan has been deprecated. Use .enablePan instead.' ); + this.enablePan = ! value; + + } + + }, + + noKeys: { + + get: function () { + + console.warn( 'THREE.OrbitControls: .noKeys has been deprecated. Use .enableKeys instead.' ); + return ! this.enableKeys; + + }, + + set: function ( value ) { + + console.warn( 'THREE.OrbitControls: .noKeys has been deprecated. Use .enableKeys instead.' ); + this.enableKeys = ! value; + + } + + }, + + staticMoving : { + + get: function () { + + console.warn( 'THREE.OrbitControls: .staticMoving has been deprecated. Use .enableDamping instead.' ); + return ! this.enableDamping; + + }, + + set: function ( value ) { + + console.warn( 'THREE.OrbitControls: .staticMoving has been deprecated. Use .enableDamping instead.' ); + this.enableDamping = ! value; + + } + + }, + + dynamicDampingFactor : { + + get: function () { + + console.warn( 'THREE.OrbitControls: .dynamicDampingFactor has been renamed. Use .dampingFactor instead.' ); + return this.dampingFactor; + + }, + + set: function ( value ) { + + console.warn( 'THREE.OrbitControls: .dynamicDampingFactor has been renamed. Use .dampingFactor instead.' ); + this.dampingFactor = value; + + } + + } + +} ); diff --git a/dependencies/three.js b/dependencies/three.js old mode 100644 new mode 100755 index e816315a76813ffe59e2e31f0715b2075fe9bdb5..81fe7f787e531edeb7249aceb8e36afaf0899567 --- a/dependencies/three.js +++ b/dependencies/three.js @@ -1,35970 +1,41795 @@ -// File:src/Three.js +var THREE = {}; +(function (global, factory) { + factory(THREE); + //console.log(THREE); + //typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + //typeof define === 'function' && define.amd ? define(['exports'], factory) : + //(factory((global.THREE = global.THREE || {}))); +}(this, (function (exports) { 'use strict'; -/** - * @author mrdoob / http://mrdoob.com/ - */ + // Polyfills -var THREE = { REVISION: '72' }; + if ( Number.EPSILON === undefined ) { -// + Number.EPSILON = Math.pow( 2, - 52 ); -if ( typeof define === 'function' && define.amd ) { + } - define( 'three', THREE ); + // -} else if ( 'undefined' !== typeof exports && 'undefined' !== typeof module ) { + if ( Math.sign === undefined ) { - module.exports = THREE; + // 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; -// polyfills + }; -if ( self.requestAnimationFrame === undefined || self.cancelAnimationFrame === undefined ) { + } - // Missing in Android stock browser. + if ( Function.prototype.name === undefined ) { - ( function () { + // Missing in IE9-11. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name - var lastTime = 0; - var vendors = [ 'ms', 'moz', 'webkit', 'o' ]; + Object.defineProperty( Function.prototype, 'name', { - for ( var x = 0; x < vendors.length && ! self.requestAnimationFrame; ++ x ) { + get: function () { - self.requestAnimationFrame = self[ vendors[ x ] + 'RequestAnimationFrame' ]; - self.cancelAnimationFrame = self[ vendors[ x ] + 'CancelAnimationFrame' ] || self[ vendors[ x ] + 'CancelRequestAnimationFrame' ]; + return this.toString().match( /^\s*function\s*(\S*)\s*\(/ )[ 1 ]; - } + } - if ( self.requestAnimationFrame === undefined && self.setTimeout !== undefined ) { + } ); - self.requestAnimationFrame = function ( callback ) { + } - var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) ); - var id = self.setTimeout( function () { + if ( Object.assign === undefined ) { - callback( currTime + timeToCall ); + // Missing in IE. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign - }, timeToCall ); - lastTime = currTime + timeToCall; - return id; + ( function () { - }; + Object.assign = function ( target ) { - } + 'use strict'; - if ( self.cancelAnimationFrame === undefined && self.clearTimeout !== undefined ) { + if ( target === undefined || target === null ) { - self.cancelAnimationFrame = function ( id ) { + throw new TypeError( 'Cannot convert undefined or null to object' ); - self.clearTimeout( id ); + } - }; + var output = Object( target ); - } + for ( var index = 1; index < arguments.length; index ++ ) { - }() ); + var source = arguments[ index ]; -} + if ( source !== undefined && source !== null ) { -if ( Math.sign === undefined ) { + for ( var nextKey in source ) { - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign + if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) { - Math.sign = function ( x ) { + output[ nextKey ] = source[ nextKey ]; - return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x; + } - }; + } -} + } -if ( Function.prototype.name === undefined && Object.defineProperty !== undefined ) { + } - // Missing in IE9-11. - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name + return output; - Object.defineProperty( Function.prototype, 'name', { + }; - get: function () { + } )(); - return this.toString().match( /^\s*function\s*(\S*)\s*\(/ )[ 1 ]; + } - } + /** + * https://github.com/mrdoob/eventdispatcher.js/ + */ - } ); + function EventDispatcher() {} -} + Object.assign( EventDispatcher.prototype, { -// https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.button + addEventListener: function ( type, listener ) { -THREE.MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 }; + if ( this._listeners === undefined ) this._listeners = {}; -// GL STATE CONSTANTS + var listeners = this._listeners; -THREE.CullFaceNone = 0; -THREE.CullFaceBack = 1; -THREE.CullFaceFront = 2; -THREE.CullFaceFrontBack = 3; + if ( listeners[ type ] === undefined ) { -THREE.FrontFaceDirectionCW = 0; -THREE.FrontFaceDirectionCCW = 1; + listeners[ type ] = []; -// SHADOWING TYPES + } -THREE.BasicShadowMap = 0; -THREE.PCFShadowMap = 1; -THREE.PCFSoftShadowMap = 2; + if ( listeners[ type ].indexOf( listener ) === - 1 ) { -// MATERIAL CONSTANTS + listeners[ type ].push( listener ); -// side + } -THREE.FrontSide = 0; -THREE.BackSide = 1; -THREE.DoubleSide = 2; + }, -// shading + hasEventListener: function ( type, listener ) { -THREE.FlatShading = 1; -THREE.SmoothShading = 2; + if ( this._listeners === undefined ) return false; -// colors + var listeners = this._listeners; -THREE.NoColors = 0; -THREE.FaceColors = 1; -THREE.VertexColors = 2; + if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) { -// blending modes + return true; -THREE.NoBlending = 0; -THREE.NormalBlending = 1; -THREE.AdditiveBlending = 2; -THREE.SubtractiveBlending = 3; -THREE.MultiplyBlending = 4; -THREE.CustomBlending = 5; + } -// custom blending equations -// (numbers start from 100 not to clash with other -// mappings to OpenGL constants defined in Texture.js) + return false; -THREE.AddEquation = 100; -THREE.SubtractEquation = 101; -THREE.ReverseSubtractEquation = 102; -THREE.MinEquation = 103; -THREE.MaxEquation = 104; + }, -// custom blending destination factors + removeEventListener: function ( type, listener ) { -THREE.ZeroFactor = 200; -THREE.OneFactor = 201; -THREE.SrcColorFactor = 202; -THREE.OneMinusSrcColorFactor = 203; -THREE.SrcAlphaFactor = 204; -THREE.OneMinusSrcAlphaFactor = 205; -THREE.DstAlphaFactor = 206; -THREE.OneMinusDstAlphaFactor = 207; + if ( this._listeners === undefined ) return; -// custom blending source factors + var listeners = this._listeners; + var listenerArray = listeners[ type ]; -//THREE.ZeroFactor = 200; -//THREE.OneFactor = 201; -//THREE.SrcAlphaFactor = 204; -//THREE.OneMinusSrcAlphaFactor = 205; -//THREE.DstAlphaFactor = 206; -//THREE.OneMinusDstAlphaFactor = 207; -THREE.DstColorFactor = 208; -THREE.OneMinusDstColorFactor = 209; -THREE.SrcAlphaSaturateFactor = 210; + if ( listenerArray !== undefined ) { -// depth modes + var index = listenerArray.indexOf( listener ); -THREE.NeverDepth = 0; -THREE.AlwaysDepth = 1; -THREE.LessDepth = 2; -THREE.LessEqualDepth = 3; -THREE.EqualDepth = 4; -THREE.GreaterEqualDepth = 5; -THREE.GreaterDepth = 6; -THREE.NotEqualDepth = 7; + if ( index !== - 1 ) { + listenerArray.splice( index, 1 ); -// TEXTURE CONSTANTS + } -THREE.MultiplyOperation = 0; -THREE.MixOperation = 1; -THREE.AddOperation = 2; + } -// Mapping modes + }, -THREE.UVMapping = 300; + dispatchEvent: function ( event ) { -THREE.CubeReflectionMapping = 301; -THREE.CubeRefractionMapping = 302; + if ( this._listeners === undefined ) return; -THREE.EquirectangularReflectionMapping = 303; -THREE.EquirectangularRefractionMapping = 304; + var listeners = this._listeners; + var listenerArray = listeners[ event.type ]; -THREE.SphericalReflectionMapping = 305; + if ( listenerArray !== undefined ) { -// Wrapping modes + event.target = this; -THREE.RepeatWrapping = 1000; -THREE.ClampToEdgeWrapping = 1001; -THREE.MirroredRepeatWrapping = 1002; + var array = [], i = 0; + var length = listenerArray.length; -// Filters + for ( i = 0; i < length; i ++ ) { -THREE.NearestFilter = 1003; -THREE.NearestMipMapNearestFilter = 1004; -THREE.NearestMipMapLinearFilter = 1005; -THREE.LinearFilter = 1006; -THREE.LinearMipMapNearestFilter = 1007; -THREE.LinearMipMapLinearFilter = 1008; + array[ i ] = listenerArray[ i ]; -// Data types + } -THREE.UnsignedByteType = 1009; -THREE.ByteType = 1010; -THREE.ShortType = 1011; -THREE.UnsignedShortType = 1012; -THREE.IntType = 1013; -THREE.UnsignedIntType = 1014; -THREE.FloatType = 1015; -THREE.HalfFloatType = 1025; + for ( i = 0; i < length; i ++ ) { -// Pixel types + array[ i ].call( this, event ); -//THREE.UnsignedByteType = 1009; -THREE.UnsignedShort4444Type = 1016; -THREE.UnsignedShort5551Type = 1017; -THREE.UnsignedShort565Type = 1018; + } -// Pixel formats + } -THREE.AlphaFormat = 1019; -THREE.RGBFormat = 1020; -THREE.RGBAFormat = 1021; -THREE.LuminanceFormat = 1022; -THREE.LuminanceAlphaFormat = 1023; -// THREE.RGBEFormat handled as THREE.RGBAFormat in shaders -THREE.RGBEFormat = THREE.RGBAFormat; //1024; + } + + } ); + + var REVISION = '81'; + 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 BlendingMode = { + NoBlending: NoBlending, + NormalBlending: NormalBlending, + AdditiveBlending: AdditiveBlending, + SubtractiveBlending: SubtractiveBlending, + MultiplyBlending: MultiplyBlending, + CustomBlending: CustomBlending + }; + 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 TextureMapping = { + UVMapping: UVMapping, + CubeReflectionMapping: CubeReflectionMapping, + CubeRefractionMapping: CubeRefractionMapping, + EquirectangularReflectionMapping: EquirectangularReflectionMapping, + EquirectangularRefractionMapping: EquirectangularRefractionMapping, + SphericalReflectionMapping: SphericalReflectionMapping, + CubeUVReflectionMapping: CubeUVReflectionMapping, + CubeUVRefractionMapping: CubeUVRefractionMapping + }; + var RepeatWrapping = 1000; + var ClampToEdgeWrapping = 1001; + var MirroredRepeatWrapping = 1002; + var TextureWrapping = { + RepeatWrapping: RepeatWrapping, + ClampToEdgeWrapping: ClampToEdgeWrapping, + MirroredRepeatWrapping: MirroredRepeatWrapping + }; + var NearestFilter = 1003; + var NearestMipMapNearestFilter = 1004; + var NearestMipMapLinearFilter = 1005; + var LinearFilter = 1006; + var LinearMipMapNearestFilter = 1007; + var LinearMipMapLinearFilter = 1008; + var TextureFilter = { + NearestFilter: NearestFilter, + NearestMipMapNearestFilter: NearestMipMapNearestFilter, + NearestMipMapLinearFilter: NearestMipMapLinearFilter, + LinearFilter: LinearFilter, + LinearMipMapNearestFilter: LinearMipMapNearestFilter, + LinearMipMapLinearFilter: LinearMipMapLinearFilter + }; + 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 () { -// DDS / ST3C Compressed texture formats + // http://www.broofa.com/Tools/Math.uuid.htm -THREE.RGB_S3TC_DXT1_Format = 2001; -THREE.RGBA_S3TC_DXT1_Format = 2002; -THREE.RGBA_S3TC_DXT3_Format = 2003; -THREE.RGBA_S3TC_DXT5_Format = 2004; + var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' ); + var uuid = new Array( 36 ); + var rnd = 0, r; + return function generateUUID() { -// PVRTC compressed texture formats + for ( var i = 0; i < 36; i ++ ) { -THREE.RGB_PVRTC_4BPPV1_Format = 2100; -THREE.RGB_PVRTC_2BPPV1_Format = 2101; -THREE.RGBA_PVRTC_4BPPV1_Format = 2102; -THREE.RGBA_PVRTC_2BPPV1_Format = 2103; + if ( i === 8 || i === 13 || i === 18 || i === 23 ) { + uuid[ i ] = '-'; -// DEPRECATED + } else if ( i === 14 ) { -THREE.Projector = function () { + uuid[ i ] = '4'; - console.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' ); + } else { - this.projectVector = function ( vector, camera ) { + if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0; + r = rnd & 0xf; + rnd = rnd >> 4; + uuid[ i ] = chars[ ( i === 19 ) ? ( r & 0x3 ) | 0x8 : r ]; - console.warn( 'THREE.Projector: .projectVector() is now vector.project().' ); - vector.project( camera ); + } - }; + } - this.unprojectVector = function ( vector, camera ) { + return uuid.join( '' ); - console.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' ); - vector.unproject( camera ); + }; - }; + }(), - this.pickingRay = function ( vector, camera ) { + clamp: function ( value, min, max ) { - console.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' ); + return Math.max( min, Math.min( max, value ) ); - }; + }, -}; + // compute euclidian modulo of m % n + // https://en.wikipedia.org/wiki/Modulo_operation -THREE.CanvasRenderer = function () { + euclideanModulo: function ( n, m ) { - console.error( 'THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js' ); + return ( ( n % m ) + m ) % m; - this.domElement = document.createElement( 'canvas' ); - this.clear = function () {}; - this.render = function () {}; - this.setClearColor = function () {}; - this.setSize = function () {}; + }, -}; + // Linear mapping from range to range -// File:src/math/Color.js + mapLinear: function ( x, a1, a2, b1, b2 ) { -/** - * @author mrdoob / http://mrdoob.com/ - */ + return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 ); -THREE.Color = function ( color ) { + }, - if ( arguments.length === 3 ) { + // http://en.wikipedia.org/wiki/Smoothstep - return this.setRGB( arguments[ 0 ], arguments[ 1 ], arguments[ 2 ] ); + smoothstep: function ( x, min, max ) { - } + if ( x <= min ) return 0; + if ( x >= max ) return 1; - return this.set( color ); + x = ( x - min ) / ( max - min ); -}; + return x * x * ( 3 - 2 * x ); -THREE.Color.prototype = { + }, - constructor: THREE.Color, + smootherstep: function ( x, min, max ) { - r: 1, g: 1, b: 1, + if ( x <= min ) return 0; + if ( x >= max ) return 1; - set: function ( value ) { + x = ( x - min ) / ( max - min ); - if ( value instanceof THREE.Color ) { + return x * x * x * ( x * ( x * 6 - 15 ) + 10 ); - this.copy( value ); + }, - } else if ( typeof value === 'number' ) { + random16: function () { - this.setHex( value ); + console.warn( 'THREE.Math.random16() has been deprecated. Use Math.random() instead.' ); + return Math.random(); - } else if ( typeof value === 'string' ) { + }, - this.setStyle( value ); + // Random integer from interval - } + randInt: function ( low, high ) { - return this; + return low + Math.floor( Math.random() * ( high - low + 1 ) ); - }, + }, - setHex: function ( hex ) { + // Random float from interval - hex = Math.floor( hex ); + randFloat: function ( low, high ) { - this.r = ( hex >> 16 & 255 ) / 255; - this.g = ( hex >> 8 & 255 ) / 255; - this.b = ( hex & 255 ) / 255; + return low + Math.random() * ( high - low ); - return this; + }, - }, + // Random float from <-range/2, range/2> interval - setRGB: function ( r, g, b ) { + randFloatSpread: function ( range ) { - this.r = r; - this.g = g; - this.b = b; + return range * ( 0.5 - Math.random() ); - return this; + }, - }, + degToRad: function ( degrees ) { - setHSL: function () { + return degrees * exports.Math.DEG2RAD; - 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; + radToDeg: function ( radians ) { - } + return radians * exports.Math.RAD2DEG; - return function ( h, s, l ) { + }, - // h,s,l ranges are in 0.0 - 1.0 - h = THREE.Math.euclideanModulo( h, 1 ); - s = THREE.Math.clamp( s, 0, 1 ); - l = THREE.Math.clamp( l, 0, 1 ); + isPowerOfTwo: function ( value ) { - if ( s === 0 ) { + return ( value & ( value - 1 ) ) === 0 && value !== 0; - this.r = this.g = this.b = l; + }, - } else { + nearestPowerOfTwo: function ( value ) { - var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s ); - var q = ( 2 * l ) - p; + return Math.pow( 2, Math.round( Math.log( value ) / Math.LN2 ) ); - this.r = hue2rgb( q, p, h + 1 / 3 ); - this.g = hue2rgb( q, p, h ); - this.b = hue2rgb( q, p, h - 1 / 3 ); + }, - } + nextPowerOfTwo: function ( value ) { - return this; + value --; + value |= value >> 1; + value |= value >> 2; + value |= value >> 4; + value |= value >> 8; + value |= value >> 16; + value ++; - }; + return value; - }(), + } - setStyle: function ( style ) { + }; - var parseAlpha = function ( strAlpha ) { + /** + * @author mrdoob / http://mrdoob.com/ + * @author philogb / http://blog.thejit.org/ + * @author egraether / http://egraether.com/ + * @author zz85 / http://www.lab4games.net/zz85/blog + */ - var alpha = parseFloat( strAlpha ); + function Vector2( x, y ) { - if ( alpha < 1 ) { + this.x = x || 0; + this.y = y || 0; - console.warn( 'THREE.Color: Alpha component of color ' + style + ' will be ignored.' ); + } - } + Vector2.prototype = { - return alpha; + constructor: Vector2, - } + isVector2: true, + get width() { - var m; + return this.x; - if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) { + }, - // rgb / hsl + set width( value ) { - var color; - var name = m[ 1 ]; - var components = m[ 2 ]; + this.x = value; - switch ( name ) { + }, - case 'rgb': + get height() { - if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*$/.exec( components ) ) { + return this.y; - // rgb(255,0,0) - 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; + }, - return this; + set height( value ) { - } + this.y = value; - if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*$/.exec( components ) ) { + }, - // rgb(100%,0%,0%) - this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100; - this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100; - this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100; + // - return this; + set: function ( x, y ) { - } + this.x = x; + this.y = y; - break; + return this; - case 'rgba': + }, - if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*([0-9]*\.?[0-9]+)\s*$/.exec( components ) ) { + setScalar: function ( scalar ) { - // 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; - parseAlpha( color[ 4 ] ); + this.x = scalar; + this.y = scalar; - return this; + return this; - } + }, - if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*([0-9]*\.?[0-9]+)\s*$/.exec( components ) ) { + setX: function ( x ) { - // 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; - parseAlpha( color[ 4 ] ); + this.x = x; - return this; + return this; - } + }, - break; + setY: function ( y ) { - case 'hsl': + this.y = y; - if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*$/.exec( components ) ) { + return this; - // hsl(120,50%,50%) - var h = parseFloat( color[ 1 ] ); - var s = parseInt( color[ 2 ], 10 ) / 100; - var l = parseInt( color[ 3 ], 10 ) / 100; + }, - return this.setHSL( h, s, l ); + setComponent: function ( index, value ) { - } + switch ( index ) { - break; + case 0: this.x = value; break; + case 1: this.y = value; break; + default: throw new Error( 'index is out of range: ' + index ); - case 'hsla': + } - if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*([0-9]*\.?[0-9]+)\s*$/.exec( components ) ) { + }, - // hsla(120,50%,50%,0.5) - var h = parseFloat( color[ 1 ] ); - var s = parseInt( color[ 2 ], 10 ) / 100; - var l = parseInt( color[ 3 ], 10 ) / 100; - parseAlpha( color[ 4 ] ); + getComponent: function ( index ) { - return this.setHSL( h, s, l ); + switch ( index ) { - } + case 0: return this.x; + case 1: return this.y; + default: throw new Error( 'index is out of range: ' + index ); - break; + } - } + }, - } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) { + clone: function () { - // hex color + return new this.constructor( this.x, this.y ); - var hex = m[ 1 ]; - var size = hex.length; + }, - if ( size === 3 ) { + copy: function ( v ) { - // #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; + this.x = v.x; + this.y = v.y; - return this; + return this; - } 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; + add: function ( v, w ) { - return this; + if ( w !== undefined ) { - } + console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); + return this.addVectors( v, w ); - } + } - if ( style && style.length > 0 ) { + this.x += v.x; + this.y += v.y; - // color keywords - var hex = THREE.ColorKeywords[ style ]; + return this; - if ( hex !== undefined ) { + }, - // red - this.setHex( hex ); + addScalar: function ( s ) { - } else { + this.x += s; + this.y += s; - // unknown color - console.warn( 'THREE.Color: Unknown color ' + style ); + return this; - } + }, - } + addVectors: function ( a, b ) { - return this; + this.x = a.x + b.x; + this.y = a.y + b.y; - }, + return this; - clone: function () { + }, - return new this.constructor( this.r, this.g, this.b ); + addScaledVector: function ( v, s ) { - }, + this.x += v.x * s; + this.y += v.y * s; - copy: function ( color ) { + return this; - this.r = color.r; - this.g = color.g; - this.b = color.b; + }, - return this; + sub: function ( v, w ) { - }, + if ( w !== undefined ) { - copyGammaToLinear: function ( color, gammaFactor ) { + console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); + return this.subVectors( v, w ); - if ( gammaFactor === undefined ) gammaFactor = 2.0; + } - this.r = Math.pow( color.r, gammaFactor ); - this.g = Math.pow( color.g, gammaFactor ); - this.b = Math.pow( color.b, gammaFactor ); + this.x -= v.x; + this.y -= v.y; - return this; + return this; - }, + }, - copyLinearToGamma: function ( color, gammaFactor ) { + subScalar: function ( s ) { - if ( gammaFactor === undefined ) gammaFactor = 2.0; + this.x -= s; + this.y -= s; - var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0; + return this; - this.r = Math.pow( color.r, safeInverse ); - this.g = Math.pow( color.g, safeInverse ); - this.b = Math.pow( color.b, safeInverse ); + }, - return this; + subVectors: function ( a, b ) { - }, + this.x = a.x - b.x; + this.y = a.y - b.y; - convertGammaToLinear: function () { + return this; - var r = this.r, g = this.g, b = this.b; + }, - this.r = r * r; - this.g = g * g; - this.b = b * b; + multiply: function ( v ) { - return this; + this.x *= v.x; + this.y *= v.y; - }, + return this; - convertLinearToGamma: function () { + }, - this.r = Math.sqrt( this.r ); - this.g = Math.sqrt( this.g ); - this.b = Math.sqrt( this.b ); + multiplyScalar: function ( scalar ) { - return this; + if ( isFinite( scalar ) ) { - }, + this.x *= scalar; + this.y *= scalar; - getHex: function () { + } else { - return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0; + this.x = 0; + this.y = 0; - }, + } - getHexString: function () { + return this; - return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 ); + }, - }, + divide: function ( v ) { - getHSL: function ( optionalTarget ) { + this.x /= v.x; + this.y /= v.y; - // h,s,l ranges are in 0.0 - 1.0 + return this; - var hsl = optionalTarget || { h: 0, s: 0, l: 0 }; + }, - var r = this.r, g = this.g, b = this.b; + divideScalar: function ( scalar ) { - var max = Math.max( r, g, b ); - var min = Math.min( r, g, b ); + return this.multiplyScalar( 1 / scalar ); - var hue, saturation; - var lightness = ( min + max ) / 2.0; + }, - if ( min === max ) { + min: function ( v ) { - hue = 0; - saturation = 0; + this.x = Math.min( this.x, v.x ); + this.y = Math.min( this.y, v.y ); - } else { + return this; - var delta = max - min; + }, - saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min ); + max: function ( v ) { - switch ( max ) { + this.x = Math.max( this.x, v.x ); + this.y = Math.max( this.y, v.y ); - 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; + return this; - } + }, - hue /= 6; + clamp: function ( min, max ) { - } + // This function assumes min < max, if this assumption isn't true it will not operate correctly - hsl.h = hue; - hsl.s = saturation; - hsl.l = lightness; + 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 hsl; + return this; - }, + }, - getStyle: function () { + clampScalar: function () { - return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')'; + var min, max; - }, + return function clampScalar( minVal, maxVal ) { - offsetHSL: function ( h, s, l ) { + if ( min === undefined ) { - var hsl = this.getHSL(); + min = new Vector2(); + max = new Vector2(); - hsl.h += h; hsl.s += s; hsl.l += l; + } - this.setHSL( hsl.h, hsl.s, hsl.l ); + min.set( minVal, minVal ); + max.set( maxVal, maxVal ); - return this; + return this.clamp( min, max ); - }, + }; - add: function ( color ) { + }(), - this.r += color.r; - this.g += color.g; - this.b += color.b; + clampLength: function ( min, max ) { - return this; + var length = this.length(); - }, + return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length ); - addColors: function ( color1, color2 ) { + }, - this.r = color1.r + color2.r; - this.g = color1.g + color2.g; - this.b = color1.b + color2.b; + floor: function () { - return this; + this.x = Math.floor( this.x ); + this.y = Math.floor( this.y ); - }, + return this; - addScalar: function ( s ) { + }, - this.r += s; - this.g += s; - this.b += s; + ceil: function () { - return this; + this.x = Math.ceil( this.x ); + this.y = Math.ceil( this.y ); - }, + return this; - multiply: function ( color ) { + }, - this.r *= color.r; - this.g *= color.g; - this.b *= color.b; + round: function () { - return this; + this.x = Math.round( this.x ); + this.y = Math.round( this.y ); - }, + return this; - multiplyScalar: function ( s ) { + }, - this.r *= s; - this.g *= s; - this.b *= s; + roundToZero: function () { - return this; + this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); + this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); - }, + return this; - lerp: function ( color, alpha ) { + }, - this.r += ( color.r - this.r ) * alpha; - this.g += ( color.g - this.g ) * alpha; - this.b += ( color.b - this.b ) * alpha; + negate: function () { - return this; + this.x = - this.x; + this.y = - this.y; - }, + return this; - equals: function ( c ) { + }, - return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b ); + dot: function ( v ) { - }, + return this.x * v.x + this.y * v.y; - fromArray: function ( array ) { + }, - this.r = array[ 0 ]; - this.g = array[ 1 ]; - this.b = array[ 2 ]; + lengthSq: function () { - return this; + return this.x * this.x + this.y * this.y; - }, + }, - toArray: function ( array, offset ) { + length: function () { - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + return Math.sqrt( this.x * this.x + this.y * this.y ); - array[ offset ] = this.r; - array[ offset + 1 ] = this.g; - array[ offset + 2 ] = this.b; + }, - return array; + lengthManhattan: function() { - } + return Math.abs( this.x ) + Math.abs( this.y ); -}; + }, -THREE.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 }; + normalize: function () { -// File:src/math/Quaternion.js + return this.divideScalar( this.length() ); -/** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author WestLangley / http://github.com/WestLangley - * @author bhouston / http://exocortex.com - */ + }, -THREE.Quaternion = function ( x, y, z, w ) { + angle: function () { - this._x = x || 0; - this._y = y || 0; - this._z = z || 0; - this._w = ( w !== undefined ) ? w : 1; + // computes the angle in radians with respect to the positive x-axis -}; + var angle = Math.atan2( this.y, this.x ); -THREE.Quaternion.prototype = { + if ( angle < 0 ) angle += 2 * Math.PI; - constructor: THREE.Quaternion, + return angle; - get x () { + }, - return this._x; + distanceTo: function ( v ) { - }, + return Math.sqrt( this.distanceToSquared( v ) ); - set x ( value ) { + }, - this._x = value; - this.onChangeCallback(); + distanceToSquared: function ( v ) { - }, + var dx = this.x - v.x, dy = this.y - v.y; + return dx * dx + dy * dy; - get y () { + }, - return this._y; + distanceToManhattan: function ( v ) { - }, + return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ); - set y ( value ) { + }, - this._y = value; - this.onChangeCallback(); + setLength: function ( length ) { - }, + return this.multiplyScalar( length / this.length() ); - get z () { + }, - return this._z; + lerp: function ( v, alpha ) { - }, + this.x += ( v.x - this.x ) * alpha; + this.y += ( v.y - this.y ) * alpha; - set z ( value ) { + return this; - this._z = value; - this.onChangeCallback(); + }, - }, + lerpVectors: function ( v1, v2, alpha ) { - get w () { + return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); - return this._w; + }, - }, + equals: function ( v ) { - set w ( value ) { + return ( ( v.x === this.x ) && ( v.y === this.y ) ); - this._w = value; - this.onChangeCallback(); + }, - }, + fromArray: function ( array, offset ) { - set: function ( x, y, z, w ) { + if ( offset === undefined ) offset = 0; - this._x = x; - this._y = y; - this._z = z; - this._w = w; + this.x = array[ offset ]; + this.y = array[ offset + 1 ]; - this.onChangeCallback(); + return this; - return this; + }, - }, + toArray: function ( array, offset ) { - clone: function () { + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - return new this.constructor( this._x, this._y, this._z, this._w ); + array[ offset ] = this.x; + array[ offset + 1 ] = this.y; - }, + return array; - copy: function ( quaternion ) { + }, - this._x = quaternion.x; - this._y = quaternion.y; - this._z = quaternion.z; - this._w = quaternion.w; + fromAttribute: function ( attribute, index, offset ) { - this.onChangeCallback(); + if ( offset === undefined ) offset = 0; - return this; + index = index * attribute.itemSize + offset; - }, + this.x = attribute.array[ index ]; + this.y = attribute.array[ index + 1 ]; - setFromEuler: function ( euler, update ) { + return this; - if ( euler instanceof THREE.Euler === false ) { + }, - throw new Error( 'THREE.Quaternion: .setFromEuler() now expects a Euler rotation rather than a Vector3 and order.' ); + rotateAround: function ( center, angle ) { - } + var c = Math.cos( angle ), s = Math.sin( angle ); - // http://www.mathworks.com/matlabcentral/fileexchange/ - // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/ - // content/SpinCalc.m + var x = this.x - center.x; + var y = this.y - center.y; - 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.x = x * c - y * s + center.x; + this.y = x * s + y * c + center.y; - 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; + }; - } else if ( order === 'YXZ' ) { + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * @author szimek / https://github.com/szimek/ + */ - 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; + function Texture( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) { - } else if ( order === 'ZXY' ) { + Object.defineProperty( this, 'id', { value: TextureIdCount() } ); - 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.uuid = exports.Math.generateUUID(); - } else if ( order === 'ZYX' ) { + this.name = ''; + this.sourceFile = ''; - 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.image = image !== undefined ? image : Texture.DEFAULT_IMAGE; + this.mipmaps = []; - } else if ( order === 'YZX' ) { + this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING; - 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.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping; + this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping; - } else if ( order === 'XZY' ) { + this.magFilter = magFilter !== undefined ? magFilter : LinearFilter; + this.minFilter = minFilter !== undefined ? minFilter : LinearMipMapLinearFilter; - 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.anisotropy = anisotropy !== undefined ? anisotropy : 1; - } + this.format = format !== undefined ? format : RGBAFormat; + this.type = type !== undefined ? type : UnsignedByteType; - if ( update !== false ) this.onChangeCallback(); + this.offset = new Vector2( 0, 0 ); + this.repeat = new Vector2( 1, 1 ); - return this; + 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) - }, - setFromAxisAngle: function ( axis, angle ) { + // 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; - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm + this.version = 0; + this.onUpdate = null; - // assumes axis is normalized + } - var halfAngle = angle / 2, s = Math.sin( halfAngle ); + Texture.DEFAULT_IMAGE = undefined; + Texture.DEFAULT_MAPPING = UVMapping; - this._x = axis.x * s; - this._y = axis.y * s; - this._z = axis.z * s; - this._w = Math.cos( halfAngle ); + Texture.prototype = { - this.onChangeCallback(); + constructor: Texture, - return this; + isTexture: true, - }, + set needsUpdate( value ) { - setFromRotationMatrix: function ( m ) { + if ( value === true ) this.version ++; - // 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) + clone: function () { - var te = m.elements, + return new this.constructor().copy( 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; + copy: function ( source ) { - if ( trace > 0 ) { + this.image = source.image; + this.mipmaps = source.mipmaps.slice( 0 ); - s = 0.5 / Math.sqrt( trace + 1.0 ); + this.mapping = source.mapping; - this._w = 0.25 / s; - this._x = ( m32 - m23 ) * s; - this._y = ( m13 - m31 ) * s; - this._z = ( m21 - m12 ) * s; + this.wrapS = source.wrapS; + this.wrapT = source.wrapT; - } else if ( m11 > m22 && m11 > m33 ) { + this.magFilter = source.magFilter; + this.minFilter = source.minFilter; - s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 ); + this.anisotropy = source.anisotropy; - this._w = ( m32 - m23 ) / s; - this._x = 0.25 * s; - this._y = ( m12 + m21 ) / s; - this._z = ( m13 + m31 ) / s; + this.format = source.format; + this.type = source.type; - } else if ( m22 > m33 ) { + this.offset.copy( source.offset ); + this.repeat.copy( source.repeat ); - s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 ); + this.generateMipmaps = source.generateMipmaps; + this.premultiplyAlpha = source.premultiplyAlpha; + this.flipY = source.flipY; + this.unpackAlignment = source.unpackAlignment; + this.encoding = source.encoding; - this._w = ( m13 - m31 ) / s; - this._x = ( m12 + m21 ) / s; - this._y = 0.25 * s; - this._z = ( m23 + m32 ) / s; + return this; - } else { + }, - s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 ); + toJSON: function ( meta ) { - this._w = ( m21 - m12 ) / s; - this._x = ( m13 + m31 ) / s; - this._y = ( m23 + m32 ) / s; - this._z = 0.25 * s; + if ( meta.textures[ this.uuid ] !== undefined ) { - } + return meta.textures[ this.uuid ]; - this.onChangeCallback(); + } - return this; + function getDataURL( image ) { - }, + var canvas; - setFromUnitVectors: function () { + if ( image.toDataURL !== undefined ) { - // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final + canvas = image; - // assumes direction vectors vFrom and vTo are normalized + } else { - var v1, r; + canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); + canvas.width = image.width; + canvas.height = image.height; - var EPS = 0.000001; + canvas.getContext( '2d' ).drawImage( image, 0, 0, image.width, image.height ); - return function ( vFrom, vTo ) { + } - if ( v1 === undefined ) v1 = new THREE.Vector3(); + if ( canvas.width > 2048 || canvas.height > 2048 ) { - r = vFrom.dot( vTo ) + 1; + return canvas.toDataURL( 'image/jpeg', 0.6 ); - if ( r < EPS ) { + } else { - r = 0; + return canvas.toDataURL( 'image/png' ); - if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) { + } - v1.set( - vFrom.y, vFrom.x, 0 ); + } - } else { + var output = { + metadata: { + version: 4.4, + type: 'Texture', + generator: 'Texture.toJSON' + }, - v1.set( 0, - vFrom.z, vFrom.y ); + uuid: this.uuid, + name: this.name, - } + mapping: this.mapping, - } else { + repeat: [ this.repeat.x, this.repeat.y ], + offset: [ this.offset.x, this.offset.y ], + wrap: [ this.wrapS, this.wrapT ], - v1.crossVectors( vFrom, vTo ); + minFilter: this.minFilter, + magFilter: this.magFilter, + anisotropy: this.anisotropy, - } + flipY: this.flipY + }; - this._x = v1.x; - this._y = v1.y; - this._z = v1.z; - this._w = r; + if ( this.image !== undefined ) { - this.normalize(); + // TODO: Move to THREE.Image - return this; + var image = this.image; - } + if ( image.uuid === undefined ) { - }(), + image.uuid = exports.Math.generateUUID(); // UGH - inverse: function () { + } - this.conjugate().normalize(); + if ( meta.images[ image.uuid ] === undefined ) { - return this; + meta.images[ image.uuid ] = { + uuid: image.uuid, + url: getDataURL( image ) + }; - }, + } - conjugate: function () { + output.image = image.uuid; - this._x *= - 1; - this._y *= - 1; - this._z *= - 1; + } - this.onChangeCallback(); + meta.textures[ this.uuid ] = output; - return this; + return output; - }, + }, - dot: function ( v ) { + dispose: function () { - return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w; + this.dispatchEvent( { type: 'dispose' } ); - }, + }, - lengthSq: function () { + transformUv: function ( uv ) { - return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; + if ( this.mapping !== UVMapping ) return; - }, + uv.multiply( this.repeat ); + uv.add( this.offset ); - length: function () { + if ( uv.x < 0 || uv.x > 1 ) { - return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w ); + switch ( this.wrapS ) { - }, + case RepeatWrapping: - normalize: function () { + uv.x = uv.x - Math.floor( uv.x ); + break; - var l = this.length(); + case ClampToEdgeWrapping: - if ( l === 0 ) { + uv.x = uv.x < 0 ? 0 : 1; + break; - this._x = 0; - this._y = 0; - this._z = 0; - this._w = 1; + case MirroredRepeatWrapping: - } else { + if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) { - l = 1 / l; + uv.x = Math.ceil( uv.x ) - uv.x; - this._x = this._x * l; - this._y = this._y * l; - this._z = this._z * l; - this._w = this._w * l; + } else { - } + uv.x = uv.x - Math.floor( uv.x ); - this.onChangeCallback(); + } + break; - return this; + } - }, + } - multiply: function ( q, p ) { + if ( uv.y < 0 || uv.y > 1 ) { - if ( p !== undefined ) { + switch ( this.wrapT ) { - console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' ); - return this.multiplyQuaternions( q, p ); + case RepeatWrapping: - } + uv.y = uv.y - Math.floor( uv.y ); + break; - return this.multiplyQuaternions( this, q ); + case ClampToEdgeWrapping: - }, + uv.y = uv.y < 0 ? 0 : 1; + break; - multiplyQuaternions: function ( a, b ) { + case MirroredRepeatWrapping: - // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm + if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) { - 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; + uv.y = Math.ceil( uv.y ) - uv.y; - 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; + } else { - this.onChangeCallback(); + uv.y = uv.y - Math.floor( uv.y ); - return this; + } + break; - }, + } - multiplyVector3: function ( vector ) { + } - console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' ); - return vector.applyQuaternion( this ); + if ( this.flipY ) { - }, + uv.y = 1 - uv.y; - slerp: function ( qb, t ) { + } - if ( t === 0 ) return this; - if ( t === 1 ) return this.copy( qb ); + } - var x = this._x, y = this._y, z = this._z, w = this._w; + }; - // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/ + Object.assign( Texture.prototype, EventDispatcher.prototype ); - var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z; + var count = 0; + function TextureIdCount() { return count++; }; - if ( cosHalfTheta < 0 ) { + /** + * @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 + */ - this._w = - qb._w; - this._x = - qb._x; - this._y = - qb._y; - this._z = - qb._z; + function Vector4( x, y, z, w ) { - cosHalfTheta = - cosHalfTheta; + this.x = x || 0; + this.y = y || 0; + this.z = z || 0; + this.w = ( w !== undefined ) ? w : 1; - } else { + } - this.copy( qb ); + Vector4.prototype = { - } + constructor: Vector4, - if ( cosHalfTheta >= 1.0 ) { + isVector4: true, - this._w = w; - this._x = x; - this._y = y; - this._z = z; + set: function ( x, y, z, w ) { - return this; + this.x = x; + this.y = y; + this.z = z; + this.w = w; - } + return this; - var halfTheta = Math.acos( cosHalfTheta ); - var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta ); + }, - if ( Math.abs( sinHalfTheta ) < 0.001 ) { + setScalar: function ( scalar ) { - 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 ); + this.x = scalar; + this.y = scalar; + this.z = scalar; + this.w = scalar; - return this; + return this; - } + }, - var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta, - ratioB = Math.sin( t * halfTheta ) / sinHalfTheta; + setX: function ( x ) { - 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 ); + this.x = x; - this.onChangeCallback(); + return this; - return this; + }, - }, + setY: function ( y ) { - equals: function ( quaternion ) { + this.y = y; - return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w ); + return this; - }, + }, - fromArray: function ( array, offset ) { + setZ: function ( z ) { - if ( offset === undefined ) offset = 0; + this.z = z; - this._x = array[ offset ]; - this._y = array[ offset + 1 ]; - this._z = array[ offset + 2 ]; - this._w = array[ offset + 3 ]; + return this; - this.onChangeCallback(); + }, - return this; + setW: function ( w ) { - }, + this.w = w; - toArray: function ( array, offset ) { + return this; - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + }, - array[ offset ] = this._x; - array[ offset + 1 ] = this._y; - array[ offset + 2 ] = this._z; - array[ offset + 3 ] = this._w; + setComponent: function ( index, value ) { - return array; + 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 ); - onChange: function ( callback ) { + } - this.onChangeCallback = callback; + }, - return this; + getComponent: function ( index ) { - }, + switch ( index ) { - onChangeCallback: function () {} + 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 ); -}; + } -THREE.Quaternion.slerp = function ( qa, qb, qm, t ) { + }, - return qm.copy( qa ).slerp( qb, t ); + clone: function () { -}; + return new this.constructor( this.x, this.y, this.z, this.w ); -// File:src/math/Vector2.js + }, -/** - * @author mrdoob / http://mrdoob.com/ - * @author philogb / http://blog.thejit.org/ - * @author egraether / http://egraether.com/ - * @author zz85 / http://www.lab4games.net/zz85/blog - */ + copy: function ( v ) { -THREE.Vector2 = function ( x, y ) { + this.x = v.x; + this.y = v.y; + this.z = v.z; + this.w = ( v.w !== undefined ) ? v.w : 1; - this.x = x || 0; - this.y = y || 0; + return this; -}; + }, -THREE.Vector2.prototype = { + add: function ( v, w ) { - constructor: THREE.Vector2, + if ( w !== undefined ) { - set: function ( x, y ) { + console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); + return this.addVectors( v, w ); - this.x = x; - this.y = y; + } - return this; + this.x += v.x; + this.y += v.y; + this.z += v.z; + this.w += v.w; - }, + return this; - setX: function ( x ) { + }, - this.x = x; + addScalar: function ( s ) { - return this; + this.x += s; + this.y += s; + this.z += s; + this.w += s; - }, + return this; - setY: function ( y ) { + }, - this.y = y; + addVectors: function ( a, b ) { - return this; + this.x = a.x + b.x; + this.y = a.y + b.y; + this.z = a.z + b.z; + this.w = a.w + b.w; - }, + return this; - setComponent: function ( index, value ) { + }, - switch ( index ) { + addScaledVector: function ( v, s ) { - case 0: this.x = value; break; - case 1: this.y = value; break; - default: throw new Error( 'index is out of range: ' + index ); + this.x += v.x * s; + this.y += v.y * s; + this.z += v.z * s; + this.w += v.w * s; - } + return this; - }, + }, - getComponent: function ( index ) { + sub: function ( v, w ) { - switch ( index ) { + if ( w !== undefined ) { - case 0: return this.x; - case 1: return this.y; - default: throw new Error( 'index is out of range: ' + index ); + console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); + return this.subVectors( v, w ); - } + } - }, + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; + this.w -= v.w; - clone: function () { + return this; - return new this.constructor( this.x, this.y ); + }, - }, + subScalar: function ( s ) { - copy: function ( v ) { + this.x -= s; + this.y -= s; + this.z -= s; + this.w -= s; - this.x = v.x; - this.y = v.y; + return this; - return this; + }, - }, + subVectors: function ( a, b ) { - add: function ( v, w ) { + this.x = a.x - b.x; + this.y = a.y - b.y; + this.z = a.z - b.z; + this.w = a.w - b.w; - if ( w !== undefined ) { + return this; - console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); - return this.addVectors( v, w ); + }, - } + multiplyScalar: function ( scalar ) { - this.x += v.x; - this.y += v.y; + if ( isFinite( scalar ) ) { - return this; + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; + this.w *= scalar; - }, + } else { - addScalar: function ( s ) { + this.x = 0; + this.y = 0; + this.z = 0; + this.w = 0; - this.x += s; - this.y += s; + } - return this; + return this; - }, + }, - addVectors: function ( a, b ) { + applyMatrix4: function ( m ) { - this.x = a.x + b.x; - this.y = a.y + b.y; + var x = this.x, y = this.y, z = this.z, w = this.w; + var e = m.elements; - return this; + this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w; + this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w; + this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w; + this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w; - }, + return this; - addScaledVector: function ( v, s ) { + }, - this.x += v.x * s; - this.y += v.y * s; + divideScalar: function ( scalar ) { - return this; + return this.multiplyScalar( 1 / scalar ); - }, + }, - sub: function ( v, w ) { + setAxisAngleFromQuaternion: function ( q ) { - if ( w !== undefined ) { + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm - console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); - return this.subVectors( v, w ); + // q is assumed to be normalized - } + this.w = 2 * Math.acos( q.w ); - this.x -= v.x; - this.y -= v.y; + var s = Math.sqrt( 1 - q.w * q.w ); - return this; + if ( s < 0.0001 ) { - }, + this.x = 1; + this.y = 0; + this.z = 0; - subScalar: function ( s ) { + } else { - this.x -= s; - this.y -= s; + this.x = q.x / s; + this.y = q.y / s; + this.z = q.z / s; - return this; + } - }, + return this; - subVectors: function ( a, b ) { + }, - this.x = a.x - b.x; - this.y = a.y - b.y; + setAxisAngleFromRotationMatrix: function ( m ) { - return this; + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm - }, + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - multiply: function ( v ) { + 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 - this.x *= v.x; - this.y *= v.y; + 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 ]; - }, + if ( ( Math.abs( m12 - m21 ) < epsilon ) && + ( Math.abs( m13 - m31 ) < epsilon ) && + ( Math.abs( m23 - m32 ) < epsilon ) ) { - multiplyScalar: function ( s ) { + // singularity found + // first check for identity matrix which must have +1 for all terms + // in leading diagonal and zero in other terms - this.x *= s; - this.y *= s; + 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 ); - divide: function ( v ) { + return this; // zero angle, arbitrary axis - this.x /= v.x; - this.y /= v.y; + } - return this; + // otherwise this singularity is angle = 180 - }, + angle = Math.PI; - divideScalar: function ( scalar ) { + var xx = ( m11 + 1 ) / 2; + var yy = ( m22 + 1 ) / 2; + var zz = ( m33 + 1 ) / 2; + var xy = ( m12 + m21 ) / 4; + var xz = ( m13 + m31 ) / 4; + var yz = ( m23 + m32 ) / 4; - if ( scalar !== 0 ) { + if ( ( xx > yy ) && ( xx > zz ) ) { - var invScalar = 1 / scalar; + // m11 is the largest diagonal term - this.x *= invScalar; - this.y *= invScalar; + if ( xx < epsilon ) { - } else { + x = 0; + y = 0.707106781; + z = 0.707106781; - this.x = 0; - this.y = 0; + } else { - } + x = Math.sqrt( xx ); + y = xy / x; + z = xz / x; - return this; + } - }, + } else if ( yy > zz ) { - min: function ( v ) { + // m22 is the largest diagonal term - if ( this.x > v.x ) { + if ( yy < epsilon ) { - this.x = v.x; + x = 0.707106781; + y = 0; + z = 0.707106781; - } + } else { - if ( this.y > v.y ) { + y = Math.sqrt( yy ); + x = xy / y; + z = yz / y; - this.y = v.y; + } - } + } else { - return this; + // m33 is the largest diagonal term so base result on this - }, + if ( zz < epsilon ) { - max: function ( v ) { + x = 0.707106781; + y = 0.707106781; + z = 0; - if ( this.x < v.x ) { + } else { - this.x = v.x; + z = Math.sqrt( zz ); + x = xz / z; + y = yz / z; - } + } - if ( this.y < v.y ) { + } - this.y = v.y; + this.set( x, y, z, angle ); - } + return this; // return 180 deg rotation - return this; + } - }, + // as we have reached here there are no singularities so we can handle normally - clamp: function ( min, max ) { + var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) + + ( m13 - m31 ) * ( m13 - m31 ) + + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize - // This function assumes min < max, if this assumption isn't true it will not operate correctly + if ( Math.abs( s ) < 0.001 ) s = 1; - if ( this.x < min.x ) { + // 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 = min.x; + this.x = ( m32 - m23 ) / s; + this.y = ( m13 - m31 ) / s; + this.z = ( m21 - m12 ) / s; + this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 ); - } else if ( this.x > max.x ) { + return this; - this.x = max.x; + }, - } + min: function ( v ) { - if ( this.y < min.y ) { + this.x = Math.min( this.x, v.x ); + this.y = Math.min( this.y, v.y ); + this.z = Math.min( this.z, v.z ); + this.w = Math.min( this.w, v.w ); - this.y = min.y; + return this; - } else if ( this.y > max.y ) { + }, - this.y = max.y; + max: function ( v ) { - } + this.x = Math.max( this.x, v.x ); + this.y = Math.max( this.y, v.y ); + this.z = Math.max( this.z, v.z ); + this.w = Math.max( this.w, v.w ); - return this; + return this; - }, + }, - clampScalar: function () { + clamp: function ( min, max ) { - var min, max; + // This function assumes min < max, if this assumption isn't true it will not operate correctly - return function clampScalar( minVal, maxVal ) { + 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 ) ); - if ( min === undefined ) { + return this; - min = new THREE.Vector2(); - max = new THREE.Vector2(); + }, - } + clampScalar: function () { - min.set( minVal, minVal ); - max.set( maxVal, maxVal ); + var min, max; - return this.clamp( min, max ); + return function clampScalar( minVal, maxVal ) { - }; + if ( min === undefined ) { - }(), + min = new Vector4(); + max = new Vector4(); - floor: function () { + } - this.x = Math.floor( this.x ); - this.y = Math.floor( this.y ); + min.set( minVal, minVal, minVal, minVal ); + max.set( maxVal, maxVal, maxVal, maxVal ); - return this; + return this.clamp( min, max ); - }, + }; - ceil: function () { + }(), - this.x = Math.ceil( this.x ); - this.y = Math.ceil( this.y ); + 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; - round: function () { + }, - this.x = Math.round( this.x ); - this.y = Math.round( this.y ); + 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; - roundToZero: function () { + }, - this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); - this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); + 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; - negate: function () { + }, - this.x = - this.x; - this.y = - this.y; + roundToZero: function () { - return this; + this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); + this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); + this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z ); + this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w ); - }, + return this; - dot: function ( v ) { + }, - return this.x * v.x + this.y * v.y; + negate: function () { - }, + this.x = - this.x; + this.y = - this.y; + this.z = - this.z; + this.w = - this.w; - lengthSq: function () { + return this; - return this.x * this.x + this.y * this.y; + }, - }, + dot: function ( v ) { - length: function () { + return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; - return Math.sqrt( this.x * this.x + this.y * this.y ); + }, - }, + lengthSq: function () { - lengthManhattan: function() { + return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; - return Math.abs( this.x ) + Math.abs( this.y ); + }, - }, + length: function () { - normalize: function () { + return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w ); - return this.divideScalar( this.length() ); + }, - }, + lengthManhattan: function () { - distanceTo: function ( v ) { + return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w ); - return Math.sqrt( this.distanceToSquared( v ) ); + }, - }, + normalize: function () { - distanceToSquared: function ( v ) { + return this.divideScalar( this.length() ); - var dx = this.x - v.x, dy = this.y - v.y; - return dx * dx + dy * dy; + }, - }, + setLength: function ( length ) { - setLength: function ( l ) { + return this.multiplyScalar( length / this.length() ); - var oldLength = this.length(); + }, - if ( oldLength !== 0 && l !== oldLength ) { + lerp: function ( v, alpha ) { - this.multiplyScalar( l / oldLength ); + 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; - return this; + }, - }, + lerpVectors: function ( v1, v2, alpha ) { - lerp: function ( v, alpha ) { + return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); - this.x += ( v.x - this.x ) * alpha; - this.y += ( v.y - this.y ) * alpha; + }, - return this; + equals: function ( v ) { - }, + return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) ); - lerpVectors: function ( v1, v2, alpha ) { + }, - this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); + 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 ]; - equals: function ( v ) { + return this; - return ( ( v.x === this.x ) && ( v.y === this.y ) ); + }, - }, + toArray: function ( array, offset ) { - fromArray: function ( array, offset ) { + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - if ( offset === undefined ) offset = 0; + array[ offset ] = this.x; + array[ offset + 1 ] = this.y; + array[ offset + 2 ] = this.z; + array[ offset + 3 ] = this.w; - this.x = array[ offset ]; - this.y = array[ offset + 1 ]; + return array; - return this; + }, - }, + fromAttribute: function ( attribute, index, offset ) { - toArray: function ( array, offset ) { + if ( offset === undefined ) offset = 0; - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + index = index * attribute.itemSize + offset; - array[ offset ] = this.x; - array[ offset + 1 ] = this.y; + this.x = attribute.array[ index ]; + this.y = attribute.array[ index + 1 ]; + this.z = attribute.array[ index + 2 ]; + this.w = attribute.array[ index + 3 ]; - return array; + return this; - }, + } - fromAttribute: function ( attribute, index, offset ) { + }; - if ( offset === undefined ) offset = 0; + /** + * @author szimek / https://github.com/szimek/ + * @author alteredq / http://alteredqualia.com/ + * @author Marius Kintel / https://github.com/kintel + */ - index = index * attribute.itemSize + offset; + /* + 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 ) { - this.x = attribute.array[ index ]; - this.y = attribute.array[ index + 1 ]; + this.uuid = exports.Math.generateUUID(); - return this; + 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 ); -// File:src/math/Vector3.js + options = options || {}; -/** - * @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 - */ + if ( options.minFilter === undefined ) options.minFilter = LinearFilter; -THREE.Vector3 = function ( x, y, z ) { + this.texture = new Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding ); - this.x = x || 0; - this.y = y || 0; - this.z = z || 0; + this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true; + this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true; + this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null; -}; + } -THREE.Vector3.prototype = { + Object.assign( WebGLRenderTarget.prototype, EventDispatcher.prototype, { - constructor: THREE.Vector3, + isWebGLRenderTarget: true, - set: function ( x, y, z ) { + setSize: function ( width, height ) { - this.x = x; - this.y = y; - this.z = z; + if ( this.width !== width || this.height !== height ) { - return this; + this.width = width; + this.height = height; - }, + this.dispose(); - setX: function ( x ) { + } - this.x = x; + this.viewport.set( 0, 0, width, height ); + this.scissor.set( 0, 0, width, height ); - return this; + }, - }, + clone: function () { - setY: function ( y ) { + return new this.constructor().copy( this ); - this.y = y; + }, - return this; + copy: function ( source ) { - }, + this.width = source.width; + this.height = source.height; - setZ: function ( z ) { + this.viewport.copy( source.viewport ); - this.z = z; + this.texture = source.texture.clone(); - return this; + this.depthBuffer = source.depthBuffer; + this.stencilBuffer = source.stencilBuffer; + this.depthTexture = source.depthTexture; - }, + return this; - setComponent: function ( index, value ) { + }, - switch ( index ) { + dispose: function () { - case 0: this.x = value; break; - case 1: this.y = value; break; - case 2: this.z = value; break; - default: throw new Error( 'index is out of range: ' + index ); + this.dispatchEvent( { type: 'dispose' } ); - } + } - }, + } ); - getComponent: function ( index ) { + /** + * @author alteredq / http://alteredqualia.com + */ - switch ( index ) { + function WebGLRenderTargetCube( width, height, options ) { - 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 ); + WebGLRenderTarget.call( this, width, height, options ); - } + this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5 + this.activeMipMapLevel = 0; - }, + } - clone: function () { + WebGLRenderTargetCube.prototype = Object.create( WebGLRenderTarget.prototype ); + WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube; - return new this.constructor( this.x, this.y, this.z ); + WebGLRenderTargetCube.prototype.isWebGLRenderTargetCube = true; - }, + /** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + * @author WestLangley / http://github.com/WestLangley + * @author bhouston / http://clara.io + */ - copy: function ( v ) { + function Quaternion( x, y, z, w ) { - this.x = v.x; - this.y = v.y; - this.z = v.z; + this._x = x || 0; + this._y = y || 0; + this._z = z || 0; + this._w = ( w !== undefined ) ? w : 1; - return this; + } - }, + Quaternion.prototype = { - add: function ( v, w ) { + constructor: Quaternion, - if ( w !== undefined ) { + get x () { - console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); - return this.addVectors( v, w ); + return this._x; - } + }, - this.x += v.x; - this.y += v.y; - this.z += v.z; + set x ( value ) { - return this; + this._x = value; + this.onChangeCallback(); - }, + }, - addScalar: function ( s ) { + get y () { - this.x += s; - this.y += s; - this.z += s; + return this._y; - return this; + }, - }, + set y ( value ) { - addVectors: function ( a, b ) { + this._y = value; + this.onChangeCallback(); - this.x = a.x + b.x; - this.y = a.y + b.y; - this.z = a.z + b.z; + }, - return this; + get z () { - }, + return this._z; - addScaledVector: function ( v, s ) { + }, - this.x += v.x * s; - this.y += v.y * s; - this.z += v.z * s; + set z ( value ) { - return this; + this._z = value; + this.onChangeCallback(); - }, + }, - sub: function ( v, w ) { + get w () { - if ( w !== undefined ) { + return this._w; - console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); - return this.subVectors( v, w ); + }, - } + set w ( value ) { - this.x -= v.x; - this.y -= v.y; - this.z -= v.z; + this._w = value; + this.onChangeCallback(); - return this; + }, - }, + set: function ( x, y, z, w ) { - subScalar: function ( s ) { + this._x = x; + this._y = y; + this._z = z; + this._w = w; - this.x -= s; - this.y -= s; - this.z -= s; + this.onChangeCallback(); - return this; + return this; - }, + }, - subVectors: function ( a, b ) { + clone: function () { - this.x = a.x - b.x; - this.y = a.y - b.y; - this.z = a.z - b.z; + return new this.constructor( this._x, this._y, this._z, this._w ); - return this; + }, - }, + copy: function ( quaternion ) { - multiply: function ( v, w ) { + this._x = quaternion.x; + this._y = quaternion.y; + this._z = quaternion.z; + this._w = quaternion.w; - if ( w !== undefined ) { + this.onChangeCallback(); - console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' ); - return this.multiplyVectors( v, w ); + return this; - } + }, - this.x *= v.x; - this.y *= v.y; - this.z *= v.z; + setFromEuler: function ( euler, update ) { - return this; + if ( (euler && euler.isEuler) === false ) { - }, + throw new Error( 'THREE.Quaternion: .setFromEuler() now expects a Euler rotation rather than a Vector3 and order.' ); - multiplyScalar: function ( scalar ) { + } - this.x *= scalar; - this.y *= scalar; - this.z *= scalar; + // http://www.mathworks.com/matlabcentral/fileexchange/ + // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/ + // content/SpinCalc.m - return this; + var c1 = Math.cos( euler._x / 2 ); + var c2 = Math.cos( euler._y / 2 ); + var c3 = Math.cos( euler._z / 2 ); + var s1 = Math.sin( euler._x / 2 ); + var s2 = Math.sin( euler._y / 2 ); + var s3 = Math.sin( euler._z / 2 ); - }, + var order = euler.order; - multiplyVectors: function ( a, b ) { + if ( order === 'XYZ' ) { - this.x = a.x * b.x; - this.y = a.y * b.y; - this.z = a.z * b.z; + 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 === '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; - applyEuler: function () { + } else if ( order === 'ZXY' ) { - var quaternion; + 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 function applyEuler( euler ) { + } else if ( order === 'ZYX' ) { - if ( euler instanceof THREE.Euler === false ) { + 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; - console.error( 'THREE.Vector3: .applyEuler() now expects a Euler rotation rather than a Vector3 and order.' ); + } 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; - if ( quaternion === undefined ) quaternion = new THREE.Quaternion(); + } else if ( order === 'XZY' ) { - this.applyQuaternion( quaternion.setFromEuler( euler ) ); + 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; + } - }; + if ( update !== false ) this.onChangeCallback(); - }(), + return this; - applyAxisAngle: function () { + }, - var quaternion; + setFromAxisAngle: function ( axis, angle ) { - return function applyAxisAngle( axis, angle ) { + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm - if ( quaternion === undefined ) quaternion = new THREE.Quaternion(); + // assumes axis is normalized - this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) ); + var halfAngle = angle / 2, s = Math.sin( halfAngle ); - return this; + this._x = axis.x * s; + this._y = axis.y * s; + this._z = axis.z * s; + this._w = Math.cos( halfAngle ); - }; + this.onChangeCallback(); - }(), + return this; - applyMatrix3: function ( m ) { + }, - var x = this.x; - var y = this.y; - var z = this.z; + setFromRotationMatrix: function ( m ) { - var e = m.elements; + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm - 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; + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - return this; + var te = m.elements, - }, + m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ], + m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ], + m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ], - applyMatrix4: function ( m ) { + trace = m11 + m22 + m33, + s; - // input: THREE.Matrix4 affine matrix + if ( trace > 0 ) { - var x = this.x, y = this.y, z = this.z; + s = 0.5 / Math.sqrt( trace + 1.0 ); - var e = m.elements; + this._w = 0.25 / s; + this._x = ( m32 - m23 ) * s; + this._y = ( m13 - m31 ) * s; + this._z = ( m21 - m12 ) * s; - 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 ]; + } else if ( m11 > m22 && m11 > m33 ) { - return this; + 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; - applyProjection: function ( m ) { + } else if ( m22 > m33 ) { - // input: THREE.Matrix4 projection matrix + s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 ); - var x = this.x, y = this.y, z = this.z; + this._w = ( m13 - m31 ) / s; + this._x = ( m12 + m21 ) / s; + this._y = 0.25 * s; + this._z = ( m23 + m32 ) / s; - var e = m.elements; - var d = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); // perspective divide + } else { - 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; + s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 ); - return this; + this._w = ( m21 - m12 ) / s; + this._x = ( m13 + m31 ) / s; + this._y = ( m23 + m32 ) / s; + this._z = 0.25 * s; - }, + } - applyQuaternion: function ( q ) { + this.onChangeCallback(); - var x = this.x; - var y = this.y; - var z = this.z; + return this; - var qx = q.x; - var qy = q.y; - var qz = q.z; - var qw = q.w; + }, - // calculate quat * vector + setFromUnitVectors: function () { - 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; + // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final - // calculate result * inverse quat + // assumes direction vectors vFrom and vTo are normalized - 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; + var v1, r; - return this; + var EPS = 0.000001; - }, + return function setFromUnitVectors( vFrom, vTo ) { - project: function () { + if ( v1 === undefined ) v1 = new Vector3(); - var matrix; + r = vFrom.dot( vTo ) + 1; - return function project( camera ) { + if ( r < EPS ) { - if ( matrix === undefined ) matrix = new THREE.Matrix4(); + r = 0; - matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) ); - return this.applyProjection( matrix ); + if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) { - }; + v1.set( - vFrom.y, vFrom.x, 0 ); - }(), + } else { - unproject: function () { + v1.set( 0, - vFrom.z, vFrom.y ); - var matrix; + } - return function unproject( camera ) { + } else { - if ( matrix === undefined ) matrix = new THREE.Matrix4(); + v1.crossVectors( vFrom, vTo ); - matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) ); - return this.applyProjection( matrix ); + } - }; + this._x = v1.x; + this._y = v1.y; + this._z = v1.z; + this._w = r; - }(), + return this.normalize(); - transformDirection: function ( m ) { + }; - // input: THREE.Matrix4 affine matrix - // vector interpreted as a direction + }(), - var x = this.x, y = this.y, z = this.z; + inverse: function () { - var e = m.elements; + return this.conjugate().normalize(); - 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; + }, - this.normalize(); + conjugate: function () { - return this; + this._x *= - 1; + this._y *= - 1; + this._z *= - 1; - }, + this.onChangeCallback(); - divide: function ( v ) { + return this; - this.x /= v.x; - this.y /= v.y; - this.z /= v.z; + }, - return this; + dot: function ( v ) { - }, + return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w; - divideScalar: function ( scalar ) { + }, - if ( scalar !== 0 ) { + lengthSq: function () { - var invScalar = 1 / scalar; + return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; - this.x *= invScalar; - this.y *= invScalar; - this.z *= invScalar; + }, - } else { + length: function () { - this.x = 0; - this.y = 0; - this.z = 0; + return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w ); - } + }, - return this; + normalize: function () { - }, + var l = this.length(); - min: function ( v ) { + if ( l === 0 ) { - if ( this.x > v.x ) { + this._x = 0; + this._y = 0; + this._z = 0; + this._w = 1; - this.x = v.x; + } else { - } + l = 1 / l; - if ( this.y > v.y ) { + this._x = this._x * l; + this._y = this._y * l; + this._z = this._z * l; + this._w = this._w * l; - this.y = v.y; + } - } + this.onChangeCallback(); - if ( this.z > v.z ) { + return this; - this.z = v.z; + }, - } + multiply: function ( q, p ) { - return this; + if ( p !== undefined ) { - }, + console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' ); + return this.multiplyQuaternions( q, p ); - max: function ( v ) { + } - if ( this.x < v.x ) { + return this.multiplyQuaternions( this, q ); - this.x = v.x; + }, - } + premultiply: function ( q ) { - if ( this.y < v.y ) { + return this.multiplyQuaternions( q, this ); - this.y = v.y; + }, - } + multiplyQuaternions: function ( a, b ) { - if ( this.z < v.z ) { + // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm - this.z = v.z; + var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w; + var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w; - } + this._x = 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; - clamp: function ( min, max ) { + }, - // This function assumes min < max, if this assumption isn't true it will not operate correctly + slerp: function ( qb, t ) { - if ( this.x < min.x ) { + if ( t === 0 ) return this; + if ( t === 1 ) return this.copy( qb ); - this.x = min.x; + var x = this._x, y = this._y, z = this._z, w = this._w; - } else if ( this.x > max.x ) { + // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/ - this.x = max.x; + var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z; - } + if ( cosHalfTheta < 0 ) { - if ( this.y < min.y ) { + this._w = - qb._w; + this._x = - qb._x; + this._y = - qb._y; + this._z = - qb._z; - this.y = min.y; + cosHalfTheta = - cosHalfTheta; - } else if ( this.y > max.y ) { + } else { - this.y = max.y; + this.copy( qb ); - } + } - if ( this.z < min.z ) { + if ( cosHalfTheta >= 1.0 ) { - this.z = min.z; + this._w = w; + this._x = x; + this._y = y; + this._z = z; - } else if ( this.z > max.z ) { + return this; - this.z = max.z; + } - } + var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta ); - return this; + if ( Math.abs( sinHalfTheta ) < 0.001 ) { - }, + this._w = 0.5 * ( w + this._w ); + this._x = 0.5 * ( x + this._x ); + this._y = 0.5 * ( y + this._y ); + this._z = 0.5 * ( z + this._z ); - clampScalar: function () { + return this; - var min, max; + } - return function clampScalar( minVal, maxVal ) { + var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta ); + var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta, + ratioB = Math.sin( t * halfTheta ) / sinHalfTheta; - if ( min === undefined ) { + 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 ); - min = new THREE.Vector3(); - max = new THREE.Vector3(); + this.onChangeCallback(); - } + return this; - min.set( minVal, minVal, minVal ); - max.set( maxVal, maxVal, maxVal ); + }, - return this.clamp( min, max ); + equals: function ( quaternion ) { - }; + return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w ); - }(), + }, - floor: function () { + fromArray: function ( array, offset ) { - this.x = Math.floor( this.x ); - this.y = Math.floor( this.y ); - this.z = Math.floor( this.z ); + if ( offset === undefined ) offset = 0; - return this; + this._x = array[ offset ]; + this._y = array[ offset + 1 ]; + this._z = array[ offset + 2 ]; + this._w = array[ offset + 3 ]; - }, + this.onChangeCallback(); - ceil: function () { + return this; - this.x = Math.ceil( this.x ); - this.y = Math.ceil( this.y ); - this.z = Math.ceil( this.z ); + }, - return this; + toArray: function ( array, offset ) { - }, + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - round: function () { + array[ offset ] = this._x; + array[ offset + 1 ] = this._y; + array[ offset + 2 ] = this._z; + array[ offset + 3 ] = this._w; - this.x = Math.round( this.x ); - this.y = Math.round( this.y ); - this.z = Math.round( this.z ); + return array; - return this; + }, - }, + onChange: function ( callback ) { - roundToZero: function () { + this.onChangeCallback = callback; - this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); - this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); - this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z ); + return this; - return this; + }, - }, + onChangeCallback: function () {} - negate: function () { + }; - this.x = - this.x; - this.y = - this.y; - this.z = - this.z; + Object.assign( Quaternion, { - return this; + slerp: function( qa, qb, qm, t ) { - }, + return qm.copy( qa ).slerp( qb, t ); - dot: function ( v ) { + }, - return this.x * v.x + this.y * v.y + this.z * v.z; + slerpFlat: function( + dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) { - }, + // fuzz-free, array-based Quaternion SLERP operation - lengthSq: function () { + var x0 = src0[ srcOffset0 + 0 ], + y0 = src0[ srcOffset0 + 1 ], + z0 = src0[ srcOffset0 + 2 ], + w0 = src0[ srcOffset0 + 3 ], - return this.x * this.x + this.y * this.y + this.z * this.z; + x1 = src1[ srcOffset1 + 0 ], + y1 = src1[ srcOffset1 + 1 ], + z1 = src1[ srcOffset1 + 2 ], + w1 = src1[ srcOffset1 + 3 ]; - }, + if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) { - length: function () { + var s = 1 - t, - return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z ); + cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1, - }, + dir = ( cos >= 0 ? 1 : - 1 ), + sqrSin = 1 - cos * cos; - lengthManhattan: function () { + // Skip the Slerp for tiny steps to avoid numeric problems: + if ( sqrSin > Number.EPSILON ) { - return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ); + var sin = Math.sqrt( sqrSin ), + len = Math.atan2( sin, cos * dir ); - }, + s = Math.sin( s * len ) / sin; + t = Math.sin( t * len ) / sin; - normalize: function () { + } - return this.divideScalar( this.length() ); + var tDir = t * dir; - }, + x0 = x0 * s + x1 * tDir; + y0 = y0 * s + y1 * tDir; + z0 = z0 * s + z1 * tDir; + w0 = w0 * s + w1 * tDir; - setLength: function ( l ) { + // Normalize in case we just did a lerp: + if ( s === 1 - t ) { - var oldLength = this.length(); + var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 ); - if ( oldLength !== 0 && l !== oldLength ) { + x0 *= f; + y0 *= f; + z0 *= f; + w0 *= f; - this.multiplyScalar( l / oldLength ); + } - } + } - return this; + dst[ dstOffset ] = x0; + dst[ dstOffset + 1 ] = y0; + dst[ dstOffset + 2 ] = z0; + dst[ dstOffset + 3 ] = w0; - }, + } - 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; + /** + * @author mrdoob / http://mrdoob.com/ + * @author *kile / http://kile.stravaganza.org/ + * @author philogb / http://blog.thejit.org/ + * @author mikael emtinger / http://gomo.se/ + * @author egraether / http://egraether.com/ + * @author WestLangley / http://github.com/WestLangley + */ - return this; + function Vector3( x, y, z ) { - }, + this.x = x || 0; + this.y = y || 0; + this.z = z || 0; - lerpVectors: function ( v1, v2, alpha ) { + } - this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); + Vector3.prototype = { - return this; + constructor: Vector3, - }, + isVector3: true, - cross: function ( v, w ) { + set: function ( x, y, z ) { - if ( w !== undefined ) { + this.x = x; + this.y = y; + this.z = z; - console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' ); - return this.crossVectors( v, w ); + return this; - } + }, - var x = this.x, y = this.y, z = this.z; + setScalar: function ( scalar ) { - this.x = y * v.z - z * v.y; - this.y = z * v.x - x * v.z; - this.z = x * v.y - y * v.x; + this.x = scalar; + this.y = scalar; + this.z = scalar; - return this; + return this; - }, + }, - crossVectors: function ( a, b ) { + setX: function ( x ) { - var ax = a.x, ay = a.y, az = a.z; - var bx = b.x, by = b.y, bz = b.z; + this.x = x; - this.x = ay * bz - az * by; - this.y = az * bx - ax * bz; - this.z = ax * by - ay * bx; + return this; - return this; + }, - }, + setY: function ( y ) { - projectOnVector: function () { + this.y = y; - var v1, dot; + return this; - return function projectOnVector( vector ) { + }, - if ( v1 === undefined ) v1 = new THREE.Vector3(); + setZ: function ( z ) { - v1.copy( vector ).normalize(); + this.z = z; - dot = this.dot( v1 ); + return this; - return this.copy( v1 ).multiplyScalar( dot ); + }, - }; + setComponent: function ( index, value ) { - }(), + switch ( index ) { - projectOnPlane: function () { + 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 v1; + } - return function projectOnPlane( planeNormal ) { + }, - if ( v1 === undefined ) v1 = new THREE.Vector3(); + getComponent: function ( index ) { - v1.copy( this ).projectOnVector( planeNormal ); + switch ( index ) { - return this.sub( v1 ); + 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 ); - } + } - }(), + }, - reflect: function () { + clone: function () { - // reflect incident vector off plane orthogonal to normal - // normal is assumed to have unit length + return new this.constructor( this.x, this.y, this.z ); - var v1; + }, - return function reflect( normal ) { + copy: function ( v ) { - if ( v1 === undefined ) v1 = new THREE.Vector3(); + this.x = v.x; + this.y = v.y; + this.z = v.z; - return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) ); + return this; - } + }, - }(), + add: function ( v, w ) { - angleTo: function ( v ) { + if ( w !== undefined ) { - var theta = this.dot( v ) / ( this.length() * v.length() ); + console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); + return this.addVectors( v, w ); - // clamp, to handle numerical problems + } - return Math.acos( THREE.Math.clamp( theta, - 1, 1 ) ); + this.x += v.x; + this.y += v.y; + this.z += v.z; - }, + return this; - distanceTo: function ( v ) { + }, - return Math.sqrt( this.distanceToSquared( v ) ); + addScalar: function ( s ) { - }, + this.x += s; + this.y += s; + this.z += s; - distanceToSquared: function ( v ) { + return this; - var dx = this.x - v.x; - var dy = this.y - v.y; - var dz = this.z - v.z; + }, - return dx * dx + dy * dy + dz * dz; + addVectors: function ( a, b ) { - }, + this.x = a.x + b.x; + this.y = a.y + b.y; + this.z = a.z + b.z; - setEulerFromRotationMatrix: function ( m, order ) { + return this; - console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' ); + }, - }, + addScaledVector: function ( v, s ) { - setEulerFromQuaternion: function ( q, order ) { + this.x += v.x * s; + this.y += v.y * s; + this.z += v.z * s; - console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' ); + return this; - }, + }, - getPositionFromMatrix: function ( m ) { + sub: function ( v, w ) { - console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' ); + if ( w !== undefined ) { - return this.setFromMatrixPosition( m ); + console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); + return this.subVectors( v, w ); - }, + } - getScaleFromMatrix: function ( m ) { + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; - console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' ); + return this; - return this.setFromMatrixScale( m ); + }, - }, + subScalar: function ( s ) { - getColumnFromMatrix: function ( index, matrix ) { + this.x -= s; + this.y -= s; + this.z -= s; - console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' ); + return this; - return this.setFromMatrixColumn( index, matrix ); + }, - }, + subVectors: function ( a, b ) { - setFromMatrixPosition: function ( m ) { + this.x = a.x - b.x; + this.y = a.y - b.y; + this.z = a.z - b.z; - this.x = m.elements[ 12 ]; - this.y = m.elements[ 13 ]; - this.z = m.elements[ 14 ]; + return this; - return this; + }, - }, + multiply: function ( v, w ) { - setFromMatrixScale: function ( m ) { + if ( w !== undefined ) { - var sx = this.set( m.elements[ 0 ], m.elements[ 1 ], m.elements[ 2 ] ).length(); - var sy = this.set( m.elements[ 4 ], m.elements[ 5 ], m.elements[ 6 ] ).length(); - var sz = this.set( m.elements[ 8 ], m.elements[ 9 ], m.elements[ 10 ] ).length(); + console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' ); + return this.multiplyVectors( v, w ); - this.x = sx; - this.y = sy; - this.z = sz; + } - return this; + this.x *= v.x; + this.y *= v.y; + this.z *= v.z; - }, + return this; - setFromMatrixColumn: function ( index, matrix ) { + }, - var offset = index * 4; + multiplyScalar: function ( scalar ) { - var me = matrix.elements; + if ( isFinite( scalar ) ) { - this.x = me[ offset ]; - this.y = me[ offset + 1 ]; - this.z = me[ offset + 2 ]; + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; - return this; + } else { - }, + this.x = 0; + this.y = 0; + this.z = 0; - equals: function ( v ) { + } - return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) ); + return this; - }, + }, - fromArray: function ( array, offset ) { + multiplyVectors: function ( a, b ) { - if ( offset === undefined ) offset = 0; + this.x = a.x * b.x; + this.y = a.y * b.y; + this.z = a.z * b.z; - this.x = array[ offset ]; - this.y = array[ offset + 1 ]; - this.z = array[ offset + 2 ]; + return this; - return this; + }, - }, + applyEuler: function () { - toArray: function ( array, offset ) { + var quaternion; - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + return function applyEuler( euler ) { - array[ offset ] = this.x; - array[ offset + 1 ] = this.y; - array[ offset + 2 ] = this.z; + if ( (euler && euler.isEuler) === false ) { - return array; + console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' ); - }, + } - fromAttribute: function ( attribute, index, offset ) { + if ( quaternion === undefined ) quaternion = new Quaternion(); - if ( offset === undefined ) offset = 0; + return this.applyQuaternion( quaternion.setFromEuler( euler ) ); - index = index * attribute.itemSize + offset; + }; - this.x = attribute.array[ index ]; - this.y = attribute.array[ index + 1 ]; - this.z = attribute.array[ index + 2 ]; + }(), - return this; + applyAxisAngle: function () { - } + var quaternion; -}; + return function applyAxisAngle( axis, angle ) { -// File:src/math/Vector4.js + if ( quaternion === undefined ) quaternion = new Quaternion(); -/** - * @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 - */ + return this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) ); -THREE.Vector4 = function ( x, y, z, w ) { + }; - this.x = x || 0; - this.y = y || 0; - this.z = z || 0; - this.w = ( w !== undefined ) ? w : 1; + }(), -}; + applyMatrix3: function ( m ) { -THREE.Vector4.prototype = { + var x = this.x, y = this.y, z = this.z; + var e = m.elements; - constructor: THREE.Vector4, + 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; - set: function ( x, y, z, w ) { + return this; - this.x = x; - this.y = y; - this.z = z; - this.w = w; + }, - return this; + applyMatrix4: function ( m ) { - }, + // input: THREE.Matrix4 affine matrix - setX: function ( x ) { + var x = this.x, y = this.y, z = this.z; + var e = m.elements; - this.x = x; + this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ]; + this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ]; + this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ]; - return this; + return this; - }, + }, - setY: function ( y ) { + applyProjection: function ( m ) { - this.y = y; + // input: THREE.Matrix4 projection matrix - return this; + 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 = ( 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; - setZ: function ( z ) { + return this; - this.z = z; + }, - return this; + applyQuaternion: function ( q ) { - }, + var x = this.x, y = this.y, z = this.z; + var qx = q.x, qy = q.y, qz = q.z, qw = q.w; - setW: function ( w ) { + // calculate quat * vector - this.w = w; + 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; - 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 ); + project: function () { - } + var matrix; - }, + return function project( camera ) { - getComponent: function ( index ) { + if ( matrix === undefined ) matrix = new Matrix4(); - switch ( index ) { + matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) ); + return this.applyProjection( matrix ); - 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 ); + }; - } + }(), - }, + unproject: function () { - clone: function () { + var matrix; - return new this.constructor( this.x, this.y, this.z, this.w ); + return function unproject( camera ) { - }, + if ( matrix === undefined ) matrix = new Matrix4(); - copy: function ( v ) { + matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) ); + return this.applyProjection( matrix ); - this.x = v.x; - this.y = v.y; - this.z = v.z; - this.w = ( v.w !== undefined ) ? v.w : 1; + }; - return this; + }(), - }, + transformDirection: function ( m ) { - add: function ( v, w ) { + // input: THREE.Matrix4 affine matrix + // vector interpreted as a direction - if ( w !== undefined ) { + var x = this.x, y = this.y, z = this.z; + var e = m.elements; - console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); - return this.addVectors( v, w ); + 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(); - this.x += v.x; - this.y += v.y; - this.z += v.z; - this.w += v.w; + }, - return this; + divide: function ( v ) { - }, + this.x /= v.x; + this.y /= v.y; + this.z /= v.z; - addScalar: function ( s ) { + return this; - this.x += s; - this.y += s; - this.z += s; - this.w += s; + }, - return this; + divideScalar: function ( scalar ) { - }, + return this.multiplyScalar( 1 / scalar ); - 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; + min: function ( v ) { - return this; + this.x = Math.min( this.x, v.x ); + this.y = Math.min( this.y, v.y ); + this.z = Math.min( this.z, v.z ); - }, + return this; - addScaledVector: function ( v, s ) { + }, - this.x += v.x * s; - this.y += v.y * s; - this.z += v.z * s; - this.w += v.w * s; + max: function ( v ) { - return this; + this.x = Math.max( this.x, v.x ); + this.y = Math.max( this.y, v.y ); + this.z = Math.max( this.z, v.z ); - }, + return this; - sub: function ( v, w ) { + }, - if ( w !== undefined ) { + clamp: function ( min, max ) { - console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); - return this.subVectors( v, 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.x -= v.x; - this.y -= v.y; - this.z -= v.z; - this.w -= v.w; + return this; - return this; + }, - }, + clampScalar: function () { - subScalar: function ( s ) { + var min, max; - this.x -= s; - this.y -= s; - this.z -= s; - this.w -= s; + return function clampScalar( minVal, maxVal ) { - return this; + if ( min === undefined ) { - }, + min = new Vector3(); + max = new Vector3(); - 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; + min.set( minVal, minVal, minVal ); + max.set( maxVal, maxVal, maxVal ); - return this; + return this.clamp( min, max ); - }, + }; - multiplyScalar: function ( scalar ) { + }(), - this.x *= scalar; - this.y *= scalar; - this.z *= scalar; - this.w *= scalar; + clampLength: function ( min, max ) { - return this; + var length = this.length(); - }, + return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length ); - applyMatrix4: function ( m ) { + }, - var x = this.x; - var y = this.y; - var z = this.z; - var w = this.w; + floor: function () { - var e = m.elements; + this.x = Math.floor( this.x ); + this.y = Math.floor( this.y ); + this.z = Math.floor( this.z ); - 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; - return this; + }, - }, + ceil: function () { - divideScalar: function ( scalar ) { + this.x = Math.ceil( this.x ); + this.y = Math.ceil( this.y ); + this.z = Math.ceil( this.z ); - if ( scalar !== 0 ) { + return this; - var invScalar = 1 / scalar; + }, - this.x *= invScalar; - this.y *= invScalar; - this.z *= invScalar; - this.w *= invScalar; + round: function () { - } else { + this.x = Math.round( this.x ); + this.y = Math.round( this.y ); + this.z = Math.round( this.z ); - this.x = 0; - this.y = 0; - this.z = 0; - this.w = 1; + return this; - } + }, - return this; + roundToZero: function () { - }, + this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); + this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); + this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z ); - setAxisAngleFromQuaternion: function ( q ) { + return this; - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm + }, - // q is assumed to be normalized + negate: function () { - this.w = 2 * Math.acos( q.w ); + this.x = - this.x; + this.y = - this.y; + this.z = - this.z; - var s = Math.sqrt( 1 - q.w * q.w ); + return this; - if ( s < 0.0001 ) { + }, - this.x = 1; - this.y = 0; - this.z = 0; + dot: function ( v ) { - } else { + return this.x * v.x + this.y * v.y + this.z * v.z; - this.x = q.x / s; - this.y = q.y / s; - this.z = q.z / s; + }, - } + lengthSq: function () { - return this; + return this.x * this.x + this.y * this.y + this.z * this.z; - }, + }, - setAxisAngleFromRotationMatrix: function ( m ) { + length: function () { - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm + return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z ); - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + }, - var angle, x, y, z, // variables for result - epsilon = 0.01, // margin to allow for rounding errors - epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees + lengthManhattan: function () { - te = m.elements, + return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ); - 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 ( ( Math.abs( m12 - m21 ) < epsilon ) - && ( Math.abs( m13 - m31 ) < epsilon ) - && ( Math.abs( m23 - m32 ) < epsilon ) ) { + normalize: function () { - // singularity found - // first check for identity matrix which must have +1 for all terms - // in leading diagonal and zero in other terms + return this.divideScalar( this.length() ); - if ( ( Math.abs( m12 + m21 ) < epsilon2 ) - && ( Math.abs( m13 + m31 ) < epsilon2 ) - && ( Math.abs( m23 + m32 ) < epsilon2 ) - && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) { + }, - // this singularity is identity matrix so angle = 0 + setLength: function ( length ) { - this.set( 1, 0, 0, 0 ); + return this.multiplyScalar( length / this.length() ); - return this; // zero angle, arbitrary axis + }, - } + lerp: function ( v, alpha ) { - // otherwise this singularity is angle = 180 + this.x += ( v.x - this.x ) * alpha; + this.y += ( v.y - this.y ) * alpha; + this.z += ( v.z - this.z ) * alpha; - angle = Math.PI; + return 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; + }, - if ( ( xx > yy ) && ( xx > zz ) ) { + lerpVectors: function ( v1, v2, alpha ) { - // m11 is the largest diagonal term + return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); - if ( xx < epsilon ) { + }, - x = 0; - y = 0.707106781; - z = 0.707106781; + cross: function ( v, w ) { - } else { + if ( w !== undefined ) { - x = Math.sqrt( xx ); - y = xy / x; - z = xz / x; + console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' ); + return this.crossVectors( v, w ); - } + } - } else if ( yy > zz ) { + var x = this.x, y = this.y, z = this.z; - // m22 is the largest diagonal term + this.x = y * v.z - z * v.y; + this.y = z * v.x - x * v.z; + this.z = x * v.y - y * v.x; - if ( yy < epsilon ) { + return this; - x = 0.707106781; - y = 0; - z = 0.707106781; + }, - } else { + crossVectors: function ( a, b ) { - y = Math.sqrt( yy ); - x = xy / y; - z = yz / y; + var ax = a.x, ay = a.y, az = a.z; + var bx = b.x, by = b.y, bz = b.z; - } + this.x = ay * bz - az * by; + this.y = az * bx - ax * bz; + this.z = ax * by - ay * bx; - } else { + return this; - // m33 is the largest diagonal term so base result on this + }, - if ( zz < epsilon ) { + projectOnVector: function ( vector ) { - x = 0.707106781; - y = 0.707106781; - z = 0; + var scalar = vector.dot( this ) / vector.lengthSq(); - } else { + return this.copy( vector ).multiplyScalar( scalar ); - z = Math.sqrt( zz ); - x = xz / z; - y = yz / z; + }, - } + projectOnPlane: function () { - } + var v1; - this.set( x, y, z, angle ); + return function projectOnPlane( planeNormal ) { - return this; // return 180 deg rotation + if ( v1 === undefined ) v1 = new Vector3(); - } + v1.copy( this ).projectOnVector( planeNormal ); - // as we have reached here there are no singularities so we can handle normally + return this.sub( v1 ); - var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) - + ( m13 - m31 ) * ( m13 - m31 ) - + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize + }; - if ( Math.abs( s ) < 0.001 ) s = 1; + }(), - // 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 + reflect: function () { - this.x = ( m32 - m23 ) / s; - this.y = ( m13 - m31 ) / s; - this.z = ( m21 - m12 ) / s; - this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 ); + // reflect incident vector off plane orthogonal to normal + // normal is assumed to have unit length - return this; + var v1; - }, + return function reflect( normal ) { - min: function ( v ) { + if ( v1 === undefined ) v1 = new Vector3(); - if ( this.x > v.x ) { + return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) ); - this.x = v.x; + }; - } + }(), - if ( this.y > v.y ) { + angleTo: function ( v ) { - this.y = v.y; + var theta = this.dot( v ) / ( Math.sqrt( this.lengthSq() * v.lengthSq() ) ); - } + // clamp, to handle numerical problems - if ( this.z > v.z ) { + return Math.acos( exports.Math.clamp( theta, - 1, 1 ) ); - this.z = v.z; + }, - } + distanceTo: function ( v ) { - if ( this.w > v.w ) { + return Math.sqrt( this.distanceToSquared( v ) ); - this.w = v.w; + }, - } + distanceToSquared: function ( v ) { - return this; + var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z; - }, + return dx * dx + dy * dy + dz * dz; - max: function ( v ) { + }, - if ( this.x < v.x ) { + distanceToManhattan: function ( v ) { - this.x = v.x; + return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z ); - } + }, - if ( this.y < v.y ) { + setFromSpherical: function( s ) { - this.y = v.y; + 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 ); - if ( this.z < v.z ) { + return this; - this.z = v.z; + }, - } + setFromMatrixPosition: function ( m ) { - if ( this.w < v.w ) { + return this.setFromMatrixColumn( m, 3 ); - this.w = v.w; + }, - } + setFromMatrixScale: function ( m ) { - return this; + var sx = this.setFromMatrixColumn( m, 0 ).length(); + var sy = this.setFromMatrixColumn( m, 1 ).length(); + var sz = this.setFromMatrixColumn( m, 2 ).length(); - }, + this.x = sx; + this.y = sy; + this.z = sz; - clamp: function ( min, max ) { + return this; - // This function assumes min < max, if this assumption isn't true it will not operate correctly + }, - if ( this.x < min.x ) { + setFromMatrixColumn: function ( m, index ) { - this.x = min.x; + if ( typeof m === 'number' ) { - } else if ( this.x > max.x ) { + console.warn( 'THREE.Vector3: setFromMatrixColumn now expects ( matrix, index ).' ); + var temp = m + m = index; + index = temp; - this.x = max.x; + } - } + return this.fromArray( m.elements, index * 4 ); - if ( this.y < min.y ) { + }, - this.y = min.y; + equals: function ( v ) { - } else if ( this.y > max.y ) { + return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) ); - this.y = max.y; + }, - } + fromArray: function ( array, offset ) { - if ( this.z < min.z ) { + if ( offset === undefined ) offset = 0; - this.z = min.z; + this.x = array[ offset ]; + this.y = array[ offset + 1 ]; + this.z = array[ offset + 2 ]; - } else if ( this.z > max.z ) { + return this; - this.z = max.z; + }, - } + toArray: function ( array, offset ) { - if ( this.w < min.w ) { + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - this.w = min.w; + array[ offset ] = this.x; + array[ offset + 1 ] = this.y; + array[ offset + 2 ] = this.z; - } else if ( this.w > max.w ) { + return array; - this.w = max.w; + }, - } + fromAttribute: function ( attribute, index, offset ) { - return this; + if ( offset === undefined ) offset = 0; - }, + index = index * attribute.itemSize + offset; - clampScalar: function () { + this.x = attribute.array[ index ]; + this.y = attribute.array[ index + 1 ]; + this.z = attribute.array[ index + 2 ]; - var min, max; + return this; - return function clampScalar( minVal, maxVal ) { + } - if ( min === undefined ) { + }; - min = new THREE.Vector4(); - max = new THREE.Vector4(); + /** + * @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() { - min.set( minVal, minVal, minVal, minVal ); - max.set( maxVal, maxVal, maxVal, maxVal ); + this.elements = new Float32Array( [ - return this.clamp( min, max ); + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 - }; + ] ); - }(), + if ( arguments.length > 0 ) { - floor: function () { + console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' ); - 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; + } - }, + Matrix4.prototype = { - ceil: function () { + constructor: Matrix4, - this.x = Math.ceil( this.x ); - this.y = Math.ceil( this.y ); - this.z = Math.ceil( this.z ); - this.w = Math.ceil( this.w ); + isMatrix4: true, - return this; + set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) { - }, + var te = this.elements; - round: function () { + 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.x = Math.round( this.x ); - this.y = Math.round( this.y ); - this.z = Math.round( this.z ); - this.w = Math.round( this.w ); + return this; - return this; + }, - }, + identity: function () { - roundToZero: function () { + this.set( - 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 ); + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 - return this; + ); - }, + return this; - negate: function () { + }, - this.x = - this.x; - this.y = - this.y; - this.z = - this.z; - this.w = - this.w; + clone: function () { - return this; + return new Matrix4().fromArray( this.elements ); - }, + }, - dot: function ( v ) { + copy: function ( m ) { - return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; + this.elements.set( m.elements ); - }, + return this; - lengthSq: function () { + }, - return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; + copyPosition: function ( m ) { - }, + var te = this.elements; + var me = m.elements; - length: function () { + te[ 12 ] = me[ 12 ]; + te[ 13 ] = me[ 13 ]; + te[ 14 ] = me[ 14 ]; - return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w ); + return this; - }, + }, - lengthManhattan: function () { + extractBasis: function ( xAxis, yAxis, zAxis ) { - return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w ); + xAxis.setFromMatrixColumn( this, 0 ); + yAxis.setFromMatrixColumn( this, 1 ); + zAxis.setFromMatrixColumn( this, 2 ); - }, + return this; - normalize: function () { + }, - return this.divideScalar( this.length() ); + 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 + ); - setLength: function ( l ) { + return this; - var oldLength = this.length(); + }, - if ( oldLength !== 0 && l !== oldLength ) { + extractRotation: function () { - this.multiplyScalar( l / oldLength ); + var v1; - } + return function extractRotation( m ) { - return this; + if ( v1 === undefined ) v1 = new Vector3(); - }, + var te = this.elements; + var me = m.elements; - lerp: function ( v, alpha ) { + var scaleX = 1 / v1.setFromMatrixColumn( m, 0 ).length(); + var scaleY = 1 / v1.setFromMatrixColumn( m, 1 ).length(); + var scaleZ = 1 / v1.setFromMatrixColumn( m, 2 ).length(); - 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; + te[ 0 ] = me[ 0 ] * scaleX; + te[ 1 ] = me[ 1 ] * scaleX; + te[ 2 ] = me[ 2 ] * scaleX; - return this; + te[ 4 ] = me[ 4 ] * scaleY; + te[ 5 ] = me[ 5 ] * scaleY; + te[ 6 ] = me[ 6 ] * scaleY; - }, + te[ 8 ] = me[ 8 ] * scaleZ; + te[ 9 ] = me[ 9 ] * scaleZ; + te[ 10 ] = me[ 10 ] * scaleZ; - lerpVectors: function ( v1, v2, alpha ) { + return this; - this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); + }; - return this; + }(), - }, + makeRotationFromEuler: function ( euler ) { - equals: function ( v ) { + if ( (euler && euler.isEuler) === false ) { - return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) ); + console.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' ); - }, + } - fromArray: function ( array, offset ) { + var te = this.elements; - if ( offset === undefined ) offset = 0; + 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 ); - this.x = array[ offset ]; - this.y = array[ offset + 1 ]; - this.z = array[ offset + 2 ]; - this.w = array[ offset + 3 ]; + if ( euler.order === 'XYZ' ) { - return this; + var ae = a * e, af = a * f, be = b * e, bf = b * f; - }, + te[ 0 ] = c * e; + te[ 4 ] = - c * f; + te[ 8 ] = d; - toArray: function ( array, offset ) { + te[ 1 ] = af + be * d; + te[ 5 ] = ae - bf * d; + te[ 9 ] = - b * c; - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + te[ 2 ] = bf - ae * d; + te[ 6 ] = be + af * d; + te[ 10 ] = a * c; - array[ offset ] = this.x; - array[ offset + 1 ] = this.y; - array[ offset + 2 ] = this.z; - array[ offset + 3 ] = this.w; + } else if ( euler.order === 'YXZ' ) { - return array; + var ce = c * e, cf = c * f, de = d * e, df = d * f; - }, + te[ 0 ] = ce + df * b; + te[ 4 ] = de * b - cf; + te[ 8 ] = a * d; - fromAttribute: function ( attribute, index, offset ) { + te[ 1 ] = a * f; + te[ 5 ] = a * e; + te[ 9 ] = - b; - if ( offset === undefined ) offset = 0; + te[ 2 ] = cf * b - de; + te[ 6 ] = df + ce * b; + te[ 10 ] = a * c; - index = index * attribute.itemSize + offset; + } else if ( euler.order === 'ZXY' ) { - this.x = attribute.array[ index ]; - this.y = attribute.array[ index + 1 ]; - this.z = attribute.array[ index + 2 ]; - this.w = attribute.array[ index + 3 ]; + var ce = c * e, cf = c * f, de = d * e, df = d * f; - return this; + te[ 0 ] = ce - df * b; + te[ 4 ] = - a * f; + te[ 8 ] = de + cf * b; - } + te[ 1 ] = cf + de * b; + te[ 5 ] = a * e; + te[ 9 ] = df - ce * b; -}; + te[ 2 ] = - a * d; + te[ 6 ] = b; + te[ 10 ] = a * c; -// File:src/math/Euler.js + } else if ( euler.order === 'ZYX' ) { -/** - * @author mrdoob / http://mrdoob.com/ - * @author WestLangley / http://github.com/WestLangley - * @author bhouston / http://exocortex.com - */ + var ae = a * e, af = a * f, be = b * e, bf = b * f; -THREE.Euler = function ( x, y, z, order ) { + te[ 0 ] = c * e; + te[ 4 ] = be * d - af; + te[ 8 ] = ae * d + bf; - this._x = x || 0; - this._y = y || 0; - this._z = z || 0; - this._order = order || THREE.Euler.DefaultOrder; + te[ 1 ] = c * f; + te[ 5 ] = bf * d + ae; + te[ 9 ] = af * d - be; -}; + te[ 2 ] = - d; + te[ 6 ] = b * c; + te[ 10 ] = a * c; -THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ]; + } else if ( euler.order === 'YZX' ) { -THREE.Euler.DefaultOrder = 'XYZ'; + var ac = a * c, ad = a * d, bc = b * c, bd = b * d; -THREE.Euler.prototype = { + te[ 0 ] = c * e; + te[ 4 ] = bd - ac * f; + te[ 8 ] = bc * f + ad; - constructor: THREE.Euler, + te[ 1 ] = f; + te[ 5 ] = a * e; + te[ 9 ] = - b * e; - get x () { + te[ 2 ] = - d * e; + te[ 6 ] = ad * f + bc; + te[ 10 ] = ac - bd * f; - return this._x; + } else if ( euler.order === 'XZY' ) { - }, + var ac = a * c, ad = a * d, bc = b * c, bd = b * d; - set x ( value ) { + te[ 0 ] = c * e; + te[ 4 ] = - f; + te[ 8 ] = d * e; - this._x = value; - this.onChangeCallback(); + te[ 1 ] = ac * f + bd; + te[ 5 ] = a * e; + te[ 9 ] = ad * f - bc; - }, + te[ 2 ] = bc * f - ad; + te[ 6 ] = b * e; + te[ 10 ] = bd * f + ac; - get y () { + } - return this._y; + // 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; - set y ( value ) { + return this; - this._y = value; - this.onChangeCallback(); + }, - }, + makeRotationFromQuaternion: function ( q ) { - get z () { + var te = this.elements; - return this._z; + 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[ 0 ] = 1 - ( yy + zz ); + te[ 4 ] = xy - wz; + te[ 8 ] = xz + wy; - set z ( value ) { + te[ 1 ] = xy + wz; + te[ 5 ] = 1 - ( xx + zz ); + te[ 9 ] = yz - wx; - this._z = value; - this.onChangeCallback(); + te[ 2 ] = xz - wy; + te[ 6 ] = yz + wx; + te[ 10 ] = 1 - ( xx + yy ); - }, + // last column + te[ 3 ] = 0; + te[ 7 ] = 0; + te[ 11 ] = 0; - get order () { + // bottom row + te[ 12 ] = 0; + te[ 13 ] = 0; + te[ 14 ] = 0; + te[ 15 ] = 1; - return this._order; + return this; - }, + }, - set order ( value ) { + lookAt: function () { - this._order = value; - this.onChangeCallback(); + var x, y, z; - }, + return function lookAt( eye, target, up ) { - set: function ( x, y, z, order ) { + if ( x === undefined ) { - this._x = x; - this._y = y; - this._z = z; - this._order = order || this._order; + x = new Vector3(); + y = new Vector3(); + z = new Vector3(); - this.onChangeCallback(); + } - return this; + var te = this.elements; - }, + z.subVectors( eye, target ).normalize(); - clone: function () { + if ( z.lengthSq() === 0 ) { - return new this.constructor( this._x, this._y, this._z, this._order); + z.z = 1; - }, + } - copy: function ( euler ) { + x.crossVectors( up, z ).normalize(); - this._x = euler._x; - this._y = euler._y; - this._z = euler._z; - this._order = euler._order; + if ( x.lengthSq() === 0 ) { - this.onChangeCallback(); + z.z += 0.0001; + x.crossVectors( up, z ).normalize(); - return this; + } - }, + y.crossVectors( z, x ); - setFromRotationMatrix: function ( m, order, update ) { - var clamp = THREE.Math.clamp; + 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; - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + return this; - 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 ]; + }; - order = order || this._order; + }(), - if ( order === 'XYZ' ) { + multiply: function ( m, n ) { - this._y = Math.asin( clamp( m13, - 1, 1 ) ); + if ( n !== undefined ) { - if ( Math.abs( m13 ) < 0.99999 ) { + console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' ); + return this.multiplyMatrices( m, n ); - this._x = Math.atan2( - m23, m33 ); - this._z = Math.atan2( - m12, m11 ); + } - } else { + return this.multiplyMatrices( this, m ); - this._x = Math.atan2( m32, m22 ); - this._z = 0; + }, - } + premultiply: function ( m ) { - } else if ( order === 'YXZ' ) { + return this.multiplyMatrices( m, this ); - this._x = Math.asin( - clamp( m23, - 1, 1 ) ); + }, - if ( Math.abs( m23 ) < 0.99999 ) { + multiplyMatrices: function ( a, b ) { - this._y = Math.atan2( m13, m33 ); - this._z = Math.atan2( m21, m22 ); + var ae = a.elements; + var be = b.elements; + var te = this.elements; - } else { + 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 ]; - this._y = Math.atan2( - m31, m11 ); - this._z = 0; + var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ]; + var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ]; + var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ]; + var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ]; - } + te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41; + te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42; + te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43; + te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44; - } else if ( order === 'ZXY' ) { + 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._x = Math.asin( clamp( m32, - 1, 1 ) ); + te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41; + te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42; + te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43; + te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44; - if ( Math.abs( m32 ) < 0.99999 ) { + 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._y = Math.atan2( - m31, m33 ); - this._z = Math.atan2( - m12, m22 ); + return this; - } else { + }, - this._y = 0; - this._z = Math.atan2( m21, m11 ); + multiplyToArray: function ( a, b, r ) { - } + var te = this.elements; - } else if ( order === 'ZYX' ) { + this.multiplyMatrices( a, b ); - this._y = Math.asin( - clamp( m31, - 1, 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 ]; - if ( Math.abs( m31 ) < 0.99999 ) { + return this; - this._x = Math.atan2( m32, m33 ); - this._z = Math.atan2( m21, m11 ); + }, - } else { + multiplyScalar: function ( s ) { - this._x = 0; - this._z = Math.atan2( - m12, m22 ); + var te = this.elements; - } + 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; - } else if ( order === 'YZX' ) { + return this; - this._z = Math.asin( clamp( m21, - 1, 1 ) ); + }, - if ( Math.abs( m21 ) < 0.99999 ) { + applyToVector3Array: function () { - this._x = Math.atan2( - m23, m22 ); - this._y = Math.atan2( - m31, m11 ); + var v1; - } else { + return function applyToVector3Array( array, offset, length ) { - this._x = 0; - this._y = Math.atan2( m13, m33 ); + if ( v1 === undefined ) v1 = new Vector3(); + if ( offset === undefined ) offset = 0; + if ( length === undefined ) length = array.length; - } + for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) { - } else if ( order === 'XZY' ) { + v1.fromArray( array, j ); + v1.applyMatrix4( this ); + v1.toArray( array, j ); - this._z = Math.asin( - clamp( m12, - 1, 1 ) ); + } - if ( Math.abs( m12 ) < 0.99999 ) { + return array; - this._x = Math.atan2( m32, m22 ); - this._y = Math.atan2( m13, m11 ); + }; - } else { + }(), - this._x = Math.atan2( - m23, m33 ); - this._y = 0; + applyToBuffer: function () { - } + var v1; - } else { + return function applyToBuffer( buffer, offset, length ) { - console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order ) + 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 ++ ) { - this._order = order; + v1.x = buffer.getX( j ); + v1.y = buffer.getY( j ); + v1.z = buffer.getZ( j ); - if ( update !== false ) this.onChangeCallback(); + v1.applyMatrix4( this ); - return this; + buffer.setXYZ( v1.x, v1.y, v1.z ); - }, + } - setFromQuaternion: function () { + return buffer; - var matrix; + }; - return function ( q, order, update ) { + }(), - if ( matrix === undefined ) matrix = new THREE.Matrix4(); - matrix.makeRotationFromQuaternion( q ); - this.setFromRotationMatrix( matrix, order, update ); + determinant: function () { - return this; + var te = this.elements; - }; + var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ]; + var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ]; + var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ]; + var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ]; - }(), + //TODO: make this more efficient + //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm ) - setFromVector3: function ( v, 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 + ) - return this.set( v.x, v.y, v.z, order || this._order ); + ); - }, + }, - reorder: function () { + transpose: function () { - // WARNING: this discards revolution information -bhouston + var te = this.elements; + var tmp; - var q = new THREE.Quaternion(); + tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp; + tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp; + tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp; - return function ( newOrder ) { + 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; - q.setFromEuler( this ); - this.setFromQuaternion( q, newOrder ); + return this; - }; + }, - }(), + flattenToArrayOffset: function ( array, offset ) { - equals: function ( euler ) { + console.warn( "THREE.Matrix3: .flattenToArrayOffset is deprecated " + + "- just use .toArray instead." ); - return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order ); + return this.toArray( array, offset ); - }, + }, - fromArray: function ( array ) { + getPosition: function () { - this._x = array[ 0 ]; - this._y = array[ 1 ]; - this._z = array[ 2 ]; - if ( array[ 3 ] !== undefined ) this._order = array[ 3 ]; + var v1; - this.onChangeCallback(); + return function getPosition() { - return this; + if ( v1 === undefined ) v1 = new Vector3(); + console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' ); - }, + return v1.setFromMatrixColumn( this, 3 ); - toArray: function ( array, offset ) { + }; - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + }(), - array[ offset ] = this._x; - array[ offset + 1 ] = this._y; - array[ offset + 2 ] = this._z; - array[ offset + 3 ] = this._order; + setPosition: function ( v ) { - return array; + var te = this.elements; - }, + te[ 12 ] = v.x; + te[ 13 ] = v.y; + te[ 14 ] = v.z; - toVector3: function ( optionalResult ) { + return this; - if ( optionalResult ) { + }, - return optionalResult.set( this._x, this._y, this._z ); + getInverse: function ( m, throwOnDegenerate ) { - } else { + // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm + var te = this.elements, + me = m.elements, - return new THREE.Vector3( this._x, this._y, this._z ); + n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ], + n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ], + n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ], + n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ], - } + t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44, + t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44, + t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44, + t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; - }, + var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14; - onChange: function ( callback ) { + if ( det === 0 ) { - this.onChangeCallback = callback; + var msg = "THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0"; - return this; + if ( throwOnDegenerate === true ) { - }, + throw new Error( msg ); - onChangeCallback: function () {} + } else { -}; + console.warn( msg ); -// File:src/math/Line3.js + } -/** - * @author bhouston / http://exocortex.com - */ + return this.identity(); -THREE.Line3 = function ( start, end ) { + } - this.start = ( start !== undefined ) ? start : new THREE.Vector3(); - this.end = ( end !== undefined ) ? end : new THREE.Vector3(); + 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; -THREE.Line3.prototype = { + 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; - constructor: THREE.Line3, + 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; - set: function ( start, end ) { + 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; - this.start.copy( start ); - this.end.copy( end ); + return this; - return this; + }, - }, + scale: function ( v ) { - clone: function () { + var te = this.elements; + var x = v.x, y = v.y, z = v.z; - return new this.constructor().copy( this ); + 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; - copy: function ( line ) { + }, - this.start.copy( line.start ); - this.end.copy( line.end ); + getMaxScaleOnAxis: function () { - return this; + 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 ]; - center: function ( optionalTarget ) { + return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) ); - var result = optionalTarget || new THREE.Vector3(); - return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 ); + }, - }, + makeTranslation: function ( x, y, z ) { - delta: function ( optionalTarget ) { + this.set( - var result = optionalTarget || new THREE.Vector3(); - return result.subVectors( this.end, this.start ); + 1, 0, 0, x, + 0, 1, 0, y, + 0, 0, 1, z, + 0, 0, 0, 1 - }, + ); - distanceSq: function () { + return this; - return this.start.distanceToSquared( this.end ); + }, - }, + makeRotationX: function ( theta ) { - distance: function () { + var c = Math.cos( theta ), s = Math.sin( theta ); - return this.start.distanceTo( this.end ); + this.set( - }, + 1, 0, 0, 0, + 0, c, - s, 0, + 0, s, c, 0, + 0, 0, 0, 1 - at: function ( t, optionalTarget ) { + ); - var result = optionalTarget || new THREE.Vector3(); + return this; - return this.delta( result ).multiplyScalar( t ).add( this.start ); + }, - }, + makeRotationY: function ( theta ) { - closestPointToPointParameter: function () { + var c = Math.cos( theta ), s = Math.sin( theta ); - var startP = new THREE.Vector3(); - var startEnd = new THREE.Vector3(); + this.set( - return function ( point, clampToLine ) { + c, 0, s, 0, + 0, 1, 0, 0, + - s, 0, c, 0, + 0, 0, 0, 1 - startP.subVectors( point, this.start ); - startEnd.subVectors( this.end, this.start ); + ); - var startEnd2 = startEnd.dot( startEnd ); - var startEnd_startP = startEnd.dot( startP ); + return this; - var t = startEnd_startP / startEnd2; + }, - if ( clampToLine ) { + makeRotationZ: function ( theta ) { - t = THREE.Math.clamp( t, 0, 1 ); + var c = Math.cos( theta ), s = Math.sin( theta ); - } + this.set( - return t; + c, - s, 0, 0, + s, c, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 - }; + ); - }(), + return this; - closestPointToPoint: function ( point, clampToLine, optionalTarget ) { + }, - var t = this.closestPointToPointParameter( point, clampToLine ); + makeRotationAxis: function ( axis, angle ) { - var result = optionalTarget || new THREE.Vector3(); + // Based on http://www.gamedev.net/reference/articles/article1199.asp - return this.delta( result ).multiplyScalar( t ).add( this.start ); + var c = Math.cos( angle ); + var s = Math.sin( angle ); + var t = 1 - c; + var x = axis.x, y = axis.y, z = axis.z; + var tx = t * x, ty = t * y; - }, + this.set( - applyMatrix4: function ( matrix ) { + tx * x + c, tx * y - s * z, tx * z + s * y, 0, + tx * y + s * z, ty * y + c, ty * z - s * x, 0, + tx * z - s * y, ty * z + s * x, t * z * z + c, 0, + 0, 0, 0, 1 - this.start.applyMatrix4( matrix ); - this.end.applyMatrix4( matrix ); + ); - return this; + return this; - }, + }, - equals: function ( line ) { + makeScale: function ( x, y, z ) { - return line.start.equals( this.start ) && line.end.equals( this.end ); + this.set( - } + x, 0, 0, 0, + 0, y, 0, 0, + 0, 0, z, 0, + 0, 0, 0, 1 -}; + ); -// File:src/math/Box2.js + return this; -/** - * @author bhouston / http://exocortex.com - */ + }, -THREE.Box2 = function ( min, max ) { + compose: function ( position, quaternion, scale ) { - this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity ); - this.max = ( max !== undefined ) ? max : new THREE.Vector2( - Infinity, - Infinity ); + this.makeRotationFromQuaternion( quaternion ); + this.scale( scale ); + this.setPosition( position ); -}; + return this; -THREE.Box2.prototype = { + }, - constructor: THREE.Box2, + decompose: function () { - set: function ( min, max ) { + var vector, matrix; - this.min.copy( min ); - this.max.copy( max ); + return function decompose( position, quaternion, scale ) { - return this; + if ( vector === undefined ) { - }, + vector = new Vector3(); + matrix = new Matrix4(); - setFromPoints: function ( points ) { + } - this.makeEmpty(); + var te = this.elements; - for ( var i = 0, il = points.length; i < il; i ++ ) { + var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length(); + var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length(); + var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length(); - this.expandByPoint( points[ i ] ) + // if determine is negative, we need to invert one scale + var det = this.determinant(); + if ( det < 0 ) { - } + sx = - sx; - return this; + } - }, + position.x = te[ 12 ]; + position.y = te[ 13 ]; + position.z = te[ 14 ]; - setFromCenterAndSize: function () { + // scale the rotation part - var v1 = new THREE.Vector2(); + matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy() - return function ( center, size ) { + var invSX = 1 / sx; + var invSY = 1 / sy; + var invSZ = 1 / sz; - var halfSize = v1.copy( size ).multiplyScalar( 0.5 ); - this.min.copy( center ).sub( halfSize ); - this.max.copy( center ).add( halfSize ); + matrix.elements[ 0 ] *= invSX; + matrix.elements[ 1 ] *= invSX; + matrix.elements[ 2 ] *= invSX; - return this; + matrix.elements[ 4 ] *= invSY; + matrix.elements[ 5 ] *= invSY; + matrix.elements[ 6 ] *= invSY; - }; + matrix.elements[ 8 ] *= invSZ; + matrix.elements[ 9 ] *= invSZ; + matrix.elements[ 10 ] *= invSZ; - }(), - - clone: function () { + quaternion.setFromRotationMatrix( matrix ); - return new this.constructor().copy( this ); + scale.x = sx; + scale.y = sy; + scale.z = sz; - }, + return this; - copy: function ( box ) { + }; - this.min.copy( box.min ); - this.max.copy( box.max ); + }(), - return this; + makeFrustum: function ( left, right, bottom, top, near, far ) { - }, + var te = this.elements; + var x = 2 * near / ( right - left ); + var y = 2 * near / ( top - bottom ); - makeEmpty: function () { + 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.min.x = this.min.y = Infinity; - this.max.x = this.max.y = - Infinity; + te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0; + te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0; + te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d; + te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0; - return this; + return this; - }, + }, - empty: function () { + makePerspective: function ( fov, aspect, near, far ) { - // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes + var ymax = near * Math.tan( exports.Math.DEG2RAD * fov * 0.5 ); + var ymin = - ymax; + var xmin = ymin * aspect; + var xmax = ymax * aspect; - return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ); + return this.makeFrustum( xmin, xmax, ymin, ymax, near, far ); - }, + }, - center: function ( optionalTarget ) { + makeOrthographic: function ( left, right, top, bottom, near, far ) { - var result = optionalTarget || new THREE.Vector2(); - return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); + 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; - size: function ( optionalTarget ) { + 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; - var result = optionalTarget || new THREE.Vector2(); - return result.subVectors( this.max, this.min ); + return this; - }, + }, - expandByPoint: function ( point ) { + equals: function ( matrix ) { - this.min.min( point ); - this.max.max( point ); + var te = this.elements; + var me = matrix.elements; - return this; + for ( var i = 0; i < 16; i ++ ) { - }, + if ( te[ i ] !== me[ i ] ) return false; - expandByVector: function ( vector ) { + } - this.min.sub( vector ); - this.max.add( vector ); + return true; - return this; + }, - }, + fromArray: function ( array, offset ) { - expandByScalar: function ( scalar ) { + if ( offset === undefined ) offset = 0; - this.min.addScalar( - scalar ); - this.max.addScalar( scalar ); + for( var i = 0; i < 16; i ++ ) { - return this; + this.elements[ i ] = array[ i + offset ]; - }, + } - containsPoint: function ( point ) { + return this; - if ( point.x < this.min.x || point.x > this.max.x || - point.y < this.min.y || point.y > this.max.y ) { + }, - return false; + toArray: function ( array, offset ) { - } + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - return true; + var te = this.elements; - }, + array[ offset ] = te[ 0 ]; + array[ offset + 1 ] = te[ 1 ]; + array[ offset + 2 ] = te[ 2 ]; + array[ offset + 3 ] = te[ 3 ]; - containsBox: function ( box ) { + array[ offset + 4 ] = te[ 4 ]; + array[ offset + 5 ] = te[ 5 ]; + array[ offset + 6 ] = te[ 6 ]; + array[ offset + 7 ] = te[ 7 ]; - 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 ) ) { + array[ offset + 8 ] = te[ 8 ]; + array[ offset + 9 ] = te[ 9 ]; + array[ offset + 10 ] = te[ 10 ]; + array[ offset + 11 ] = te[ 11 ]; - return true; + array[ offset + 12 ] = te[ 12 ]; + array[ offset + 13 ] = te[ 13 ]; + array[ offset + 14 ] = te[ 14 ]; + array[ offset + 15 ] = te[ 15 ]; - } + return array; - return false; + } - }, + }; - getParameter: function ( point, optionalTarget ) { + /** + * @author mrdoob / http://mrdoob.com/ + */ - // This can potentially have a divide by zero if the box - // has a size dimension of 0. + function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) { - var result = optionalTarget || new THREE.Vector2(); + images = images !== undefined ? images : []; + mapping = mapping !== undefined ? mapping : CubeReflectionMapping; - 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 ) - ); + Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); - }, + this.flipY = false; - isIntersectionBox: function ( box ) { + } - // using 6 splitting planes to rule out intersections. + CubeTexture.prototype = Object.create( Texture.prototype ); + CubeTexture.prototype.constructor = CubeTexture; - 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 ) { + CubeTexture.prototype.isCubeTexture = true; - return false; + Object.defineProperty( CubeTexture.prototype, 'images', { - } + get: function () { - return true; + return this.image; - }, + }, - clampPoint: function ( point, optionalTarget ) { + set: function ( value ) { - var result = optionalTarget || new THREE.Vector2(); - return result.copy( point ).clamp( this.min, this.max ); + this.image = value; - }, + } - distanceToPoint: function () { + } ); - var v1 = new THREE.Vector2(); + var emptyTexture = new Texture(); + var emptyCubeTexture = new CubeTexture(); - return function ( point ) { + // --- Base for inner nodes (including the root) --- - var clampedPoint = v1.copy( point ).clamp( this.min, this.max ); - return clampedPoint.sub( point ).length(); + function UniformContainer() { - }; + this.seq = []; + this.map = {}; - }(), + } - intersect: function ( box ) { + // --- Utilities --- - this.min.max( box.min ); - this.max.min( box.max ); + // Array Caches (provide typed arrays for temporary by size) - return this; + var arrayCacheF32 = []; + var arrayCacheI32 = []; - }, + // Flattening for arrays of vectors and matrices - union: function ( box ) { + function flatten( array, nBlocks, blockSize ) { - this.min.min( box.min ); - this.max.max( box.max ); + var firstElem = array[ 0 ]; - return this; + if ( firstElem <= 0 || firstElem > 0 ) return array; + // unoptimized: ! isNaN( firstElem ) + // see http://jacksondunstan.com/articles/983 - }, + var n = nBlocks * blockSize, + r = arrayCacheF32[ n ]; - translate: function ( offset ) { + if ( r === undefined ) { - this.min.add( offset ); - this.max.add( offset ); + r = new Float32Array( n ); + arrayCacheF32[ n ] = r; - return this; + } - }, + if ( nBlocks !== 0 ) { - equals: function ( box ) { + firstElem.toArray( r, 0 ); - return box.min.equals( this.min ) && box.max.equals( this.max ); + for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) { - } + offset += blockSize; + array[ i ].toArray( r, offset ); -}; + } -// File:src/math/Box3.js + } -/** - * @author bhouston / http://exocortex.com - * @author WestLangley / http://github.com/WestLangley - */ + return r; -THREE.Box3 = function ( min, max ) { + } - this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity ); - this.max = ( max !== undefined ) ? max : new THREE.Vector3( - Infinity, - Infinity, - Infinity ); + // Texture unit allocation -}; + function allocTexUnits( renderer, n ) { -THREE.Box3.prototype = { + var r = arrayCacheI32[ n ]; - constructor: THREE.Box3, + if ( r === undefined ) { - set: function ( min, max ) { + r = new Int32Array( n ); + arrayCacheI32[ n ] = r; - this.min.copy( min ); - this.max.copy( max ); + } - return this; + for ( var i = 0; i !== n; ++ i ) + r[ i ] = renderer.allocTextureUnit(); - }, + return r; - setFromPoints: function ( points ) { + } - this.makeEmpty(); + // --- Setters --- - for ( var i = 0, il = points.length; i < il; i ++ ) { + // Note: Defining these methods externally, because they come in a bunch + // and this way their names minify. - this.expandByPoint( points[ i ] ); + // Single scalar - } + function setValue1f( gl, v ) { gl.uniform1f( this.addr, v ); } + function setValue1i( gl, v ) { gl.uniform1i( this.addr, v ); } - return this; + // Single float vector (from flat array or THREE.VectorN) - }, + function setValue2fv( gl, v ) { - setFromCenterAndSize: function () { + if ( v.x === undefined ) gl.uniform2fv( this.addr, v ); + else gl.uniform2f( this.addr, v.x, v.y ); - var v1 = new THREE.Vector3(); + } - return function ( center, size ) { + function setValue3fv( gl, v ) { - var halfSize = v1.copy( size ).multiplyScalar( 0.5 ); + if ( v.x !== undefined ) + gl.uniform3f( this.addr, v.x, v.y, v.z ); + else if ( v.r !== undefined ) + gl.uniform3f( this.addr, v.r, v.g, v.b ); + else + gl.uniform3fv( this.addr, v ); - this.min.copy( center ).sub( halfSize ); - this.max.copy( center ).add( halfSize ); + } - return this; + function setValue4fv( gl, v ) { - }; + if ( v.x === undefined ) gl.uniform4fv( this.addr, v ); + else gl.uniform4f( this.addr, v.x, v.y, v.z, v.w ); - }(), + } - setFromObject: function () { + // Single matrix (from flat array or MatrixN) - // Computes the world-axis-aligned bounding box of an object (including its children), - // accounting for both the object's, and children's, world transforms + function setValue2fm( gl, v ) { - var v1 = new THREE.Vector3(); + gl.uniformMatrix2fv( this.addr, false, v.elements || v ); - return function ( object ) { + } - var scope = this; + function setValue3fm( gl, v ) { - object.updateMatrixWorld( true ); + gl.uniformMatrix3fv( this.addr, false, v.elements || v ); - this.makeEmpty(); + } - object.traverse( function ( node ) { + function setValue4fm( gl, v ) { - var geometry = node.geometry; + gl.uniformMatrix4fv( this.addr, false, v.elements || v ); - if ( geometry !== undefined ) { + } - if ( geometry instanceof THREE.Geometry ) { + // Single texture (2D / Cube) - var vertices = geometry.vertices; + function setValueT1( gl, v, renderer ) { - for ( var i = 0, il = vertices.length; i < il; i ++ ) { + var unit = renderer.allocTextureUnit(); + gl.uniform1i( this.addr, unit ); + renderer.setTexture2D( v || emptyTexture, unit ); - v1.copy( vertices[ i ] ); + } - v1.applyMatrix4( node.matrixWorld ); + function setValueT6( gl, v, renderer ) { - scope.expandByPoint( v1 ); + var unit = renderer.allocTextureUnit(); + gl.uniform1i( this.addr, unit ); + renderer.setTextureCube( v || emptyCubeTexture, unit ); - } + } - } else if ( geometry instanceof THREE.BufferGeometry && geometry.attributes[ 'position' ] !== undefined ) { + // Integer / Boolean vectors or arrays thereof (always flat arrays) - var positions = geometry.attributes[ 'position' ].array; + function setValue2iv( gl, v ) { gl.uniform2iv( this.addr, v ); } + function setValue3iv( gl, v ) { gl.uniform3iv( this.addr, v ); } + function setValue4iv( gl, v ) { gl.uniform4iv( this.addr, v ); } - for ( var i = 0, il = positions.length; i < il; i += 3 ) { + // Helper to pick the right setter for the singular case - v1.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ); + function getSingularSetter( type ) { - v1.applyMatrix4( node.matrixWorld ); + switch ( type ) { - scope.expandByPoint( v1 ); + case 0x1406: return setValue1f; // FLOAT + case 0x8b50: return setValue2fv; // _VEC2 + case 0x8b51: return setValue3fv; // _VEC3 + case 0x8b52: return setValue4fv; // _VEC4 - } + case 0x8b5a: return setValue2fm; // _MAT2 + case 0x8b5b: return setValue3fm; // _MAT3 + case 0x8b5c: return setValue4fm; // _MAT4 - } + case 0x8b5e: return setValueT1; // SAMPLER_2D + case 0x8b60: return setValueT6; // SAMPLER_CUBE - } + 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 - } ); + } - return this; + } - }; + // Array of scalars - }(), + function setValue1fv( gl, v ) { gl.uniform1fv( this.addr, v ); } + function setValue1iv( gl, v ) { gl.uniform1iv( this.addr, v ); } - clone: function () { + // Array of vectors (flat or from THREE classes) - return new this.constructor().copy( this ); + function setValueV2a( gl, v ) { - }, + gl.uniform2fv( this.addr, flatten( v, this.size, 2 ) ); - copy: function ( box ) { + } - this.min.copy( box.min ); - this.max.copy( box.max ); + function setValueV3a( gl, v ) { - return this; + gl.uniform3fv( this.addr, flatten( v, this.size, 3 ) ); - }, + } - makeEmpty: function () { + function setValueV4a( gl, v ) { - this.min.x = this.min.y = this.min.z = Infinity; - this.max.x = this.max.y = this.max.z = - Infinity; + gl.uniform4fv( this.addr, flatten( v, this.size, 4 ) ); - return this; + } - }, + // Array of matrices (flat or from THREE clases) - empty: function () { + function setValueM2a( gl, v ) { - // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes + gl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) ); - return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z ); + } - }, + function setValueM3a( gl, v ) { - center: function ( optionalTarget ) { + gl.uniformMatrix3fv( this.addr, false, flatten( v, this.size, 9 ) ); - var result = optionalTarget || new THREE.Vector3(); - return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); + } - }, + function setValueM4a( gl, v ) { - size: function ( optionalTarget ) { + gl.uniformMatrix4fv( this.addr, false, flatten( v, this.size, 16 ) ); - var result = optionalTarget || new THREE.Vector3(); - return result.subVectors( this.max, this.min ); + } - }, + // Array of textures (2D / Cube) - expandByPoint: function ( point ) { + function setValueT1a( gl, v, renderer ) { - this.min.min( point ); - this.max.max( point ); + var n = v.length, + units = allocTexUnits( renderer, n ); - return this; + gl.uniform1iv( this.addr, units ); - }, + for ( var i = 0; i !== n; ++ i ) { - expandByVector: function ( vector ) { + renderer.setTexture2D( v[ i ] || emptyTexture, units[ i ] ); - this.min.sub( vector ); - this.max.add( vector ); + } - return this; + } - }, + function setValueT6a( gl, v, renderer ) { - expandByScalar: function ( scalar ) { + var n = v.length, + units = allocTexUnits( renderer, n ); - this.min.addScalar( - scalar ); - this.max.addScalar( scalar ); + gl.uniform1iv( this.addr, units ); - return this; + for ( var i = 0; i !== n; ++ i ) { - }, + renderer.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] ); - containsPoint: function ( point ) { + } - 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 ) { + } - return false; + // Helper to pick the right setter for a pure (bottom-level) array - } + function getPureArraySetter( type ) { - return true; + switch ( type ) { - }, + case 0x1406: return setValue1fv; // FLOAT + case 0x8b50: return setValueV2a; // _VEC2 + case 0x8b51: return setValueV3a; // _VEC3 + case 0x8b52: return setValueV4a; // _VEC4 - containsBox: function ( box ) { + case 0x8b5a: return setValueM2a; // _MAT2 + case 0x8b5b: return setValueM3a; // _MAT3 + case 0x8b5c: return setValueM4a; // _MAT4 - 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 ) ) { + case 0x8b5e: return setValueT1a; // SAMPLER_2D + case 0x8b60: return setValueT6a; // SAMPLER_CUBE - return true; + 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 false; + } - }, + // --- Uniform Classes --- - getParameter: function ( point, optionalTarget ) { + function SingleUniform( id, activeInfo, addr ) { - // This can potentially have a divide by zero if the box - // has a size dimension of 0. + this.id = id; + this.addr = addr; + this.setValue = getSingularSetter( activeInfo.type ); - var result = optionalTarget || new THREE.Vector3(); + // this.path = activeInfo.name; // DEBUG - 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 ) - ); + } - }, + function PureArrayUniform( id, activeInfo, addr ) { - isIntersectionBox: function ( box ) { + this.id = id; + this.addr = addr; + this.size = activeInfo.size; + this.setValue = getPureArraySetter( activeInfo.type ); - // using 6 splitting planes to rule out intersections. + // this.path = activeInfo.name; // DEBUG - 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 false; + function StructuredUniform( id ) { - } + this.id = id; - return true; + UniformContainer.call( this ); // mix-in - }, + } - clampPoint: function ( point, optionalTarget ) { + StructuredUniform.prototype.setValue = function( gl, value ) { - var result = optionalTarget || new THREE.Vector3(); - return result.copy( point ).clamp( this.min, this.max ); + // Note: Don't need an extra 'renderer' parameter, since samplers + // are not allowed in structured uniforms. - }, + var seq = this.seq; - distanceToPoint: function () { + for ( var i = 0, n = seq.length; i !== n; ++ i ) { - var v1 = new THREE.Vector3(); + var u = seq[ i ]; + u.setValue( gl, value[ u.id ] ); - return function ( point ) { + } - var clampedPoint = v1.copy( point ).clamp( this.min, this.max ); - return clampedPoint.sub( point ).length(); + }; - }; + // --- Top-level --- - }(), + // Parser - builds up the property tree from the path strings - getBoundingSphere: function () { + var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g; - var v1 = new THREE.Vector3(); + // 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. - return function ( optionalTarget ) { + function addUniform( container, uniformObject ) { - var result = optionalTarget || new THREE.Sphere(); + container.seq.push( uniformObject ); + container.map[ uniformObject.id ] = uniformObject; - result.center = this.center(); - result.radius = this.size( v1 ).length() * 0.5; + } - return result; + function parseUniform( activeInfo, addr, container ) { - }; + var path = activeInfo.name, + pathLength = path.length; - }(), + // reset RegExp object, because of the early exit of a previous run + RePathPart.lastIndex = 0; - intersect: function ( box ) { + for (; ;) { - this.min.max( box.min ); - this.max.min( box.max ); + var match = RePathPart.exec( path ), + matchEnd = RePathPart.lastIndex, - return this; + id = match[ 1 ], + idIsIndex = match[ 2 ] === ']', + subscript = match[ 3 ]; - }, + if ( idIsIndex ) id = id | 0; // convert to integer - union: function ( box ) { + if ( subscript === undefined || + subscript === '[' && matchEnd + 2 === pathLength ) { + // bare name or "pure" bottom-level array "[0]" suffix - this.min.min( box.min ); - this.max.max( box.max ); + addUniform( container, subscript === undefined ? + new SingleUniform( id, activeInfo, addr ) : + new PureArrayUniform( id, activeInfo, addr ) ); - return this; + break; - }, + } else { + // step into inner node / create it in case it doesn't exist - applyMatrix4: function () { + var map = container.map, + next = map[ id ]; - var points = [ - new THREE.Vector3(), - new THREE.Vector3(), - new THREE.Vector3(), - new THREE.Vector3(), - new THREE.Vector3(), - new THREE.Vector3(), - new THREE.Vector3(), - new THREE.Vector3() - ]; + if ( next === undefined ) { - return function ( matrix ) { + next = new StructuredUniform( id ); + addUniform( container, next ); - // 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.makeEmpty(); - this.setFromPoints( points ); + container = next; - return this; + } - }; + } - }(), + } - translate: function ( offset ) { + // Root Container - this.min.add( offset ); - this.max.add( offset ); + function WebGLUniforms( gl, program, renderer ) { - return this; + UniformContainer.call( this ); - }, + this.renderer = renderer; - equals: function ( box ) { + var n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS ); - return box.min.equals( this.min ) && box.max.equals( this.max ); + for ( var i = 0; i !== n; ++ i ) { - } + var info = gl.getActiveUniform( program, i ), + path = info.name, + addr = gl.getUniformLocation( program, path ); -}; + parseUniform( info, addr, this ); -// File:src/math/Matrix3.js + } -/** - * @author alteredq / http://alteredqualia.com/ - * @author WestLangley / http://github.com/WestLangley - * @author bhouston / http://exocortex.com - */ + } -THREE.Matrix3 = function () { + WebGLUniforms.prototype.setValue = function( gl, name, value ) { - this.elements = new Float32Array( [ + var u = this.map[ name ]; - 1, 0, 0, - 0, 1, 0, - 0, 0, 1 + if ( u !== undefined ) u.setValue( gl, value, this.renderer ); - ] ); + }; - if ( arguments.length > 0 ) { + WebGLUniforms.prototype.set = function( gl, object, name ) { - console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' ); + var u = this.map[ name ]; - } + if ( u !== undefined ) u.setValue( gl, object[ name ], this.renderer ); -}; + }; -THREE.Matrix3.prototype = { + WebGLUniforms.prototype.setOptional = function( gl, object, name ) { - constructor: THREE.Matrix3, + var v = object[ name ]; - set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) { + if ( v !== undefined ) this.setValue( gl, name, v ); - var te = this.elements; + }; - te[ 0 ] = n11; te[ 3 ] = n12; te[ 6 ] = n13; - te[ 1 ] = n21; te[ 4 ] = n22; te[ 7 ] = n23; - te[ 2 ] = n31; te[ 5 ] = n32; te[ 8 ] = n33; - return this; + // Static interface - }, + WebGLUniforms.upload = function( gl, seq, values, renderer ) { - identity: function () { + for ( var i = 0, n = seq.length; i !== n; ++ i ) { - this.set( + var u = seq[ i ], + v = values[ u.id ]; - 1, 0, 0, - 0, 1, 0, - 0, 0, 1 + if ( v.needsUpdate !== false ) { + // note: always updating when .needsUpdate is undefined - ); + u.setValue( gl, v.value, renderer ); - return this; + } - }, + } - clone: function () { + }; - return new this.constructor().fromArray( this.elements ); + WebGLUniforms.seqWithValue = function( seq, values ) { - }, + var r = []; - copy: function ( m ) { + for ( var i = 0, n = seq.length; i !== n; ++ i ) { - var me = m.elements; + var u = seq[ i ]; + if ( u.id in values ) r.push( u ); - this.set( + } - me[ 0 ], me[ 3 ], me[ 6 ], - me[ 1 ], me[ 4 ], me[ 7 ], - me[ 2 ], me[ 5 ], me[ 8 ] + return r; - ); + }; - return this; + WebGLUniforms.splitDynamic = function( seq, values ) { - }, + var r = null, + n = seq.length, + w = 0; - multiplyVector3: function ( vector ) { + for ( var i = 0; i !== n; ++ i ) { - console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' ); - return vector.applyMatrix3( this ); + var u = seq[ i ], + v = values[ u.id ]; - }, + if ( v && v.dynamic === true ) { - multiplyVector3Array: function ( a ) { + if ( r === null ) r = []; + r.push( u ); - console.warn( 'THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' ); - return this.applyToVector3Array( a ); + } else { - }, + // in-place compact 'seq', removing the matches + if ( w < i ) seq[ w ] = u; + ++ w; - applyToVector3Array: function () { + } - var v1; + } - return function ( array, offset, length ) { + if ( w < n ) seq.length = w; - if ( v1 === undefined ) v1 = new THREE.Vector3(); - if ( offset === undefined ) offset = 0; - if ( length === undefined ) length = array.length; + return r; - for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) { + }; - v1.fromArray( array, j ); - v1.applyMatrix3( this ); - v1.toArray( array, j ); + WebGLUniforms.evalDynamic = function( seq, values, object, material, camera ) { - } + for ( var i = 0, n = seq.length; i !== n; ++ i ) { - return array; + var v = values[ seq[ i ].id ], + f = v.onUpdateCallback; - }; + if ( f !== undefined ) f.call( v, object, material, camera ); - }(), + } - applyToBuffer: function () { + }; - var v1; + /** + * Uniform Utilities + */ - return function applyToBuffer( buffer, offset, length ) { + exports.UniformsUtils = { - if ( v1 === undefined ) v1 = new THREE.Vector3(); - if ( offset === undefined ) offset = 0; - if ( length === undefined ) length = buffer.length / buffer.itemSize; + merge: function ( uniforms ) { - for ( var i = 0, j = offset; i < length; i ++, j ++ ) { + var merged = {}; - v1.x = buffer.getX( j ); - v1.y = buffer.getY( j ); - v1.z = buffer.getZ( j ); + for ( var u = 0; u < uniforms.length; u ++ ) { - v1.applyMatrix3( this ); + var tmp = this.clone( uniforms[ u ] ); - buffer.setXYZ( v1.x, v1.y, v1.z ); + for ( var p in tmp ) { - } + merged[ p ] = tmp[ p ]; - return buffer; + } - }; + } - }(), + return merged; - multiplyScalar: function ( s ) { + }, - var te = this.elements; + clone: function ( uniforms_src ) { - 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; + var uniforms_dst = {}; - return this; + for ( var u in uniforms_src ) { - }, + uniforms_dst[ u ] = {}; - determinant: function () { + for ( var p in uniforms_src[ u ] ) { - var te = this.elements; + var parameter_src = uniforms_src[ u ][ p ]; - 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 ]; + 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) ) { - return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g; + uniforms_dst[ u ][ p ] = parameter_src.clone(); - }, + } else if ( Array.isArray( parameter_src ) ) { - getInverse: function ( matrix, throwOnInvertible ) { + uniforms_dst[ u ][ p ] = parameter_src.slice(); - // input: THREE.Matrix4 - // ( based on http://code.google.com/p/webgl-mjs/ ) + } else { - var me = matrix.elements; - var te = this.elements; + uniforms_dst[ u ][ p ] = parameter_src; - te[ 0 ] = me[ 10 ] * me[ 5 ] - me[ 6 ] * me[ 9 ]; - te[ 1 ] = - me[ 10 ] * me[ 1 ] + me[ 2 ] * me[ 9 ]; - te[ 2 ] = me[ 6 ] * me[ 1 ] - me[ 2 ] * me[ 5 ]; - te[ 3 ] = - me[ 10 ] * me[ 4 ] + me[ 6 ] * me[ 8 ]; - te[ 4 ] = me[ 10 ] * me[ 0 ] - me[ 2 ] * me[ 8 ]; - te[ 5 ] = - me[ 6 ] * me[ 0 ] + me[ 2 ] * me[ 4 ]; - te[ 6 ] = me[ 9 ] * me[ 4 ] - me[ 5 ] * me[ 8 ]; - te[ 7 ] = - me[ 9 ] * me[ 0 ] + me[ 1 ] * me[ 8 ]; - te[ 8 ] = me[ 5 ] * me[ 0 ] - me[ 1 ] * me[ 4 ]; + } - var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ]; + } - // no inverse + } - if ( det === 0 ) { + return uniforms_dst; - var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0"; + } - if ( throwOnInvertible || false ) { + }; - throw new Error( msg ); + var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n"; - } else { + var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif\n"; - console.warn( msg ); + 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"; - this.identity(); + var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif"; - return this; + var begin_vertex = "\nvec3 transformed = vec3( position );\n"; - } + var beginnormal_vertex = "\nvec3 objectNormal = vec3( normal );\n"; - this.multiplyScalar( 1.0 / det ); + 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"; - return this; + var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\t\tvec3 vSigmaX = dFdx( surf_pos );\n\t\tvec3 vSigmaY = dFdy( surf_pos );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 );\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif\n"; - }, + var 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"; - transpose: function () { + 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 tmp, m = this.elements; + var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvarying vec3 vViewPosition;\n#endif\n"; - 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; + var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n"; - return this; + var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif"; - }, + var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif\n"; - flattenToArrayOffset: function ( array, offset ) { + var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif"; - var te = this.elements; + var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif"; - array[ offset ] = te[ 0 ]; - array[ offset + 1 ] = te[ 1 ]; - array[ offset + 2 ] = te[ 2 ]; + 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"; - array[ offset + 3 ] = te[ 3 ]; - array[ offset + 4 ] = te[ 4 ]; - array[ offset + 5 ] = te[ 5 ]; + 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"; - array[ offset + 6 ] = te[ 6 ]; - array[ offset + 7 ] = te[ 7 ]; - array[ offset + 8 ] = te[ 8 ]; + var defaultnormal_vertex = "#ifdef FLIP_SIDED\n\tobjectNormal = -objectNormal;\n#endif\nvec3 transformedNormal = normalMatrix * objectNormal;\n"; - return array; + 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"; - getNormalMatrix: function ( m ) { + 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"; - // input: THREE.Matrix4 + var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif\n"; - this.getInverse( m ).transpose(); + var encodings_fragment = " gl_FragColor = linearToOutputTexel( gl_FragColor );\n"; - return this; + var encodings_pars_fragment = "\nvec4 LinearToLinear( in vec4 value ) {\n return value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.w );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n return vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n float maxComponent = max( max( value.r, value.g ), value.b );\n float fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n return vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n return vec4( value.xyz * value.w * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n float maxRGB = max( value.x, max( value.g, value.b ) );\n float M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n M = ceil( M * 255.0 ) / 255.0;\n return vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n return vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n float maxRGB = max( value.x, max( value.g, value.b ) );\n float D = max( maxRange / maxRGB, 1.0 );\n D = min( floor( D ) / 255.0, 1.0 );\n return vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n vec3 Xp_Y_XYZp = value.rgb * cLogLuvM;\n Xp_Y_XYZp = max(Xp_Y_XYZp, vec3(1e-6, 1e-6, 1e-6));\n vec4 vResult;\n vResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n float Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n vResult.w = fract(Le);\n vResult.z = (Le - (floor(vResult.w*255.0))/255.0)/255.0;\n return vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n float Le = value.z * 255.0 + value.w;\n vec3 Xp_Y_XYZp;\n Xp_Y_XYZp.y = exp2((Le - 127.0) / 2.0);\n Xp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n Xp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n vec3 vRGB = Xp_Y_XYZp.rgb * cLogLuvInverseM;\n return vec4( max(vRGB, 0.0), 1.0 );\n}\n"; - }, + var envmap_fragment = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\tvec2 sampleUV;\n\t\tsampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n\t\tsampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\tvec3 reflectView = flipNormal * normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\n\t\tvec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\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"; - transposeIntoArray: function ( r ) { + 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 m = this.elements; + 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"; - 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 ]; + 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"; - return this; + 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 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"; - fromArray: function ( array ) { + var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif\n"; - this.elements.set( array ); + var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif"; - return this; + 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"; - }, + 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"; - toArray: function () { + var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n"; - var te = this.elements; + 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"; - return [ - te[ 0 ], te[ 1 ], te[ 2 ], - te[ 3 ], te[ 4 ], te[ 5 ], - te[ 6 ], te[ 7 ], te[ 8 ] - ]; + 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 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"; -}; + 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"; -// File:src/math/Matrix4.js + var logdepthbuf_fragment = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\tgl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n#endif"; -/** - * @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://exocortex.com - * @author WestLangley / http://github.com/WestLangley - */ + 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"; -THREE.Matrix4 = function () { + 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.elements = new Float32Array( [ + 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"; - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 + 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"; - if ( arguments.length > 0 ) { + 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"; - console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' ); + 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"; -}; + var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif"; -THREE.Matrix4.prototype = { + 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"; - constructor: THREE.Matrix4, + 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"; - set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) { + 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"; - var te = this.elements; + 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"; - 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; + 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"; - return this; + 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"; - }, + 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"; - identity: function () { + var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif\n"; - this.set( + 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"; - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 + var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.r;\n#endif\n"; - ); + var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif"; - return this; + var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tfloat texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\n\t\tconst vec2 offset = vec2( 0.0, 1.0 );\n\t\tvec2 texelSize = vec2( 1.0 ) / size;\n\t\tvec2 centroidUV = floor( uv * size + 0.5 ) / size;\n\t\tfloat lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\n\t\tfloat lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\n\t\tfloat rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\n\t\tfloat rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\n\t\tvec2 f = fract( uv * size + 0.5 );\n\t\tfloat a = mix( lb, lt, f.y );\n\t\tfloat b = mix( rb, rt, f.y );\n\t\tfloat c = mix( a, b, f.x );\n\t\treturn c;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\treturn (\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn 1.0;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\tfloat dp = ( length( lightToPosition ) - shadowBias ) / 1000.0;\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif\n"; - }, + var shadowmap_pars_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n#endif\n"; - clone: function () { + 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"; - return new THREE.Matrix4().fromArray( this.elements ); + 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"; - copy: function ( m ) { + 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"; - this.elements.set( m.elements ); + 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"; - return this; + var skinnormal_vertex = "#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n#endif\n"; - }, + var 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"; - extractPosition: function ( m ) { + var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif"; - console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' ); - return this.copyPosition( m ); + 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"; - copyPosition: function ( m ) { + 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"; - var te = this.elements; - var me = m.elements; + 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"; - te[ 12 ] = me[ 12 ]; - te[ 13 ] = me[ 13 ]; - te[ 14 ] = me[ 14 ]; + 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"; - return this; + var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif"; - }, + var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif"; - extractBasis: function ( xAxis, yAxis, zAxis ) { + var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif"; - var te = this.elements; + 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"; - xAxis.set( te[ 0 ], te[ 1 ], te[ 2 ] ); - yAxis.set( te[ 4 ], te[ 5 ], te[ 6 ] ); - zAxis.set( te[ 8 ], te[ 9 ], te[ 10 ] ); + 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"; - makeBasis: function ( xAxis, yAxis, zAxis ) { + 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"; - 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 - ); + 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"; - return this; + var distanceRGBA_vert = "varying vec4 vWorldPosition;\n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvWorldPosition = worldPosition;\n}\n"; - }, + var 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"; - extractRotation: function () { + var equirect_vert = "varying vec3 vWorldPosition;\n#include \nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}\n"; - var v1; + 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"; - return function ( m ) { + 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"; - if ( v1 === undefined ) v1 = new THREE.Vector3(); + var meshbasic_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tReflectedLight reflectedLight;\n\treflectedLight.directDiffuse = vec3( 0.0 );\n\treflectedLight.directSpecular = vec3( 0.0 );\n\treflectedLight.indirectDiffuse = diffuseColor.rgb;\n\treflectedLight.indirectSpecular = vec3( 0.0 );\n\t#include \n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include \n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; - var te = this.elements; - var me = m.elements; + var meshbasic_vert = "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_ENVMAP\n\t#include \n\t#include \n\t#include \n\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; - var scaleX = 1 / v1.set( me[ 0 ], me[ 1 ], me[ 2 ] ).length(); - var scaleY = 1 / v1.set( me[ 4 ], me[ 5 ], me[ 6 ] ).length(); - var scaleZ = 1 / v1.set( me[ 8 ], me[ 9 ], me[ 10 ] ).length(); + 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"; - te[ 0 ] = me[ 0 ] * scaleX; - te[ 1 ] = me[ 1 ] * scaleX; - te[ 2 ] = me[ 2 ] * scaleX; + 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"; - te[ 4 ] = me[ 4 ] * scaleY; - te[ 5 ] = me[ 5 ] * scaleY; - te[ 6 ] = me[ 6 ] * scaleY; + 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"; - te[ 8 ] = me[ 8 ] * scaleZ; - te[ 9 ] = me[ 9 ] * scaleZ; - te[ 10 ] = me[ 10 ] * scaleZ; + 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"; - return this; + var meshphysical_frag = "#define PHYSICAL\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifndef STANDARD\n\tuniform float clearCoat;\n\tuniform float clearCoatRoughness;\n#endif\nuniform float envMapIntensity;\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; - }; + var 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"; - makeRotationFromEuler: function ( euler ) { + 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"; - if ( euler instanceof THREE.Euler === false ) { + 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"; - console.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' ); + 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"; - var te = this.elements; + var shadow_vert = "#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; - 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 ); + 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 ); + + } - if ( euler.order === 'XYZ' ) { + Color.prototype = { - var ae = a * e, af = a * f, be = b * e, bf = b * f; + constructor: Color, - te[ 0 ] = c * e; - te[ 4 ] = - c * f; - te[ 8 ] = d; + isColor: true, - te[ 1 ] = af + be * d; - te[ 5 ] = ae - bf * d; - te[ 9 ] = - b * c; + r: 1, g: 1, b: 1, - te[ 2 ] = bf - ae * d; - te[ 6 ] = be + af * d; - te[ 10 ] = a * c; + set: function ( value ) { - } else if ( euler.order === 'YXZ' ) { + if ( (value && value.isColor) ) { - var ce = c * e, cf = c * f, de = d * e, df = d * f; + this.copy( value ); - te[ 0 ] = ce + df * b; - te[ 4 ] = de * b - cf; - te[ 8 ] = a * d; + } else if ( typeof value === 'number' ) { - te[ 1 ] = a * f; - te[ 5 ] = a * e; - te[ 9 ] = - b; + this.setHex( value ); - te[ 2 ] = cf * b - de; - te[ 6 ] = df + ce * b; - te[ 10 ] = a * c; + } else if ( typeof value === 'string' ) { - } else if ( euler.order === 'ZXY' ) { + this.setStyle( value ); - var ce = c * e, cf = c * f, de = d * e, df = d * f; + } - te[ 0 ] = ce - df * b; - te[ 4 ] = - a * f; - te[ 8 ] = de + cf * b; + return this; - te[ 1 ] = cf + de * b; - te[ 5 ] = a * e; - te[ 9 ] = df - ce * b; + }, - te[ 2 ] = - a * d; - te[ 6 ] = b; - te[ 10 ] = a * c; + setScalar: function ( scalar ) { - } else if ( euler.order === 'ZYX' ) { + this.r = scalar; + this.g = scalar; + this.b = scalar; - var ae = a * e, af = a * f, be = b * e, bf = b * f; + }, - te[ 0 ] = c * e; - te[ 4 ] = be * d - af; - te[ 8 ] = ae * d + bf; + setHex: function ( hex ) { - te[ 1 ] = c * f; - te[ 5 ] = bf * d + ae; - te[ 9 ] = af * d - be; + hex = Math.floor( hex ); - te[ 2 ] = - d; - te[ 6 ] = b * c; - te[ 10 ] = a * c; + this.r = ( hex >> 16 & 255 ) / 255; + this.g = ( hex >> 8 & 255 ) / 255; + this.b = ( hex & 255 ) / 255; - } else if ( euler.order === 'YZX' ) { + return this; - var ac = a * c, ad = a * d, bc = b * c, bd = b * d; + }, - te[ 0 ] = c * e; - te[ 4 ] = bd - ac * f; - te[ 8 ] = bc * f + ad; + setRGB: function ( r, g, b ) { - te[ 1 ] = f; - te[ 5 ] = a * e; - te[ 9 ] = - b * e; + this.r = r; + this.g = g; + this.b = b; - te[ 2 ] = - d * e; - te[ 6 ] = ad * f + bc; - te[ 10 ] = ac - bd * f; + return this; - } else if ( euler.order === 'XZY' ) { + }, - var ac = a * c, ad = a * d, bc = b * c, bd = b * d; + setHSL: function () { - te[ 0 ] = c * e; - te[ 4 ] = - f; - te[ 8 ] = d * e; + function hue2rgb( p, q, t ) { - te[ 1 ] = ac * f + bd; - te[ 5 ] = a * e; - te[ 9 ] = ad * f - bc; + 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; - te[ 2 ] = bc * f - ad; - te[ 6 ] = b * e; - te[ 10 ] = bd * f + ac; + } - } + return function setHSL( h, s, l ) { - // last column - te[ 3 ] = 0; - te[ 7 ] = 0; - te[ 11 ] = 0; + // h,s,l ranges are in 0.0 - 1.0 + h = exports.Math.euclideanModulo( h, 1 ); + s = exports.Math.clamp( s, 0, 1 ); + l = exports.Math.clamp( l, 0, 1 ); - // bottom row - te[ 12 ] = 0; - te[ 13 ] = 0; - te[ 14 ] = 0; - te[ 15 ] = 1; + if ( s === 0 ) { - return this; + this.r = this.g = this.b = l; - }, + } else { - setRotationFromQuaternion: function ( q ) { + var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s ); + var q = ( 2 * l ) - p; - console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' ); + this.r = hue2rgb( q, p, h + 1 / 3 ); + this.g = hue2rgb( q, p, h ); + this.b = hue2rgb( q, p, h - 1 / 3 ); - return this.makeRotationFromQuaternion( q ); + } - }, + return this; - makeRotationFromQuaternion: function ( q ) { + }; - var te = this.elements; + }(), - var x = q.x, y = q.y, z = q.z, w = q.w; - var x2 = x + x, y2 = y + y, z2 = z + z; - var xx = x * x2, xy = x * y2, xz = x * z2; - var yy = y * y2, yz = y * z2, zz = z * z2; - var wx = w * x2, wy = w * y2, wz = w * z2; + setStyle: function ( style ) { - te[ 0 ] = 1 - ( yy + zz ); - te[ 4 ] = xy - wz; - te[ 8 ] = xz + wy; + function handleAlpha( string ) { - te[ 1 ] = xy + wz; - te[ 5 ] = 1 - ( xx + zz ); - te[ 9 ] = yz - wx; + if ( string === undefined ) return; - te[ 2 ] = xz - wy; - te[ 6 ] = yz + wx; - te[ 10 ] = 1 - ( xx + yy ); + if ( parseFloat( string ) < 1 ) { - // last column - te[ 3 ] = 0; - te[ 7 ] = 0; - te[ 11 ] = 0; + console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' ); - // bottom row - te[ 12 ] = 0; - te[ 13 ] = 0; - te[ 14 ] = 0; - te[ 15 ] = 1; + } - return this; + } - }, - lookAt: function () { + var m; - var x, y, z; + if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) { - return function ( eye, target, up ) { + // rgb / hsl - if ( x === undefined ) x = new THREE.Vector3(); - if ( y === undefined ) y = new THREE.Vector3(); - if ( z === undefined ) z = new THREE.Vector3(); + var color; + var name = m[ 1 ]; + var components = m[ 2 ]; - var te = this.elements; + switch ( name ) { - z.subVectors( eye, target ).normalize(); + case 'rgb': + case 'rgba': - if ( z.length() === 0 ) { + if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) { - z.z = 1; + // rgb(255,0,0) rgba(255,0,0,0.5) + this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255; + this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255; + this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255; - } + handleAlpha( color[ 5 ] ); - x.crossVectors( up, z ).normalize(); + return this; - if ( x.length() === 0 ) { + } - z.x += 0.0001; - x.crossVectors( up, z ).normalize(); + if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) { - } + // 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; - y.crossVectors( z, x ); + handleAlpha( color[ 5 ] ); + 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; + break; - }; + case 'hsl': + case 'hsla': - }(), + if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) { - multiply: function ( m, 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; - if ( n !== undefined ) { + handleAlpha( color[ 5 ] ); - console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' ); - return this.multiplyMatrices( m, n ); + return this.setHSL( h, s, l ); - } + } - return this.multiplyMatrices( this, m ); + break; - }, + } - multiplyMatrices: function ( a, b ) { + } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) { - var ae = a.elements; - var be = b.elements; - var te = this.elements; + // hex color - 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 hex = m[ 1 ]; + var size = hex.length; - 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 ]; + if ( size === 3 ) { - 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; + // #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; - 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; + return this; - 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; + } else if ( size === 6 ) { - 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; + // #ff0000 + this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255; + this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255; + this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255; - return this; + return this; - }, + } - multiplyToArray: function ( a, b, r ) { + } - var te = this.elements; + if ( style && style.length > 0 ) { - this.multiplyMatrices( a, b ); + // color keywords + var hex = exports.ColorKeywords[ style ]; - 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 ]; + if ( hex !== undefined ) { - return this; + // red + this.setHex( hex ); - }, + } else { - multiplyScalar: function ( s ) { + // unknown color + console.warn( 'THREE.Color: Unknown color ' + style ); - var te = this.elements; + } - 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; - }, + }, - multiplyVector3: function ( vector ) { + clone: function () { - console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' ); - return vector.applyProjection( this ); + return new this.constructor( this.r, this.g, this.b ); - }, + }, - multiplyVector4: function ( vector ) { + copy: function ( color ) { - console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); - return vector.applyMatrix4( this ); + this.r = color.r; + this.g = color.g; + this.b = color.b; - }, + return this; - multiplyVector3Array: function ( a ) { + }, - console.warn( 'THREE.Matrix4: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' ); - return this.applyToVector3Array( a ); + copyGammaToLinear: function ( color, gammaFactor ) { - }, + if ( gammaFactor === undefined ) gammaFactor = 2.0; - applyToVector3Array: function () { + this.r = Math.pow( color.r, gammaFactor ); + this.g = Math.pow( color.g, gammaFactor ); + this.b = Math.pow( color.b, gammaFactor ); - var v1; + return this; - return function ( array, offset, length ) { + }, - if ( v1 === undefined ) v1 = new THREE.Vector3(); - if ( offset === undefined ) offset = 0; - if ( length === undefined ) length = array.length; + copyLinearToGamma: function ( color, gammaFactor ) { - for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) { + if ( gammaFactor === undefined ) gammaFactor = 2.0; - v1.fromArray( array, j ); - v1.applyMatrix4( this ); - v1.toArray( array, j ); + var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0; - } + this.r = Math.pow( color.r, safeInverse ); + this.g = Math.pow( color.g, safeInverse ); + this.b = Math.pow( color.b, safeInverse ); - return array; + return this; - }; + }, - }(), + convertGammaToLinear: function () { - applyToBuffer: function () { + var r = this.r, g = this.g, b = this.b; - var v1; + this.r = r * r; + this.g = g * g; + this.b = b * b; - return function applyToBuffer( buffer, offset, length ) { + return this; - if ( v1 === undefined ) v1 = new THREE.Vector3(); - if ( offset === undefined ) offset = 0; - if ( length === undefined ) length = buffer.length / buffer.itemSize; + }, - for ( var i = 0, j = offset; i < length; i ++, j ++ ) { + convertLinearToGamma: function () { - v1.x = buffer.getX( j ); - v1.y = buffer.getY( j ); - v1.z = buffer.getZ( j ); + this.r = Math.sqrt( this.r ); + this.g = Math.sqrt( this.g ); + this.b = Math.sqrt( this.b ); - v1.applyMatrix4( this ); + return this; - buffer.setXYZ( v1.x, v1.y, v1.z ); + }, - } + getHex: function () { - return buffer; + return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0; - }; + }, - }(), + getHexString: function () { - rotateAxis: function ( v ) { + return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 ); - console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' ); + }, - v.transformDirection( this ); + getHSL: function ( optionalTarget ) { - }, + // h,s,l ranges are in 0.0 - 1.0 - crossVector: function ( vector ) { + var hsl = optionalTarget || { h: 0, s: 0, l: 0 }; - console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); - return vector.applyMatrix4( this ); + var r = this.r, g = this.g, b = this.b; - }, + var max = Math.max( r, g, b ); + var min = Math.min( r, g, b ); - determinant: function () { + var hue, saturation; + var lightness = ( min + max ) / 2.0; - var te = this.elements; + if ( min === max ) { - 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 ]; + hue = 0; + saturation = 0; - //TODO: make this more efficient - //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm ) + } else { - 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 delta = max - min; - ); + saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min ); - }, + switch ( max ) { - transpose: function () { + case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break; + case g: hue = ( b - r ) / delta + 2; break; + case b: hue = ( r - g ) / delta + 4; break; - var te = this.elements; - var tmp; + } - tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp; - tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp; - tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp; + hue /= 6; - tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp; - tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp; - tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp; + } - return this; + hsl.h = hue; + hsl.s = saturation; + hsl.l = lightness; - }, + return hsl; - flattenToArrayOffset: function ( array, offset ) { + }, - var te = this.elements; + getStyle: function () { - array[ offset ] = te[ 0 ]; - array[ offset + 1 ] = te[ 1 ]; - array[ offset + 2 ] = te[ 2 ]; - array[ offset + 3 ] = te[ 3 ]; + return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')'; - 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 ]; + offsetHSL: function ( h, s, l ) { - array[ offset + 12 ] = te[ 12 ]; - array[ offset + 13 ] = te[ 13 ]; - array[ offset + 14 ] = te[ 14 ]; - array[ offset + 15 ] = te[ 15 ]; + var hsl = this.getHSL(); - return array; + hsl.h += h; hsl.s += s; hsl.l += l; - }, + this.setHSL( hsl.h, hsl.s, hsl.l ); - getPosition: function () { + return this; - var v1; + }, - return function () { + add: function ( color ) { - if ( v1 === undefined ) v1 = new THREE.Vector3(); - console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' ); + this.r += color.r; + this.g += color.g; + this.b += color.b; - var te = this.elements; - return v1.set( te[ 12 ], te[ 13 ], te[ 14 ] ); + return this; - }; + }, - }(), + addColors: function ( color1, color2 ) { - setPosition: function ( v ) { + this.r = color1.r + color2.r; + this.g = color1.g + color2.g; + this.b = color1.b + color2.b; - var te = this.elements; + return this; - te[ 12 ] = v.x; - te[ 13 ] = v.y; - te[ 14 ] = v.z; + }, - return this; + addScalar: function ( s ) { - }, + this.r += s; + this.g += s; + this.b += s; - getInverse: function ( m, throwOnInvertible ) { + return this; - // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm - var te = this.elements; - var me = m.elements; + }, - var n11 = me[ 0 ], n12 = me[ 4 ], n13 = me[ 8 ], n14 = me[ 12 ]; - var n21 = me[ 1 ], n22 = me[ 5 ], n23 = me[ 9 ], n24 = me[ 13 ]; - var n31 = me[ 2 ], n32 = me[ 6 ], n33 = me[ 10 ], n34 = me[ 14 ]; - var n41 = me[ 3 ], n42 = me[ 7 ], n43 = me[ 11 ], n44 = me[ 15 ]; + sub: function( color ) { - te[ 0 ] = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44; - te[ 4 ] = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44; - te[ 8 ] = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44; - te[ 12 ] = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; - te[ 1 ] = n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44; - te[ 5 ] = n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44; - te[ 9 ] = n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44; - te[ 13 ] = n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34; - te[ 2 ] = n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44; - te[ 6 ] = n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44; - te[ 10 ] = n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44; - te[ 14 ] = n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34; - te[ 3 ] = n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43; - te[ 7 ] = n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43; - te[ 11 ] = n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43; - te[ 15 ] = n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33; + 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 ); - var det = n11 * te[ 0 ] + n21 * te[ 4 ] + n31 * te[ 8 ] + n41 * te[ 12 ]; + return this; - if ( det === 0 ) { + }, - var msg = "THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0"; + multiply: function ( color ) { - if ( throwOnInvertible || false ) { + this.r *= color.r; + this.g *= color.g; + this.b *= color.b; - throw new Error( msg ); + return this; - } else { + }, - console.warn( msg ); + multiplyScalar: function ( s ) { - } + this.r *= s; + this.g *= s; + this.b *= s; - this.identity(); + return this; - return this; + }, - } + lerp: function ( color, alpha ) { - this.multiplyScalar( 1 / det ); + this.r += ( color.r - this.r ) * alpha; + this.g += ( color.g - this.g ) * alpha; + this.b += ( color.b - this.b ) * alpha; - return this; + return this; - }, + }, - translate: function ( v ) { + equals: function ( c ) { - console.error( 'THREE.Matrix4: .translate() has been removed.' ); + return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b ); - }, + }, - rotateX: function ( angle ) { + fromArray: function ( array, offset ) { - console.error( 'THREE.Matrix4: .rotateX() has been removed.' ); + if ( offset === undefined ) offset = 0; - }, + this.r = array[ offset ]; + this.g = array[ offset + 1 ]; + this.b = array[ offset + 2 ]; - rotateY: function ( angle ) { + return this; - console.error( 'THREE.Matrix4: .rotateY() has been removed.' ); + }, - }, + toArray: function ( array, offset ) { - rotateZ: function ( angle ) { + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - console.error( 'THREE.Matrix4: .rotateZ() has been removed.' ); + array[ offset ] = this.r; + array[ offset + 1 ] = this.g; + array[ offset + 2 ] = this.b; - }, + return array; - rotateByAxis: function ( axis, angle ) { + }, - console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' ); + toJSON: function () { - }, + return this.getHex(); - scale: function ( v ) { + } - var te = this.elements; - var x = v.x, y = v.y, z = v.z; + }; - 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; + 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 }; - return this; + /** + * Uniforms library for shared webgl shaders + */ - }, + var UniformsLib = { - getMaxScaleOnAxis: function () { + common: { - var te = this.elements; + diffuse: { value: new Color( 0xeeeeee ) }, + opacity: { value: 1.0 }, - 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 ]; + map: { value: null }, + offsetRepeat: { value: new Vector4( 0, 0, 1, 1 ) }, - return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) ); + specularMap: { value: null }, + alphaMap: { value: null }, - }, + envMap: { value: null }, + flipEnvMap: { value: - 1 }, + reflectivity: { value: 1.0 }, + refractionRatio: { value: 0.98 } - makeTranslation: function ( x, y, z ) { + }, - this.set( + aomap: { - 1, 0, 0, x, - 0, 1, 0, y, - 0, 0, 1, z, - 0, 0, 0, 1 + aoMap: { value: null }, + aoMapIntensity: { value: 1 } - ); + }, - return this; + lightmap: { - }, + lightMap: { value: null }, + lightMapIntensity: { value: 1 } - makeRotationX: function ( theta ) { + }, - var c = Math.cos( theta ), s = Math.sin( theta ); + emissivemap: { - this.set( + emissiveMap: { value: null } - 1, 0, 0, 0, - 0, c, - s, 0, - 0, s, c, 0, - 0, 0, 0, 1 + }, - ); + bumpmap: { - return this; + bumpMap: { value: null }, + bumpScale: { value: 1 } - }, + }, - makeRotationY: function ( theta ) { + normalmap: { - var c = Math.cos( theta ), s = Math.sin( theta ); + normalMap: { value: null }, + normalScale: { value: new Vector2( 1, 1 ) } - this.set( + }, - c, 0, s, 0, - 0, 1, 0, 0, - - s, 0, c, 0, - 0, 0, 0, 1 + displacementmap: { - ); + displacementMap: { value: null }, + displacementScale: { value: 1 }, + displacementBias: { value: 0 } - return this; + }, - }, + roughnessmap: { - makeRotationZ: function ( theta ) { + roughnessMap: { value: null } - var c = Math.cos( theta ), s = Math.sin( theta ); + }, - this.set( + metalnessmap: { - c, - s, 0, 0, - s, c, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 + metalnessMap: { value: null } - ); + }, - return this; + fog: { - }, + fogDensity: { value: 0.00025 }, + fogNear: { value: 1 }, + fogFar: { value: 2000 }, + fogColor: { value: new Color( 0xffffff ) } - makeRotationAxis: function ( axis, angle ) { + }, - // Based on http://www.gamedev.net/reference/articles/article1199.asp + lights: { - 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; + ambientLightColor: { value: [] }, - this.set( + directionalLights: { value: [], properties: { + direction: {}, + color: {}, - 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 + shadow: {}, + shadowBias: {}, + shadowRadius: {}, + shadowMapSize: {} + } }, - ); + directionalShadowMap: { value: [] }, + directionalShadowMatrix: { value: [] }, - return this; + spotLights: { value: [], properties: { + color: {}, + position: {}, + direction: {}, + distance: {}, + coneCos: {}, + penumbraCos: {}, + decay: {}, - }, + shadow: {}, + shadowBias: {}, + shadowRadius: {}, + shadowMapSize: {} + } }, - makeScale: function ( x, y, z ) { + spotShadowMap: { value: [] }, + spotShadowMatrix: { value: [] }, - this.set( + pointLights: { value: [], properties: { + color: {}, + position: {}, + decay: {}, + distance: {}, - x, 0, 0, 0, - 0, y, 0, 0, - 0, 0, z, 0, - 0, 0, 0, 1 + shadow: {}, + shadowBias: {}, + shadowRadius: {}, + shadowMapSize: {} + } }, - ); + pointShadowMap: { value: [] }, + pointShadowMatrix: { value: [] }, - return this; + hemisphereLights: { value: [], properties: { + direction: {}, + skyColor: {}, + groundColor: {} + } } - }, + }, - compose: function ( position, quaternion, scale ) { + points: { - this.makeRotationFromQuaternion( quaternion ); - this.scale( scale ); - this.setPosition( position ); + 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 ) } - return this; + } - }, + }; - decompose: function () { + /** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + * @author mikael emtinger / http://gomo.se/ + */ - var vector, matrix; + var ShaderLib = { - return function ( position, quaternion, scale ) { + basic: { - if ( vector === undefined ) vector = new THREE.Vector3(); - if ( matrix === undefined ) matrix = new THREE.Matrix4(); + uniforms: exports.UniformsUtils.merge( [ - var te = this.elements; + UniformsLib.common, + UniformsLib.aomap, + UniformsLib.fog - 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 ) { + vertexShader: ShaderChunk.meshbasic_vert, + fragmentShader: ShaderChunk.meshbasic_frag - sx = - sx; + }, - } + lambert: { - position.x = te[ 12 ]; - position.y = te[ 13 ]; - position.z = te[ 14 ]; + uniforms: exports.UniformsUtils.merge( [ - // scale the rotation part + UniformsLib.common, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.fog, + UniformsLib.lights, - matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy() + { + emissive : { value: new Color( 0x000000 ) } + } - var invSX = 1 / sx; - var invSY = 1 / sy; - var invSZ = 1 / sz; + ] ), - matrix.elements[ 0 ] *= invSX; - matrix.elements[ 1 ] *= invSX; - matrix.elements[ 2 ] *= invSX; + vertexShader: ShaderChunk.meshlambert_vert, + fragmentShader: ShaderChunk.meshlambert_frag - matrix.elements[ 4 ] *= invSY; - matrix.elements[ 5 ] *= invSY; - matrix.elements[ 6 ] *= invSY; + }, - matrix.elements[ 8 ] *= invSZ; - matrix.elements[ 9 ] *= invSZ; - matrix.elements[ 10 ] *= invSZ; + phong: { - quaternion.setFromRotationMatrix( matrix ); + uniforms: exports.UniformsUtils.merge( [ - scale.x = sx; - scale.y = sy; - scale.z = sz; + UniformsLib.common, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.fog, + UniformsLib.lights, - return this; + { + emissive : { value: new Color( 0x000000 ) }, + specular : { value: new Color( 0x111111 ) }, + shininess: { value: 30 } + } - }; + ] ), - }(), + vertexShader: ShaderChunk.meshphong_vert, + fragmentShader: ShaderChunk.meshphong_frag - makeFrustum: function ( left, right, bottom, top, near, far ) { + }, - var te = this.elements; - var x = 2 * near / ( right - left ); - var y = 2 * near / ( top - bottom ); + standard: { - 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 ); + uniforms: exports.UniformsUtils.merge( [ - 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; + UniformsLib.common, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.roughnessmap, + UniformsLib.metalnessmap, + UniformsLib.fog, + UniformsLib.lights, - return this; + { + emissive : { value: new Color( 0x000000 ) }, + roughness: { value: 0.5 }, + metalness: { value: 0 }, + envMapIntensity : { value: 1 }, // temporary + } - }, + ] ), - makePerspective: function ( fov, aspect, near, far ) { + vertexShader: ShaderChunk.meshphysical_vert, + fragmentShader: ShaderChunk.meshphysical_frag - var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) ); - var ymin = - ymax; - var xmin = ymin * aspect; - var xmax = ymax * aspect; + }, - return this.makeFrustum( xmin, xmax, ymin, ymax, near, far ); + points: { - }, + uniforms: exports.UniformsUtils.merge( [ - makeOrthographic: function ( left, right, top, bottom, near, far ) { + UniformsLib.points, + UniformsLib.fog - var te = this.elements; - var w = right - left; - var h = top - bottom; - var p = far - near; + ] ), - var x = ( right + left ) / w; - var y = ( top + bottom ) / h; - var z = ( far + near ) / p; + vertexShader: ShaderChunk.points_vert, + fragmentShader: ShaderChunk.points_frag - te[ 0 ] = 2 / w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x; - te[ 1 ] = 0; te[ 5 ] = 2 / h; te[ 9 ] = 0; te[ 13 ] = - y; - te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 / p; te[ 14 ] = - z; - te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1; + }, - return this; + dashed: { - }, + uniforms: exports.UniformsUtils.merge( [ - equals: function ( matrix ) { + UniformsLib.common, + UniformsLib.fog, - var te = this.elements; - var me = matrix.elements; + { + scale : { value: 1 }, + dashSize : { value: 1 }, + totalSize: { value: 2 } + } - for ( var i = 0; i < 16; i ++ ) { + ] ), - if ( te[ i ] !== me[ i ] ) return false; + vertexShader: ShaderChunk.linedashed_vert, + fragmentShader: ShaderChunk.linedashed_frag - } + }, - return true; + depth: { - }, + uniforms: exports.UniformsUtils.merge( [ - fromArray: function ( array ) { + UniformsLib.common, + UniformsLib.displacementmap - this.elements.set( array ); + ] ), - return this; + vertexShader: ShaderChunk.depth_vert, + fragmentShader: ShaderChunk.depth_frag - }, + }, - toArray: function () { + normal: { - var te = this.elements; + uniforms: { - return [ - te[ 0 ], te[ 1 ], te[ 2 ], te[ 3 ], - te[ 4 ], te[ 5 ], te[ 6 ], te[ 7 ], - te[ 8 ], te[ 9 ], te[ 10 ], te[ 11 ], - te[ 12 ], te[ 13 ], te[ 14 ], te[ 15 ] - ]; + opacity : { value: 1.0 } - } + }, -}; + vertexShader: ShaderChunk.normal_vert, + fragmentShader: ShaderChunk.normal_frag -// File:src/math/Ray.js + }, -/** - * @author bhouston / http://exocortex.com - */ + /* ------------------------------------------------------------------------- + // Cube map shader + ------------------------------------------------------------------------- */ -THREE.Ray = function ( origin, direction ) { + cube: { - this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3(); - this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3(); + uniforms: { + tCube: { value: null }, + tFlip: { value: - 1 }, + opacity: { value: 1.0 } + }, -}; + vertexShader: ShaderChunk.cube_vert, + fragmentShader: ShaderChunk.cube_frag -THREE.Ray.prototype = { + }, - constructor: THREE.Ray, + /* ------------------------------------------------------------------------- + // Cube map shader + ------------------------------------------------------------------------- */ - set: function ( origin, direction ) { + equirect: { - this.origin.copy( origin ); - this.direction.copy( direction ); + uniforms: { + tEquirect: { value: null }, + tFlip: { value: - 1 } + }, - return this; + vertexShader: ShaderChunk.equirect_vert, + fragmentShader: ShaderChunk.equirect_frag - }, + }, - clone: function () { + distanceRGBA: { - return new this.constructor().copy( this ); + uniforms: { - }, + lightPos: { value: new Vector3() } - copy: function ( ray ) { + }, - this.origin.copy( ray.origin ); - this.direction.copy( ray.direction ); + vertexShader: ShaderChunk.distanceRGBA_vert, + fragmentShader: ShaderChunk.distanceRGBA_frag - return this; + } - }, + }; - at: function ( t, optionalTarget ) { + ShaderLib.physical = { - var result = optionalTarget || new THREE.Vector3(); + uniforms: exports.UniformsUtils.merge( [ - return result.copy( this.direction ).multiplyScalar( t ).add( this.origin ); + ShaderLib.standard.uniforms, - }, + { + clearCoat: { value: 0 }, + clearCoatRoughness: { value: 0 } + } - recast: function () { + ] ), - var v1 = new THREE.Vector3(); + vertexShader: ShaderChunk.meshphysical_vert, + fragmentShader: ShaderChunk.meshphysical_frag - return function ( t ) { + }; - this.origin.copy( this.at( t, v1 ) ); + /** + * @author bhouston / http://clara.io + */ - return this; + function Box2( min, max ) { - }; + this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity ); + this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity ); - }(), + } - closestPointToPoint: function ( point, optionalTarget ) { + Box2.prototype = { - var result = optionalTarget || new THREE.Vector3(); - result.subVectors( point, this.origin ); - var directionDistance = result.dot( this.direction ); + constructor: Box2, - if ( directionDistance < 0 ) { + set: function ( min, max ) { - return result.copy( this.origin ); + this.min.copy( min ); + this.max.copy( max ); - } + return this; - return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); + }, - }, + setFromPoints: function ( points ) { - distanceToPoint: function ( point ) { + this.makeEmpty(); - return Math.sqrt( this.distanceSqToPoint( point ) ); + for ( var i = 0, il = points.length; i < il; i ++ ) { - }, + this.expandByPoint( points[ i ] ); - distanceSqToPoint: function () { + } - var v1 = new THREE.Vector3(); + return this; - return function ( point ) { + }, - var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction ); + setFromCenterAndSize: function () { - // point behind the ray + var v1 = new Vector2(); - if ( directionDistance < 0 ) { + return function setFromCenterAndSize( center, size ) { - return this.origin.distanceToSquared( point ); + var halfSize = v1.copy( size ).multiplyScalar( 0.5 ); + this.min.copy( center ).sub( halfSize ); + this.max.copy( center ).add( halfSize ); - } + return this; - v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); + }; - return v1.distanceToSquared( point ); + }(), - }; + clone: function () { - }(), + return new this.constructor().copy( this ); - distanceSqToSegment: function () { + }, - var segCenter = new THREE.Vector3(); - var segDir = new THREE.Vector3(); - var diff = new THREE.Vector3(); + copy: function ( box ) { - return function ( v0, v1, optionalPointOnRay, optionalPointOnSegment ) { + this.min.copy( box.min ); + this.max.copy( box.max ); - // from http://www.geometrictools.com/LibMathematics/Distance/Wm5DistRay3Segment3.cpp - // 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 + return this; - segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 ); - segDir.copy( v1 ).sub( v0 ).normalize(); - diff.copy( this.origin ).sub( segCenter ); + }, - 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; + makeEmpty: function () { - if ( det > 0 ) { + this.min.x = this.min.y = + Infinity; + this.max.x = this.max.y = - Infinity; - // The ray and segment are not parallel. + return this; - s0 = a01 * b1 - b0; - s1 = a01 * b0 - b1; - extDet = segExtent * det; + }, - if ( s0 >= 0 ) { + isEmpty: function () { - if ( s1 >= - extDet ) { + // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes - if ( s1 <= extDet ) { + return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ); - // region 0 - // Minimum at interior points of ray and segment. + }, - var invDet = 1 / det; - s0 *= invDet; - s1 *= invDet; - sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c; + getCenter: function ( optionalTarget ) { - } else { + var result = optionalTarget || new Vector2(); + return this.isEmpty() ? result.set( 0, 0 ) : result.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); - // region 1 + }, - s1 = segExtent; - s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + getSize: function ( optionalTarget ) { - } + var result = optionalTarget || new Vector2(); + return this.isEmpty() ? result.set( 0, 0 ) : result.subVectors( this.max, this.min ); - } else { + }, - // region 5 + expandByPoint: function ( point ) { - s1 = - segExtent; - s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + this.min.min( point ); + this.max.max( point ); - } + return this; - } else { + }, - if ( s1 <= - extDet ) { + expandByVector: function ( vector ) { - // region 4 + this.min.sub( vector ); + this.max.add( vector ); - 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; + return this; - } else if ( s1 <= extDet ) { + }, - // region 3 + expandByScalar: function ( scalar ) { - s0 = 0; - s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent ); - sqrDist = s1 * ( s1 + 2 * b1 ) + c; + this.min.addScalar( - scalar ); + this.max.addScalar( scalar ); - } else { + return this; - // region 2 + }, - 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; + containsPoint: function ( point ) { - } + if ( point.x < this.min.x || point.x > this.max.x || + point.y < this.min.y || point.y > this.max.y ) { - } + return false; - } else { + } - // Ray and segment are parallel. + return true; - s1 = ( a01 > 0 ) ? - segExtent : segExtent; - s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + }, - } + containsBox: function ( box ) { - if ( optionalPointOnRay ) { + 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 ) ) { - optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin ); + return true; - } + } - if ( optionalPointOnSegment ) { + return false; - optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter ); + }, - } + getParameter: function ( point, optionalTarget ) { - return sqrDist; + // This can potentially have a divide by zero if the box + // has a size dimension of 0. - }; + var result = optionalTarget || new Vector2(); - }(), + return result.set( + ( point.x - this.min.x ) / ( this.max.x - this.min.x ), + ( point.y - this.min.y ) / ( this.max.y - this.min.y ) + ); + }, - isIntersectionSphere: function ( sphere ) { + intersectsBox: function ( box ) { - return this.distanceToPoint( sphere.center ) <= sphere.radius; + // 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 ) { - intersectSphere: function () { + return false; - // from http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-sphere-intersection/ + } - var v1 = new THREE.Vector3(); + return true; - return function ( sphere, optionalTarget ) { + }, - v1.subVectors( sphere.center, this.origin ); + clampPoint: function ( point, optionalTarget ) { - var tca = v1.dot( this.direction ); + var result = optionalTarget || new Vector2(); + return result.copy( point ).clamp( this.min, this.max ); - var d2 = v1.dot( v1 ) - tca * tca; + }, - var radius2 = sphere.radius * sphere.radius; + distanceToPoint: function () { - if ( d2 > radius2 ) return null; + var v1 = new Vector2(); - var thc = Math.sqrt( radius2 - d2 ); + return function distanceToPoint( point ) { - // t0 = first intersect point - entrance on front of sphere - var t0 = tca - thc; + var clampedPoint = v1.copy( point ).clamp( this.min, this.max ); + return clampedPoint.sub( point ).length(); - // t1 = second intersect point - exit point on back of sphere - var t1 = tca + thc; + }; - // 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 ); + intersect: function ( box ) { - // else t0 is in front of the ray, so return the first collision point scaled by t0 - return this.at( t0, optionalTarget ); + this.min.max( box.min ); + this.max.min( box.max ); - } + return this; - }(), + }, - isIntersectionPlane: function ( plane ) { + union: function ( box ) { - // check if the ray lies on the plane first + this.min.min( box.min ); + this.max.max( box.max ); - var distToPoint = plane.distanceToPoint( this.origin ); + return this; - if ( distToPoint === 0 ) { + }, - return true; + translate: function ( offset ) { - } + this.min.add( offset ); + this.max.add( offset ); - var denominator = plane.normal.dot( this.direction ); + return this; - if ( denominator * distToPoint < 0 ) { + }, - return true; + equals: function ( box ) { - } + return box.min.equals( this.min ) && box.max.equals( this.max ); - // ray origin is behind the plane (and is pointing behind it) + } - return false; + }; - }, + /** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + */ - distanceToPlane: function ( plane ) { + function LensFlarePlugin( renderer, flares ) { - var denominator = plane.normal.dot( this.direction ); - if ( denominator === 0 ) { + var gl = renderer.context; + var state = renderer.state; - // line is coplanar, return origin - if ( plane.distanceToPoint( this.origin ) === 0 ) { + var vertexBuffer, elementBuffer; + var shader, program, attributes, uniforms; - return 0; + var tempTexture, occlusionTexture; - } + function init() { - // Null is preferable to undefined since undefined means.... it is undefined + var vertices = new Float32Array( [ + - 1, - 1, 0, 0, + 1, - 1, 1, 0, + 1, 1, 1, 1, + - 1, 1, 0, 1 + ] ); - return null; + var faces = new Uint16Array( [ + 0, 1, 2, + 0, 2, 3 + ] ); - } + // buffers - var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator; + vertexBuffer = gl.createBuffer(); + elementBuffer = gl.createBuffer(); - // Return if the ray never intersects the plane + gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer ); + gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW ); - return t >= 0 ? t : null; + gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); + gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW ); - }, + // textures - intersectPlane: function ( plane, optionalTarget ) { + tempTexture = gl.createTexture(); + occlusionTexture = gl.createTexture(); - var t = this.distanceToPlane( plane ); + 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 ); - if ( t === null ) { + 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 null; + shader = { - } + vertexShader: [ - return this.at( t, optionalTarget ); + "uniform lowp int renderType;", - }, + "uniform vec3 screenPosition;", + "uniform vec2 scale;", + "uniform float rotation;", - isIntersectionBox: function () { + "uniform sampler2D occlusionMap;", - var v = new THREE.Vector3(); + "attribute vec2 position;", + "attribute vec2 uv;", - return function ( box ) { + "varying vec2 vUV;", + "varying float vVisibility;", - return this.intersectBox( box, v ) !== null; + "void main() {", - }; + "vUV = uv;", - }(), + "vec2 pos = position;", - intersectBox: function ( box, optionalTarget ) { + "if ( renderType == 2 ) {", - // http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-box-intersection/ + "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 ) );", - var tmin, tmax, tymin, tymax, tzmin, tzmax; + "vVisibility = visibility.r / 9.0;", + "vVisibility *= 1.0 - visibility.g / 9.0;", + "vVisibility *= visibility.b / 9.0;", + "vVisibility *= 1.0 - visibility.a / 9.0;", - var invdirx = 1 / this.direction.x, - invdiry = 1 / this.direction.y, - invdirz = 1 / this.direction.z; + "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;", + "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;", - var origin = this.origin; + "}", - if ( invdirx >= 0 ) { + "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );", - tmin = ( box.min.x - origin.x ) * invdirx; - tmax = ( box.max.x - origin.x ) * invdirx; + "}" - } else { + ].join( "\n" ), - tmin = ( box.max.x - origin.x ) * invdirx; - tmax = ( box.min.x - origin.x ) * invdirx; + fragmentShader: [ - } + "uniform lowp int renderType;", - if ( invdiry >= 0 ) { + "uniform sampler2D map;", + "uniform float opacity;", + "uniform vec3 color;", - tymin = ( box.min.y - origin.y ) * invdiry; - tymax = ( box.max.y - origin.y ) * invdiry; + "varying vec2 vUV;", + "varying float vVisibility;", - } else { + "void main() {", - tymin = ( box.max.y - origin.y ) * invdiry; - tymax = ( box.min.y - origin.y ) * invdiry; + // pink square - } + "if ( renderType == 0 ) {", - if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null; + "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );", - // These lines also handle the case where tmin or tmax is NaN - // (result of 0 * Infinity). x !== x returns true if x is NaN + // restore - if ( tymin > tmin || tmin !== tmin ) tmin = tymin; + "} else if ( renderType == 1 ) {", - if ( tymax < tmax || tmax !== tmax ) tmax = tymax; + "gl_FragColor = texture2D( map, vUV );", - if ( invdirz >= 0 ) { + // flare - tzmin = ( box.min.z - origin.z ) * invdirz; - tzmax = ( box.max.z - origin.z ) * invdirz; + "} else {", - } else { + "vec4 texture = texture2D( map, vUV );", + "texture.a *= opacity * vVisibility;", + "gl_FragColor = texture;", + "gl_FragColor.rgb *= color;", - tzmin = ( box.max.z - origin.z ) * invdirz; - tzmax = ( box.min.z - origin.z ) * invdirz; + "}", - } + "}" - if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null; + ].join( "\n" ) - if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin; + }; - if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax; + program = createProgram( shader ); - //return point closest to the ray (positive side) + attributes = { + vertex: gl.getAttribLocation ( program, "position" ), + uv: gl.getAttribLocation ( program, "uv" ) + }; - if ( tmax < 0 ) return null; + 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 this.at( tmin >= 0 ? tmin : tmax, optionalTarget ); + } - }, + /* + * Render lens flares + * Method: renders 16x16 0xff00ff-colored points scattered over the light source area, + * reads these back and calculates occlusion. + */ - intersectTriangle: function () { + this.render = function ( scene, camera, viewport ) { - // Compute the offset origin, edges, and normal. - var diff = new THREE.Vector3(); - var edge1 = new THREE.Vector3(); - var edge2 = new THREE.Vector3(); - var normal = new THREE.Vector3(); + if ( flares.length === 0 ) return; - return function ( a, b, c, backfaceCulling, optionalTarget ) { + var tempPosition = new Vector3(); - // from http://www.geometrictools.com/LibMathematics/Intersection/Wm5IntrRay3Triangle3.cpp + var invAspect = viewport.w / viewport.z, + halfViewportWidth = viewport.z * 0.5, + halfViewportHeight = viewport.w * 0.5; - edge1.subVectors( b, a ); - edge2.subVectors( c, a ); - normal.crossVectors( edge1, edge2 ); + var size = 16 / viewport.w, + scale = new Vector2( size * invAspect, size ); - // 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 screenPosition = new Vector3( 1, 1, 0 ), + screenPositionPixels = new Vector2( 1, 1 ); - if ( DdN > 0 ) { + var validArea = new Box2(); - if ( backfaceCulling ) return null; - sign = 1; + validArea.min.set( 0, 0 ); + validArea.max.set( viewport.z - 16, viewport.w - 16 ); - } else if ( DdN < 0 ) { + if ( program === undefined ) { - sign = - 1; - DdN = - DdN; + init(); - } else { + } - return null; + gl.useProgram( program ); - } + state.initAttributes(); + state.enableAttribute( attributes.vertex ); + state.enableAttribute( attributes.uv ); + state.disableUnusedAttributes(); - diff.subVectors( this.origin, a ); - var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) ); + // loop through all lens flares to update their occlusion and positions + // setup gl and common used attribs/uniforms - // b1 < 0, no intersection - if ( DdQxE2 < 0 ) { + gl.uniform1i( uniforms.occlusionMap, 0 ); + gl.uniform1i( uniforms.map, 1 ); - return null; + 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 ); - var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) ); + state.disable( gl.CULL_FACE ); + state.setDepthWrite( false ); - // b2 < 0, no intersection - if ( DdE1xQ < 0 ) { + for ( var i = 0, l = flares.length; i < l; i ++ ) { - return null; + size = 16 / viewport.w; + scale.set( size * invAspect, size ); - } + // calc object screen position - // b1+b2 > 1, no intersection - if ( DdQxE2 + DdE1xQ > DdN ) { + var flare = flares[ i ]; - return null; + tempPosition.set( flare.matrixWorld.elements[ 12 ], flare.matrixWorld.elements[ 13 ], flare.matrixWorld.elements[ 14 ] ); - } + tempPosition.applyMatrix4( camera.matrixWorldInverse ); + tempPosition.applyProjection( camera.projectionMatrix ); - // Line intersects triangle, check if ray does. - var QdN = - sign * diff.dot( normal ); + // setup arrays for gl programs - // t < 0, no intersection - if ( QdN < 0 ) { + screenPosition.copy( tempPosition ); - return null; + // horizontal and vertical coordinate of the lower left corner of the pixels to copy - } + screenPositionPixels.x = viewport.x + ( screenPosition.x * halfViewportWidth ) + halfViewportWidth - 8; + screenPositionPixels.y = viewport.y + ( screenPosition.y * halfViewportHeight ) + halfViewportHeight - 8; - // Ray intersects triangle. - return this.at( QdN / DdN, optionalTarget ); + // screen cull - }; + if ( validArea.containsPoint( screenPositionPixels ) === true ) { - }(), + // save current RGB to temp texture - applyMatrix4: function ( matrix4 ) { + 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 ); - this.direction.add( this.origin ).applyMatrix4( matrix4 ); - this.origin.applyMatrix4( matrix4 ); - this.direction.sub( this.origin ); - this.direction.normalize(); - return this; + // render pink quad - }, + gl.uniform1i( uniforms.renderType, 0 ); + gl.uniform2f( uniforms.scale, scale.x, scale.y ); + gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z ); - equals: function ( ray ) { + state.disable( gl.BLEND ); + state.enable( gl.DEPTH_TEST ); - return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction ); + gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); - } -}; + // copy result to occlusionMap -// File:src/math/Sphere.js + 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 ); -/** - * @author bhouston / http://exocortex.com - * @author mrdoob / http://mrdoob.com/ - */ -THREE.Sphere = function ( center, radius ) { + // restore graphics - this.center = ( center !== undefined ) ? center : new THREE.Vector3(); - this.radius = ( radius !== undefined ) ? radius : 0; + 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 ); -THREE.Sphere.prototype = { - constructor: THREE.Sphere, + // update object positions - set: function ( center, radius ) { + flare.positionScreen.copy( screenPosition ); - this.center.copy( center ); - this.radius = radius; + if ( flare.customUpdateCallback ) { - return this; + flare.customUpdateCallback( flare ); - }, + } else { - setFromPoints: function () { + flare.updateLensFlares(); - var box = new THREE.Box3(); + } - return function ( points, optionalCenter ) { + // render flares - var center = this.center; + gl.uniform1i( uniforms.renderType, 2 ); + state.enable( gl.BLEND ); - if ( optionalCenter !== undefined ) { + for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) { - center.copy( optionalCenter ); + var sprite = flare.lensFlares[ j ]; - } else { + if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) { - box.setFromPoints( points ).center( center ); + screenPosition.x = sprite.x; + screenPosition.y = sprite.y; + screenPosition.z = sprite.z; - } + size = sprite.size * sprite.scale / viewport.w; - var maxRadiusSq = 0; + scale.x = size * invAspect; + scale.y = size; - for ( var i = 0, il = points.length; i < il; i ++ ) { + gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z ); + gl.uniform2f( uniforms.scale, scale.x, scale.y ); + gl.uniform1f( uniforms.rotation, sprite.rotation ); - maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) ); + 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 ); - this.radius = Math.sqrt( maxRadiusSq ); + gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); - return this; + } - }; + } - }(), + } - clone: function () { + } - return new this.constructor().copy( this ); + // restore gl - }, + state.enable( gl.CULL_FACE ); + state.enable( gl.DEPTH_TEST ); + state.setDepthWrite( true ); - copy: function ( sphere ) { + renderer.resetGLState(); - this.center.copy( sphere.center ); - this.radius = sphere.radius; + }; - return this; + function createProgram( shader ) { - }, + var program = gl.createProgram(); - empty: function () { + var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER ); + var vertexShader = gl.createShader( gl.VERTEX_SHADER ); - return ( this.radius <= 0 ); + var prefix = "precision " + renderer.getPrecision() + " float;\n"; - }, + gl.shaderSource( fragmentShader, prefix + shader.fragmentShader ); + gl.shaderSource( vertexShader, prefix + shader.vertexShader ); - containsPoint: function ( point ) { + gl.compileShader( fragmentShader ); + gl.compileShader( vertexShader ); - return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) ); + gl.attachShader( program, fragmentShader ); + gl.attachShader( program, vertexShader ); - }, + gl.linkProgram( program ); - distanceToPoint: function ( point ) { + return program; - return ( point.distanceTo( this.center ) - this.radius ); + } - }, + } - intersectsSphere: function ( sphere ) { + /** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + */ - var radiusSum = this.radius + sphere.radius; + function SpritePlugin( renderer, sprites ) { - return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum ); + var gl = renderer.context; + var state = renderer.state; - }, + var vertexBuffer, elementBuffer; + var program, attributes, uniforms; - clampPoint: function ( point, optionalTarget ) { + var texture; - var deltaLengthSq = this.center.distanceToSquared( point ); + // decompose matrixWorld - var result = optionalTarget || new THREE.Vector3(); - result.copy( point ); + var spritePosition = new Vector3(); + var spriteRotation = new Quaternion(); + var spriteScale = new Vector3(); - if ( deltaLengthSq > ( this.radius * this.radius ) ) { + function init() { - result.sub( this.center ).normalize(); - result.multiplyScalar( this.radius ).add( this.center ); + 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 + ] ); - return result; + vertexBuffer = gl.createBuffer(); + elementBuffer = gl.createBuffer(); - }, + gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer ); + gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW ); - getBoundingBox: function ( optionalTarget ) { + gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); + gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW ); - var box = optionalTarget || new THREE.Box3(); + program = createProgram(); - box.set( this.center, this.center ); - box.expandByScalar( this.radius ); + attributes = { + position: gl.getAttribLocation ( program, 'position' ), + uv: gl.getAttribLocation ( program, 'uv' ) + }; - return box; + uniforms = { + uvOffset: gl.getUniformLocation( program, 'uvOffset' ), + uvScale: gl.getUniformLocation( program, 'uvScale' ), - }, + rotation: gl.getUniformLocation( program, 'rotation' ), + scale: gl.getUniformLocation( program, 'scale' ), - applyMatrix4: function ( matrix ) { + color: gl.getUniformLocation( program, 'color' ), + map: gl.getUniformLocation( program, 'map' ), + opacity: gl.getUniformLocation( program, 'opacity' ), - this.center.applyMatrix4( matrix ); - this.radius = this.radius * matrix.getMaxScaleOnAxis(); + modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ), + projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ), - return this; + fogType: gl.getUniformLocation( program, 'fogType' ), + fogDensity: gl.getUniformLocation( program, 'fogDensity' ), + fogNear: gl.getUniformLocation( program, 'fogNear' ), + fogFar: gl.getUniformLocation( program, 'fogFar' ), + fogColor: gl.getUniformLocation( program, 'fogColor' ), - }, + alphaTest: gl.getUniformLocation( program, 'alphaTest' ) + }; - translate: function ( offset ) { + var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); + canvas.width = 8; + canvas.height = 8; - this.center.add( offset ); + var context = canvas.getContext( '2d' ); + context.fillStyle = 'white'; + context.fillRect( 0, 0, 8, 8 ); - return this; + texture = new Texture( canvas ); + texture.needsUpdate = true; - }, + } - equals: function ( sphere ) { + this.render = function ( scene, camera ) { - return sphere.center.equals( this.center ) && ( sphere.radius === this.radius ); + if ( sprites.length === 0 ) return; - } + // setup gl -}; + if ( program === undefined ) { -// File:src/math/Frustum.js + init(); -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * @author bhouston / http://exocortex.com - */ + } -THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) { + gl.useProgram( program ); - this.planes = [ + state.initAttributes(); + state.enableAttribute( attributes.position ); + state.enableAttribute( attributes.uv ); + state.disableUnusedAttributes(); - ( p0 !== undefined ) ? p0 : new THREE.Plane(), - ( p1 !== undefined ) ? p1 : new THREE.Plane(), - ( p2 !== undefined ) ? p2 : new THREE.Plane(), - ( p3 !== undefined ) ? p3 : new THREE.Plane(), - ( p4 !== undefined ) ? p4 : new THREE.Plane(), - ( p5 !== undefined ) ? p5 : new THREE.Plane() + state.disable( gl.CULL_FACE ); + state.enable( gl.BLEND ); - ]; + gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer ); + gl.vertexAttribPointer( attributes.position, 2, gl.FLOAT, false, 2 * 8, 0 ); + gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 ); -}; + gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); -THREE.Frustum.prototype = { + gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements ); - constructor: THREE.Frustum, + state.activeTexture( gl.TEXTURE0 ); + gl.uniform1i( uniforms.map, 0 ); - set: function ( p0, p1, p2, p3, p4, p5 ) { + var oldFogType = 0; + var sceneFogType = 0; + var fog = scene.fog; - var planes = this.planes; + if ( fog ) { - planes[ 0 ].copy( p0 ); - planes[ 1 ].copy( p1 ); - planes[ 2 ].copy( p2 ); - planes[ 3 ].copy( p3 ); - planes[ 4 ].copy( p4 ); - planes[ 5 ].copy( p5 ); + gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b ); - return this; + 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 ( frustum ) { + gl.uniform1i( uniforms.fogType, 2 ); + oldFogType = 2; + sceneFogType = 2; - var planes = this.planes; + } - for ( var i = 0; i < 6; i ++ ) { + } else { - planes[ i ].copy( frustum.planes[ i ] ); + gl.uniform1i( uniforms.fogType, 0 ); + oldFogType = 0; + sceneFogType = 0; - } + } - return this; - }, + // update positions and sort - setFromMatrix: function ( m ) { + for ( var i = 0, l = sprites.length; i < l; i ++ ) { - 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 ]; + var sprite = sprites[ i ]; - 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(); + sprite.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld ); + sprite.z = - sprite.modelViewMatrix.elements[ 14 ]; - return this; + } - }, + sprites.sort( painterSortStable ); - intersectsObject: function () { + // render all sprites - var sphere = new THREE.Sphere(); + var scale = []; - return function ( object ) { + for ( var i = 0, l = sprites.length; i < l; i ++ ) { - var geometry = object.geometry; + var sprite = sprites[ i ]; + var material = sprite.material; - if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + if ( material.visible === false ) continue; - sphere.copy( geometry.boundingSphere ); - sphere.applyMatrix4( object.matrixWorld ); + gl.uniform1f( uniforms.alphaTest, material.alphaTest ); + gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite.modelViewMatrix.elements ); - return this.intersectsSphere( sphere ); + sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale ); - }; + scale[ 0 ] = spriteScale.x; + scale[ 1 ] = spriteScale.y; - }(), + var fogType = 0; - intersectsSphere: function ( sphere ) { + if ( scene.fog && material.fog ) { - var planes = this.planes; - var center = sphere.center; - var negRadius = - sphere.radius; + fogType = sceneFogType; - for ( var i = 0; i < 6; i ++ ) { + } - var distance = planes[ i ].distanceToPoint( center ); + if ( oldFogType !== fogType ) { - if ( distance < negRadius ) { + gl.uniform1i( uniforms.fogType, fogType ); + oldFogType = fogType; - return false; + } - } + if ( material.map !== null ) { - } + 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 true; + } else { - }, + gl.uniform2f( uniforms.uvOffset, 0, 0 ); + gl.uniform2f( uniforms.uvScale, 1, 1 ); - intersectsBox: function () { + } - var p1 = new THREE.Vector3(), - p2 = new THREE.Vector3(); + gl.uniform1f( uniforms.opacity, material.opacity ); + gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b ); - return function ( box ) { + gl.uniform1f( uniforms.rotation, material.rotation ); + gl.uniform2fv( uniforms.scale, scale ); - var planes = this.planes; + state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst ); + state.setDepthTest( material.depthTest ); + state.setDepthWrite( material.depthWrite ); - for ( var i = 0; i < 6 ; i ++ ) { + if ( material.map ) { - var plane = planes[ i ]; + renderer.setTexture2D( material.map, 0 ); - 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; + } else { - var d1 = plane.distanceToPoint( p1 ); - var d2 = plane.distanceToPoint( p2 ); + renderer.setTexture2D( texture, 0 ); - // if both outside plane, no intersection + } - if ( d1 < 0 && d2 < 0 ) { + gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); - return false; + } - } + // restore gl - } + state.enable( gl.CULL_FACE ); - return true; + renderer.resetGLState(); - }; + }; - }(), + function createProgram() { + var program = gl.createProgram(); - containsPoint: function ( point ) { + var vertexShader = gl.createShader( gl.VERTEX_SHADER ); + var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER ); - var planes = this.planes; + gl.shaderSource( vertexShader, [ - for ( var i = 0; i < 6; i ++ ) { + 'precision ' + renderer.getPrecision() + ' float;', - if ( planes[ i ].distanceToPoint( point ) < 0 ) { + 'uniform mat4 modelViewMatrix;', + 'uniform mat4 projectionMatrix;', + 'uniform float rotation;', + 'uniform vec2 scale;', + 'uniform vec2 uvOffset;', + 'uniform vec2 uvScale;', - return false; + 'attribute vec2 position;', + 'attribute vec2 uv;', - } + 'varying vec2 vUV;', - } + 'void main() {', - return true; + 'vUV = uvOffset + uv * uvScale;', - } + 'vec2 alignedPosition = position * scale;', -}; + 'vec2 rotatedPosition;', + 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;', + 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;', -// File:src/math/Plane.js + 'vec4 finalPosition;', -/** - * @author bhouston / http://exocortex.com - */ + 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );', + 'finalPosition.xy += rotatedPosition;', + 'finalPosition = projectionMatrix * finalPosition;', -THREE.Plane = function ( normal, constant ) { + 'gl_Position = finalPosition;', - this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 ); - this.constant = ( constant !== undefined ) ? constant : 0; + '}' -}; + ].join( '\n' ) ); -THREE.Plane.prototype = { + gl.shaderSource( fragmentShader, [ - constructor: THREE.Plane, + 'precision ' + renderer.getPrecision() + ' float;', - set: function ( normal, constant ) { + 'uniform vec3 color;', + 'uniform sampler2D map;', + 'uniform float opacity;', - this.normal.copy( normal ); - this.constant = constant; + 'uniform int fogType;', + 'uniform vec3 fogColor;', + 'uniform float fogDensity;', + 'uniform float fogNear;', + 'uniform float fogFar;', + 'uniform float alphaTest;', - return this; + 'varying vec2 vUV;', - }, + 'void main() {', - setComponents: function ( x, y, z, w ) { + 'vec4 texture = texture2D( map, vUV );', - this.normal.set( x, y, z ); - this.constant = w; + 'if ( texture.a < alphaTest ) discard;', - return this; + 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );', - }, + 'if ( fogType > 0 ) {', - setFromNormalAndCoplanarPoint: function ( normal, point ) { + 'float depth = gl_FragCoord.z / gl_FragCoord.w;', + 'float fogFactor = 0.0;', - this.normal.copy( normal ); - this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized + 'if ( fogType == 1 ) {', - return this; + 'fogFactor = smoothstep( fogNear, fogFar, depth );', - }, + '} else {', - setFromCoplanarPoints: function () { + 'const float LOG2 = 1.442695;', + 'fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );', + 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );', - var v1 = new THREE.Vector3(); - var v2 = new THREE.Vector3(); + '}', - return function ( a, b, c ) { + 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );', - 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)? + '}' - this.setFromNormalAndCoplanarPoint( normal, a ); + ].join( '\n' ) ); - return this; + gl.compileShader( vertexShader ); + gl.compileShader( fragmentShader ); - }; + gl.attachShader( program, vertexShader ); + gl.attachShader( program, fragmentShader ); - }(), + gl.linkProgram( program ); - clone: function () { + return program; - return new this.constructor().copy( this ); + } - }, + function painterSortStable( a, b ) { - copy: function ( plane ) { + if ( a.renderOrder !== b.renderOrder ) { - this.normal.copy( plane.normal ); - this.constant = plane.constant; + return a.renderOrder - b.renderOrder; - return this; + } else if ( a.z !== b.z ) { - }, + return b.z - a.z; - normalize: function () { + } else { - // Note: will lead to a divide by zero if the plane is invalid. + return b.id - a.id; - var inverseNormalLength = 1.0 / this.normal.length(); - this.normal.multiplyScalar( inverseNormalLength ); - this.constant *= inverseNormalLength; + } - return this; + } - }, + } - negate: function () { + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - this.constant *= - 1; - this.normal.negate(); + function Material() { - return this; + Object.defineProperty( this, 'id', { value: MaterialIdCount() } ); - }, + this.uuid = exports.Math.generateUUID(); - distanceToPoint: function ( point ) { + this.name = ''; + this.type = 'Material'; - return this.normal.dot( point ) + this.constant; + this.fog = true; + this.lights = true; - }, + this.blending = NormalBlending; + this.side = FrontSide; + this.shading = SmoothShading; // THREE.FlatShading, THREE.SmoothShading + this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors - distanceToSphere: function ( sphere ) { + this.opacity = 1; + this.transparent = false; - return this.distanceToPoint( sphere.center ) - sphere.radius; + this.blendSrc = SrcAlphaFactor; + this.blendDst = OneMinusSrcAlphaFactor; + this.blendEquation = AddEquation; + this.blendSrcAlpha = null; + this.blendDstAlpha = null; + this.blendEquationAlpha = null; - }, + this.depthFunc = LessEqualDepth; + this.depthTest = true; + this.depthWrite = true; - projectPoint: function ( point, optionalTarget ) { + this.clippingPlanes = null; + this.clipShadows = false; - return this.orthoPoint( point, optionalTarget ).sub( point ).negate(); + this.colorWrite = true; - }, + this.precision = null; // override the renderer's default precision for this material - orthoPoint: function ( point, optionalTarget ) { + this.polygonOffset = false; + this.polygonOffsetFactor = 0; + this.polygonOffsetUnits = 0; - var perpendicularMagnitude = this.distanceToPoint( point ); + this.alphaTest = 0; + this.premultipliedAlpha = false; - var result = optionalTarget || new THREE.Vector3(); - return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude ); + this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer - }, + this.visible = true; - isIntersectionLine: function ( line ) { + this._needsUpdate = true; - // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it. + } - var startSign = this.distanceToPoint( line.start ); - var endSign = this.distanceToPoint( line.end ); + Material.prototype = { - return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 ); + constructor: Material, - }, + isMaterial: true, - intersectLine: function () { + get needsUpdate() { - var v1 = new THREE.Vector3(); + return this._needsUpdate; - return function ( line, optionalTarget ) { + }, - var result = optionalTarget || new THREE.Vector3(); + set needsUpdate( value ) { - var direction = line.delta( v1 ); + if ( value === true ) this.update(); + this._needsUpdate = value; - var denominator = this.normal.dot( direction ); + }, - if ( denominator === 0 ) { + setValues: function ( values ) { - // line is coplanar, return origin - if ( this.distanceToPoint( line.start ) === 0 ) { + if ( values === undefined ) return; - return result.copy( line.start ); + for ( var key in values ) { - } + var newValue = values[ key ]; - // Unsure if this is the correct method to handle this case. - return undefined; + if ( newValue === undefined ) { - } + console.warn( "THREE.Material: '" + key + "' parameter is undefined." ); + continue; - var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator; + } - if ( t < 0 || t > 1 ) { + var currentValue = this[ key ]; - return undefined; + if ( currentValue === undefined ) { - } + console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." ); + continue; - return result.copy( direction ).multiplyScalar( t ).add( line.start ); + } - }; + if ( (currentValue && currentValue.isColor) ) { - }(), + currentValue.set( newValue ); + } else if ( (currentValue && currentValue.isVector3) && (newValue && newValue.isVector3) ) { - coplanarPoint: function ( optionalTarget ) { + currentValue.copy( newValue ); - var result = optionalTarget || new THREE.Vector3(); - return result.copy( this.normal ).multiplyScalar( - this.constant ); + } else if ( key === 'overdraw' ) { - }, + // ensure overdraw is backwards-compatible with legacy boolean type + this[ key ] = Number( newValue ); - applyMatrix4: function () { + } else { - var v1 = new THREE.Vector3(); - var v2 = new THREE.Vector3(); - var m1 = new THREE.Matrix3(); + this[ key ] = newValue; - return function ( matrix, optionalNormalMatrix ) { + } - // compute new normal based on theory here: - // http://www.songho.ca/opengl/gl_normaltransform.html - var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix ); - var newNormal = v1.copy( this.normal ).applyMatrix3( normalMatrix ); + } - var newCoplanarPoint = this.coplanarPoint( v2 ); - newCoplanarPoint.applyMatrix4( matrix ); + }, - this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint ); + toJSON: function ( meta ) { - return this; + var isRoot = meta === undefined; - }; + if ( isRoot ) { - }(), + meta = { + textures: {}, + images: {} + }; - translate: function ( offset ) { + } - this.constant = this.constant - offset.dot( this.normal ); + var data = { + metadata: { + version: 4.4, + type: 'Material', + generator: 'Material.toJSON' + } + }; - return this; + // standard Material serialization + data.uuid = this.uuid; + data.type = this.type; - }, + if ( this.name !== '' ) data.name = this.name; - equals: function ( plane ) { + if ( (this.color && this.color.isColor) ) data.color = this.color.getHex(); - return plane.normal.equals( this.normal ) && ( plane.constant === this.constant ); + 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; -}; + 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) ) { -// File:src/math/Math.js + data.bumpMap = this.bumpMap.toJSON( meta ).uuid; + data.bumpScale = this.bumpScale; -/** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - */ + } + if ( (this.normalMap && this.normalMap.isTexture) ) { -THREE.Math = { + data.normalMap = this.normalMap.toJSON( meta ).uuid; + data.normalScale = this.normalScale.toArray(); - generateUUID: function () { + } + if ( (this.displacementMap && this.displacementMap.isTexture) ) { - // http://www.broofa.com/Tools/Math.uuid.htm + data.displacementMap = this.displacementMap.toJSON( meta ).uuid; + data.displacementScale = this.displacementScale; + data.displacementBias = this.displacementBias; - var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' ); - var uuid = new Array( 36 ); - var rnd = 0, r; + } + if ( (this.roughnessMap && this.roughnessMap.isTexture) ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid; + if ( (this.metalnessMap && this.metalnessMap.isTexture) ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid; - return function () { + 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; - for ( var i = 0; i < 36; i ++ ) { + if ( (this.envMap && this.envMap.isTexture) ) { - if ( i === 8 || i === 13 || i === 18 || i === 23 ) { + data.envMap = this.envMap.toJSON( meta ).uuid; + data.reflectivity = this.reflectivity; // Scale behind envMap - uuid[ i ] = '-'; + } - } else if ( i === 14 ) { + if ( this.size !== undefined ) data.size = this.size; + if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation; - uuid[ i ] = '4'; + 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; - } else { + if ( this.opacity < 1 ) data.opacity = this.opacity; + if ( this.transparent === true ) data.transparent = this.transparent; - if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0; - r = rnd & 0xf; - rnd = rnd >> 4; - uuid[ i ] = chars[ ( i === 19 ) ? ( r & 0x3 ) | 0x8 : r ]; + data.depthFunc = this.depthFunc; + data.depthTest = this.depthTest; + data.depthWrite = this.depthWrite; - } + if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest; + if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha; + if ( this.wireframe === true ) data.wireframe = this.wireframe; + if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth; + if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap; + if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin; - } + data.skinning = this.skinning; + data.morphTargets = this.morphTargets; - return uuid.join( '' ); + // TODO: Copied from Object3D.toJSON - }; + function extractFromCache( cache ) { - }(), + var values = []; - // Clamp value to range + for ( var key in cache ) { - clamp: function ( x, a, b ) { + var data = cache[ key ]; + delete data.metadata; + values.push( data ); - return ( x < a ) ? a : ( ( x > b ) ? b : x ); + } - }, + return values; - // Clamp value to range 0 ) data.textures = textures; + if ( images.length > 0 ) data.images = images; - // compute euclidian modulo of m % n - // https://en.wikipedia.org/wiki/Modulo_operation + } - euclideanModulo: function ( n, m ) { + return data; - return ( ( n % m ) + m ) % m; + }, - }, + clone: function () { - // Linear mapping from range to range + return new this.constructor().copy( this ); - mapLinear: function ( x, a1, a2, b1, b2 ) { + }, - return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 ); + copy: function ( source ) { - }, + this.name = source.name; - // http://en.wikipedia.org/wiki/Smoothstep + this.fog = source.fog; + this.lights = source.lights; - smoothstep: function ( x, min, max ) { + this.blending = source.blending; + this.side = source.side; + this.shading = source.shading; + this.vertexColors = source.vertexColors; - if ( x <= min ) return 0; - if ( x >= max ) return 1; + this.opacity = source.opacity; + this.transparent = source.transparent; - x = ( x - min ) / ( max - min ); + this.blendSrc = source.blendSrc; + this.blendDst = source.blendDst; + this.blendEquation = source.blendEquation; + this.blendSrcAlpha = source.blendSrcAlpha; + this.blendDstAlpha = source.blendDstAlpha; + this.blendEquationAlpha = source.blendEquationAlpha; - return x * x * ( 3 - 2 * x ); + this.depthFunc = source.depthFunc; + this.depthTest = source.depthTest; + this.depthWrite = source.depthWrite; - }, + this.colorWrite = source.colorWrite; - smootherstep: function ( x, min, max ) { + this.precision = source.precision; - if ( x <= min ) return 0; - if ( x >= max ) return 1; + this.polygonOffset = source.polygonOffset; + this.polygonOffsetFactor = source.polygonOffsetFactor; + this.polygonOffsetUnits = source.polygonOffsetUnits; - x = ( x - min ) / ( max - min ); + this.alphaTest = source.alphaTest; - return x * x * x * ( x * ( x * 6 - 15 ) + 10 ); + this.premultipliedAlpha = source.premultipliedAlpha; - }, + this.overdraw = source.overdraw; - // Random float from <0, 1> with 16 bits of randomness - // (standard Math.random() creates repetitive patterns when applied over larger space) + this.visible = source.visible; + this.clipShadows = source.clipShadows; - random16: function () { + var srcPlanes = source.clippingPlanes, + dstPlanes = null; - return ( 65280 * Math.random() + 255 * Math.random() ) / 65535; + if ( srcPlanes !== null ) { - }, + var n = srcPlanes.length; + dstPlanes = new Array( n ); - // Random integer from interval + for ( var i = 0; i !== n; ++ i ) + dstPlanes[ i ] = srcPlanes[ i ].clone(); - randInt: function ( low, high ) { + } - return low + Math.floor( Math.random() * ( high - low + 1 ) ); + this.clippingPlanes = dstPlanes; - }, + return this; - // Random float from interval + }, - randFloat: function ( low, high ) { + update: function () { - return low + Math.random() * ( high - low ); + this.dispatchEvent( { type: 'update' } ); - }, + }, - // Random float from <-range/2, range/2> interval + dispose: function () { - randFloatSpread: function ( range ) { + this.dispatchEvent( { type: 'dispose' } ); - return range * ( 0.5 - Math.random() ); + } - }, + }; - degToRad: function () { + Object.assign( Material.prototype, EventDispatcher.prototype ); - var degreeToRadiansFactor = Math.PI / 180; + var count$1 = 0; + function MaterialIdCount() { return count$1++; }; - return function ( degrees ) { + /** + * @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: + * } + */ - return degrees * degreeToRadiansFactor; + function ShaderMaterial( parameters ) { - }; + Material.call( this ); - }(), + this.type = 'ShaderMaterial'; - radToDeg: function () { + this.defines = {}; + this.uniforms = {}; - var radianToDegreesFactor = 180 / Math.PI; + 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}'; - return function ( radians ) { + this.linewidth = 1; - return radians * radianToDegreesFactor; + this.wireframe = false; + this.wireframeLinewidth = 1; - }; + 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 - }(), + 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 - isPowerOfTwo: function ( value ) { + 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 + }; - return ( value & ( value - 1 ) ) === 0 && value !== 0; + // 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 ] + }; - }, + this.index0AttributeName = undefined; - nextPowerOfTwo: function ( value ) { + if ( parameters !== undefined ) { - value --; - value |= value >> 1; - value |= value >> 2; - value |= value >> 4; - value |= value >> 8; - value |= value >> 16; - value ++; + if ( parameters.attributes !== undefined ) { - return value; + console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' ); - } + } -}; + this.setValues( parameters ); -// File:src/math/Spline.js + } -/** - * 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/ - */ + } -THREE.Spline = function ( points ) { + ShaderMaterial.prototype = Object.create( Material.prototype ); + ShaderMaterial.prototype.constructor = ShaderMaterial; - this.points = points; + ShaderMaterial.prototype.isShaderMaterial = true; - var c = [], v3 = { x: 0, y: 0, z: 0 }, - point, intPoint, weight, w2, w3, - pa, pb, pc, pd; + ShaderMaterial.prototype.copy = function ( source ) { - this.initFromArray = function ( a ) { + Material.prototype.copy.call( this, source ); - this.points = []; + this.fragmentShader = source.fragmentShader; + this.vertexShader = source.vertexShader; - for ( var i = 0; i < a.length; i ++ ) { + this.uniforms = exports.UniformsUtils.clone( source.uniforms ); - this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] }; + this.defines = source.defines; - } + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; - }; + this.lights = source.lights; + this.clipping = source.clipping; - this.getPoint = function ( k ) { + this.skinning = source.skinning; - point = ( this.points.length - 1 ) * k; - intPoint = Math.floor( point ); - weight = point - intPoint; + this.morphTargets = source.morphTargets; + this.morphNormals = source.morphNormals; - 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; + this.extensions = source.extensions; - pa = this.points[ c[ 0 ] ]; - pb = this.points[ c[ 1 ] ]; - pc = this.points[ c[ 2 ] ]; - pd = this.points[ c[ 3 ] ]; + return this; - 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 ); + ShaderMaterial.prototype.toJSON = function ( meta ) { - return v3; + var data = Material.prototype.toJSON.call( this, meta ); - }; + data.uniforms = this.uniforms; + data.vertexShader = this.vertexShader; + data.fragmentShader = this.fragmentShader; - this.getControlPointsArray = function () { + return data; - var i, p, l = this.points.length, - coords = []; + }; - for ( i = 0; i < l; i ++ ) { + /** + * @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: + * } + */ - p = this.points[ i ]; - coords[ i ] = [ p.x, p.y, p.z ]; + function MeshDepthMaterial( parameters ) { - } + Material.call( this ); - return coords; + this.type = 'MeshDepthMaterial'; - }; + this.depthPacking = BasicDepthPacking; - // approximate length by summing linear segments + this.skinning = false; + this.morphTargets = false; - this.getLength = function ( nSubDivisions ) { + this.map = null; - var i, index, nSamples, position, - point = 0, intPoint = 0, oldIntPoint = 0, - oldPosition = new THREE.Vector3(), - tmpVec = new THREE.Vector3(), - chunkLengths = [], - totalLength = 0; + this.alphaMap = null; - // first point has 0 length + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; - chunkLengths[ 0 ] = 0; + this.wireframe = false; + this.wireframeLinewidth = 1; - if ( ! nSubDivisions ) nSubDivisions = 100; + this.fog = false; + this.lights = false; - nSamples = this.points.length * nSubDivisions; + this.setValues( parameters ); - oldPosition.copy( this.points[ 0 ] ); + } - for ( i = 1; i < nSamples; i ++ ) { + MeshDepthMaterial.prototype = Object.create( Material.prototype ); + MeshDepthMaterial.prototype.constructor = MeshDepthMaterial; - index = i / nSamples; + MeshDepthMaterial.prototype.isMeshDepthMaterial = true; - position = this.getPoint( index ); - tmpVec.copy( position ); + MeshDepthMaterial.prototype.copy = function ( source ) { - totalLength += tmpVec.distanceTo( oldPosition ); + Material.prototype.copy.call( this, source ); - oldPosition.copy( position ); + this.depthPacking = source.depthPacking; - point = ( this.points.length - 1 ) * index; - intPoint = Math.floor( point ); + this.skinning = source.skinning; + this.morphTargets = source.morphTargets; - if ( intPoint !== oldIntPoint ) { + this.map = source.map; - chunkLengths[ intPoint ] = totalLength; - oldIntPoint = intPoint; + this.alphaMap = source.alphaMap; - } + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; - } + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; - // last point ends with total length + return this; - chunkLengths[ chunkLengths.length ] = totalLength; + }; - return { chunks: chunkLengths, total: totalLength }; + /** + * @author bhouston / http://clara.io + * @author WestLangley / http://github.com/WestLangley + */ - }; + function Box3( min, max ) { - this.reparametrizeByArcLength = function ( samplingCoef ) { + this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity ); + this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity ); - var i, j, - index, indexCurrent, indexNext, - realDistance, - sampling, position, - newpoints = [], - tmpVec = new THREE.Vector3(), - sl = this.getLength(); + } - newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() ); + Box3.prototype = { - for ( i = 1; i < this.points.length; i ++ ) { + constructor: Box3, - //tmpVec.copy( this.points[ i - 1 ] ); - //linearDistance = tmpVec.distanceTo( this.points[ i ] ); + isBox3: true, - realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ]; + set: function ( min, max ) { - sampling = Math.ceil( samplingCoef * realDistance / sl.total ); + this.min.copy( min ); + this.max.copy( max ); - indexCurrent = ( i - 1 ) / ( this.points.length - 1 ); - indexNext = i / ( this.points.length - 1 ); + return this; - for ( j = 1; j < sampling - 1; j ++ ) { + }, - index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent ); + setFromArray: function ( array ) { - position = this.getPoint( index ); - newpoints.push( tmpVec.copy( position ).clone() ); + var minX = + Infinity; + var minY = + Infinity; + var minZ = + Infinity; - } + var maxX = - Infinity; + var maxY = - Infinity; + var maxZ = - Infinity; - newpoints.push( tmpVec.copy( this.points[ i ] ).clone() ); + 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 ]; - this.points = newpoints; + if ( x < minX ) minX = x; + if ( y < minY ) minY = y; + if ( z < minZ ) minZ = z; - }; + if ( x > maxX ) maxX = x; + if ( y > maxY ) maxY = y; + if ( z > maxZ ) maxZ = z; - // Catmull-Rom + } - function interpolate( p0, p1, p2, p3, t, t2, t3 ) { + this.min.set( minX, minY, minZ ); + this.max.set( maxX, maxY, maxZ ); - 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; + setFromPoints: function ( points ) { - } + this.makeEmpty(); -}; + for ( var i = 0, il = points.length; i < il; i ++ ) { -// File:src/math/Triangle.js + this.expandByPoint( points[ i ] ); -/** - * @author bhouston / http://exocortex.com - * @author mrdoob / http://mrdoob.com/ - */ + } -THREE.Triangle = function ( a, b, c ) { + return this; - this.a = ( a !== undefined ) ? a : new THREE.Vector3(); - this.b = ( b !== undefined ) ? b : new THREE.Vector3(); - this.c = ( c !== undefined ) ? c : new THREE.Vector3(); + }, -}; + setFromCenterAndSize: function () { -THREE.Triangle.normal = function () { + var v1 = new Vector3(); - var v0 = new THREE.Vector3(); + return function setFromCenterAndSize( center, size ) { - return function ( a, b, c, optionalTarget ) { + var halfSize = v1.copy( size ).multiplyScalar( 0.5 ); - var result = optionalTarget || new THREE.Vector3(); + this.min.copy( center ).sub( halfSize ); + this.max.copy( center ).add( halfSize ); - result.subVectors( c, b ); - v0.subVectors( a, b ); - result.cross( v0 ); + return this; - var resultLengthSq = result.lengthSq(); - if ( resultLengthSq > 0 ) { + }; - return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) ); + }(), - } + setFromObject: function () { - return result.set( 0, 0, 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 - }; + var v1 = new Vector3(); -}(); + return function setFromObject( object ) { -// static/instance method to calculate barycentric coordinates -// based on: http://www.blackpawn.com/texts/pointinpoly/default.html -THREE.Triangle.barycoordFromPoint = function () { + var scope = this; - var v0 = new THREE.Vector3(); - var v1 = new THREE.Vector3(); - var v2 = new THREE.Vector3(); + object.updateMatrixWorld( true ); - return function ( point, a, b, c, optionalTarget ) { + this.makeEmpty(); - v0.subVectors( c, a ); - v1.subVectors( b, a ); - v2.subVectors( point, a ); + object.traverse( function ( node ) { - var dot00 = v0.dot( v0 ); - var dot01 = v0.dot( v1 ); - var dot02 = v0.dot( v2 ); - var dot11 = v1.dot( v1 ); - var dot12 = v1.dot( v2 ); + var geometry = node.geometry; - var denom = ( dot00 * dot11 - dot01 * dot01 ); + if ( geometry !== undefined ) { - var result = optionalTarget || new THREE.Vector3(); + if ( (geometry && geometry.isGeometry) ) { - // collinear or singular triangle - if ( denom === 0 ) { + var vertices = geometry.vertices; - // arbitrary location outside of triangle? - // not sure if this is the best idea, maybe should be returning undefined - return result.set( - 2, - 1, - 1 ); + for ( var i = 0, il = vertices.length; i < il; i ++ ) { - } + v1.copy( vertices[ i ] ); + v1.applyMatrix4( node.matrixWorld ); - var invDenom = 1 / denom; - var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom; - var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom; + scope.expandByPoint( v1 ); - // barycentric coordinates must always sum to 1 - return result.set( 1 - u - v, v, u ); + } - }; + } else if ( (geometry && geometry.isBufferGeometry) ) { -}(); + var attribute = geometry.attributes.position; -THREE.Triangle.containsPoint = function () { + if ( attribute !== undefined ) { - var v1 = new THREE.Vector3(); + var array, offset, stride; - return function ( point, a, b, c ) { + if ( (attribute && attribute.isInterleavedBufferAttribute) ) { - var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 ); + array = attribute.data.array; + offset = attribute.offset; + stride = attribute.data.stride; - return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 ); + } else { - }; + array = attribute.array; + offset = 0; + stride = 3; -}(); + } -THREE.Triangle.prototype = { + for ( var i = offset, il = array.length; i < il; i += stride ) { - constructor: THREE.Triangle, + v1.fromArray( array, i ); + v1.applyMatrix4( node.matrixWorld ); - set: function ( a, b, c ) { + scope.expandByPoint( v1 ); - this.a.copy( a ); - this.b.copy( b ); - this.c.copy( c ); + } - return this; + } - }, + } - setFromPointsAndIndices: function ( points, i0, i1, i2 ) { + } - this.a.copy( points[ i0 ] ); - this.b.copy( points[ i1 ] ); - this.c.copy( points[ i2 ] ); + } ); - return this; + return this; - }, + }; - clone: function () { + }(), - return new this.constructor().copy( this ); + clone: function () { - }, + return new this.constructor().copy( this ); - copy: function ( triangle ) { + }, - this.a.copy( triangle.a ); - this.b.copy( triangle.b ); - this.c.copy( triangle.c ); + copy: function ( box ) { - return this; + this.min.copy( box.min ); + this.max.copy( box.max ); - }, + return this; - area: function () { + }, - var v0 = new THREE.Vector3(); - var v1 = new THREE.Vector3(); + makeEmpty: function () { - return function () { + this.min.x = this.min.y = this.min.z = + Infinity; + this.max.x = this.max.y = this.max.z = - Infinity; - v0.subVectors( this.c, this.b ); - v1.subVectors( this.a, this.b ); + return this; - return v0.cross( v1 ).length() * 0.5; + }, - }; + isEmpty: function () { - }(), + // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes - midpoint: function ( optionalTarget ) { + return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z ); - var result = optionalTarget || new THREE.Vector3(); - return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 ); + }, - }, + getCenter: function ( optionalTarget ) { - normal: function ( optionalTarget ) { + var result = optionalTarget || new Vector3(); + return this.isEmpty() ? result.set( 0, 0, 0 ) : result.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); - return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget ); + }, - }, + getSize: function ( optionalTarget ) { - plane: function ( optionalTarget ) { + var result = optionalTarget || new Vector3(); + return this.isEmpty() ? result.set( 0, 0, 0 ) : result.subVectors( this.max, this.min ); - var result = optionalTarget || new THREE.Plane(); + }, - return result.setFromCoplanarPoints( this.a, this.b, this.c ); + expandByPoint: function ( point ) { - }, + this.min.min( point ); + this.max.max( point ); - barycoordFromPoint: function ( point, optionalTarget ) { + return this; - return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget ); + }, - }, + expandByVector: function ( vector ) { - containsPoint: function ( point ) { + this.min.sub( vector ); + this.max.add( vector ); - return THREE.Triangle.containsPoint( point, this.a, this.b, this.c ); + return this; - }, + }, - equals: function ( triangle ) { + expandByScalar: function ( scalar ) { - return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c ); + this.min.addScalar( - scalar ); + this.max.addScalar( scalar ); - } + return this; -}; + }, -// File:src/core/Clock.js + containsPoint: function ( point ) { -/** - * @author alteredq / http://alteredqualia.com/ - */ + 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 ) { -THREE.Clock = function ( autoStart ) { + return false; - this.autoStart = ( autoStart !== undefined ) ? autoStart : true; + } - this.startTime = 0; - this.oldTime = 0; - this.elapsedTime = 0; + return true; - this.running = false; + }, -}; + containsBox: function ( box ) { -THREE.Clock.prototype = { + 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 ) ) { - constructor: THREE.Clock, + return true; - start: function () { + } - this.startTime = self.performance !== undefined && self.performance.now !== undefined - ? self.performance.now() - : Date.now(); + return false; - this.oldTime = this.startTime; - this.running = true; + }, - }, + getParameter: function ( point, optionalTarget ) { - stop: function () { + // This can potentially have a divide by zero if the box + // has a size dimension of 0. - this.getElapsedTime(); - this.running = false; + 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 ) + ); - getElapsedTime: function () { + }, - this.getDelta(); - return this.elapsedTime; + intersectsBox: function ( box ) { - }, + // using 6 splitting planes to rule out intersections. - getDelta: function () { + if ( box.max.x < this.min.x || box.min.x > this.max.x || + box.max.y < this.min.y || box.min.y > this.max.y || + box.max.z < this.min.z || box.min.z > this.max.z ) { - var diff = 0; + return false; - if ( this.autoStart && ! this.running ) { + } - this.start(); + return true; - } + }, - if ( this.running ) { + intersectsSphere: ( function () { - var newTime = self.performance !== undefined && self.performance.now !== undefined - ? self.performance.now() - : Date.now(); + var closestPoint; - diff = 0.001 * ( newTime - this.oldTime ); - this.oldTime = newTime; + return function intersectsSphere( sphere ) { - this.elapsedTime += diff; + if ( closestPoint === undefined ) closestPoint = new Vector3(); - } + // Find the point on the AABB closest to the sphere center. + this.clampPoint( sphere.center, closestPoint ); - return diff; + // If that point is inside the sphere, the AABB and sphere intersect. + return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius ); - } + }; -}; + } )(), -// File:src/core/EventDispatcher.js + intersectsPlane: function ( plane ) { -/** - * https://github.com/mrdoob/eventdispatcher.js/ - */ + // 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. -THREE.EventDispatcher = function () {}; + var min, max; -THREE.EventDispatcher.prototype = { + if ( plane.normal.x > 0 ) { - constructor: THREE.EventDispatcher, + min = plane.normal.x * this.min.x; + max = plane.normal.x * this.max.x; - apply: function ( object ) { + } else { - object.addEventListener = THREE.EventDispatcher.prototype.addEventListener; - object.hasEventListener = THREE.EventDispatcher.prototype.hasEventListener; - object.removeEventListener = THREE.EventDispatcher.prototype.removeEventListener; - object.dispatchEvent = THREE.EventDispatcher.prototype.dispatchEvent; + min = plane.normal.x * this.max.x; + max = plane.normal.x * this.min.x; - }, + } - addEventListener: function ( type, listener ) { + if ( plane.normal.y > 0 ) { - if ( this._listeners === undefined ) this._listeners = {}; + min += plane.normal.y * this.min.y; + max += plane.normal.y * this.max.y; - var listeners = this._listeners; + } else { - if ( listeners[ type ] === undefined ) { + min += plane.normal.y * this.max.y; + max += plane.normal.y * this.min.y; - listeners[ type ] = []; + } - } + if ( plane.normal.z > 0 ) { - if ( listeners[ type ].indexOf( listener ) === - 1 ) { + min += plane.normal.z * this.min.z; + max += plane.normal.z * this.max.z; - listeners[ type ].push( listener ); + } else { - } + min += plane.normal.z * this.max.z; + max += plane.normal.z * this.min.z; - }, + } - hasEventListener: function ( type, listener ) { + return ( min <= plane.constant && max >= plane.constant ); - if ( this._listeners === undefined ) return false; + }, - var listeners = this._listeners; + clampPoint: function ( point, optionalTarget ) { - if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) { + var result = optionalTarget || new Vector3(); + return result.copy( point ).clamp( this.min, this.max ); - return true; + }, - } + distanceToPoint: function () { - return false; + var v1 = new Vector3(); - }, + return function distanceToPoint( point ) { - removeEventListener: function ( type, listener ) { + var clampedPoint = v1.copy( point ).clamp( this.min, this.max ); + return clampedPoint.sub( point ).length(); - if ( this._listeners === undefined ) return; + }; - var listeners = this._listeners; - var listenerArray = listeners[ type ]; + }(), - if ( listenerArray !== undefined ) { + getBoundingSphere: function () { - var index = listenerArray.indexOf( listener ); + var v1 = new Vector3(); - if ( index !== - 1 ) { + return function getBoundingSphere( optionalTarget ) { - listenerArray.splice( index, 1 ); + var result = optionalTarget || new Sphere(); - } + this.getCenter( result.center ); - } + result.radius = this.size( v1 ).length() * 0.5; - }, + return result; - dispatchEvent: function ( event ) { + }; - if ( this._listeners === undefined ) return; + }(), - var listeners = this._listeners; - var listenerArray = listeners[ event.type ]; + intersect: function ( box ) { - if ( listenerArray !== undefined ) { + this.min.max( box.min ); + this.max.min( box.max ); - event.target = this; + // 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(); - var array = []; - var length = listenerArray.length; + return this; - for ( var i = 0; i < length; i ++ ) { + }, - array[ i ] = listenerArray[ i ]; + union: function ( box ) { - } + this.min.min( box.min ); + this.max.max( box.max ); - for ( var i = 0; i < length; i ++ ) { + return this; - array[ i ].call( this, event ); + }, - } + applyMatrix4: function () { - } + var points = [ + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3() + ]; - } + return function applyMatrix4( matrix ) { -}; + // transform of empty box is an empty box. + if( this.isEmpty() ) return this; -// File:src/core/Raycaster.js + // 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 -/** - * @author mrdoob / http://mrdoob.com/ - * @author bhouston / http://exocortex.com/ - * @author stephomi / http://stephaneginier.com/ - */ + this.setFromPoints( points ); -( function ( THREE ) { + return this; - THREE.Raycaster = function ( origin, direction, near, far ) { + }; - this.ray = new THREE.Ray( origin, direction ); - // direction is assumed to be normalized (for accurate distance calculations) + }(), - this.near = near || 0; - this.far = far || Infinity; + translate: function ( offset ) { - this.params = { - Mesh: {}, - Line: {}, - LOD: {}, - Points: { threshold: 1 }, - Sprite: {} - }; + this.min.add( offset ); + this.max.add( offset ); - Object.defineProperties( this.params, { - PointCloud: { - get: function () { - console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' ); - return this.Points; - } - } - } ); + return this; - }; + }, - function descSort( a, b ) { + equals: function ( box ) { - return a.distance - b.distance; + return box.min.equals( this.min ) && box.max.equals( this.max ); - } + } - var intersectObject = function ( object, raycaster, intersects, recursive ) { + }; -// if ( object.visible === false ) return; + /** + * @author bhouston / http://clara.io + * @author mrdoob / http://mrdoob.com/ + */ - object.raycast( raycaster, intersects ); + function Sphere( center, radius ) { - if ( recursive === true ) { + this.center = ( center !== undefined ) ? center : new Vector3(); + this.radius = ( radius !== undefined ) ? radius : 0; - var children = object.children; + } - for ( var i = 0, l = children.length; i < l; i ++ ) { + Sphere.prototype = { - intersectObject( children[ i ], raycaster, intersects, true ); + constructor: Sphere, - } + set: function ( center, radius ) { - } + this.center.copy( center ); + this.radius = radius; - }; + return this; - // + }, - THREE.Raycaster.prototype = { + setFromPoints: function () { - constructor: THREE.Raycaster, + var box = new Box3(); - linePrecision: 1, + return function setFromPoints( points, optionalCenter ) { - set: function ( origin, direction ) { + var center = this.center; - // direction is assumed to be normalized (for accurate distance calculations) + if ( optionalCenter !== undefined ) { - this.ray.set( origin, direction ); + center.copy( optionalCenter ); - }, + } else { - setFromCamera: function ( coords, camera ) { + box.setFromPoints( points ).getCenter( center ); - if ( camera instanceof THREE.PerspectiveCamera ) { + } - this.ray.origin.setFromMatrixPosition( camera.matrixWorld ); - this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize(); + var maxRadiusSq = 0; - } else if ( camera instanceof THREE.OrthographicCamera ) { + for ( var i = 0, il = points.length; i < il; i ++ ) { - this.ray.origin.set( coords.x, coords.y, - 1 ).unproject( camera ); - this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld ); + maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) ); - } else { + } - console.error( 'THREE.Raycaster: Unsupported camera type.' ); + this.radius = Math.sqrt( maxRadiusSq ); - } + return this; - }, + }; - intersectObject: function ( object, recursive ) { + }(), - var intersects = []; + clone: function () { - intersectObject( object, this, intersects, recursive ); + return new this.constructor().copy( this ); - intersects.sort( descSort ); + }, - return intersects; + copy: function ( sphere ) { - }, + this.center.copy( sphere.center ); + this.radius = sphere.radius; - intersectObjects: function ( objects, recursive ) { + return this; - var intersects = []; + }, - if ( Array.isArray( objects ) === false ) { + empty: function () { - console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' ); - return intersects; + return ( this.radius <= 0 ); - } + }, - for ( var i = 0, l = objects.length; i < l; i ++ ) { + containsPoint: function ( point ) { - intersectObject( objects[ i ], this, intersects, recursive ); + return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) ); - } + }, - intersects.sort( descSort ); + distanceToPoint: function ( point ) { - return intersects; + return ( point.distanceTo( this.center ) - this.radius ); - } + }, - }; + intersectsSphere: function ( sphere ) { -}( THREE ) ); + var radiusSum = this.radius + sphere.radius; -// File:src/core/Object3D.js + return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum ); -/** - * @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 - */ + }, -THREE.Object3D = function () { + intersectsBox: function ( box ) { - Object.defineProperty( this, 'id', { value: THREE.Object3DIdCount ++ } ); + return box.intersectsSphere( this ); - this.uuid = THREE.Math.generateUUID(); + }, - this.name = ''; - this.type = 'Object3D'; + intersectsPlane: function ( plane ) { - this.parent = null; - this.children = []; + // 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. - this.up = THREE.Object3D.DefaultUp.clone(); + return Math.abs( this.center.dot( plane.normal ) - plane.constant ) <= this.radius; - var position = new THREE.Vector3(); - var rotation = new THREE.Euler(); - var quaternion = new THREE.Quaternion(); - var scale = new THREE.Vector3( 1, 1, 1 ); + }, - var onRotationChange = function () { + clampPoint: function ( point, optionalTarget ) { - quaternion.setFromEuler( rotation, false ); + var deltaLengthSq = this.center.distanceToSquared( point ); - }; + var result = optionalTarget || new Vector3(); - var onQuaternionChange = function () { + result.copy( point ); - rotation.setFromQuaternion( quaternion, undefined, false ); + if ( deltaLengthSq > ( this.radius * this.radius ) ) { - }; + result.sub( this.center ).normalize(); + result.multiplyScalar( this.radius ).add( this.center ); - 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 THREE.Matrix4() - }, - normalMatrix: { - value: new THREE.Matrix3() - } - } ); + return result; - this.rotationAutoUpdate = true; + }, - this.matrix = new THREE.Matrix4(); - this.matrixWorld = new THREE.Matrix4(); + getBoundingBox: function ( optionalTarget ) { - this.matrixAutoUpdate = THREE.Object3D.DefaultMatrixAutoUpdate; - this.matrixWorldNeedsUpdate = false; + var box = optionalTarget || new Box3(); - this.visible = true; + box.set( this.center, this.center ); + box.expandByScalar( this.radius ); - this.castShadow = false; - this.receiveShadow = false; + return box; - this.frustumCulled = true; - this.renderOrder = 0; + }, - this.userData = {}; + applyMatrix4: function ( matrix ) { -}; + this.center.applyMatrix4( matrix ); + this.radius = this.radius * matrix.getMaxScaleOnAxis(); -THREE.Object3D.DefaultUp = new THREE.Vector3( 0, 1, 0 ); -THREE.Object3D.DefaultMatrixAutoUpdate = true; + return this; -THREE.Object3D.prototype = { + }, - constructor: THREE.Object3D, + translate: function ( offset ) { - get eulerOrder () { + this.center.add( offset ); - console.warn( 'THREE.Object3D: .eulerOrder has been moved to .rotation.order.' ); + return this; - return this.rotation.order; + }, - }, + equals: function ( sphere ) { - set eulerOrder ( value ) { + return sphere.center.equals( this.center ) && ( sphere.radius === this.radius ); - console.warn( 'THREE.Object3D: .eulerOrder has been moved to .rotation.order.' ); + } - this.rotation.order = value; + }; - }, + /** + * @author alteredq / http://alteredqualia.com/ + * @author WestLangley / http://github.com/WestLangley + * @author bhouston / http://clara.io + * @author tschw + */ - get useQuaternion () { + function Matrix3() { - console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' ); + this.elements = new Float32Array( [ - }, + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 - set useQuaternion ( value ) { + ] ); - console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' ); + if ( arguments.length > 0 ) { - }, + console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' ); - set renderDepth ( value ) { + } - console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' ); + } - }, + Matrix3.prototype = { - applyMatrix: function ( matrix ) { + constructor: Matrix3, - this.matrix.multiplyMatrices( matrix, this.matrix ); + isMatrix3: true, - this.matrix.decompose( this.position, this.quaternion, this.scale ); + set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) { - }, + var te = this.elements; - setRotationFromAxisAngle: function ( axis, angle ) { + 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; - // assumes axis is normalized + return this; - this.quaternion.setFromAxisAngle( axis, angle ); + }, - }, + identity: function () { - setRotationFromEuler: function ( euler ) { + this.set( - this.quaternion.setFromEuler( euler, true ); + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 - }, + ); - setRotationFromMatrix: function ( m ) { + return this; - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + }, - this.quaternion.setFromRotationMatrix( m ); + clone: function () { - }, + return new this.constructor().fromArray( this.elements ); - setRotationFromQuaternion: function ( q ) { + }, - // assumes q is normalized + copy: function ( m ) { - this.quaternion.copy( q ); + var me = m.elements; - }, + this.set( - rotateOnAxis: function () { + me[ 0 ], me[ 3 ], me[ 6 ], + me[ 1 ], me[ 4 ], me[ 7 ], + me[ 2 ], me[ 5 ], me[ 8 ] - // rotate object on axis in object space - // axis is assumed to be normalized + ); - var q1 = new THREE.Quaternion(); + return this; - return function ( axis, angle ) { + }, - q1.setFromAxisAngle( axis, angle ); + setFromMatrix4: function( m ) { - this.quaternion.multiply( q1 ); + var me = m.elements; - return this; + this.set( - }; + me[ 0 ], me[ 4 ], me[ 8 ], + me[ 1 ], me[ 5 ], me[ 9 ], + me[ 2 ], me[ 6 ], me[ 10 ] - }(), + ); - rotateX: function () { + return this; - var v1 = new THREE.Vector3( 1, 0, 0 ); + }, - return function ( angle ) { + applyToVector3Array: function () { - return this.rotateOnAxis( v1, angle ); + var v1; - }; + return function applyToVector3Array( array, offset, length ) { - }(), + if ( v1 === undefined ) v1 = new Vector3(); + if ( offset === undefined ) offset = 0; + if ( length === undefined ) length = array.length; - rotateY: function () { + for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) { - var v1 = new THREE.Vector3( 0, 1, 0 ); + v1.fromArray( array, j ); + v1.applyMatrix3( this ); + v1.toArray( array, j ); - return function ( angle ) { + } - return this.rotateOnAxis( v1, angle ); + return array; - }; + }; - }(), + }(), - rotateZ: function () { + applyToBuffer: function () { - var v1 = new THREE.Vector3( 0, 0, 1 ); + var v1; - return function ( angle ) { + return function applyToBuffer( buffer, offset, length ) { - return this.rotateOnAxis( v1, angle ); + 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 ++ ) { - }(), + v1.x = buffer.getX( j ); + v1.y = buffer.getY( j ); + v1.z = buffer.getZ( j ); - translateOnAxis: function () { + v1.applyMatrix3( this ); - // translate object by distance along axis in object space - // axis is assumed to be normalized + buffer.setXYZ( v1.x, v1.y, v1.z ); - var v1 = new THREE.Vector3(); + } - return function ( axis, distance ) { + return buffer; - v1.copy( axis ).applyQuaternion( this.quaternion ); + }; - this.position.add( v1.multiplyScalar( distance ) ); + }(), - return this; + multiplyScalar: function ( s ) { - }; + 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; - translate: function ( distance, axis ) { + return this; - console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' ); - return this.translateOnAxis( axis, distance ); + }, - }, + determinant: function () { - translateX: function () { + var te = this.elements; - var v1 = new THREE.Vector3( 1, 0, 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 function ( distance ) { + return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g; - return this.translateOnAxis( v1, distance ); + }, - }; + getInverse: function ( matrix, throwOnDegenerate ) { - }(), + if ( (matrix && matrix.isMatrix4) ) { - translateY: function () { + console.error( "THREE.Matrix3.getInverse no longer takes a Matrix4 argument." ); - var v1 = new THREE.Vector3( 0, 1, 0 ); + } - return function ( distance ) { + var me = matrix.elements, + te = this.elements, - return this.translateOnAxis( v1, distance ); + n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], + n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ], + n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ], - }; + t11 = n33 * n22 - n32 * n23, + t12 = n32 * n13 - n33 * n12, + t13 = n23 * n12 - n22 * n13, - }(), + det = n11 * t11 + n21 * t12 + n31 * t13; - translateZ: function () { + if ( det === 0 ) { - var v1 = new THREE.Vector3( 0, 0, 1 ); + var msg = "THREE.Matrix3.getInverse(): can't invert matrix, determinant is 0"; - return function ( distance ) { + if ( throwOnDegenerate === true ) { - return this.translateOnAxis( v1, distance ); + throw new Error( msg ); - }; + } else { - }(), + console.warn( msg ); - localToWorld: function ( vector ) { + } - return vector.applyMatrix4( this.matrixWorld ); + return this.identity(); + } - }, + var detInv = 1 / det; - worldToLocal: function () { + te[ 0 ] = t11 * detInv; + te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv; + te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv; - var m1 = new THREE.Matrix4(); + te[ 3 ] = t12 * detInv; + te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv; + te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv; - return function ( vector ) { + te[ 6 ] = t13 * detInv; + te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv; + te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv; - return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) ); + return this; - }; + }, - }(), + transpose: function () { - lookAt: function () { + var tmp, m = this.elements; - // This routine does not support objects with rotated and/or translated parent(s) + 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; - var m1 = new THREE.Matrix4(); + return this; - return function ( vector ) { + }, - m1.lookAt( vector, this.position, this.up ); + flattenToArrayOffset: function ( array, offset ) { - this.quaternion.setFromRotationMatrix( m1 ); + console.warn( "THREE.Matrix3: .flattenToArrayOffset is deprecated " + + "- just use .toArray instead." ); - }; + return this.toArray( array, offset ); - }(), + }, - add: function ( object ) { + getNormalMatrix: function ( matrix4 ) { - if ( arguments.length > 1 ) { + return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose(); - for ( var i = 0; i < arguments.length; i ++ ) { + }, - this.add( arguments[ i ] ); + transposeIntoArray: function ( r ) { - } + var m = this.elements; - return this; + r[ 0 ] = m[ 0 ]; + r[ 1 ] = m[ 3 ]; + r[ 2 ] = m[ 6 ]; + r[ 3 ] = m[ 1 ]; + r[ 4 ] = m[ 4 ]; + r[ 5 ] = m[ 7 ]; + r[ 6 ] = m[ 2 ]; + r[ 7 ] = m[ 5 ]; + r[ 8 ] = m[ 8 ]; - } + return this; - if ( object === this ) { + }, - console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object ); - return this; + fromArray: function ( array, offset ) { - } + if ( offset === undefined ) offset = 0; - if ( object instanceof THREE.Object3D ) { + for( var i = 0; i < 9; i ++ ) { - if ( object.parent !== null ) { + this.elements[ i ] = array[ i + offset ]; - object.parent.remove( object ); + } - } + return this; - object.parent = this; - object.dispatchEvent( { type: 'added' } ); + }, - this.children.push( object ); + toArray: function ( array, offset ) { - } else { + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object ); + var te = this.elements; - } + array[ offset ] = te[ 0 ]; + array[ offset + 1 ] = te[ 1 ]; + array[ offset + 2 ] = te[ 2 ]; - return this; + 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 ]; - remove: function ( object ) { + return array; - if ( arguments.length > 1 ) { + } - for ( var i = 0; i < arguments.length; i ++ ) { + }; - this.remove( arguments[ i ] ); + /** + * @author bhouston / http://clara.io + */ - } + function Plane( normal, constant ) { - } + this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 ); + this.constant = ( constant !== undefined ) ? constant : 0; - var index = this.children.indexOf( object ); + } - if ( index !== - 1 ) { + Plane.prototype = { - object.parent = null; + constructor: Plane, - object.dispatchEvent( { type: 'removed' } ); + set: function ( normal, constant ) { - this.children.splice( index, 1 ); + this.normal.copy( normal ); + this.constant = constant; - } + return this; - }, + }, - getChildByName: function ( name ) { + setComponents: function ( x, y, z, w ) { - console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' ); - return this.getObjectByName( name ); + this.normal.set( x, y, z ); + this.constant = w; - }, + return this; - getObjectById: function ( id ) { + }, - return this.getObjectByProperty( 'id', id ); + 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 - getObjectByName: function ( name ) { + return this; - return this.getObjectByProperty( 'name', name ); + }, - }, + setFromCoplanarPoints: function () { - getObjectByProperty: function ( name, value ) { + var v1 = new Vector3(); + var v2 = new Vector3(); - if ( this[ name ] === value ) return this; + return function setFromCoplanarPoints( a, b, c ) { - for ( var i = 0, l = this.children.length; i < l; i ++ ) { + var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize(); - var child = this.children[ i ]; - var object = child.getObjectByProperty( name, value ); + // Q: should an error be thrown if normal is zero (e.g. degenerate plane)? - if ( object !== undefined ) { + this.setFromNormalAndCoplanarPoint( normal, a ); - return object; + return this; - } + }; - } + }(), - return undefined; + clone: function () { - }, + return new this.constructor().copy( this ); - getWorldPosition: function ( optionalTarget ) { + }, - var result = optionalTarget || new THREE.Vector3(); + copy: function ( plane ) { - this.updateMatrixWorld( true ); + this.normal.copy( plane.normal ); + this.constant = plane.constant; - return result.setFromMatrixPosition( this.matrixWorld ); + return this; - }, + }, - getWorldQuaternion: function () { + normalize: function () { - var position = new THREE.Vector3(); - var scale = new THREE.Vector3(); + // Note: will lead to a divide by zero if the plane is invalid. - return function ( optionalTarget ) { + var inverseNormalLength = 1.0 / this.normal.length(); + this.normal.multiplyScalar( inverseNormalLength ); + this.constant *= inverseNormalLength; - var result = optionalTarget || new THREE.Quaternion(); + return this; - this.updateMatrixWorld( true ); + }, - this.matrixWorld.decompose( position, result, scale ); + negate: function () { - return result; + this.constant *= - 1; + this.normal.negate(); - }; + return this; - }(), + }, - getWorldRotation: function () { + distanceToPoint: function ( point ) { - var quaternion = new THREE.Quaternion(); + return this.normal.dot( point ) + this.constant; - return function ( optionalTarget ) { + }, - var result = optionalTarget || new THREE.Euler(); + distanceToSphere: function ( sphere ) { - this.getWorldQuaternion( quaternion ); + return this.distanceToPoint( sphere.center ) - sphere.radius; - return result.setFromQuaternion( quaternion, this.rotation.order, false ); + }, - }; + projectPoint: function ( point, optionalTarget ) { - }(), + return this.orthoPoint( point, optionalTarget ).sub( point ).negate(); - getWorldScale: function () { + }, - var position = new THREE.Vector3(); - var quaternion = new THREE.Quaternion(); + orthoPoint: function ( point, optionalTarget ) { - return function ( optionalTarget ) { + var perpendicularMagnitude = this.distanceToPoint( point ); - var result = optionalTarget || new THREE.Vector3(); + var result = optionalTarget || new Vector3(); + return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude ); - this.updateMatrixWorld( true ); + }, - this.matrixWorld.decompose( position, quaternion, result ); + intersectLine: function () { - return result; + var v1 = new Vector3(); - }; + return function intersectLine( line, optionalTarget ) { - }(), + var result = optionalTarget || new Vector3(); - getWorldDirection: function () { + var direction = line.delta( v1 ); - var quaternion = new THREE.Quaternion(); + var denominator = this.normal.dot( direction ); - return function ( optionalTarget ) { + if ( denominator === 0 ) { - var result = optionalTarget || new THREE.Vector3(); + // line is coplanar, return origin + if ( this.distanceToPoint( line.start ) === 0 ) { - this.getWorldQuaternion( quaternion ); + return result.copy( line.start ); - return result.set( 0, 0, 1 ).applyQuaternion( quaternion ); + } - }; + // Unsure if this is the correct method to handle this case. + return undefined; - }(), + } - raycast: function () {}, + var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator; - traverse: function ( callback ) { + if ( t < 0 || t > 1 ) { - callback( this ); + return undefined; - var children = this.children; + } - for ( var i = 0, l = children.length; i < l; i ++ ) { + return result.copy( direction ).multiplyScalar( t ).add( line.start ); - children[ i ].traverse( callback ); + }; - } + }(), - }, + intersectsLine: function ( line ) { - traverseVisible: function ( callback ) { + // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it. - if ( this.visible === false ) return; + var startSign = this.distanceToPoint( line.start ); + var endSign = this.distanceToPoint( line.end ); - callback( this ); + return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 ); - var children = this.children; + }, - for ( var i = 0, l = children.length; i < l; i ++ ) { + intersectsBox: function ( box ) { - children[ i ].traverseVisible( callback ); + return box.intersectsPlane( this ); - } + }, - }, + intersectsSphere: function ( sphere ) { - traverseAncestors: function ( callback ) { + return sphere.intersectsPlane( this ); - var parent = this.parent; + }, - if ( parent !== null ) { + coplanarPoint: function ( optionalTarget ) { - callback( parent ); + var result = optionalTarget || new Vector3(); + return result.copy( this.normal ).multiplyScalar( - this.constant ); - parent.traverseAncestors( callback ); + }, - } + applyMatrix4: function () { - }, + var v1 = new Vector3(); + var m1 = new Matrix3(); - updateMatrix: function () { + return function applyMatrix4( matrix, optionalNormalMatrix ) { - this.matrix.compose( this.position, this.quaternion, this.scale ); + var referencePoint = this.coplanarPoint( v1 ).applyMatrix4( matrix ); - this.matrixWorldNeedsUpdate = true; + // 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(); - }, + // recalculate constant (like in setFromNormalAndCoplanarPoint) + this.constant = - referencePoint.dot( normal ); - updateMatrixWorld: function ( force ) { + return this; - if ( this.matrixAutoUpdate === true ) this.updateMatrix(); + }; - if ( this.matrixWorldNeedsUpdate === true || force === true ) { + }(), - if ( this.parent === null ) { + translate: function ( offset ) { - this.matrixWorld.copy( this.matrix ); + this.constant = this.constant - offset.dot( this.normal ); - } else { + return this; - this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); + }, - } + equals: function ( plane ) { - this.matrixWorldNeedsUpdate = false; + return plane.normal.equals( this.normal ) && ( plane.constant === this.constant ); - force = true; + } - } + }; - // update children + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * @author bhouston / http://clara.io + */ - for ( var i = 0, l = this.children.length; i < l; i ++ ) { + function Frustum( p0, p1, p2, p3, p4, p5 ) { - this.children[ i ].updateMatrixWorld( force ); + this.planes = [ - } + ( p0 !== undefined ) ? p0 : new Plane(), + ( p1 !== undefined ) ? p1 : new Plane(), + ( p2 !== undefined ) ? p2 : new Plane(), + ( p3 !== undefined ) ? p3 : new Plane(), + ( p4 !== undefined ) ? p4 : new Plane(), + ( p5 !== undefined ) ? p5 : new Plane() - }, + ]; - toJSON: function ( meta ) { + } - var isRootObject = ( meta === undefined ); + Frustum.prototype = { - var data = {}; + constructor: Frustum, - // meta is a hash used to collect geometries, materials. - // not providing it implies that this is the root object - // being serialized. - if ( isRootObject ) { + set: function ( p0, p1, p2, p3, p4, p5 ) { - // initialize meta obj - meta = { - geometries: {}, - materials: {}, - textures: {}, - images: {} - }; + var planes = this.planes; - data.metadata = { - version: 4.4, - type: 'Object', - generator: 'Object3D.toJSON' - }; + 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; - // standard Object3D serialization + }, - data.uuid = this.uuid; - data.type = this.type; + clone: function () { - if ( this.name !== '' ) data.name = this.name; - if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData; - if ( this.visible !== true ) data.visible = this.visible; + return new this.constructor().copy( this ); - data.matrix = this.matrix.toArray(); + }, - if ( this.children.length > 0 ) { + copy: function ( frustum ) { - data.children = []; + var planes = this.planes; - for ( var i = 0; i < this.children.length; i ++ ) { + for ( var i = 0; i < 6; i ++ ) { - data.children.push( this.children[ i ].toJSON( meta ).object ); + planes[ i ].copy( frustum.planes[ i ] ); - } + } - } + return this; - var output = {}; + }, - if ( isRootObject ) { + setFromMatrix: function ( m ) { - var geometries = extractFromCache( meta.geometries ); - var materials = extractFromCache( meta.materials ); - var textures = extractFromCache( meta.textures ); - var images = extractFromCache( meta.images ); + 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 ( 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; + planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize(); + planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize(); + planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize(); + planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize(); + planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); + planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize(); - } + return this; - output.object = data; + }, - return output; + intersectsObject: function () { - // extract data from the cache hash - // remove metadata on each item - // and return as array - function extractFromCache ( cache ) { + var sphere = new Sphere(); - var values = []; - for ( var key in cache ) { + return function intersectsObject( object ) { - var data = cache[ key ]; - delete data.metadata; - values.push( data ); + var geometry = object.geometry; - } - return values; + if ( geometry.boundingSphere === null ) + geometry.computeBoundingSphere(); - } + sphere.copy( geometry.boundingSphere ) + .applyMatrix4( object.matrixWorld ); - }, + return this.intersectsSphere( sphere ); - clone: function ( recursive ) { + }; - return new this.constructor().copy( this, recursive ); + }(), - }, + intersectsSprite: function () { - copy: function ( source, recursive ) { + var sphere = new Sphere(); - if ( recursive === undefined ) recursive = true; + return function intersectsSprite( sprite ) { - this.name = source.name; + sphere.center.set( 0, 0, 0 ); + sphere.radius = 0.7071067811865476; + sphere.applyMatrix4( sprite.matrixWorld ); - this.up.copy( source.up ); + return this.intersectsSphere( sphere ); - this.position.copy( source.position ); - this.quaternion.copy( source.quaternion ); - this.scale.copy( source.scale ); + }; - this.rotationAutoUpdate = source.rotationAutoUpdate; + }(), - this.matrix.copy( source.matrix ); - this.matrixWorld.copy( source.matrixWorld ); + intersectsSphere: function ( sphere ) { - this.matrixAutoUpdate = source.matrixAutoUpdate; - this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate; + var planes = this.planes; + var center = sphere.center; + var negRadius = - sphere.radius; - this.visible = source.visible; + for ( var i = 0; i < 6; i ++ ) { - this.castShadow = source.castShadow; - this.receiveShadow = source.receiveShadow; + var distance = planes[ i ].distanceToPoint( center ); - this.frustumCulled = source.frustumCulled; - this.renderOrder = source.renderOrder; + if ( distance < negRadius ) { - this.userData = JSON.parse( JSON.stringify( source.userData ) ); + return false; - if ( recursive === true ) { + } - for ( var i = 0; i < source.children.length; i ++ ) { + } - var child = source.children[ i ]; - this.add( child.clone() ); + return true; - } + }, - } + intersectsBox: function () { - return this; + var p1 = new Vector3(), + p2 = new Vector3(); - } + return function intersectsBox( box ) { -}; + var planes = this.planes; -THREE.EventDispatcher.prototype.apply( THREE.Object3D.prototype ); + for ( var i = 0; i < 6 ; i ++ ) { -THREE.Object3DIdCount = 0; + var plane = planes[ i ]; -// File:src/core/Face3.js + 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; -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + var d1 = plane.distanceToPoint( p1 ); + var d2 = plane.distanceToPoint( p2 ); -THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) { + // if both outside plane, no intersection - this.a = a; - this.b = b; - this.c = c; + if ( d1 < 0 && d2 < 0 ) { - this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3(); - this.vertexNormals = Array.isArray( normal ) ? normal : []; + return false; - this.color = color instanceof THREE.Color ? color : new THREE.Color(); - this.vertexColors = Array.isArray( color ) ? color : []; + } - this.materialIndex = materialIndex !== undefined ? materialIndex : 0; + } -}; + return true; -THREE.Face3.prototype = { + }; - constructor: THREE.Face3, + }(), - clone: function () { - return new this.constructor().copy( this ); + containsPoint: function ( point ) { - }, + var planes = this.planes; - copy: function ( source ) { + for ( var i = 0; i < 6; i ++ ) { - this.a = source.a; - this.b = source.b; - this.c = source.c; + if ( planes[ i ].distanceToPoint( point ) < 0 ) { - this.normal.copy( source.normal ); - this.color.copy( source.color ); + return false; - this.materialIndex = source.materialIndex; + } - for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) { + } - this.vertexNormals[ i ] = source.vertexNormals[ i ].clone(); + return true; - } + } - for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) { + }; - this.vertexColors[ i ] = source.vertexColors[ i ].clone(); + function WebGLShadowMap( _renderer, _lights, _objects, capabilities ) { - } + var _gl = _renderer.context, + _state = _renderer.state, + _frustum = new Frustum(), + _projScreenMatrix = new Matrix4(), - return this; + _lightShadows = _lights.shadows, - } + _shadowMapSize = new Vector2(), + _maxShadowMapSize = new Vector2( capabilities.maxTextureSize, capabilities.maxTextureSize ), -}; + _lookTarget = new Vector3(), + _lightPositionWorld = new Vector3(), -// File:src/core/Face4.js + _renderList = [], -/** - * @author mrdoob / http://mrdoob.com/ - */ + _MorphingFlag = 1, + _SkinningFlag = 2, -THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) { + _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1, - console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' ); - return new THREE.Face3( a, b, c, normal, color, materialIndex ); + _depthMaterials = new Array( _NumberOfMaterialVariants ), + _distanceMaterials = new Array( _NumberOfMaterialVariants ), -}; + _materialCache = {}; -// File:src/core/BufferAttribute.js + 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 ) + ]; -/** - * @author mrdoob / http://mrdoob.com/ - */ + 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 ) + ]; -THREE.BufferAttribute = function ( array, itemSize ) { + var cube2DViewPorts = [ + new Vector4(), new Vector4(), new Vector4(), + new Vector4(), new Vector4(), new Vector4() + ]; - this.uuid = THREE.Math.generateUUID(); + // init - this.array = array; - this.itemSize = itemSize; + var depthMaterialTemplate = new MeshDepthMaterial(); + depthMaterialTemplate.depthPacking = RGBADepthPacking; + depthMaterialTemplate.clipping = true; - this.dynamic = false; - this.updateRange = { offset: 0, count: - 1 }; + var distanceShader = ShaderLib[ "distanceRGBA" ]; + var distanceUniforms = exports.UniformsUtils.clone( distanceShader.uniforms ); - this.version = 0; + for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) { -}; + var useMorphing = ( i & _MorphingFlag ) !== 0; + var useSkinning = ( i & _SkinningFlag ) !== 0; -THREE.BufferAttribute.prototype = { + var depthMaterial = depthMaterialTemplate.clone(); + depthMaterial.morphTargets = useMorphing; + depthMaterial.skinning = useSkinning; - constructor: THREE.BufferAttribute, + _depthMaterials[ i ] = depthMaterial; - get length() { + var distanceMaterial = new ShaderMaterial( { + defines: { + 'USE_SHADOWMAP': '' + }, + uniforms: distanceUniforms, + vertexShader: distanceShader.vertexShader, + fragmentShader: distanceShader.fragmentShader, + morphTargets: useMorphing, + skinning: useSkinning, + clipping: true + } ); - console.warn( 'THREE.BufferAttribute: .length has been deprecated. Please use .count.' ); - return this.array.length; + _distanceMaterials[ i ] = distanceMaterial; - }, + } - get count() { + // - return this.array.length / this.itemSize; + var scope = this; - }, + this.enabled = false; - set needsUpdate( value ) { + this.autoUpdate = true; + this.needsUpdate = false; - if ( value === true ) this.version ++; + this.type = PCFShadowMap; - }, + this.renderReverseSided = true; + this.renderSingleSided = true; - setDynamic: function ( value ) { + this.render = function ( scene, camera ) { - this.dynamic = value; + if ( scope.enabled === false ) return; + if ( scope.autoUpdate === false && scope.needsUpdate === false ) return; - return this; + if ( _lightShadows.length === 0 ) return; - }, + // Set GL state for depth map. + _state.clearColor( 1, 1, 1, 1 ); + _state.disable( _gl.BLEND ); + _state.setDepthTest( true ); + _state.setScissorTest( false ); - copy: function ( source ) { + // render depth map - this.array = new source.array.constructor( source.array ); - this.itemSize = source.itemSize; + var faceCount, isPointLight; - this.dynamic = source.dynamic; + for ( var i = 0, il = _lightShadows.length; i < il; i ++ ) { - return this; + var light = _lightShadows[ i ]; + var shadow = light.shadow; - }, + if ( shadow === undefined ) { - copyAt: function ( index1, attribute, index2 ) { + console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' ); + continue; - index1 *= this.itemSize; - index2 *= attribute.itemSize; + } - for ( var i = 0, l = this.itemSize; i < l; i ++ ) { + var shadowCamera = shadow.camera; - this.array[ index1 + i ] = attribute.array[ index2 + i ]; + _shadowMapSize.copy( shadow.mapSize ); + _shadowMapSize.min( _maxShadowMapSize ); - } + if ( (light && light.isPointLight) ) { - return this; + faceCount = 6; + isPointLight = true; - }, + var vpWidth = _shadowMapSize.x; + var vpHeight = _shadowMapSize.y; - copyArray: function ( array ) { + // 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 - this.array.set( array ); + // positive X + cube2DViewPorts[ 0 ].set( vpWidth * 2, vpHeight, vpWidth, vpHeight ); + // negative X + cube2DViewPorts[ 1 ].set( 0, vpHeight, vpWidth, vpHeight ); + // positive Z + cube2DViewPorts[ 2 ].set( vpWidth * 3, vpHeight, vpWidth, vpHeight ); + // negative Z + cube2DViewPorts[ 3 ].set( vpWidth, vpHeight, vpWidth, vpHeight ); + // positive Y + cube2DViewPorts[ 4 ].set( vpWidth * 3, 0, vpWidth, vpHeight ); + // negative Y + cube2DViewPorts[ 5 ].set( vpWidth, 0, vpWidth, vpHeight ); - return this; + _shadowMapSize.x *= 4.0; + _shadowMapSize.y *= 2.0; - }, + } else { - copyColorsArray: function ( colors ) { + faceCount = 1; + isPointLight = false; - var array = this.array, offset = 0; + } - for ( var i = 0, l = colors.length; i < l; i ++ ) { + if ( shadow.map === null ) { - var color = colors[ i ]; + var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat }; - if ( color === undefined ) { + shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars ); - console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i ); - color = new THREE.Color(); + shadowCamera.updateProjectionMatrix(); - } + } - array[ offset ++ ] = color.r; - array[ offset ++ ] = color.g; - array[ offset ++ ] = color.b; + if ( (shadow && shadow.isSpotLightShadow) ) { - } + shadow.update( light ); - return this; + } - }, + var shadowMap = shadow.map; + var shadowMatrix = shadow.matrix; - copyIndicesArray: function ( indices ) { + _lightPositionWorld.setFromMatrixPosition( light.matrixWorld ); + shadowCamera.position.copy( _lightPositionWorld ); - var array = this.array, offset = 0; + _renderer.setRenderTarget( shadowMap ); + _renderer.clear(); - for ( var i = 0, l = indices.length; i < l; i ++ ) { + // render shadow map for each cube face (if omni-directional) or + // run a single pass if not - var index = indices[ i ]; + for ( var face = 0; face < faceCount; face ++ ) { - array[ offset ++ ] = index.a; - array[ offset ++ ] = index.b; - array[ offset ++ ] = index.c; + if ( isPointLight ) { - } + _lookTarget.copy( shadowCamera.position ); + _lookTarget.add( cubeDirections[ face ] ); + shadowCamera.up.copy( cubeUps[ face ] ); + shadowCamera.lookAt( _lookTarget ); - return this; + var vpDimensions = cube2DViewPorts[ face ]; + _state.viewport( vpDimensions ); - }, + } else { - copyVector2sArray: function ( vectors ) { + _lookTarget.setFromMatrixPosition( light.target.matrixWorld ); + shadowCamera.lookAt( _lookTarget ); - var array = this.array, offset = 0; + } - for ( var i = 0, l = vectors.length; i < l; i ++ ) { + shadowCamera.updateMatrixWorld(); + shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld ); - var vector = vectors[ i ]; + // compute shadow matrix - if ( vector === undefined ) { + 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 + ); - console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i ); - vector = new THREE.Vector2(); + shadowMatrix.multiply( shadowCamera.projectionMatrix ); + shadowMatrix.multiply( shadowCamera.matrixWorldInverse ); - } + // update camera matrices and frustum - array[ offset ++ ] = vector.x; - array[ offset ++ ] = vector.y; + _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse ); + _frustum.setFromMatrix( _projScreenMatrix ); - } + // set object matrices & frustum culling - return this; + _renderList.length = 0; - }, + projectObject( scene, camera, shadowCamera ); - copyVector3sArray: function ( vectors ) { + // render shadow map + // render regular objects - var array = this.array, offset = 0; + for ( var j = 0, jl = _renderList.length; j < jl; j ++ ) { - for ( var i = 0, l = vectors.length; i < l; i ++ ) { + var object = _renderList[ j ]; + var geometry = _objects.update( object ); + var material = object.material; - var vector = vectors[ i ]; + if ( (material && material.isMultiMaterial) ) { - if ( vector === undefined ) { + var groups = geometry.groups; + var materials = material.materials; - console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i ); - vector = new THREE.Vector3(); + for ( var k = 0, kl = groups.length; k < kl; k ++ ) { - } + var group = groups[ k ]; + var groupMaterial = materials[ group.materialIndex ]; - array[ offset ++ ] = vector.x; - array[ offset ++ ] = vector.y; - array[ offset ++ ] = vector.z; + if ( groupMaterial.visible === true ) { - } + var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld ); + _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group ); - return this; + } - }, + } - copyVector4sArray: function ( vectors ) { + } else { - var array = this.array, offset = 0; + var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld ); + _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null ); - for ( var i = 0, l = vectors.length; i < l; i ++ ) { + } - var vector = vectors[ i ]; + } - if ( vector === undefined ) { + } - console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i ); - vector = new THREE.Vector4(); + } - } + // Restore GL state. + var clearColor = _renderer.getClearColor(), + clearAlpha = _renderer.getClearAlpha(); + _renderer.setClearColor( clearColor, clearAlpha ); - array[ offset ++ ] = vector.x; - array[ offset ++ ] = vector.y; - array[ offset ++ ] = vector.z; - array[ offset ++ ] = vector.w; + scope.needsUpdate = false; - } + }; - return this; + function getDepthMaterial( object, material, isPointLight, lightPositionWorld ) { - }, + var geometry = object.geometry; - set: function ( value, offset ) { + var result = null; - if ( offset === undefined ) offset = 0; + var materialVariants = _depthMaterials; + var customMaterial = object.customDepthMaterial; - this.array.set( value, offset ); + if ( isPointLight ) { - return this; + materialVariants = _distanceMaterials; + customMaterial = object.customDistanceMaterial; - }, + } - getX: function ( index ) { + if ( ! customMaterial ) { - return this.array[ index * this.itemSize ]; + var useMorphing = false; - }, + if ( material.morphTargets ) { - setX: function ( index, x ) { + if ( (geometry && geometry.isBufferGeometry) ) { - this.array[ index * this.itemSize ] = x; + useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0; - return this; + } else if ( (geometry && geometry.isGeometry) ) { - }, + useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0; - getY: function ( index ) { + } - return this.array[ index * this.itemSize + 1 ]; + } - }, + var useSkinning = object.isSkinnedMesh && material.skinning; - setY: function ( index, y ) { + var variantIndex = 0; - this.array[ index * this.itemSize + 1 ] = y; + if ( useMorphing ) variantIndex |= _MorphingFlag; + if ( useSkinning ) variantIndex |= _SkinningFlag; - return this; + result = materialVariants[ variantIndex ]; - }, + } else { - getZ: function ( index ) { + result = customMaterial; - return this.array[ index * this.itemSize + 2 ]; + } - }, + if ( _renderer.localClippingEnabled && + material.clipShadows === true && + material.clippingPlanes.length !== 0 ) { - setZ: function ( index, z ) { + // in this case we need a unique material instance reflecting the + // appropriate state - this.array[ index * this.itemSize + 2 ] = z; + var keyA = result.uuid, keyB = material.uuid; - return this; + var materialsForVariant = _materialCache[ keyA ]; - }, + if ( materialsForVariant === undefined ) { - getW: function ( index ) { + materialsForVariant = {}; + _materialCache[ keyA ] = materialsForVariant; - return this.array[ index * this.itemSize + 3 ]; + } - }, + var cachedMaterial = materialsForVariant[ keyB ]; - setW: function ( index, w ) { + if ( cachedMaterial === undefined ) { - this.array[ index * this.itemSize + 3 ] = w; + cachedMaterial = result.clone(); + materialsForVariant[ keyB ] = cachedMaterial; - return this; + } - }, + result = cachedMaterial; - setXY: function ( index, x, y ) { + } - index *= this.itemSize; + result.visible = material.visible; + result.wireframe = material.wireframe; - this.array[ index + 0 ] = x; - this.array[ index + 1 ] = y; + var side = material.side; - return this; + if ( scope.renderSingleSided && side == DoubleSide ) { - }, + side = FrontSide; - setXYZ: function ( index, x, y, z ) { + } - index *= this.itemSize; + if ( scope.renderReverseSided ) { - this.array[ index + 0 ] = x; - this.array[ index + 1 ] = y; - this.array[ index + 2 ] = z; + if ( side === FrontSide ) side = BackSide; + else if ( side === BackSide ) side = FrontSide; - return this; + } - }, + result.side = side; - setXYZW: function ( index, x, y, z, w ) { + result.clipShadows = material.clipShadows; + result.clippingPlanes = material.clippingPlanes; - index *= this.itemSize; + result.wireframeLinewidth = material.wireframeLinewidth; + result.linewidth = material.linewidth; - this.array[ index + 0 ] = x; - this.array[ index + 1 ] = y; - this.array[ index + 2 ] = z; - this.array[ index + 3 ] = w; + if ( isPointLight && result.uniforms.lightPos !== undefined ) { - return this; + result.uniforms.lightPos.value.copy( lightPositionWorld ); - }, + } - clone: function () { + return result; - return new this.constructor().copy( this ); + } - } + function projectObject( object, camera, shadowCamera ) { -}; + if ( object.visible === false ) return; -// + var visible = ( object.layers.mask & camera.layers.mask ) !== 0; -THREE.Int8Attribute = function ( array, itemSize ) { + if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) { - return new THREE.BufferAttribute( new Int8Array( array ), itemSize ); + if ( object.castShadow && ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) ) { -}; + var material = object.material; -THREE.Uint8Attribute = function ( array, itemSize ) { + if ( material.visible === true ) { - return new THREE.BufferAttribute( new Uint8Array( array ), itemSize ); + object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld ); + _renderList.push( object ); -}; + } -THREE.Uint8ClampedAttribute = function ( array, itemSize ) { + } - return new THREE.BufferAttribute( new Uint8ClampedArray( array ), itemSize ); + } -}; + var children = object.children; -THREE.Int16Attribute = function ( array, itemSize ) { + for ( var i = 0, l = children.length; i < l; i ++ ) { - return new THREE.BufferAttribute( new Int16Array( array ), itemSize ); + projectObject( children[ i ], camera, shadowCamera ); -}; + } -THREE.Uint16Attribute = function ( array, itemSize ) { + } - return new THREE.BufferAttribute( new Uint16Array( array ), itemSize ); + } -}; + /** + * @author bhouston / http://clara.io + */ -THREE.Int32Attribute = function ( array, itemSize ) { + function Ray( origin, direction ) { - return new THREE.BufferAttribute( new Int32Array( array ), itemSize ); + this.origin = ( origin !== undefined ) ? origin : new Vector3(); + this.direction = ( direction !== undefined ) ? direction : new Vector3(); -}; + } -THREE.Uint32Attribute = function ( array, itemSize ) { + Ray.prototype = { - return new THREE.BufferAttribute( new Uint32Array( array ), itemSize ); + constructor: Ray, -}; + set: function ( origin, direction ) { -THREE.Float32Attribute = function ( array, itemSize ) { + this.origin.copy( origin ); + this.direction.copy( direction ); - return new THREE.BufferAttribute( new Float32Array( array ), itemSize ); + return this; -}; + }, -THREE.Float64Attribute = function ( array, itemSize ) { + clone: function () { - return new THREE.BufferAttribute( new Float64Array( array ), itemSize ); + return new this.constructor().copy( this ); -}; + }, + copy: function ( ray ) { -// Deprecated + this.origin.copy( ray.origin ); + this.direction.copy( ray.direction ); -THREE.DynamicBufferAttribute = function ( array, itemSize ) { + return this; - console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' ); - return new THREE.BufferAttribute( array, itemSize ).setDynamic( true ); + }, -}; + at: function ( t, optionalTarget ) { -// File:src/core/InstancedBufferAttribute.js + var result = optionalTarget || new Vector3(); -/** - * @author benaadams / https://twitter.com/ben_a_adams - */ + return result.copy( this.direction ).multiplyScalar( t ).add( this.origin ); -THREE.InstancedBufferAttribute = function ( array, itemSize, meshPerAttribute ) { + }, - THREE.BufferAttribute.call( this, array, itemSize ); + lookAt: function ( v ) { - this.meshPerAttribute = meshPerAttribute || 1; + this.direction.copy( v ).sub( this.origin ).normalize(); -}; + return this; -THREE.InstancedBufferAttribute.prototype = Object.create( THREE.BufferAttribute.prototype ); -THREE.InstancedBufferAttribute.prototype.constructor = THREE.InstancedBufferAttribute; + }, -THREE.InstancedBufferAttribute.prototype.copy = function ( source ) { + recast: function () { - THREE.BufferAttribute.prototype.copy.call( this, source ); + var v1 = new Vector3(); - this.meshPerAttribute = source.meshPerAttribute; + return function recast( t ) { - return this; + this.origin.copy( this.at( t, v1 ) ); -}; + return this; -// File:src/core/InterleavedBuffer.js + }; -/** - * @author benaadams / https://twitter.com/ben_a_adams - */ + }(), -THREE.InterleavedBuffer = function ( array, stride ) { + closestPointToPoint: function ( point, optionalTarget ) { - this.uuid = THREE.Math.generateUUID(); + var result = optionalTarget || new Vector3(); + result.subVectors( point, this.origin ); + var directionDistance = result.dot( this.direction ); - this.array = array; - this.stride = stride; + if ( directionDistance < 0 ) { - this.dynamic = false; - this.updateRange = { offset: 0, count: - 1 }; + return result.copy( this.origin ); - this.version = 0; + } -}; + return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); -THREE.InterleavedBuffer.prototype = { + }, - constructor: THREE.InterleavedBuffer, + distanceToPoint: function ( point ) { - get length () { + return Math.sqrt( this.distanceSqToPoint( point ) ); - return this.array.length; + }, - }, + distanceSqToPoint: function () { - get count () { + var v1 = new Vector3(); - return this.array.length / this.stride; + return function distanceSqToPoint( point ) { - }, + var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction ); - set needsUpdate( value ) { + // point behind the ray - if ( value === true ) this.version ++; + if ( directionDistance < 0 ) { - }, + return this.origin.distanceToSquared( point ); - setDynamic: function ( value ) { + } - this.dynamic = value; + v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); - return this; + return v1.distanceToSquared( point ); - }, + }; - copy: function ( source ) { + }(), - this.array = new source.array.constructor( source.array ); - this.stride = source.stride; - this.dynamic = source.dynamic; + distanceSqToSegment: function () { - }, + var segCenter = new Vector3(); + var segDir = new Vector3(); + var diff = new Vector3(); - copyAt: function ( index1, attribute, index2 ) { + return function distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) { - index1 *= this.stride; - index2 *= attribute.stride; + // 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 - for ( var i = 0, l = this.stride; i < l; i ++ ) { + segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 ); + segDir.copy( v1 ).sub( v0 ).normalize(); + diff.copy( this.origin ).sub( segCenter ); - this.array[ index1 + i ] = attribute.array[ index2 + i ]; + 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; - } + if ( det > 0 ) { - return this; + // The ray and segment are not parallel. - }, + s0 = a01 * b1 - b0; + s1 = a01 * b0 - b1; + extDet = segExtent * det; - set: function ( value, offset ) { + if ( s0 >= 0 ) { - if ( offset === undefined ) offset = 0; + if ( s1 >= - extDet ) { - this.array.set( value, offset ); + if ( s1 <= extDet ) { - return this; + // region 0 + // Minimum at interior points of ray and segment. - }, + var invDet = 1 / det; + s0 *= invDet; + s1 *= invDet; + sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c; - clone: function () { + } else { - return new this.constructor().copy( this ); + // region 1 - } + s1 = segExtent; + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; -}; + } -// File:src/core/InstancedInterleavedBuffer.js + } else { -/** - * @author benaadams / https://twitter.com/ben_a_adams - */ + // region 5 -THREE.InstancedInterleavedBuffer = function ( array, stride, meshPerAttribute ) { + s1 = - segExtent; + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - THREE.InterleavedBuffer.call( this, array, stride ); + } - this.meshPerAttribute = meshPerAttribute || 1; + } else { -}; + if ( s1 <= - extDet ) { -THREE.InstancedInterleavedBuffer.prototype = Object.create( THREE.InterleavedBuffer.prototype ); -THREE.InstancedInterleavedBuffer.prototype.constructor = THREE.InstancedInterleavedBuffer; + // region 4 -THREE.InstancedInterleavedBuffer.prototype.copy = function ( source ) { + 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; - THREE.InterleavedBuffer.prototype.copy.call( this, source ); + } else if ( s1 <= extDet ) { - this.meshPerAttribute = source.meshPerAttribute; + // region 3 - return this; + s0 = 0; + s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent ); + sqrDist = s1 * ( s1 + 2 * b1 ) + c; -}; + } else { -// File:src/core/InterleavedBufferAttribute.js + // region 2 -/** - * @author benaadams / https://twitter.com/ben_a_adams - */ + 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; -THREE.InterleavedBufferAttribute = function ( interleavedBuffer, itemSize, offset ) { + } - this.uuid = THREE.Math.generateUUID(); + } - this.data = interleavedBuffer; - this.itemSize = itemSize; - this.offset = offset; + } else { -}; + // Ray and segment are parallel. + s1 = ( a01 > 0 ) ? - segExtent : segExtent; + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; -THREE.InterleavedBufferAttribute.prototype = { + } - constructor: THREE.InterleavedBufferAttribute, + if ( optionalPointOnRay ) { - get length() { + optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin ); - console.warn( 'THREE.BufferAttribute: .length has been deprecated. Please use .count.' ); - return this.array.length; + } - }, + if ( optionalPointOnSegment ) { - get count() { + optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter ); - return this.data.array.length / this.data.stride; + } - }, + return sqrDist; - setX: function ( index, x ) { + }; - this.data.array[ index * this.data.stride + this.offset ] = x; + }(), - return this; + intersectSphere: function () { - }, + var v1 = new Vector3(); - setY: function ( index, y ) { + return function intersectSphere( sphere, optionalTarget ) { - this.data.array[ index * this.data.stride + this.offset + 1 ] = y; + 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; - return this; + if ( d2 > radius2 ) return null; - }, + var thc = Math.sqrt( radius2 - d2 ); - setZ: function ( index, z ) { + // t0 = first intersect point - entrance on front of sphere + var t0 = tca - thc; - this.data.array[ index * this.data.stride + this.offset + 2 ] = z; + // 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 ); - setW: function ( index, w ) { + // else t0 is in front of the ray, so return the first collision point scaled by t0 + return this.at( t0, optionalTarget ); - this.data.array[ index * this.data.stride + this.offset + 3 ] = w; + }; - return this; + }(), - }, + intersectsSphere: function ( sphere ) { - getX: function ( index ) { + return this.distanceToPoint( sphere.center ) <= sphere.radius; - return this.data.array[ index * this.data.stride + this.offset ]; + }, - }, + distanceToPlane: function ( plane ) { - getY: function ( index ) { + var denominator = plane.normal.dot( this.direction ); - return this.data.array[ index * this.data.stride + this.offset + 1 ]; + if ( denominator === 0 ) { - }, + // line is coplanar, return origin + if ( plane.distanceToPoint( this.origin ) === 0 ) { - getZ: function ( index ) { + return 0; - return this.data.array[ index * this.data.stride + this.offset + 2 ]; + } - }, + // Null is preferable to undefined since undefined means.... it is undefined - getW: function ( index ) { + return null; - return this.data.array[ index * this.data.stride + this.offset + 3 ]; + } - }, + var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator; - setXY: function ( index, x, y ) { + // Return if the ray never intersects the plane - index = index * this.data.stride + this.offset; + return t >= 0 ? t : null; - this.data.array[ index + 0 ] = x; - this.data.array[ index + 1 ] = y; + }, - return this; + intersectPlane: function ( plane, optionalTarget ) { - }, + var t = this.distanceToPlane( plane ); - setXYZ: function ( index, x, y, z ) { + if ( t === null ) { - index = index * this.data.stride + this.offset; + return null; - this.data.array[ index + 0 ] = x; - this.data.array[ index + 1 ] = y; - this.data.array[ index + 2 ] = z; + } - return this; + return this.at( t, optionalTarget ); - }, + }, - setXYZW: function ( index, x, y, z, w ) { - 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; + intersectsPlane: function ( plane ) { - return this; + // check if the ray lies on the plane first - } + var distToPoint = plane.distanceToPoint( this.origin ); -}; + if ( distToPoint === 0 ) { -// File:src/core/Geometry.js + return true; -/** - * @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://exocortex.com - */ + } -THREE.Geometry = function () { + var denominator = plane.normal.dot( this.direction ); - Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } ); + if ( denominator * distToPoint < 0 ) { - this.uuid = THREE.Math.generateUUID(); + return true; - this.name = ''; - this.type = 'Geometry'; + } - this.vertices = []; - this.colors = []; - this.faces = []; - this.faceVertexUvs = [ [] ]; + // ray origin is behind the plane (and is pointing behind it) - this.morphTargets = []; - this.morphColors = []; - this.morphNormals = []; + return false; - this.skinWeights = []; - this.skinIndices = []; + }, - this.lineDistances = []; + intersectBox: function ( box, optionalTarget ) { - this.boundingBox = null; - this.boundingSphere = null; + var tmin, tmax, tymin, tymax, tzmin, tzmax; - // update flags + var invdirx = 1 / this.direction.x, + invdiry = 1 / this.direction.y, + invdirz = 1 / this.direction.z; - this.verticesNeedUpdate = false; - this.elementsNeedUpdate = false; - this.uvsNeedUpdate = false; - this.normalsNeedUpdate = false; - this.colorsNeedUpdate = false; - this.lineDistancesNeedUpdate = false; - this.groupsNeedUpdate = false; + var origin = this.origin; -}; + if ( invdirx >= 0 ) { -THREE.Geometry.prototype = { + tmin = ( box.min.x - origin.x ) * invdirx; + tmax = ( box.max.x - origin.x ) * invdirx; - constructor: THREE.Geometry, + } else { - applyMatrix: function ( matrix ) { + tmin = ( box.max.x - origin.x ) * invdirx; + tmax = ( box.min.x - origin.x ) * invdirx; - var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix ); + } - for ( var i = 0, il = this.vertices.length; i < il; i ++ ) { + if ( invdiry >= 0 ) { - var vertex = this.vertices[ i ]; - vertex.applyMatrix4( matrix ); + tymin = ( box.min.y - origin.y ) * invdiry; + tymax = ( box.max.y - origin.y ) * invdiry; - } + } else { - for ( var i = 0, il = this.faces.length; i < il; i ++ ) { + tymin = ( box.max.y - origin.y ) * invdiry; + tymax = ( box.min.y - origin.y ) * invdiry; - var face = this.faces[ i ]; - face.normal.applyMatrix3( normalMatrix ).normalize(); + } - for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) { + if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null; - face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize(); + // 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; - } + if ( tymax < tmax || tmax !== tmax ) tmax = tymax; - if ( this.boundingBox !== null ) { + if ( invdirz >= 0 ) { - this.computeBoundingBox(); + tzmin = ( box.min.z - origin.z ) * invdirz; + tzmax = ( box.max.z - origin.z ) * invdirz; - } + } else { - if ( this.boundingSphere !== null ) { + tzmin = ( box.max.z - origin.z ) * invdirz; + tzmax = ( box.min.z - origin.z ) * invdirz; - this.computeBoundingSphere(); + } - } + if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null; - this.verticesNeedUpdate = true; - this.normalsNeedUpdate = true; + if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin; - }, + if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax; - rotateX: function () { + //return point closest to the ray (positive side) - // rotate geometry around world x-axis + if ( tmax < 0 ) return null; - var m1; + return this.at( tmin >= 0 ? tmin : tmax, optionalTarget ); - return function rotateX( angle ) { + }, - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + intersectsBox: ( function () { - m1.makeRotationX( angle ); + var v = new Vector3(); - this.applyMatrix( m1 ); + return function intersectsBox( box ) { - return this; + return this.intersectBox( box, v ) !== null; - }; + }; - }(), + } )(), - rotateY: function () { + intersectTriangle: function () { - // rotate geometry around world y-axis + // Compute the offset origin, edges, and normal. + var diff = new Vector3(); + var edge1 = new Vector3(); + var edge2 = new Vector3(); + var normal = new Vector3(); - var m1; + return function intersectTriangle( a, b, c, backfaceCulling, optionalTarget ) { - return function rotateY( angle ) { + // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + edge1.subVectors( b, a ); + edge2.subVectors( c, a ); + normal.crossVectors( edge1, edge2 ); - m1.makeRotationY( angle ); + // 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; - this.applyMatrix( m1 ); + if ( DdN > 0 ) { - return this; + if ( backfaceCulling ) return null; + sign = 1; - }; + } else if ( DdN < 0 ) { - }(), + sign = - 1; + DdN = - DdN; - rotateZ: function () { + } else { - // rotate geometry around world z-axis + return null; - var m1; + } - return function rotateZ( angle ) { + diff.subVectors( this.origin, a ); + var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) ); - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + // b1 < 0, no intersection + if ( DdQxE2 < 0 ) { - m1.makeRotationZ( angle ); + return null; - this.applyMatrix( m1 ); + } - return this; + var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) ); - }; + // b2 < 0, no intersection + if ( DdE1xQ < 0 ) { - }(), + return null; - translate: function () { + } - // translate geometry + // b1+b2 > 1, no intersection + if ( DdQxE2 + DdE1xQ > DdN ) { - var m1; + return null; - return function translate( x, y, z ) { + } - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + // Line intersects triangle, check if ray does. + var QdN = - sign * diff.dot( normal ); - m1.makeTranslation( x, y, z ); + // t < 0, no intersection + if ( QdN < 0 ) { - this.applyMatrix( m1 ); + return null; - return this; + } - }; + // Ray intersects triangle. + return this.at( QdN / DdN, optionalTarget ); - }(), + }; - scale: function () { + }(), - // scale geometry + applyMatrix4: function ( matrix4 ) { - var m1; + this.direction.add( this.origin ).applyMatrix4( matrix4 ); + this.origin.applyMatrix4( matrix4 ); + this.direction.sub( this.origin ); + this.direction.normalize(); - return function scale( x, y, z ) { + return this; - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + }, - m1.makeScale( x, y, z ); + equals: function ( ray ) { - this.applyMatrix( m1 ); + return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction ); - return this; + } - }; + }; - }(), + /** + * @author mrdoob / http://mrdoob.com/ + * @author WestLangley / http://github.com/WestLangley + * @author bhouston / http://clara.io + */ - lookAt: function () { + function Euler( x, y, z, order ) { - var obj; + this._x = x || 0; + this._y = y || 0; + this._z = z || 0; + this._order = order || Euler.DefaultOrder; - return function lookAt( vector ) { + } - if ( obj === undefined ) obj = new THREE.Object3D(); + Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ]; - obj.lookAt( vector ); + Euler.DefaultOrder = 'XYZ'; - obj.updateMatrix(); + Euler.prototype = { - this.applyMatrix( obj.matrix ); + constructor: Euler, - }; + isEuler: true, - }(), + get x () { - fromBufferGeometry: function ( geometry ) { + return this._x; - var scope = this; + }, - var indices = geometry.index !== null ? geometry.index.array : undefined; - var attributes = geometry.attributes; + set x ( value ) { - var vertices = 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._x = value; + this.onChangeCallback(); - if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = []; + }, - var tempNormals = []; - var tempUVs = []; - var tempUVs2 = []; + get y () { - for ( var i = 0, j = 0, k = 0; i < vertices.length; i += 3, j += 2, k += 4 ) { + return this._y; - scope.vertices.push( new THREE.Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) ); + }, - if ( normals !== undefined ) { + set y ( value ) { - tempNormals.push( new THREE.Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) ); + this._y = value; + this.onChangeCallback(); - } + }, - if ( colors !== undefined ) { + get z () { - scope.colors.push( new THREE.Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) ); + return this._z; - } + }, - if ( uvs !== undefined ) { + set z ( value ) { - tempUVs.push( new THREE.Vector2( uvs[ j ], uvs[ j + 1 ] ) ); + this._z = value; + this.onChangeCallback(); - } + }, - if ( uvs2 !== undefined ) { + get order () { - tempUVs2.push( new THREE.Vector2( uvs2[ j ], uvs2[ j + 1 ] ) ); + return this._order; - } + }, - } + set order ( value ) { - var addFace = function ( a, b, c ) { + this._order = value; + this.onChangeCallback(); - var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : []; - var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : []; + }, - var face = new THREE.Face3( a, b, c, vertexNormals, vertexColors ); + set: function ( x, y, z, order ) { - scope.faces.push( face ); + this._x = x; + this._y = y; + this._z = z; + this._order = order || this._order; - if ( uvs !== undefined ) { + this.onChangeCallback(); - scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] ); + return this; - } + }, - if ( uvs2 !== undefined ) { + clone: function () { - scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] ); + return new this.constructor( this._x, this._y, this._z, this._order ); - } + }, - }; + copy: function ( euler ) { - if ( indices !== undefined ) { + this._x = euler._x; + this._y = euler._y; + this._z = euler._z; + this._order = euler._order; - var groups = geometry.groups; + this.onChangeCallback(); - if ( groups.length > 0 ) { + return this; - for ( var i = 0; i < groups.length; i ++ ) { + }, - var group = groups[ i ]; + setFromRotationMatrix: function ( m, order, update ) { - var start = group.start; - var count = group.count; + var clamp = exports.Math.clamp; - for ( var j = start, jl = start + count; j < jl; j += 3 ) { + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ] ); + 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 ]; - } + order = order || this._order; - } + if ( order === 'XYZ' ) { - } else { + this._y = Math.asin( clamp( m13, - 1, 1 ) ); - for ( var i = 0; i < indices.length; i += 3 ) { + if ( Math.abs( m13 ) < 0.99999 ) { - addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] ); + this._x = Math.atan2( - m23, m33 ); + this._z = Math.atan2( - m12, m11 ); - } + } else { - } + this._x = Math.atan2( m32, m22 ); + this._z = 0; - } else { + } - for ( var i = 0; i < vertices.length / 3; i += 3 ) { + } else if ( order === 'YXZ' ) { - addFace( i, i + 1, i + 2 ); + this._x = Math.asin( - clamp( m23, - 1, 1 ) ); - } + if ( Math.abs( m23 ) < 0.99999 ) { - } + this._y = Math.atan2( m13, m33 ); + this._z = Math.atan2( m21, m22 ); - this.computeFaceNormals(); + } else { - if ( geometry.boundingBox !== null ) { + this._y = Math.atan2( - m31, m11 ); + this._z = 0; - this.boundingBox = geometry.boundingBox.clone(); + } - } + } else if ( order === 'ZXY' ) { - if ( geometry.boundingSphere !== null ) { + this._x = Math.asin( clamp( m32, - 1, 1 ) ); - this.boundingSphere = geometry.boundingSphere.clone(); + if ( Math.abs( m32 ) < 0.99999 ) { - } + this._y = Math.atan2( - m31, m33 ); + this._z = Math.atan2( - m12, m22 ); - return this; + } else { - }, + this._y = 0; + this._z = Math.atan2( m21, m11 ); - center: function () { + } - this.computeBoundingBox(); + } else if ( order === 'ZYX' ) { - var offset = this.boundingBox.center().negate(); + this._y = Math.asin( - clamp( m31, - 1, 1 ) ); - this.translate( offset.x, offset.y, offset.z ); + if ( Math.abs( m31 ) < 0.99999 ) { - return offset; + this._x = Math.atan2( m32, m33 ); + this._z = Math.atan2( m21, m11 ); - }, + } else { - normalize: function () { + this._x = 0; + this._z = Math.atan2( - m12, m22 ); - this.computeBoundingSphere(); + } - var center = this.boundingSphere.center; - var radius = this.boundingSphere.radius; + } else if ( order === 'YZX' ) { - var s = radius === 0 ? 1 : 1.0 / radius; + this._z = Math.asin( clamp( m21, - 1, 1 ) ); - var matrix = new THREE.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 - ); + if ( Math.abs( m21 ) < 0.99999 ) { - this.applyMatrix( matrix ); + this._x = Math.atan2( - m23, m22 ); + this._y = Math.atan2( - m31, m11 ); - return this; + } else { - }, + this._x = 0; + this._y = Math.atan2( m13, m33 ); - computeFaceNormals: function () { + } - var cb = new THREE.Vector3(), ab = new THREE.Vector3(); + } else if ( order === 'XZY' ) { - for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) { + this._z = Math.asin( - clamp( m12, - 1, 1 ) ); - var face = this.faces[ f ]; + if ( Math.abs( m12 ) < 0.99999 ) { - var vA = this.vertices[ face.a ]; - var vB = this.vertices[ face.b ]; - var vC = this.vertices[ face.c ]; + this._x = Math.atan2( m32, m22 ); + this._y = Math.atan2( m13, m11 ); - cb.subVectors( vC, vB ); - ab.subVectors( vA, vB ); - cb.cross( ab ); + } else { - cb.normalize(); + this._x = Math.atan2( - m23, m33 ); + this._y = 0; - face.normal.copy( cb ); + } - } + } else { - }, + console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order ); - computeVertexNormals: function ( areaWeighted ) { + } - var v, vl, f, fl, face, vertices; + this._order = order; - vertices = new Array( this.vertices.length ); + if ( update !== false ) this.onChangeCallback(); - for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) { + return this; - vertices[ v ] = new THREE.Vector3(); + }, - } + setFromQuaternion: function () { - if ( areaWeighted ) { + var matrix; - // vertex normals weighted by triangle areas - // http://www.iquilezles.org/www/articles/normals/normals.htm + return function setFromQuaternion( q, order, update ) { - var vA, vB, vC; - var cb = new THREE.Vector3(), ab = new THREE.Vector3(); + if ( matrix === undefined ) matrix = new Matrix4(); - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + matrix.makeRotationFromQuaternion( q ); - face = this.faces[ f ]; + return this.setFromRotationMatrix( matrix, order, update ); - vA = this.vertices[ face.a ]; - vB = this.vertices[ face.b ]; - vC = this.vertices[ face.c ]; + }; - cb.subVectors( vC, vB ); - ab.subVectors( vA, vB ); - cb.cross( ab ); + }(), - vertices[ face.a ].add( cb ); - vertices[ face.b ].add( cb ); - vertices[ face.c ].add( cb ); + setFromVector3: function ( v, order ) { - } + return this.set( v.x, v.y, v.z, order || this._order ); - } else { + }, - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + reorder: function () { - face = this.faces[ f ]; + // WARNING: this discards revolution information -bhouston - vertices[ face.a ].add( face.normal ); - vertices[ face.b ].add( face.normal ); - vertices[ face.c ].add( face.normal ); + var q = new Quaternion(); - } + return function reorder( newOrder ) { - } + q.setFromEuler( this ); - for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) { + return this.setFromQuaternion( q, newOrder ); - vertices[ v ].normalize(); + }; - } + }(), - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + equals: function ( euler ) { - face = this.faces[ f ]; + return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order ); - var vertexNormals = face.vertexNormals; + }, - if ( vertexNormals.length === 3 ) { + fromArray: function ( array ) { - vertexNormals[ 0 ].copy( vertices[ face.a ] ); - vertexNormals[ 1 ].copy( vertices[ face.b ] ); - vertexNormals[ 2 ].copy( vertices[ face.c ] ); + this._x = array[ 0 ]; + this._y = array[ 1 ]; + this._z = array[ 2 ]; + if ( array[ 3 ] !== undefined ) this._order = array[ 3 ]; - } else { + this.onChangeCallback(); - vertexNormals[ 0 ] = vertices[ face.a ].clone(); - vertexNormals[ 1 ] = vertices[ face.b ].clone(); - vertexNormals[ 2 ] = vertices[ face.c ].clone(); + return this; - } + }, - } + toArray: function ( array, offset ) { - }, + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - computeMorphNormals: function () { + array[ offset ] = this._x; + array[ offset + 1 ] = this._y; + array[ offset + 2 ] = this._z; + array[ offset + 3 ] = this._order; - var i, il, f, fl, face; + return array; - // 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 ++ ) { + toVector3: function ( optionalResult ) { - face = this.faces[ f ]; + if ( optionalResult ) { - if ( ! face.__originalFaceNormal ) { + return optionalResult.set( this._x, this._y, this._z ); - face.__originalFaceNormal = face.normal.clone(); + } else { - } else { + return new Vector3( this._x, this._y, this._z ); - face.__originalFaceNormal.copy( face.normal ); + } - } + }, - if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = []; + onChange: function ( callback ) { - for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) { + this.onChangeCallback = callback; - if ( ! face.__originalVertexNormals[ i ] ) { + return this; - face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone(); + }, - } else { + onChangeCallback: function () {} - face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] ); + }; - } + /** + * @author mrdoob / http://mrdoob.com/ + */ - } + function Layers() { - } + this.mask = 1; - // use temp geometry to compute face and vertex normals for each morph + } - var tmpGeo = new THREE.Geometry(); - tmpGeo.faces = this.faces; + Layers.prototype = { - for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) { + constructor: Layers, - // create on first access + set: function ( channel ) { - if ( ! this.morphNormals[ i ] ) { + this.mask = 1 << channel; - this.morphNormals[ i ] = {}; - this.morphNormals[ i ].faceNormals = []; - this.morphNormals[ i ].vertexNormals = []; + }, - var dstNormalsFace = this.morphNormals[ i ].faceNormals; - var dstNormalsVertex = this.morphNormals[ i ].vertexNormals; + enable: function ( channel ) { - var faceNormal, vertexNormals; + this.mask |= 1 << channel; - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + }, - faceNormal = new THREE.Vector3(); - vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() }; + toggle: function ( channel ) { - dstNormalsFace.push( faceNormal ); - dstNormalsVertex.push( vertexNormals ); + this.mask ^= 1 << channel; - } + }, - } + disable: function ( channel ) { - var morphNormals = this.morphNormals[ i ]; + this.mask &= ~ ( 1 << channel ); - // set vertices to morph target + }, - tmpGeo.vertices = this.morphTargets[ i ].vertices; + test: function ( layers ) { - // compute morph normals + return ( this.mask & layers.mask ) !== 0; - tmpGeo.computeFaceNormals(); - tmpGeo.computeVertexNormals(); + } - // store morph normals + }; - var faceNormal, vertexNormals; + /** + * @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 + */ - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + function Object3D() { - face = this.faces[ f ]; + Object.defineProperty( this, 'id', { value: Object3DIdCount() } ); - faceNormal = morphNormals.faceNormals[ f ]; - vertexNormals = morphNormals.vertexNormals[ f ]; + this.uuid = exports.Math.generateUUID(); - faceNormal.copy( face.normal ); + this.name = ''; + this.type = 'Object3D'; - vertexNormals.a.copy( face.vertexNormals[ 0 ] ); - vertexNormals.b.copy( face.vertexNormals[ 1 ] ); - vertexNormals.c.copy( face.vertexNormals[ 2 ] ); + this.parent = null; + this.children = []; - } + this.up = Object3D.DefaultUp.clone(); - } + var position = new Vector3(); + var rotation = new Euler(); + var quaternion = new Quaternion(); + var scale = new Vector3( 1, 1, 1 ); - // restore original normals + function onRotationChange() { - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + quaternion.setFromEuler( rotation, false ); - face = this.faces[ f ]; + } - face.normal = face.__originalFaceNormal; - face.vertexNormals = face.__originalVertexNormals; + function onQuaternionChange() { - } + rotation.setFromQuaternion( quaternion, undefined, false ); - }, + } - computeTangents: function () { + rotation.onChange( onRotationChange ); + quaternion.onChange( onQuaternionChange ); - console.warn( 'THREE.Geometry: .computeTangents() has been removed.' ); + Object.defineProperties( this, { + position: { + enumerable: true, + value: position + }, + rotation: { + enumerable: true, + value: rotation + }, + quaternion: { + enumerable: true, + value: quaternion + }, + scale: { + enumerable: true, + value: scale + }, + modelViewMatrix: { + value: new Matrix4() + }, + normalMatrix: { + value: new Matrix3() + } + } ); - }, + this.matrix = new Matrix4(); + this.matrixWorld = new Matrix4(); - computeLineDistances: function () { + this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate; + this.matrixWorldNeedsUpdate = false; - var d = 0; - var vertices = this.vertices; + this.layers = new Layers(); + this.visible = true; - for ( var i = 0, il = vertices.length; i < il; i ++ ) { + this.castShadow = false; + this.receiveShadow = false; - if ( i > 0 ) { + this.frustumCulled = true; + this.renderOrder = 0; - d += vertices[ i ].distanceTo( vertices[ i - 1 ] ); + this.userData = {}; - } + this.onBeforeRender = null; - this.lineDistances[ i ] = d; + } - } + Object3D.DefaultUp = new Vector3( 0, 1, 0 ); + Object3D.DefaultMatrixAutoUpdate = true; - }, + Object.assign( Object3D.prototype, EventDispatcher.prototype, { - computeBoundingBox: function () { + isObject3D: true, - if ( this.boundingBox === null ) { + applyMatrix: function ( matrix ) { - this.boundingBox = new THREE.Box3(); + this.matrix.multiplyMatrices( matrix, this.matrix ); - } + this.matrix.decompose( this.position, this.quaternion, this.scale ); - this.boundingBox.setFromPoints( this.vertices ); + }, - }, + setRotationFromAxisAngle: function ( axis, angle ) { - computeBoundingSphere: function () { + // assumes axis is normalized - if ( this.boundingSphere === null ) { + this.quaternion.setFromAxisAngle( axis, angle ); - this.boundingSphere = new THREE.Sphere(); + }, - } + setRotationFromEuler: function ( euler ) { - this.boundingSphere.setFromPoints( this.vertices ); + this.quaternion.setFromEuler( euler, true ); - }, + }, - merge: function ( geometry, matrix, materialIndexOffset ) { + setRotationFromMatrix: function ( m ) { - if ( geometry instanceof THREE.Geometry === false ) { + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry ); - return; + this.quaternion.setFromRotationMatrix( m ); - } + }, - 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 ]; + setRotationFromQuaternion: function ( q ) { - if ( materialIndexOffset === undefined ) materialIndexOffset = 0; + // assumes q is normalized - if ( matrix !== undefined ) { + this.quaternion.copy( q ); - normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix ); + }, - } + rotateOnAxis: function () { - // vertices + // rotate object on axis in object space + // axis is assumed to be normalized - for ( var i = 0, il = vertices2.length; i < il; i ++ ) { + var q1 = new Quaternion(); - var vertex = vertices2[ i ]; + return function rotateOnAxis( axis, angle ) { - var vertexCopy = vertex.clone(); + q1.setFromAxisAngle( axis, angle ); - if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix ); + this.quaternion.multiply( q1 ); - vertices1.push( vertexCopy ); + return this; - } + }; - // faces + }(), - for ( i = 0, il = faces2.length; i < il; i ++ ) { + rotateX: function () { - var face = faces2[ i ], faceCopy, normal, color, - faceVertexNormals = face.vertexNormals, - faceVertexColors = face.vertexColors; + var v1 = new Vector3( 1, 0, 0 ); - faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset ); - faceCopy.normal.copy( face.normal ); + return function rotateX( angle ) { - if ( normalMatrix !== undefined ) { + return this.rotateOnAxis( v1, angle ); - faceCopy.normal.applyMatrix3( normalMatrix ).normalize(); + }; - } + }(), - for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) { + rotateY: function () { - normal = faceVertexNormals[ j ].clone(); + var v1 = new Vector3( 0, 1, 0 ); - if ( normalMatrix !== undefined ) { + return function rotateY( angle ) { - normal.applyMatrix3( normalMatrix ).normalize(); + return this.rotateOnAxis( v1, angle ); - } + }; - faceCopy.vertexNormals.push( normal ); + }(), - } + rotateZ: function () { - faceCopy.color.copy( face.color ); + var v1 = new Vector3( 0, 0, 1 ); - for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) { + return function rotateZ( angle ) { - color = faceVertexColors[ j ]; - faceCopy.vertexColors.push( color.clone() ); + return this.rotateOnAxis( v1, angle ); - } + }; - faceCopy.materialIndex = face.materialIndex + materialIndexOffset; + }(), - faces1.push( faceCopy ); + translateOnAxis: function () { - } + // translate object by distance along axis in object space + // axis is assumed to be normalized - // uvs + var v1 = new Vector3(); - for ( i = 0, il = uvs2.length; i < il; i ++ ) { + return function translateOnAxis( axis, distance ) { - var uv = uvs2[ i ], uvCopy = []; + v1.copy( axis ).applyQuaternion( this.quaternion ); - if ( uv === undefined ) { + this.position.add( v1.multiplyScalar( distance ) ); - continue; + return this; - } + }; - for ( var j = 0, jl = uv.length; j < jl; j ++ ) { + }(), - uvCopy.push( uv[ j ].clone() ); + translateX: function () { - } + var v1 = new Vector3( 1, 0, 0 ); - uvs1.push( uvCopy ); + return function translateX( distance ) { - } + return this.translateOnAxis( v1, distance ); - }, + }; - mergeMesh: function ( mesh ) { + }(), - if ( mesh instanceof THREE.Mesh === false ) { + translateY: function () { - console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh ); - return; + var v1 = new Vector3( 0, 1, 0 ); - } + return function translateY( distance ) { - mesh.matrixAutoUpdate && mesh.updateMatrix(); + return this.translateOnAxis( v1, distance ); - this.merge( mesh.geometry, mesh.matrix ); + }; - }, + }(), - /* - * Checks for duplicate vertices with hashmap. - * Duplicated vertices are removed - * and faces' vertices are updated. - */ + translateZ: function () { - mergeVertices: function () { + var v1 = new Vector3( 0, 0, 1 ); - var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique) - var unique = [], changes = []; + return function translateZ( distance ) { - 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; + return this.translateOnAxis( v1, distance ); - for ( i = 0, il = this.vertices.length; i < il; i ++ ) { + }; - v = this.vertices[ i ]; - key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision ); + }(), - if ( verticesMap[ key ] === undefined ) { + localToWorld: function ( vector ) { - verticesMap[ key ] = i; - unique.push( this.vertices[ i ] ); - changes[ i ] = unique.length - 1; + return vector.applyMatrix4( this.matrixWorld ); - } else { + }, - //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]); - changes[ i ] = changes[ verticesMap[ key ] ]; + worldToLocal: function () { - } + var m1 = new Matrix4(); - } + return function worldToLocal( vector ) { + return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) ); - // if faces are completely degenerate after merging vertices, we - // have to remove them from the geometry. - var faceIndicesToRemove = []; + }; - for ( i = 0, il = this.faces.length; i < il; i ++ ) { + }(), - face = this.faces[ i ]; + lookAt: function () { - face.a = changes[ face.a ]; - face.b = changes[ face.b ]; - face.c = changes[ face.c ]; + // This routine does not support objects with rotated and/or translated parent(s) - indices = [ face.a, face.b, face.c ]; + var m1 = new Matrix4(); - var dupIndex = - 1; + return function lookAt( vector ) { - // 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 ++ ) { + m1.lookAt( vector, this.position, this.up ); - if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) { + this.quaternion.setFromRotationMatrix( m1 ); - dupIndex = n; - faceIndicesToRemove.push( i ); - break; + }; - } + }(), - } + add: function ( object ) { - } + if ( arguments.length > 1 ) { - for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) { + for ( var i = 0; i < arguments.length; i ++ ) { - var idx = faceIndicesToRemove[ i ]; + this.add( arguments[ i ] ); - this.faces.splice( idx, 1 ); + } - for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) { + return this; - this.faceVertexUvs[ j ].splice( idx, 1 ); + } - } + if ( object === this ) { - } + console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object ); + return this; - // Use unique set of vertices + } - var diff = this.vertices.length - unique.length; - this.vertices = unique; - return diff; + if ( (object && object.isObject3D) ) { - }, + if ( object.parent !== null ) { - toJSON: function () { + object.parent.remove( object ); - var data = { - metadata: { - version: 4.4, - type: 'Geometry', - generator: 'Geometry.toJSON' - } - }; + } - // standard Geometry serialization + object.parent = this; + object.dispatchEvent( { type: 'added' } ); - data.uuid = this.uuid; - data.type = this.type; - if ( this.name !== '' ) data.name = this.name; + this.children.push( object ); - if ( this.parameters !== undefined ) { + } else { - var parameters = this.parameters; + console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object ); - for ( var key in parameters ) { + } - if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ]; + return this; - } + }, - return data; + remove: function ( object ) { - } + if ( arguments.length > 1 ) { - var vertices = []; + for ( var i = 0; i < arguments.length; i ++ ) { - for ( var i = 0; i < this.vertices.length; i ++ ) { + this.remove( arguments[ i ] ); - var vertex = this.vertices[ i ]; - vertices.push( vertex.x, vertex.y, vertex.z ); + } - } + } - var faces = []; - var normals = []; - var normalsHash = {}; - var colors = []; - var colorsHash = {}; - var uvs = []; - var uvsHash = {}; + var index = this.children.indexOf( object ); - for ( var i = 0; i < this.faces.length; i ++ ) { + if ( index !== - 1 ) { - var face = this.faces[ i ]; + object.parent = null; - var hasMaterial = false; // face.materialIndex !== undefined; - 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; + object.dispatchEvent( { type: 'removed' } ); - var faceType = 0; + this.children.splice( index, 1 ); - faceType = setBit( faceType, 0, 0 ); - 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 ); + } - faces.push( faceType ); - faces.push( face.a, face.b, face.c ); + }, - if ( hasFaceVertexUv ) { + getObjectById: function ( id ) { - var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ]; + return this.getObjectByProperty( 'id', id ); - faces.push( - getUvIndex( faceVertexUvs[ 0 ] ), - getUvIndex( faceVertexUvs[ 1 ] ), - getUvIndex( faceVertexUvs[ 2 ] ) - ); + }, - } + getObjectByName: function ( name ) { - if ( hasFaceNormal ) { + return this.getObjectByProperty( 'name', name ); - faces.push( getNormalIndex( face.normal ) ); + }, - } + getObjectByProperty: function ( name, value ) { - if ( hasFaceVertexNormal ) { + if ( this[ name ] === value ) return this; - var vertexNormals = face.vertexNormals; + for ( var i = 0, l = this.children.length; i < l; i ++ ) { - faces.push( - getNormalIndex( vertexNormals[ 0 ] ), - getNormalIndex( vertexNormals[ 1 ] ), - getNormalIndex( vertexNormals[ 2 ] ) - ); + var child = this.children[ i ]; + var object = child.getObjectByProperty( name, value ); - } + if ( object !== undefined ) { - if ( hasFaceColor ) { + return object; - faces.push( getColorIndex( face.color ) ); + } - } + } - if ( hasFaceVertexColor ) { + return undefined; - var vertexColors = face.vertexColors; + }, - faces.push( - getColorIndex( vertexColors[ 0 ] ), - getColorIndex( vertexColors[ 1 ] ), - getColorIndex( vertexColors[ 2 ] ) - ); + getWorldPosition: function ( optionalTarget ) { - } + var result = optionalTarget || new Vector3(); - } + this.updateMatrixWorld( true ); - function setBit( value, position, enabled ) { + return result.setFromMatrixPosition( this.matrixWorld ); - return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) ); + }, - } + getWorldQuaternion: function () { - function getNormalIndex( normal ) { + var position = new Vector3(); + var scale = new Vector3(); - var hash = normal.x.toString() + normal.y.toString() + normal.z.toString(); + return function getWorldQuaternion( optionalTarget ) { - if ( normalsHash[ hash ] !== undefined ) { + var result = optionalTarget || new Quaternion(); - return normalsHash[ hash ]; + this.updateMatrixWorld( true ); - } + this.matrixWorld.decompose( position, result, scale ); - normalsHash[ hash ] = normals.length / 3; - normals.push( normal.x, normal.y, normal.z ); + return result; - return normalsHash[ hash ]; + }; - } + }(), - function getColorIndex( color ) { + getWorldRotation: function () { - var hash = color.r.toString() + color.g.toString() + color.b.toString(); + var quaternion = new Quaternion(); - if ( colorsHash[ hash ] !== undefined ) { + return function getWorldRotation( optionalTarget ) { - return colorsHash[ hash ]; + var result = optionalTarget || new Euler(); - } + this.getWorldQuaternion( quaternion ); - colorsHash[ hash ] = colors.length; - colors.push( color.getHex() ); + return result.setFromQuaternion( quaternion, this.rotation.order, false ); - return colorsHash[ hash ]; + }; - } + }(), - function getUvIndex( uv ) { + getWorldScale: function () { - var hash = uv.x.toString() + uv.y.toString(); + var position = new Vector3(); + var quaternion = new Quaternion(); - if ( uvsHash[ hash ] !== undefined ) { + return function getWorldScale( optionalTarget ) { - return uvsHash[ hash ]; + var result = optionalTarget || new Vector3(); - } + this.updateMatrixWorld( true ); - uvsHash[ hash ] = uvs.length / 2; - uvs.push( uv.x, uv.y ); + this.matrixWorld.decompose( position, quaternion, result ); - return uvsHash[ hash ]; + return result; - } + }; - 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; + getWorldDirection: function () { - return data; + var quaternion = new Quaternion(); - }, + return function getWorldDirection( optionalTarget ) { - clone: function () { + var result = optionalTarget || new Vector3(); - return new this.constructor().copy( this ); + this.getWorldQuaternion( quaternion ); - }, + return result.set( 0, 0, 1 ).applyQuaternion( quaternion ); - copy: function ( source ) { + }; - this.vertices = []; - this.faces = []; - this.faceVertexUvs = [ [] ]; + }(), - var vertices = source.vertices; + raycast: function () {}, - for ( var i = 0, il = vertices.length; i < il; i ++ ) { + traverse: function ( callback ) { - this.vertices.push( vertices[ i ].clone() ); + callback( this ); - } + var children = this.children; - var faces = source.faces; + for ( var i = 0, l = children.length; i < l; i ++ ) { - for ( var i = 0, il = faces.length; i < il; i ++ ) { + children[ i ].traverse( callback ); - this.faces.push( faces[ i ].clone() ); + } - } + }, - for ( var i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) { + traverseVisible: function ( callback ) { - var faceVertexUvs = source.faceVertexUvs[ i ]; + if ( this.visible === false ) return; - if ( this.faceVertexUvs[ i ] === undefined ) { + callback( this ); - this.faceVertexUvs[ i ] = []; + var children = this.children; - } + for ( var i = 0, l = children.length; i < l; i ++ ) { - for ( var j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) { + children[ i ].traverseVisible( callback ); - var uvs = faceVertexUvs[ j ], uvsCopy = []; + } - for ( var k = 0, kl = uvs.length; k < kl; k ++ ) { + }, - var uv = uvs[ k ]; + traverseAncestors: function ( callback ) { - uvsCopy.push( uv.clone() ); + var parent = this.parent; - } + if ( parent !== null ) { - this.faceVertexUvs[ i ].push( uvsCopy ); + callback( parent ); - } + parent.traverseAncestors( callback ); - } + } - return this; + }, - }, + updateMatrix: function () { - dispose: function () { + this.matrix.compose( this.position, this.quaternion, this.scale ); - this.dispatchEvent( { type: 'dispose' } ); + this.matrixWorldNeedsUpdate = true; - } + }, -}; + updateMatrixWorld: function ( force ) { -THREE.EventDispatcher.prototype.apply( THREE.Geometry.prototype ); + if ( this.matrixAutoUpdate === true ) this.updateMatrix(); -THREE.GeometryIdCount = 0; + if ( this.matrixWorldNeedsUpdate === true || force === true ) { -// File:src/core/DirectGeometry.js + if ( this.parent === null ) { -/** - * @author mrdoob / http://mrdoob.com/ - */ + this.matrixWorld.copy( this.matrix ); -THREE.DirectGeometry = function () { + } else { - Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } ); + this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); - this.uuid = THREE.Math.generateUUID(); + } - this.name = ''; - this.type = 'DirectGeometry'; + this.matrixWorldNeedsUpdate = false; - this.indices = []; - this.vertices = []; - this.normals = []; - this.colors = []; - this.uvs = []; - this.uvs2 = []; + force = true; - this.groups = []; + } - this.morphTargets = {}; + // update children - this.skinWeights = []; - this.skinIndices = []; + var children = this.children; - // this.lineDistances = []; + for ( var i = 0, l = children.length; i < l; i ++ ) { - this.boundingBox = null; - this.boundingSphere = null; + children[ i ].updateMatrixWorld( force ); - // update flags + } - this.verticesNeedUpdate = false; - this.normalsNeedUpdate = false; - this.colorsNeedUpdate = false; - this.uvsNeedUpdate = false; - this.groupsNeedUpdate = false; + }, -}; + toJSON: function ( meta ) { -THREE.DirectGeometry.prototype = { + // meta is '' when called from JSON.stringify + var isRootObject = ( meta === undefined || meta === '' ); - constructor: THREE.DirectGeometry, + var output = {}; - computeBoundingBox: THREE.Geometry.prototype.computeBoundingBox, - computeBoundingSphere: THREE.Geometry.prototype.computeBoundingSphere, + // meta is a hash used to collect geometries, materials. + // not providing it implies that this is the root object + // being serialized. + if ( isRootObject ) { - computeFaceNormals: function () { + // initialize meta obj + meta = { + geometries: {}, + materials: {}, + textures: {}, + images: {} + }; - console.warn( 'THREE.DirectGeometry: computeFaceNormals() is not a method of this type of geometry.' ); + output.metadata = { + version: 4.4, + type: 'Object', + generator: 'Object3D.toJSON' + }; - }, + } - computeVertexNormals: function () { + // standard Object3D serialization - console.warn( 'THREE.DirectGeometry: computeVertexNormals() is not a method of this type of geometry.' ); + var object = {}; - }, + object.uuid = this.uuid; + object.type = this.type; - computeGroups: function ( geometry ) { + 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; - var group; - var groups = []; - var materialIndex; + object.matrix = this.matrix.toArray(); - var faces = geometry.faces; + // - for ( var i = 0; i < faces.length; i ++ ) { + if ( this.geometry !== undefined ) { - var face = faces[ i ]; + if ( meta.geometries[ this.geometry.uuid ] === undefined ) { - // materials + meta.geometries[ this.geometry.uuid ] = this.geometry.toJSON( meta ); - if ( face.materialIndex !== materialIndex ) { + } - materialIndex = face.materialIndex; + object.geometry = this.geometry.uuid; - if ( group !== undefined ) { + } - group.count = ( i * 3 ) - group.start; - groups.push( group ); + if ( this.material !== undefined ) { - } + if ( meta.materials[ this.material.uuid ] === undefined ) { - group = { - start: i * 3, - materialIndex: materialIndex - }; + meta.materials[ this.material.uuid ] = this.material.toJSON( meta ); - } + } - } + object.material = this.material.uuid; - if ( group !== undefined ) { + } - group.count = ( i * 3 ) - group.start; - groups.push( group ); + // - } + if ( this.children.length > 0 ) { - this.groups = groups; + object.children = []; - }, + for ( var i = 0; i < this.children.length; i ++ ) { - fromGeometry: function ( geometry ) { + object.children.push( this.children[ i ].toJSON( meta ).object ); - 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; + } - // morphs + if ( isRootObject ) { - var morphTargets = geometry.morphTargets; - var morphTargetsLength = morphTargets.length; + var geometries = extractFromCache( meta.geometries ); + var materials = extractFromCache( meta.materials ); + var textures = extractFromCache( meta.textures ); + var images = extractFromCache( meta.images ); - if ( morphTargetsLength > 0 ) { + if ( geometries.length > 0 ) output.geometries = geometries; + if ( materials.length > 0 ) output.materials = materials; + if ( textures.length > 0 ) output.textures = textures; + if ( images.length > 0 ) output.images = images; - var morphTargetsPosition = []; + } - for ( var i = 0; i < morphTargetsLength; i ++ ) { + output.object = object; - morphTargetsPosition[ i ] = []; + return output; - } + // extract data from the cache hash + // remove metadata on each item + // and return as array + function extractFromCache( cache ) { - this.morphTargets.position = morphTargetsPosition; + var values = []; + for ( var key in cache ) { - } + var data = cache[ key ]; + delete data.metadata; + values.push( data ); - var morphNormals = geometry.morphNormals; - var morphNormalsLength = morphNormals.length; + } + return values; - if ( morphNormalsLength > 0 ) { + } - var morphTargetsNormal = []; + }, - for ( var i = 0; i < morphNormalsLength; i ++ ) { + clone: function ( recursive ) { - morphTargetsNormal[ i ] = []; + return new this.constructor().copy( this, recursive ); - } + }, - this.morphTargets.normal = morphTargetsNormal; + copy: function ( source, recursive ) { - } + if ( recursive === undefined ) recursive = true; - // skins + this.name = source.name; - var skinIndices = geometry.skinIndices; - var skinWeights = geometry.skinWeights; + this.up.copy( source.up ); - var hasSkinIndices = skinIndices.length === vertices.length; - var hasSkinWeights = skinWeights.length === vertices.length; + 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 ); - for ( var i = 0; i < faces.length; i ++ ) { + this.matrixAutoUpdate = source.matrixAutoUpdate; + this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate; - var face = faces[ i ]; + this.visible = source.visible; - this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] ); + this.castShadow = source.castShadow; + this.receiveShadow = source.receiveShadow; - var vertexNormals = face.vertexNormals; + this.frustumCulled = source.frustumCulled; + this.renderOrder = source.renderOrder; - if ( vertexNormals.length === 3 ) { + this.userData = JSON.parse( JSON.stringify( source.userData ) ); - this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] ); + if ( recursive === true ) { - } else { + for ( var i = 0; i < source.children.length; i ++ ) { - var normal = face.normal; + var child = source.children[ i ]; + this.add( child.clone() ); - this.normals.push( normal, normal, normal ); + } - } + } - var vertexColors = face.vertexColors; + return this; - if ( vertexColors.length === 3 ) { + } - this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] ); + } ); - } else { + var count$2 = 0; + function Object3DIdCount() { return count$2++; }; - var color = face.color; + /** + * @author bhouston / http://clara.io + */ - this.colors.push( color, color, color ); + function Line3( start, end ) { - } + this.start = ( start !== undefined ) ? start : new Vector3(); + this.end = ( end !== undefined ) ? end : new Vector3(); - if ( hasFaceVertexUv === true ) { + } - var vertexUvs = faceVertexUvs[ 0 ][ i ]; + Line3.prototype = { - if ( vertexUvs !== undefined ) { + constructor: Line3, - this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] ); + set: function ( start, end ) { - } else { + this.start.copy( start ); + this.end.copy( end ); - console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i ); + return this; - this.uvs.push( new THREE.Vector2(), new THREE.Vector2(), new THREE.Vector2() ); + }, - } + clone: function () { - } + return new this.constructor().copy( this ); - if ( hasFaceVertexUv2 === true ) { + }, - var vertexUvs = faceVertexUvs[ 1 ][ i ]; + copy: function ( line ) { - if ( vertexUvs !== undefined ) { + this.start.copy( line.start ); + this.end.copy( line.end ); - this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] ); + return this; - } else { + }, - console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i ); + getCenter: function ( optionalTarget ) { - this.uvs2.push( new THREE.Vector2(), new THREE.Vector2(), new THREE.Vector2() ); + var result = optionalTarget || new Vector3(); + return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 ); - } + }, - } + delta: function ( optionalTarget ) { - // morphs + var result = optionalTarget || new Vector3(); + return result.subVectors( this.end, this.start ); - for ( var j = 0; j < morphTargetsLength; j ++ ) { + }, - var morphTarget = morphTargets[ j ].vertices; + distanceSq: function () { - morphTargetsPosition[ j ].push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] ); + return this.start.distanceToSquared( this.end ); - } + }, - for ( var j = 0; j < morphNormalsLength; j ++ ) { + distance: function () { - var morphNormal = morphNormals[ j ].vertexNormals[ i ]; + return this.start.distanceTo( this.end ); - morphTargetsNormal[ j ].push( morphNormal.a, morphNormal.b, morphNormal.c ); + }, - } + at: function ( t, optionalTarget ) { - // skins + var result = optionalTarget || new Vector3(); - if ( hasSkinIndices ) { + return this.delta( result ).multiplyScalar( t ).add( this.start ); - this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] ); + }, - } + closestPointToPointParameter: function () { - if ( hasSkinWeights ) { + var startP = new Vector3(); + var startEnd = new Vector3(); - this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] ); + return function closestPointToPointParameter( point, clampToLine ) { - } + startP.subVectors( point, this.start ); + startEnd.subVectors( this.end, this.start ); - } + var startEnd2 = startEnd.dot( startEnd ); + var startEnd_startP = startEnd.dot( startP ); - this.computeGroups( geometry ); + var t = startEnd_startP / startEnd2; - this.verticesNeedUpdate = geometry.verticesNeedUpdate; - this.normalsNeedUpdate = geometry.normalsNeedUpdate; - this.colorsNeedUpdate = geometry.colorsNeedUpdate; - this.uvsNeedUpdate = geometry.uvsNeedUpdate; - this.groupsNeedUpdate = geometry.groupsNeedUpdate; + if ( clampToLine ) { - return this; + t = exports.Math.clamp( t, 0, 1 ); - }, + } - dispose: function () { + return t; - this.dispatchEvent( { type: 'dispose' } ); + }; - } + }(), -}; + closestPointToPoint: function ( point, clampToLine, optionalTarget ) { -THREE.EventDispatcher.prototype.apply( THREE.DirectGeometry.prototype ); + var t = this.closestPointToPointParameter( point, clampToLine ); -// File:src/core/BufferGeometry.js + var result = optionalTarget || new Vector3(); -/** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - */ + return this.delta( result ).multiplyScalar( t ).add( this.start ); -THREE.BufferGeometry = function () { + }, - Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } ); + applyMatrix4: function ( matrix ) { - this.uuid = THREE.Math.generateUUID(); + this.start.applyMatrix4( matrix ); + this.end.applyMatrix4( matrix ); - this.name = ''; - this.type = 'BufferGeometry'; + return this; - this.index = null; - this.attributes = {}; + }, - this.morphAttributes = {}; + equals: function ( line ) { - this.groups = []; + return line.start.equals( this.start ) && line.end.equals( this.end ); - this.boundingBox = null; - this.boundingSphere = null; + } - this.drawRange = { start: 0, count: Infinity }; + }; -}; + /** + * @author bhouston / http://clara.io + * @author mrdoob / http://mrdoob.com/ + */ -THREE.BufferGeometry.prototype = { + function Triangle( a, b, c ) { - constructor: THREE.BufferGeometry, + this.a = ( a !== undefined ) ? a : new Vector3(); + this.b = ( b !== undefined ) ? b : new Vector3(); + this.c = ( c !== undefined ) ? c : new Vector3(); - addIndex: function ( index ) { + } - console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' ); - this.setIndex( index ); + Triangle.normal = function () { - }, + var v0 = new Vector3(); - getIndex: function () { + return function normal( a, b, c, optionalTarget ) { - return this.index; + var result = optionalTarget || new Vector3(); - }, + result.subVectors( c, b ); + v0.subVectors( a, b ); + result.cross( v0 ); - setIndex: function ( index ) { + var resultLengthSq = result.lengthSq(); + if ( resultLengthSq > 0 ) { - this.index = index; + return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) ); - }, + } - addAttribute: function ( name, attribute ) { + return result.set( 0, 0, 0 ); - if ( attribute instanceof THREE.BufferAttribute === false && attribute instanceof THREE.InterleavedBufferAttribute === false ) { + }; - console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' ); + }(); - this.addAttribute( name, new THREE.BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) ); + // static/instance method to calculate barycentric coordinates + // based on: http://www.blackpawn.com/texts/pointinpoly/default.html + Triangle.barycoordFromPoint = function () { - return; + var v0 = new Vector3(); + var v1 = new Vector3(); + var v2 = new Vector3(); - } + return function barycoordFromPoint( point, a, b, c, optionalTarget ) { - if ( name === 'index' ) { + v0.subVectors( c, a ); + v1.subVectors( b, a ); + v2.subVectors( point, a ); - console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' ); - this.setIndex( attribute ); + var dot00 = v0.dot( v0 ); + var dot01 = v0.dot( v1 ); + var dot02 = v0.dot( v2 ); + var dot11 = v1.dot( v1 ); + var dot12 = v1.dot( v2 ); - } + var denom = ( dot00 * dot11 - dot01 * dot01 ); - this.attributes[ name ] = attribute; + var result = optionalTarget || new Vector3(); - }, + // collinear or singular triangle + if ( denom === 0 ) { - getAttribute: function ( name ) { + // arbitrary location outside of triangle? + // not sure if this is the best idea, maybe should be returning undefined + return result.set( - 2, - 1, - 1 ); - return this.attributes[ name ]; + } - }, + var invDenom = 1 / denom; + var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom; + var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom; - removeAttribute: function ( name ) { + // barycentric coordinates must always sum to 1 + return result.set( 1 - u - v, v, u ); - delete this.attributes[ name ]; + }; - }, + }(); - get drawcalls() { + Triangle.containsPoint = function () { - console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' ); - return this.groups; + var v1 = new Vector3(); - }, + return function containsPoint( point, a, b, c ) { - get offsets() { + var result = Triangle.barycoordFromPoint( point, a, b, c, v1 ); - console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' ); - return this.groups; + return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 ); - }, + }; - addDrawCall: function ( start, count, indexOffset ) { + }(); - if ( indexOffset !== undefined ) { + Triangle.prototype = { - console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' ); + constructor: Triangle, - } + set: function ( a, b, c ) { - console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' ); - this.addGroup( start, count ); + this.a.copy( a ); + this.b.copy( b ); + this.c.copy( c ); - }, + return this; - clearDrawCalls: function () { + }, - console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' ); - this.clearGroups(); + setFromPointsAndIndices: function ( points, i0, i1, i2 ) { - }, + this.a.copy( points[ i0 ] ); + this.b.copy( points[ i1 ] ); + this.c.copy( points[ i2 ] ); - addGroup: function ( start, count, materialIndex ) { + return this; - this.groups.push( { + }, - start: start, - count: count, - materialIndex: materialIndex !== undefined ? materialIndex : 0 + clone: function () { - } ); + return new this.constructor().copy( this ); - }, + }, - clearGroups: function () { + copy: function ( triangle ) { - this.groups = []; + this.a.copy( triangle.a ); + this.b.copy( triangle.b ); + this.c.copy( triangle.c ); - }, + return this; - setDrawRange: function ( start, count ) { + }, - this.drawRange.start = start; - this.drawRange.count = count; + area: function () { - }, + var v0 = new Vector3(); + var v1 = new Vector3(); - applyMatrix: function ( matrix ) { + return function area() { - var position = this.attributes.position; + v0.subVectors( this.c, this.b ); + v1.subVectors( this.a, this.b ); - if ( position !== undefined ) { + return v0.cross( v1 ).length() * 0.5; - matrix.applyToVector3Array( position.array ); - position.needsUpdate = true; + }; - } + }(), - var normal = this.attributes.normal; + midpoint: function ( optionalTarget ) { - if ( normal !== undefined ) { + var result = optionalTarget || new Vector3(); + return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 ); - var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix ); + }, - normalMatrix.applyToVector3Array( normal.array ); - normal.needsUpdate = true; + normal: function ( optionalTarget ) { - } + return Triangle.normal( this.a, this.b, this.c, optionalTarget ); - if ( this.boundingBox !== null ) { + }, - this.computeBoundingBox(); + plane: function ( optionalTarget ) { - } + var result = optionalTarget || new Plane(); - if ( this.boundingSphere !== null ) { + return result.setFromCoplanarPoints( this.a, this.b, this.c ); - this.computeBoundingSphere(); + }, - } + barycoordFromPoint: function ( point, optionalTarget ) { - }, + return Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget ); - rotateX: function () { + }, - // rotate geometry around world x-axis + containsPoint: function ( point ) { - var m1; + return Triangle.containsPoint( point, this.a, this.b, this.c ); - return function rotateX( angle ) { + }, - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + closestPointToPoint: function () { - m1.makeRotationX( angle ); + var plane, edgeList, projectedPoint, closestPoint; - this.applyMatrix( m1 ); + return function closestPointToPoint( point, optionalTarget ) { - return this; + if ( plane === undefined ) { - }; + plane = new Plane(); + edgeList = [ new Line3(), new Line3(), new Line3() ]; + projectedPoint = new Vector3(); + closestPoint = new Vector3(); - }(), + } - rotateY: function () { + var result = optionalTarget || new Vector3(); + var minDistance = Infinity; - // rotate geometry around world y-axis + // project the point onto the plane of the triangle - var m1; + plane.setFromCoplanarPoints( this.a, this.b, this.c ); + plane.projectPoint( point, projectedPoint ); - return function rotateY( angle ) { + // check if the projection lies within the triangle - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + if( this.containsPoint( projectedPoint ) === true ) { - m1.makeRotationY( angle ); + // if so, this is the closest point - this.applyMatrix( m1 ); + result.copy( projectedPoint ); - return this; + } else { - }; + // if not, the point falls outside the triangle. the result is the closest point to the triangle's edges or vertices - }(), + edgeList[ 0 ].set( this.a, this.b ); + edgeList[ 1 ].set( this.b, this.c ); + edgeList[ 2 ].set( this.c, this.a ); - rotateZ: function () { + for( var i = 0; i < edgeList.length; i ++ ) { - // rotate geometry around world z-axis + edgeList[ i ].closestPointToPoint( projectedPoint, true, closestPoint ); - var m1; + var distance = projectedPoint.distanceToSquared( closestPoint ); - return function rotateZ( angle ) { + if( distance < minDistance ) { - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + minDistance = distance; - m1.makeRotationZ( angle ); + result.copy( closestPoint ); - this.applyMatrix( m1 ); + } - return this; + } - }; + } - }(), + return result; - translate: function () { + }; - // translate geometry + }(), - var m1; + equals: function ( triangle ) { - return function translate( x, y, z ) { + return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c ); - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + } - m1.makeTranslation( x, y, z ); + }; - this.applyMatrix( m1 ); + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - return this; + function Face3( a, b, c, normal, color, materialIndex ) { - }; + this.a = a; + this.b = b; + this.c = c; - }(), + this.normal = (normal && normal.isVector3) ? normal : new Vector3(); + this.vertexNormals = Array.isArray( normal ) ? normal : []; - scale: function () { + this.color = (color && color.isColor) ? color : new Color(); + this.vertexColors = Array.isArray( color ) ? color : []; - // scale geometry + this.materialIndex = materialIndex !== undefined ? materialIndex : 0; - var m1; + } - return function scale( x, y, z ) { + Face3.prototype = { - if ( m1 === undefined ) m1 = new THREE.Matrix4(); + constructor: Face3, - m1.makeScale( x, y, z ); + clone: function () { - this.applyMatrix( m1 ); + return new this.constructor().copy( this ); - return this; + }, - }; + copy: function ( source ) { - }(), + this.a = source.a; + this.b = source.b; + this.c = source.c; - lookAt: function () { + this.normal.copy( source.normal ); + this.color.copy( source.color ); - var obj; + this.materialIndex = source.materialIndex; - return function lookAt( vector ) { + for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) { - if ( obj === undefined ) obj = new THREE.Object3D(); + this.vertexNormals[ i ] = source.vertexNormals[ i ].clone(); - obj.lookAt( vector ); + } - obj.updateMatrix(); + for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) { - this.applyMatrix( obj.matrix ); + this.vertexColors[ i ] = source.vertexColors[ i ].clone(); - }; + } - }(), + return this; - center: function () { + } - this.computeBoundingBox(); + }; - var offset = this.boundingBox.center().negate(); + /** + * @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: + * } + */ - this.translate( offset.x, offset.y, offset.z ); + function MeshBasicMaterial( parameters ) { - return offset; + Material.call( this ); - }, + this.type = 'MeshBasicMaterial'; - setFromObject: function ( object ) { + this.color = new Color( 0xffffff ); // emissive - // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this ); + this.map = null; - var geometry = object.geometry; + this.aoMap = null; + this.aoMapIntensity = 1.0; - if ( object instanceof THREE.Points || object instanceof THREE.Line ) { + this.specularMap = null; - var positions = new THREE.Float32Attribute( geometry.vertices.length * 3, 3 ); - var colors = new THREE.Float32Attribute( geometry.colors.length * 3, 3 ); + this.alphaMap = null; - this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) ); - this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) ); + this.envMap = null; + this.combine = MultiplyOperation; + this.reflectivity = 1; + this.refractionRatio = 0.98; - if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) { + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; - var lineDistances = new THREE.Float32Attribute( geometry.lineDistances.length, 1 ); + this.skinning = false; + this.morphTargets = false; - this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) ); + this.lights = false; - } + this.setValues( parameters ); - if ( geometry.boundingSphere !== null ) { + } - this.boundingSphere = geometry.boundingSphere.clone(); + MeshBasicMaterial.prototype = Object.create( Material.prototype ); + MeshBasicMaterial.prototype.constructor = MeshBasicMaterial; - } + MeshBasicMaterial.prototype.isMeshBasicMaterial = true; - if ( geometry.boundingBox !== null ) { + MeshBasicMaterial.prototype.copy = function ( source ) { - this.boundingBox = geometry.boundingBox.clone(); + Material.prototype.copy.call( this, source ); - } + this.color.copy( source.color ); - } else if ( object instanceof THREE.Mesh ) { + this.map = source.map; - if ( geometry instanceof THREE.Geometry ) { + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; - this.fromGeometry( geometry ); + this.specularMap = source.specularMap; - } + this.alphaMap = source.alphaMap; - } + this.envMap = source.envMap; + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; - return this; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; - }, + this.skinning = source.skinning; + this.morphTargets = source.morphTargets; - updateFromObject: function ( object ) { + return this; - var geometry = object.geometry; + }; - if ( object instanceof THREE.Mesh ) { + /** + * @author mrdoob / http://mrdoob.com/ + */ - var direct = geometry.__directGeometry; + function BufferAttribute( array, itemSize, normalized ) { - if ( direct === undefined ) { + if ( Array.isArray( array ) ) { - return this.fromGeometry( geometry ); + throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' ); - } + } - direct.verticesNeedUpdate = geometry.verticesNeedUpdate; - direct.normalsNeedUpdate = geometry.normalsNeedUpdate; - direct.colorsNeedUpdate = geometry.colorsNeedUpdate; - direct.uvsNeedUpdate = geometry.uvsNeedUpdate; - direct.groupsNeedUpdate = geometry.groupsNeedUpdate; + this.uuid = exports.Math.generateUUID(); - geometry.verticesNeedUpdate = false; - geometry.normalsNeedUpdate = false; - geometry.colorsNeedUpdate = false; - geometry.uvsNeedUpdate = false; - geometry.groupsNeedUpdate = false; + this.array = array; + this.itemSize = itemSize; + this.count = array !== undefined ? array.length / itemSize : 0; + this.normalized = normalized === true; - geometry = direct; + this.dynamic = false; + this.updateRange = { offset: 0, count: - 1 }; - } + this.version = 0; - if ( geometry.verticesNeedUpdate === true ) { + } - var attribute = this.attributes.position; + BufferAttribute.prototype = { - if ( attribute !== undefined ) { + constructor: BufferAttribute, - attribute.copyVector3sArray( geometry.vertices ); - attribute.needsUpdate = true; + isBufferAttribute: true, - } + set needsUpdate( value ) { - geometry.verticesNeedUpdate = false; + if ( value === true ) this.version ++; - } + }, - if ( geometry.normalsNeedUpdate === true ) { + setDynamic: function ( value ) { - var attribute = this.attributes.normal; + this.dynamic = value; - if ( attribute !== undefined ) { + return this; - attribute.copyVector3sArray( geometry.normals ); - attribute.needsUpdate = true; + }, - } + copy: function ( source ) { - geometry.normalsNeedUpdate = false; + this.array = new source.array.constructor( source.array ); + this.itemSize = source.itemSize; + this.count = source.count; + this.normalized = source.normalized; - } + this.dynamic = source.dynamic; - if ( geometry.colorsNeedUpdate === true ) { + return this; - var attribute = this.attributes.color; + }, - if ( attribute !== undefined ) { + copyAt: function ( index1, attribute, index2 ) { - attribute.copyColorsArray( geometry.colors ); - attribute.needsUpdate = true; + index1 *= this.itemSize; + index2 *= attribute.itemSize; - } + for ( var i = 0, l = this.itemSize; i < l; i ++ ) { - geometry.colorsNeedUpdate = false; + this.array[ index1 + i ] = attribute.array[ index2 + i ]; - } + } - if ( geometry.lineDistancesNeedUpdate ) { + return this; - var attribute = this.attributes.lineDistance; + }, - if ( attribute !== undefined ) { + copyArray: function ( array ) { - attribute.copyArray( geometry.lineDistances ); - attribute.needsUpdate = true; + this.array.set( array ); - } + return this; - geometry.lineDistancesNeedUpdate = false; + }, - } + copyColorsArray: function ( colors ) { - if ( geometry.groupsNeedUpdate ) { + var array = this.array, offset = 0; - geometry.computeGroups( object.geometry ); - this.groups = geometry.groups; + for ( var i = 0, l = colors.length; i < l; i ++ ) { - geometry.groupsNeedUpdate = false; + var color = colors[ i ]; - } + if ( color === undefined ) { - return this; + console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i ); + color = new Color(); - }, + } - fromGeometry: function ( geometry ) { + array[ offset ++ ] = color.r; + array[ offset ++ ] = color.g; + array[ offset ++ ] = color.b; - geometry.__directGeometry = new THREE.DirectGeometry().fromGeometry( geometry ); + } - return this.fromDirectGeometry( geometry.__directGeometry ); + return this; - }, + }, - fromDirectGeometry: function ( geometry ) { + copyIndicesArray: function ( indices ) { - var positions = new Float32Array( geometry.vertices.length * 3 ); - this.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) ); + var array = this.array, offset = 0; - if ( geometry.normals.length > 0 ) { + for ( var i = 0, l = indices.length; i < l; i ++ ) { - var normals = new Float32Array( geometry.normals.length * 3 ); - this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) ); + var index = indices[ i ]; - } + array[ offset ++ ] = index.a; + array[ offset ++ ] = index.b; + array[ offset ++ ] = index.c; - if ( geometry.colors.length > 0 ) { + } - var colors = new Float32Array( geometry.colors.length * 3 ); - this.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) ); + return this; - } + }, - if ( geometry.uvs.length > 0 ) { + copyVector2sArray: function ( vectors ) { - var uvs = new Float32Array( geometry.uvs.length * 2 ); - this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) ); + var array = this.array, offset = 0; - } + for ( var i = 0, l = vectors.length; i < l; i ++ ) { - if ( geometry.uvs2.length > 0 ) { + var vector = vectors[ i ]; - var uvs2 = new Float32Array( geometry.uvs2.length * 2 ); - this.addAttribute( 'uv2', new THREE.BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) ); + if ( vector === undefined ) { - } + console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i ); + vector = new Vector2(); - if ( geometry.indices.length > 0 ) { + } - var TypeArray = geometry.vertices.length > 65535 ? Uint32Array : Uint16Array; - var indices = new TypeArray( geometry.indices.length * 3 ); - this.setIndex( new THREE.BufferAttribute( indices, 1 ).copyIndicesArray( geometry.indices ) ); + array[ offset ++ ] = vector.x; + array[ offset ++ ] = vector.y; - } + } - // groups + return this; - this.groups = geometry.groups; + }, - // morphs + copyVector3sArray: function ( vectors ) { - for ( var name in geometry.morphTargets ) { + var array = this.array, offset = 0; - var array = []; - var morphTargets = geometry.morphTargets[ name ]; + for ( var i = 0, l = vectors.length; i < l; i ++ ) { - for ( var i = 0, l = morphTargets.length; i < l; i ++ ) { + var vector = vectors[ i ]; - var morphTarget = morphTargets[ i ]; + if ( vector === undefined ) { - var attribute = new THREE.Float32Attribute( morphTarget.length * 3, 3 ); + console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i ); + vector = new Vector3(); - array.push( attribute.copyVector3sArray( morphTarget ) ); + } - } + array[ offset ++ ] = vector.x; + array[ offset ++ ] = vector.y; + array[ offset ++ ] = vector.z; - this.morphAttributes[ name ] = array; + } - } + return this; - // skinning + }, - if ( geometry.skinIndices.length > 0 ) { + copyVector4sArray: function ( vectors ) { - var skinIndices = new THREE.Float32Attribute( geometry.skinIndices.length * 4, 4 ); - this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) ); + var array = this.array, offset = 0; - } + for ( var i = 0, l = vectors.length; i < l; i ++ ) { - if ( geometry.skinWeights.length > 0 ) { + var vector = vectors[ i ]; - var skinWeights = new THREE.Float32Attribute( geometry.skinWeights.length * 4, 4 ); - this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) ); + if ( vector === undefined ) { - } + console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i ); + vector = new Vector4(); - // + } - if ( geometry.boundingSphere !== null ) { + array[ offset ++ ] = vector.x; + array[ offset ++ ] = vector.y; + array[ offset ++ ] = vector.z; + array[ offset ++ ] = vector.w; - this.boundingSphere = geometry.boundingSphere.clone(); + } - } + return this; - if ( geometry.boundingBox !== null ) { + }, - this.boundingBox = geometry.boundingBox.clone(); + set: function ( value, offset ) { - } + if ( offset === undefined ) offset = 0; - return this; + this.array.set( value, offset ); - }, + return this; - computeBoundingBox: function () { + }, - var vector = new THREE.Vector3(); + getX: function ( index ) { - return function () { + return this.array[ index * this.itemSize ]; - if ( this.boundingBox === null ) { + }, - this.boundingBox = new THREE.Box3(); + setX: function ( index, x ) { - } + this.array[ index * this.itemSize ] = x; - var positions = this.attributes.position.array; + return this; - if ( positions ) { + }, - var bb = this.boundingBox; - bb.makeEmpty(); + getY: function ( index ) { - for ( var i = 0, il = positions.length; i < il; i += 3 ) { + return this.array[ index * this.itemSize + 1 ]; - vector.fromArray( positions, i ); - bb.expandByPoint( vector ); + }, - } + setY: function ( index, y ) { - } + this.array[ index * this.itemSize + 1 ] = y; - if ( positions === undefined || positions.length === 0 ) { + return this; - this.boundingBox.min.set( 0, 0, 0 ); - this.boundingBox.max.set( 0, 0, 0 ); + }, - } + getZ: function ( index ) { - if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) { + return this.array[ index * this.itemSize + 2 ]; - console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this ); + }, - } + setZ: function ( index, z ) { - }; + this.array[ index * this.itemSize + 2 ] = z; - }(), + return this; - computeBoundingSphere: function () { + }, - var box = new THREE.Box3(); - var vector = new THREE.Vector3(); + getW: function ( index ) { - return function () { + return this.array[ index * this.itemSize + 3 ]; - if ( this.boundingSphere === null ) { + }, - this.boundingSphere = new THREE.Sphere(); + setW: function ( index, w ) { - } + this.array[ index * this.itemSize + 3 ] = w; - var positions = this.attributes.position.array; + return this; - if ( positions ) { + }, - box.makeEmpty(); + setXY: function ( index, x, y ) { - var center = this.boundingSphere.center; + index *= this.itemSize; - for ( var i = 0, il = positions.length; i < il; i += 3 ) { + this.array[ index + 0 ] = x; + this.array[ index + 1 ] = y; - vector.fromArray( positions, i ); - box.expandByPoint( vector ); + return this; - } + }, - box.center( center ); + setXYZ: function ( index, x, y, z ) { - // hoping to find a boundingSphere with a radius smaller than the - // boundingSphere of the boundingBox: sqrt(3) smaller in the best case + index *= this.itemSize; - var maxRadiusSq = 0; + this.array[ index + 0 ] = x; + this.array[ index + 1 ] = y; + this.array[ index + 2 ] = z; - for ( var i = 0, il = positions.length; i < il; i += 3 ) { + return this; - vector.fromArray( positions, i ); - maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) ); + }, - } + setXYZW: function ( index, x, y, z, w ) { - this.boundingSphere.radius = Math.sqrt( maxRadiusSq ); + index *= this.itemSize; - if ( isNaN( this.boundingSphere.radius ) ) { + this.array[ index + 0 ] = x; + this.array[ index + 1 ] = y; + this.array[ index + 2 ] = z; + this.array[ index + 3 ] = w; - console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this ); + return this; - } + }, - } + clone: function () { - }; + return new this.constructor().copy( this ); - }(), + } - computeFaceNormals: function () { + }; - // backwards compatibility + // - }, + function Int8Attribute( array, itemSize ) { - computeVertexNormals: function () { + return new BufferAttribute( new Int8Array( array ), itemSize ); - var index = this.index; - var attributes = this.attributes; - var groups = this.groups; + } - if ( attributes.position ) { + function Uint8Attribute( array, itemSize ) { - var positions = attributes.position.array; + return new BufferAttribute( new Uint8Array( array ), itemSize ); - if ( attributes.normal === undefined ) { + } - this.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( positions.length ), 3 ) ); + function Uint8ClampedAttribute( array, itemSize ) { - } else { + return new BufferAttribute( new Uint8ClampedArray( array ), itemSize ); - // reset existing normals to zero + } - var normals = attributes.normal.array; + function Int16Attribute( array, itemSize ) { - for ( var i = 0, il = normals.length; i < il; i ++ ) { + return new BufferAttribute( new Int16Array( array ), itemSize ); - normals[ i ] = 0; + } - } + function Uint16Attribute( array, itemSize ) { - } + return new BufferAttribute( new Uint16Array( array ), itemSize ); - var normals = attributes.normal.array; + } - var vA, vB, vC, + function Int32Attribute( array, itemSize ) { - pA = new THREE.Vector3(), - pB = new THREE.Vector3(), - pC = new THREE.Vector3(), + return new BufferAttribute( new Int32Array( array ), itemSize ); - cb = new THREE.Vector3(), - ab = new THREE.Vector3(); + } - // indexed elements + function Uint32Attribute( array, itemSize ) { - if ( index ) { + return new BufferAttribute( new Uint32Array( array ), itemSize ); - var indices = index.array; + } - if ( groups.length === 0 ) { + function Float32Attribute( array, itemSize ) { - this.addGroup( 0, indices.length ); + return new BufferAttribute( new Float32Array( array ), itemSize ); - } + } - for ( var j = 0, jl = groups.length; j < jl; ++ j ) { + function Float64Attribute( array, itemSize ) { - var group = groups[ j ]; + return new BufferAttribute( new Float64Array( array ), itemSize ); - var start = group.start; - var count = group.count; + } - for ( var i = start, il = start + count; i < il; i += 3 ) { + // Deprecated - vA = indices[ i + 0 ] * 3; - vB = indices[ i + 1 ] * 3; - vC = indices[ i + 2 ] * 3; + function DynamicBufferAttribute( array, itemSize ) { - pA.fromArray( positions, vA ); - pB.fromArray( positions, vB ); - pC.fromArray( positions, vC ); + console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' ); + return new BufferAttribute( array, itemSize ).setDynamic( true ); - cb.subVectors( pC, pB ); - ab.subVectors( pA, pB ); - cb.cross( ab ); + } - normals[ vA ] += cb.x; - normals[ vA + 1 ] += cb.y; - normals[ vA + 2 ] += cb.z; + /** + * @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 + */ - normals[ vB ] += cb.x; - normals[ vB + 1 ] += cb.y; - normals[ vB + 2 ] += cb.z; + function Geometry() { - normals[ vC ] += cb.x; - normals[ vC + 1 ] += cb.y; - normals[ vC + 2 ] += cb.z; + Object.defineProperty( this, 'id', { value: GeometryIdCount() } ); - } + this.uuid = exports.Math.generateUUID(); - } + this.name = ''; + this.type = 'Geometry'; - } else { + this.vertices = []; + this.colors = []; + this.faces = []; + this.faceVertexUvs = [ [] ]; - // non-indexed elements (unconnected triangle soup) + this.morphTargets = []; + this.morphNormals = []; - for ( var i = 0, il = positions.length; i < il; i += 9 ) { + this.skinWeights = []; + this.skinIndices = []; - pA.fromArray( positions, i ); - pB.fromArray( positions, i + 3 ); - pC.fromArray( positions, i + 6 ); + this.lineDistances = []; - cb.subVectors( pC, pB ); - ab.subVectors( pA, pB ); - cb.cross( ab ); + this.boundingBox = null; + this.boundingSphere = null; - normals[ i ] = cb.x; - normals[ i + 1 ] = cb.y; - normals[ i + 2 ] = cb.z; + // update flags - normals[ i + 3 ] = cb.x; - normals[ i + 4 ] = cb.y; - normals[ i + 5 ] = cb.z; + this.elementsNeedUpdate = false; + this.verticesNeedUpdate = false; + this.uvsNeedUpdate = false; + this.normalsNeedUpdate = false; + this.colorsNeedUpdate = false; + this.lineDistancesNeedUpdate = false; + this.groupsNeedUpdate = false; - normals[ i + 6 ] = cb.x; - normals[ i + 7 ] = cb.y; - normals[ i + 8 ] = cb.z; + } - } + Object.assign( Geometry.prototype, EventDispatcher.prototype, { - } + isGeometry: true, - this.normalizeNormals(); + applyMatrix: function ( matrix ) { - attributes.normal.needsUpdate = true; + 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 ); - computeTangents: function () { + } - console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' ); + for ( var i = 0, il = this.faces.length; i < il; i ++ ) { - }, + var face = this.faces[ i ]; + face.normal.applyMatrix3( normalMatrix ).normalize(); - computeOffsets: function ( size ) { + for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) { - console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.') + face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize(); - }, + } - merge: function ( geometry, offset ) { + } - if ( geometry instanceof THREE.BufferGeometry === false ) { + if ( this.boundingBox !== null ) { - console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry ); - return; + this.computeBoundingBox(); - } + } - if ( offset === undefined ) offset = 0; + if ( this.boundingSphere !== null ) { - var attributes = this.attributes; + this.computeBoundingSphere(); - for ( var key in attributes ) { + } - if ( geometry.attributes[ key ] === undefined ) continue; + this.verticesNeedUpdate = true; + this.normalsNeedUpdate = true; - var attribute1 = attributes[ key ]; - var attributeArray1 = attribute1.array; + return this; - var attribute2 = geometry.attributes[ key ]; - var attributeArray2 = attribute2.array; + }, - var attributeSize = attribute2.itemSize; + rotateX: function () { - for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) { + // rotate geometry around world x-axis - attributeArray1[ j ] = attributeArray2[ i ]; + var m1; - } + return function rotateX( angle ) { - } + if ( m1 === undefined ) m1 = new Matrix4(); - return this; + m1.makeRotationX( angle ); - }, + this.applyMatrix( m1 ); - normalizeNormals: function () { + return this; - var normals = this.attributes.normal.array; + }; - var x, y, z, n; + }(), - for ( var i = 0, il = normals.length; i < il; i += 3 ) { + rotateY: function () { - x = normals[ i ]; - y = normals[ i + 1 ]; - z = normals[ i + 2 ]; + // rotate geometry around world y-axis - n = 1.0 / Math.sqrt( x * x + y * y + z * z ); + var m1; - normals[ i ] *= n; - normals[ i + 1 ] *= n; - normals[ i + 2 ] *= n; + return function rotateY( angle ) { - } + if ( m1 === undefined ) m1 = new Matrix4(); - }, + m1.makeRotationY( angle ); - toJSON: function () { + this.applyMatrix( m1 ); - var data = { - metadata: { - version: 4.4, - type: 'BufferGeometry', - generator: 'BufferGeometry.toJSON' - } - }; + return this; - // standard BufferGeometry serialization + }; - data.uuid = this.uuid; - data.type = this.type; - if ( this.name !== '' ) data.name = this.name; + }(), - if ( this.parameters !== undefined ) { + rotateZ: function () { - var parameters = this.parameters; + // rotate geometry around world z-axis - for ( var key in parameters ) { + var m1; - if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ]; + return function rotateZ( angle ) { - } + if ( m1 === undefined ) m1 = new Matrix4(); - return data; + m1.makeRotationZ( angle ); - } + this.applyMatrix( m1 ); - data.data = { attributes: {} }; + return this; - var index = this.index; + }; - if ( index !== null ) { + }(), - var array = Array.prototype.slice.call( index.array ); + translate: function () { - data.data.index = { - type: index.array.constructor.name, - array: array - }; + // translate geometry - } + var m1; - var attributes = this.attributes; + return function translate( x, y, z ) { - for ( var key in attributes ) { + if ( m1 === undefined ) m1 = new Matrix4(); - var attribute = attributes[ key ]; + m1.makeTranslation( x, y, z ); - var array = Array.prototype.slice.call( attribute.array ); + this.applyMatrix( m1 ); - data.data.attributes[ key ] = { - itemSize: attribute.itemSize, - type: attribute.array.constructor.name, - array: array - }; + return this; - } + }; - var groups = this.groups; + }(), - if ( groups.length > 0 ) { + scale: function () { - data.data.groups = JSON.parse( JSON.stringify( groups ) ); + // scale geometry - } + var m1; - var boundingSphere = this.boundingSphere; + return function scale( x, y, z ) { - if ( boundingSphere !== null ) { + if ( m1 === undefined ) m1 = new Matrix4(); - data.data.boundingSphere = { - center: boundingSphere.center.toArray(), - radius: boundingSphere.radius - }; + m1.makeScale( x, y, z ); - } + this.applyMatrix( m1 ); - return data; + return this; - }, + }; - clone: function () { + }(), - return new this.constructor().copy( this ); + lookAt: function () { - }, + var obj; - copy: function ( source ) { + return function lookAt( vector ) { - var index = source.index; + if ( obj === undefined ) obj = new Object3D(); - if ( index !== null ) { + obj.lookAt( vector ); - this.setIndex( index.clone() ); + obj.updateMatrix(); - } + this.applyMatrix( obj.matrix ); - var attributes = source.attributes; + }; - for ( var name in attributes ) { + }(), - var attribute = attributes[ name ]; - this.addAttribute( name, attribute.clone() ); + fromBufferGeometry: function ( geometry ) { - } + var scope = this; - var groups = source.groups; + var indices = geometry.index !== null ? geometry.index.array : undefined; + var attributes = geometry.attributes; - for ( var i = 0, l = groups.length; i < l; i ++ ) { + var positions = attributes.position.array; + var normals = attributes.normal !== undefined ? attributes.normal.array : undefined; + var colors = attributes.color !== undefined ? attributes.color.array : undefined; + var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined; + var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined; - var group = groups[ i ]; - this.addGroup( group.start, group.count ); + if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = []; - } + var tempNormals = []; + var tempUVs = []; + var tempUVs2 = []; - return this; + for ( var i = 0, j = 0; i < positions.length; i += 3, j += 2 ) { - }, + scope.vertices.push( new Vector3( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ) ); - dispose: function () { + if ( normals !== undefined ) { - this.dispatchEvent( { type: 'dispose' } ); + tempNormals.push( new Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) ); - } + } -}; + if ( colors !== undefined ) { -THREE.EventDispatcher.prototype.apply( THREE.BufferGeometry.prototype ); + scope.colors.push( new Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) ); -THREE.BufferGeometry.MaxIndex = 65535; + } -// File:src/core/InstancedBufferGeometry.js + if ( uvs !== undefined ) { -/** - * @author benaadams / https://twitter.com/ben_a_adams - */ + tempUVs.push( new Vector2( uvs[ j ], uvs[ j + 1 ] ) ); -THREE.InstancedBufferGeometry = function () { + } - THREE.BufferGeometry.call( this ); + if ( uvs2 !== undefined ) { - this.type = 'InstancedBufferGeometry'; - this.maxInstancedCount = undefined; + tempUVs2.push( new Vector2( uvs2[ j ], uvs2[ j + 1 ] ) ); -}; + } -THREE.InstancedBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype ); -THREE.InstancedBufferGeometry.prototype.constructor = THREE.InstancedBufferGeometry; + } -THREE.InstancedBufferGeometry.prototype.addGroup = function ( start, count, instances ) { + function addFace( a, b, c, materialIndex ) { - this.groups.push( { + 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() ] : []; - start: start, - count: count, - instances: instances + var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex ); - } ); + scope.faces.push( face ); -}; + if ( uvs !== undefined ) { -THREE.InstancedBufferGeometry.prototype.copy = function ( source ) { + scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] ); - var index = source.index; + } - if ( index !== null ) { + if ( uvs2 !== undefined ) { - this.setIndex( index.clone() ); + scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] ); - } + } - var attributes = source.attributes; + } - for ( var name in attributes ) { + if ( indices !== undefined ) { - var attribute = attributes[ name ]; - this.addAttribute( name, attribute.clone() ); + var groups = geometry.groups; - } + if ( groups.length > 0 ) { - var groups = source.groups; + for ( var i = 0; i < groups.length; i ++ ) { - for ( var i = 0, l = groups.length; i < l; i ++ ) { + var group = groups[ i ]; - var group = groups[ i ]; - this.addGroup( group.start, group.count, group.instances ); + var start = group.start; + var count = group.count; - } + for ( var j = start, jl = start + count; j < jl; j += 3 ) { - return this; + addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex ); -}; + } -THREE.EventDispatcher.prototype.apply( THREE.InstancedBufferGeometry.prototype ); + } -// File:src/cameras/Camera.js + } else { -/** - * @author mrdoob / http://mrdoob.com/ - * @author mikael emtinger / http://gomo.se/ - * @author WestLangley / http://github.com/WestLangley -*/ + for ( var i = 0; i < indices.length; i += 3 ) { -THREE.Camera = function () { + addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] ); - THREE.Object3D.call( this ); + } - this.type = 'Camera'; + } - this.matrixWorldInverse = new THREE.Matrix4(); - this.projectionMatrix = new THREE.Matrix4(); + } else { -}; + for ( var i = 0; i < positions.length / 3; i += 3 ) { -THREE.Camera.prototype = Object.create( THREE.Object3D.prototype ); -THREE.Camera.prototype.constructor = THREE.Camera; + addFace( i, i + 1, i + 2 ); -THREE.Camera.prototype.getWorldDirection = function () { + } - var quaternion = new THREE.Quaternion(); + } - return function ( optionalTarget ) { + this.computeFaceNormals(); - var result = optionalTarget || new THREE.Vector3(); + if ( geometry.boundingBox !== null ) { - this.getWorldQuaternion( quaternion ); + this.boundingBox = geometry.boundingBox.clone(); - return result.set( 0, 0, - 1 ).applyQuaternion( quaternion ); + } - }; + if ( geometry.boundingSphere !== null ) { -}(); + this.boundingSphere = geometry.boundingSphere.clone(); -THREE.Camera.prototype.lookAt = function () { + } - // This routine does not support cameras with rotated and/or translated parent(s) + return this; - var m1 = new THREE.Matrix4(); + }, - return function ( vector ) { + center: function () { - m1.lookAt( this.position, vector, this.up ); + this.computeBoundingBox(); - this.quaternion.setFromRotationMatrix( m1 ); + var offset = this.boundingBox.getCenter().negate(); - }; + this.translate( offset.x, offset.y, offset.z ); -}(); + return offset; -THREE.Camera.prototype.clone = function () { + }, - return new this.constructor().copy( this ); + normalize: function () { -}; + this.computeBoundingSphere(); -THREE.Camera.prototype.copy = function ( source ) { + var center = this.boundingSphere.center; + var radius = this.boundingSphere.radius; - THREE.Object3D.prototype.copy.call( this, source ); + var s = radius === 0 ? 1 : 1.0 / radius; - this.matrixWorldInverse.copy( source.matrixWorldInverse ); - this.projectionMatrix.copy( source.projectionMatrix ); + var matrix = new Matrix4(); + matrix.set( + s, 0, 0, - s * center.x, + 0, s, 0, - s * center.y, + 0, 0, s, - s * center.z, + 0, 0, 0, 1 + ); - return this; + this.applyMatrix( matrix ); -}; + return this; -// File:src/cameras/CubeCamera.js + }, -/** - * Camera for rendering cube maps - * - renders scene into axis-aligned cube - * - * @author alteredq / http://alteredqualia.com/ - */ + computeFaceNormals: function () { -THREE.CubeCamera = function ( near, far, cubeResolution ) { + var cb = new Vector3(), ab = new Vector3(); - THREE.Object3D.call( this ); + for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) { - this.type = 'CubeCamera'; + var face = this.faces[ f ]; - var fov = 90, aspect = 1; + var vA = this.vertices[ face.a ]; + var vB = this.vertices[ face.b ]; + var vC = this.vertices[ face.c ]; - var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far ); - cameraPX.up.set( 0, - 1, 0 ); - cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) ); - this.add( cameraPX ); + cb.subVectors( vC, vB ); + ab.subVectors( vA, vB ); + cb.cross( ab ); - var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far ); - cameraNX.up.set( 0, - 1, 0 ); - cameraNX.lookAt( new THREE.Vector3( - 1, 0, 0 ) ); - this.add( cameraNX ); + cb.normalize(); - var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far ); - cameraPY.up.set( 0, 0, 1 ); - cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) ); - this.add( cameraPY ); + face.normal.copy( cb ); - var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far ); - cameraNY.up.set( 0, 0, - 1 ); - cameraNY.lookAt( new THREE.Vector3( 0, - 1, 0 ) ); - this.add( cameraNY ); + } - var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far ); - cameraPZ.up.set( 0, - 1, 0 ); - cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) ); - this.add( cameraPZ ); + }, - var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far ); - cameraNZ.up.set( 0, - 1, 0 ); - cameraNZ.lookAt( new THREE.Vector3( 0, 0, - 1 ) ); - this.add( cameraNZ ); + computeVertexNormals: function ( areaWeighted ) { - this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } ); + if ( areaWeighted === undefined ) areaWeighted = true; - this.updateCubeMap = function ( renderer, scene ) { + var v, vl, f, fl, face, vertices; - if ( this.parent === null ) this.updateMatrixWorld(); + vertices = new Array( this.vertices.length ); - var renderTarget = this.renderTarget; - var generateMipmaps = renderTarget.generateMipmaps; + for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) { - renderTarget.generateMipmaps = false; + vertices[ v ] = new Vector3(); - renderTarget.activeCubeFace = 0; - renderer.render( scene, cameraPX, renderTarget ); + } - renderTarget.activeCubeFace = 1; - renderer.render( scene, cameraNX, renderTarget ); + if ( areaWeighted ) { - renderTarget.activeCubeFace = 2; - renderer.render( scene, cameraPY, renderTarget ); + // vertex normals weighted by triangle areas + // http://www.iquilezles.org/www/articles/normals/normals.htm - renderTarget.activeCubeFace = 3; - renderer.render( scene, cameraNY, renderTarget ); + var vA, vB, vC; + var cb = new Vector3(), ab = new Vector3(); - renderTarget.activeCubeFace = 4; - renderer.render( scene, cameraPZ, renderTarget ); + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - renderTarget.generateMipmaps = generateMipmaps; + face = this.faces[ f ]; - renderTarget.activeCubeFace = 5; - renderer.render( scene, cameraNZ, renderTarget ); + vA = this.vertices[ face.a ]; + vB = this.vertices[ face.b ]; + vC = this.vertices[ face.c ]; - renderer.setRenderTarget( null ); + cb.subVectors( vC, vB ); + ab.subVectors( vA, vB ); + cb.cross( ab ); - }; + vertices[ face.a ].add( cb ); + vertices[ face.b ].add( cb ); + vertices[ face.c ].add( cb ); -}; + } -THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype ); -THREE.CubeCamera.prototype.constructor = THREE.CubeCamera; + } else { -// File:src/cameras/OrthographicCamera.js + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { -/** - * @author alteredq / http://alteredqualia.com/ - */ + face = this.faces[ f ]; -THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) { + vertices[ face.a ].add( face.normal ); + vertices[ face.b ].add( face.normal ); + vertices[ face.c ].add( face.normal ); - THREE.Camera.call( this ); + } - this.type = 'OrthographicCamera'; + } - this.zoom = 1; + for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) { - this.left = left; - this.right = right; - this.top = top; - this.bottom = bottom; + vertices[ v ].normalize(); - this.near = ( near !== undefined ) ? near : 0.1; - this.far = ( far !== undefined ) ? far : 2000; + } - this.updateProjectionMatrix(); + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { -}; + face = this.faces[ f ]; -THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype ); -THREE.OrthographicCamera.prototype.constructor = THREE.OrthographicCamera; + var vertexNormals = face.vertexNormals; -THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () { + if ( vertexNormals.length === 3 ) { - 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; + vertexNormals[ 0 ].copy( vertices[ face.a ] ); + vertexNormals[ 1 ].copy( vertices[ face.b ] ); + vertexNormals[ 2 ].copy( vertices[ face.c ] ); - this.projectionMatrix.makeOrthographic( cx - dx, cx + dx, cy + dy, cy - dy, this.near, this.far ); + } else { -}; + vertexNormals[ 0 ] = vertices[ face.a ].clone(); + vertexNormals[ 1 ] = vertices[ face.b ].clone(); + vertexNormals[ 2 ] = vertices[ face.c ].clone(); -THREE.OrthographicCamera.prototype.copy = function ( source ) { - - THREE.Camera.prototype.copy.call( this, source ); - - this.left = source.left; - this.right = source.right; - this.top = source.top; - this.bottom = source.bottom; - this.near = source.near; - this.far = source.far; - - this.zoom = source.zoom; - - return this; - -}; + } -THREE.OrthographicCamera.prototype.toJSON = function ( meta ) { + } - var data = THREE.Object3D.prototype.toJSON.call( this, meta ); + if ( this.faces.length > 0 ) { - 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; + this.normalsNeedUpdate = true; - return data; + } -}; + }, -// File:src/cameras/PerspectiveCamera.js + computeMorphNormals: function () { -/** - * @author mrdoob / http://mrdoob.com/ - * @author greggman / http://games.greggman.com/ - * @author zz85 / http://www.lab4games.net/zz85/blog - */ + var i, il, f, fl, face; -THREE.PerspectiveCamera = function ( fov, aspect, near, far ) { + // save original normals + // - create temp variables on first access + // otherwise just copy (for faster repeated calls) - THREE.Camera.call( this ); + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - this.type = 'PerspectiveCamera'; + face = this.faces[ f ]; - this.zoom = 1; + if ( ! face.__originalFaceNormal ) { - this.fov = fov !== undefined ? fov : 50; - this.aspect = aspect !== undefined ? aspect : 1; - this.near = near !== undefined ? near : 0.1; - this.far = far !== undefined ? far : 2000; + face.__originalFaceNormal = face.normal.clone(); - this.updateProjectionMatrix(); + } else { -}; + face.__originalFaceNormal.copy( face.normal ); -THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype ); -THREE.PerspectiveCamera.prototype.constructor = THREE.PerspectiveCamera; + } + if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = []; -/** - * Uses Focal Length (in mm) to estimate and set FOV - * 35mm (full-frame) camera is used if frame size is not specified; - * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html - */ + for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) { -THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) { - - if ( frameHeight === undefined ) frameHeight = 24; - - this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) ); - this.updateProjectionMatrix(); - -}; + if ( ! face.__originalVertexNormals[ i ] ) { + face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone(); -/** - * 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. - */ + } else { -THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) { + face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] ); - this.fullWidth = fullWidth; - this.fullHeight = fullHeight; - this.x = x; - this.y = y; - this.width = width; - this.height = height; + } - this.updateProjectionMatrix(); + } -}; + } + // use temp geometry to compute face and vertex normals for each morph -THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () { + var tmpGeo = new Geometry(); + tmpGeo.faces = this.faces; - var fov = THREE.Math.radToDeg( 2 * Math.atan( Math.tan( THREE.Math.degToRad( this.fov ) * 0.5 ) / this.zoom ) ); + for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) { - if ( this.fullWidth ) { + // create on first access - var aspect = this.fullWidth / this.fullHeight; - var top = Math.tan( THREE.Math.degToRad( fov * 0.5 ) ) * this.near; - var bottom = - top; - var left = aspect * bottom; - var right = aspect * top; - var width = Math.abs( right - left ); - var height = Math.abs( top - bottom ); + if ( ! this.morphNormals[ i ] ) { - this.projectionMatrix.makeFrustum( - left + this.x * width / this.fullWidth, - left + ( this.x + this.width ) * width / this.fullWidth, - top - ( this.y + this.height ) * height / this.fullHeight, - top - this.y * height / this.fullHeight, - this.near, - this.far - ); + this.morphNormals[ i ] = {}; + this.morphNormals[ i ].faceNormals = []; + this.morphNormals[ i ].vertexNormals = []; - } else { + var dstNormalsFace = this.morphNormals[ i ].faceNormals; + var dstNormalsVertex = this.morphNormals[ i ].vertexNormals; - this.projectionMatrix.makePerspective( fov, this.aspect, this.near, this.far ); + var faceNormal, vertexNormals; - } + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { -}; + faceNormal = new Vector3(); + vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() }; -THREE.PerspectiveCamera.prototype.copy = function ( source ) { - - THREE.Camera.prototype.copy.call( this, source ); - - this.fov = source.fov; - this.aspect = source.aspect; - this.near = source.near; - this.far = source.far; - - this.zoom = source.zoom; - - return this; - -}; + dstNormalsFace.push( faceNormal ); + dstNormalsVertex.push( vertexNormals ); -THREE.PerspectiveCamera.prototype.toJSON = function ( meta ) { + } - var data = THREE.Object3D.prototype.toJSON.call( this, meta ); + } - data.object.zoom = this.zoom; - data.object.fov = this.fov; - data.object.aspect = this.aspect; - data.object.near = this.near; - data.object.far = this.far; + var morphNormals = this.morphNormals[ i ]; - return data; + // set vertices to morph target -}; + tmpGeo.vertices = this.morphTargets[ i ].vertices; -// File:src/lights/Light.js + // compute morph normals -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + tmpGeo.computeFaceNormals(); + tmpGeo.computeVertexNormals(); -THREE.Light = function ( color ) { + // store morph normals - THREE.Object3D.call( this ); + var faceNormal, vertexNormals; - this.type = 'Light'; + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - this.color = new THREE.Color( color ); + face = this.faces[ f ]; -}; + faceNormal = morphNormals.faceNormals[ f ]; + vertexNormals = morphNormals.vertexNormals[ f ]; -THREE.Light.prototype = Object.create( THREE.Object3D.prototype ); -THREE.Light.prototype.constructor = THREE.Light; + faceNormal.copy( face.normal ); -THREE.Light.prototype.copy = function ( source ) { - - THREE.Object3D.prototype.copy.call( this, source ); - - this.color.copy( source.color ); - - return this; + vertexNormals.a.copy( face.vertexNormals[ 0 ] ); + vertexNormals.b.copy( face.vertexNormals[ 1 ] ); + vertexNormals.c.copy( face.vertexNormals[ 2 ] ); -}; -// File:src/lights/AmbientLight.js + } -/** - * @author mrdoob / http://mrdoob.com/ - */ + } -THREE.AmbientLight = function ( color ) { + // restore original normals - THREE.Light.call( this, color ); + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - this.type = 'AmbientLight'; + face = this.faces[ f ]; -}; + face.normal = face.__originalFaceNormal; + face.vertexNormals = face.__originalVertexNormals; -THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype ); -THREE.AmbientLight.prototype.constructor = THREE.AmbientLight; + } -THREE.AmbientLight.prototype.toJSON = function ( meta ) { + }, - var data = THREE.Object3D.prototype.toJSON.call( this, meta ); + computeTangents: function () { - data.object.color = this.color.getHex(); + console.warn( 'THREE.Geometry: .computeTangents() has been removed.' ); - return data; + }, -}; + computeLineDistances: function () { -// File:src/lights/DirectionalLight.js + var d = 0; + var vertices = this.vertices; -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + for ( var i = 0, il = vertices.length; i < il; i ++ ) { -THREE.DirectionalLight = function ( color, intensity ) { + if ( i > 0 ) { - THREE.Light.call( this, color ); + d += vertices[ i ].distanceTo( vertices[ i - 1 ] ); - this.type = 'DirectionalLight'; + } - this.position.set( 0, 1, 0 ); - this.updateMatrix(); + this.lineDistances[ i ] = d; - this.target = new THREE.Object3D(); + } - this.intensity = ( intensity !== undefined ) ? intensity : 1; + }, - this.castShadow = false; - this.onlyShadow = false; + computeBoundingBox: function () { - this.shadowCameraNear = 50; - this.shadowCameraFar = 5000; + if ( this.boundingBox === null ) { - this.shadowCameraLeft = - 500; - this.shadowCameraRight = 500; - this.shadowCameraTop = 500; - this.shadowCameraBottom = - 500; + this.boundingBox = new Box3(); - this.shadowCameraVisible = false; + } - this.shadowBias = 0; - this.shadowDarkness = 0.5; + this.boundingBox.setFromPoints( this.vertices ); - this.shadowMapWidth = 512; - this.shadowMapHeight = 512; + }, - this.shadowMap = null; - this.shadowMapSize = null; - this.shadowCamera = null; - this.shadowMatrix = null; + computeBoundingSphere: function () { -}; + if ( this.boundingSphere === null ) { -THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype ); -THREE.DirectionalLight.prototype.constructor = THREE.DirectionalLight; + this.boundingSphere = new Sphere(); -THREE.DirectionalLight.prototype.copy = function ( source ) { + } - THREE.Light.prototype.copy.call( this, source ); + this.boundingSphere.setFromPoints( this.vertices ); - this.intensity = source.intensity; - this.target = source.target.clone(); + }, - this.castShadow = source.castShadow; - this.onlyShadow = source.onlyShadow; + merge: function ( geometry, matrix, materialIndexOffset ) { - this.shadowCameraNear = source.shadowCameraNear; - this.shadowCameraFar = source.shadowCameraFar; + if ( (geometry && geometry.isGeometry) === false ) { - this.shadowCameraLeft = source.shadowCameraLeft; - this.shadowCameraRight = source.shadowCameraRight; - this.shadowCameraTop = source.shadowCameraTop; - this.shadowCameraBottom = source.shadowCameraBottom; + console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry ); + return; - this.shadowCameraVisible = source.shadowCameraVisible; + } - this.shadowBias = source.shadowBias; - this.shadowDarkness = source.shadowDarkness; + 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 ], + colors1 = this.colors, + colors2 = geometry.colors; - this.shadowMapWidth = source.shadowMapWidth; - this.shadowMapHeight = source.shadowMapHeight; + if ( materialIndexOffset === undefined ) materialIndexOffset = 0; - return this; + if ( matrix !== undefined ) { -}; + normalMatrix = new Matrix3().getNormalMatrix( matrix ); -THREE.DirectionalLight.prototype.toJSON = function ( meta ) { + } - var data = THREE.Object3D.prototype.toJSON.call( this, meta ); + // vertices - data.object.color = this.color.getHex(); - data.object.intensity = this.intensity; + for ( var i = 0, il = vertices2.length; i < il; i ++ ) { - return data; + var vertex = vertices2[ i ]; -}; + var vertexCopy = vertex.clone(); -// File:src/lights/HemisphereLight.js + if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix ); -/** - * @author alteredq / http://alteredqualia.com/ - */ + vertices1.push( vertexCopy ); -THREE.HemisphereLight = function ( skyColor, groundColor, intensity ) { + } - THREE.Light.call( this, skyColor ); + // colors - this.type = 'HemisphereLight'; + for ( var i = 0, il = colors2.length; i < il; i ++ ) { - this.position.set( 0, 1, 0 ); - this.updateMatrix(); + colors1.push( colors2[ i ].clone() ); - this.groundColor = new THREE.Color( groundColor ); - this.intensity = ( intensity !== undefined ) ? intensity : 1; + } -}; + // faces -THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype ); -THREE.HemisphereLight.prototype.constructor = THREE.HemisphereLight; + for ( i = 0, il = faces2.length; i < il; i ++ ) { -THREE.HemisphereLight.prototype.copy = function ( source ) { + var face = faces2[ i ], faceCopy, normal, color, + faceVertexNormals = face.vertexNormals, + faceVertexColors = face.vertexColors; - THREE.Light.prototype.copy.call( this, source ); + faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset ); + faceCopy.normal.copy( face.normal ); - this.groundColor.copy( source.groundColor ); - this.intensity = source.intensity; + if ( normalMatrix !== undefined ) { - return this; + faceCopy.normal.applyMatrix3( normalMatrix ).normalize(); -}; + } -THREE.HemisphereLight.prototype.toJSON = function ( meta ) { + for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) { - var data = THREE.Object3D.prototype.toJSON.call( this, meta ); + normal = faceVertexNormals[ j ].clone(); - data.object.color = this.color.getHex(); - data.object.groundColor = this.groundColor.getHex(); - data.object.intensity = this.intensity; + if ( normalMatrix !== undefined ) { - return data; + normal.applyMatrix3( normalMatrix ).normalize(); -}; + } -// File:src/lights/PointLight.js + faceCopy.vertexNormals.push( normal ); -/** - * @author mrdoob / http://mrdoob.com/ - */ + } -THREE.PointLight = function ( color, intensity, distance, decay ) { + faceCopy.color.copy( face.color ); - THREE.Light.call( this, color ); + for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) { - this.type = 'PointLight'; + color = faceVertexColors[ j ]; + faceCopy.vertexColors.push( color.clone() ); - this.intensity = ( intensity !== undefined ) ? intensity : 1; - this.distance = ( distance !== undefined ) ? distance : 0; - this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2. + } -}; + faceCopy.materialIndex = face.materialIndex + materialIndexOffset; -THREE.PointLight.prototype = Object.create( THREE.Light.prototype ); -THREE.PointLight.prototype.constructor = THREE.PointLight; + faces1.push( faceCopy ); -THREE.PointLight.prototype.copy = function ( source ) { + } - THREE.Light.prototype.copy.call( this, source ); + // uvs - this.intensity = source.intensity; - this.distance = source.distance; - this.decay = source.decay; + for ( i = 0, il = uvs2.length; i < il; i ++ ) { - return this; + var uv = uvs2[ i ], uvCopy = []; -}; + if ( uv === undefined ) { -THREE.PointLight.prototype.toJSON = function ( meta ) { + continue; - var data = THREE.Object3D.prototype.toJSON.call( this, meta ); + } - data.object.color = this.color.getHex(); - data.object.intensity = this.intensity; - data.object.distance = this.distance; - data.object.decay = this.decay; + for ( var j = 0, jl = uv.length; j < jl; j ++ ) { - return data; + uvCopy.push( uv[ j ].clone() ); -}; + } -// File:src/lights/SpotLight.js + uvs1.push( uvCopy ); -/** - * @author alteredq / http://alteredqualia.com/ - */ + } -THREE.SpotLight = function ( color, intensity, distance, angle, exponent, decay ) { + }, - THREE.Light.call( this, color ); + mergeMesh: function ( mesh ) { - this.type = 'SpotLight'; + if ( (mesh && mesh.isMesh) === false ) { - this.position.set( 0, 1, 0 ); - this.updateMatrix(); + console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh ); + return; - this.target = new THREE.Object3D(); + } - this.intensity = ( intensity !== undefined ) ? intensity : 1; - this.distance = ( distance !== undefined ) ? distance : 0; - this.angle = ( angle !== undefined ) ? angle : Math.PI / 3; - this.exponent = ( exponent !== undefined ) ? exponent : 10; - this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2. + mesh.matrixAutoUpdate && mesh.updateMatrix(); - this.castShadow = false; - this.onlyShadow = false; + this.merge( mesh.geometry, mesh.matrix ); - this.shadowCameraNear = 50; - this.shadowCameraFar = 5000; - this.shadowCameraFov = 50; + }, - this.shadowCameraVisible = false; + /* + * Checks for duplicate vertices with hashmap. + * Duplicated vertices are removed + * and faces' vertices are updated. + */ - this.shadowBias = 0; - this.shadowDarkness = 0.5; + mergeVertices: function () { - this.shadowMapWidth = 512; - this.shadowMapHeight = 512; + var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique) + var unique = [], changes = []; - this.shadowMap = null; - this.shadowMapSize = null; - this.shadowCamera = null; - this.shadowMatrix = null; + 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; -}; + for ( i = 0, il = this.vertices.length; i < il; i ++ ) { -THREE.SpotLight.prototype = Object.create( THREE.Light.prototype ); -THREE.SpotLight.prototype.constructor = THREE.SpotLight; + v = this.vertices[ i ]; + key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision ); -THREE.SpotLight.prototype.copy = function ( source ) { + if ( verticesMap[ key ] === undefined ) { - THREE.Light.prototype.copy.call( this, source ); + verticesMap[ key ] = i; + unique.push( this.vertices[ i ] ); + changes[ i ] = unique.length - 1; - this.intensity = source.intensity; - this.distance = source.distance; - this.angle = source.angle; - this.exponent = source.exponent; - this.decay = source.decay; + } else { - this.target = source.target.clone(); + //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]); + changes[ i ] = changes[ verticesMap[ key ] ]; - this.castShadow = source.castShadow; - this.onlyShadow = source.onlyShadow; + } - this.shadowCameraNear = source.shadowCameraNear; - this.shadowCameraFar = source.shadowCameraFar; - this.shadowCameraFov = source.shadowCameraFov; + } - this.shadowCameraVisible = source.shadowCameraVisible; - this.shadowBias = source.shadowBias; - this.shadowDarkness = source.shadowDarkness; + // if faces are completely degenerate after merging vertices, we + // have to remove them from the geometry. + var faceIndicesToRemove = []; - this.shadowMapWidth = source.shadowMapWidth; - this.shadowMapHeight = source.shadowMapHeight; + for ( i = 0, il = this.faces.length; i < il; i ++ ) { - return this; -} + face = this.faces[ i ]; -THREE.SpotLight.prototype.toJSON = function ( meta ) { + face.a = changes[ face.a ]; + face.b = changes[ face.b ]; + face.c = changes[ face.c ]; - var data = THREE.Object3D.prototype.toJSON.call( this, meta ); + indices = [ face.a, face.b, face.c ]; - data.object.color = this.color.getHex(); - data.object.intensity = this.intensity; - data.object.distance = this.distance; - data.object.angle = this.angle; - data.object.exponent = this.exponent; - data.object.decay = this.decay; + var dupIndex = - 1; - return data; + // 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 ++ ) { -}; + if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) { -// File:src/loaders/Cache.js + dupIndex = n; + faceIndicesToRemove.push( i ); + break; -/** - * @author mrdoob / http://mrdoob.com/ - */ + } -THREE.Cache = { + } - enabled: false, + } - files: {}, + for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) { - add: function ( key, file ) { + var idx = faceIndicesToRemove[ i ]; - if ( this.enabled === false ) return; + this.faces.splice( idx, 1 ); - // console.log( 'THREE.Cache', 'Adding key:', key ); + for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) { - this.files[ key ] = file; + this.faceVertexUvs[ j ].splice( idx, 1 ); - }, + } - get: function ( key ) { + } - if ( this.enabled === false ) return; + // Use unique set of vertices - // console.log( 'THREE.Cache', 'Checking key:', key ); + var diff = this.vertices.length - unique.length; + this.vertices = unique; + return diff; - return this.files[ key ]; + }, - }, + sortFacesByMaterialIndex: function () { - remove: function ( key ) { + var faces = this.faces; + var length = faces.length; - delete this.files[ key ]; + // tag faces - }, + for ( var i = 0; i < length; i ++ ) { - clear: function () { + faces[ i ]._id = i; - this.files = {}; + } - } + // sort faces -}; + function materialIndexSort( a, b ) { -// File:src/loaders/Loader.js + return a.materialIndex - b.materialIndex; -/** - * @author alteredq / http://alteredqualia.com/ - */ + } -THREE.Loader = function () { + faces.sort( materialIndexSort ); - this.onLoadStart = function () {}; - this.onLoadProgress = function () {}; - this.onLoadComplete = function () {}; + // sort uvs -}; + var uvs1 = this.faceVertexUvs[ 0 ]; + var uvs2 = this.faceVertexUvs[ 1 ]; -THREE.Loader.prototype = { + var newUvs1, newUvs2; - constructor: THREE.Loader, + if ( uvs1 && uvs1.length === length ) newUvs1 = []; + if ( uvs2 && uvs2.length === length ) newUvs2 = []; - crossOrigin: undefined, + for ( var i = 0; i < length; i ++ ) { - extractUrlBase: function ( url ) { + var id = faces[ i ]._id; - var parts = url.split( '/' ); + if ( newUvs1 ) newUvs1.push( uvs1[ id ] ); + if ( newUvs2 ) newUvs2.push( uvs2[ id ] ); - if ( parts.length === 1 ) return './'; + } - parts.pop(); + if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1; + if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2; - return parts.join( '/' ) + '/'; + }, - }, + toJSON: function () { - initMaterials: function ( materials, texturePath, crossOrigin ) { + var data = { + metadata: { + version: 4.4, + type: 'Geometry', + generator: 'Geometry.toJSON' + } + }; - var array = []; + // standard Geometry serialization - for ( var i = 0; i < materials.length; ++ i ) { + data.uuid = this.uuid; + data.type = this.type; + if ( this.name !== '' ) data.name = this.name; - array[ i ] = this.createMaterial( materials[ i ], texturePath, crossOrigin ); + if ( this.parameters !== undefined ) { - } + var parameters = this.parameters; - return array; + for ( var key in parameters ) { - }, + if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ]; - createMaterial: ( function () { + } - var imageLoader; + return data; - return function createMaterial( m, texturePath, crossOrigin ) { + } - var scope = this; + var vertices = []; - if ( crossOrigin === undefined && scope.crossOrigin !== undefined ) crossOrigin = scope.crossOrigin; + for ( var i = 0; i < this.vertices.length; i ++ ) { - if ( imageLoader === undefined ) imageLoader = new THREE.ImageLoader(); + var vertex = this.vertices[ i ]; + vertices.push( vertex.x, vertex.y, vertex.z ); - function nearest_pow2( n ) { + } - var l = Math.log( n ) / Math.LN2; - return Math.pow( 2, Math.round( l ) ); + var faces = []; + var normals = []; + var normalsHash = {}; + var colors = []; + var colorsHash = {}; + var uvs = []; + var uvsHash = {}; - } + for ( var i = 0; i < this.faces.length; i ++ ) { - function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) { + var face = this.faces[ i ]; - var fullPath = texturePath + sourceFile; + 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 texture; + var faceType = 0; - var loader = THREE.Loader.Handlers.get( fullPath ); + 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 ( loader !== null ) { + faces.push( faceType ); + faces.push( face.a, face.b, face.c ); + faces.push( face.materialIndex ); - texture = loader.load( fullPath ); + if ( hasFaceVertexUv ) { - } else { + var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ]; - texture = new THREE.Texture(); + faces.push( + getUvIndex( faceVertexUvs[ 0 ] ), + getUvIndex( faceVertexUvs[ 1 ] ), + getUvIndex( faceVertexUvs[ 2 ] ) + ); - loader = imageLoader; - loader.setCrossOrigin( crossOrigin ); - loader.load( fullPath, function ( image ) { + } - if ( THREE.Math.isPowerOfTwo( image.width ) === false || - THREE.Math.isPowerOfTwo( image.height ) === false ) { + if ( hasFaceNormal ) { - var width = nearest_pow2( image.width ); - var height = nearest_pow2( image.height ); + faces.push( getNormalIndex( face.normal ) ); - var canvas = document.createElement( 'canvas' ); - canvas.width = width; - canvas.height = height; + } - var context = canvas.getContext( '2d' ); - context.drawImage( image, 0, 0, width, height ); + if ( hasFaceVertexNormal ) { - texture.image = canvas; + var vertexNormals = face.vertexNormals; - } else { + faces.push( + getNormalIndex( vertexNormals[ 0 ] ), + getNormalIndex( vertexNormals[ 1 ] ), + getNormalIndex( vertexNormals[ 2 ] ) + ); - texture.image = image; + } - } + if ( hasFaceColor ) { - texture.needsUpdate = true; + faces.push( getColorIndex( face.color ) ); - } ); + } - } + if ( hasFaceVertexColor ) { - texture.sourceFile = sourceFile; + var vertexColors = face.vertexColors; - if ( repeat ) { + faces.push( + getColorIndex( vertexColors[ 0 ] ), + getColorIndex( vertexColors[ 1 ] ), + getColorIndex( vertexColors[ 2 ] ) + ); - texture.repeat.set( repeat[ 0 ], repeat[ 1 ] ); + } - if ( repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping; - if ( repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping; + } - } + function setBit( value, position, enabled ) { - if ( offset ) { + return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) ); - texture.offset.set( offset[ 0 ], offset[ 1 ] ); + } - } + function getNormalIndex( normal ) { - if ( wrap ) { + var hash = normal.x.toString() + normal.y.toString() + normal.z.toString(); - var wrapMap = { - 'repeat': THREE.RepeatWrapping, - 'mirror': THREE.MirroredRepeatWrapping - }; + if ( normalsHash[ hash ] !== undefined ) { - if ( wrapMap[ wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ wrap[ 0 ] ]; - if ( wrapMap[ wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ wrap[ 1 ] ]; + return normalsHash[ hash ]; - } + } - if ( anisotropy ) { + normalsHash[ hash ] = normals.length / 3; + normals.push( normal.x, normal.y, normal.z ); - texture.anisotropy = anisotropy; + return normalsHash[ hash ]; - } + } - where[ name ] = texture; + function getColorIndex( color ) { - } + var hash = color.r.toString() + color.g.toString() + color.b.toString(); - function rgb2hex( rgb ) { + if ( colorsHash[ hash ] !== undefined ) { - return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255; + return colorsHash[ hash ]; - } + } - // defaults + colorsHash[ hash ] = colors.length; + colors.push( color.getHex() ); - var mtype = 'MeshLambertMaterial'; - var mpars = {}; + return colorsHash[ hash ]; - // parameters from model file + } - if ( m.shading ) { + function getUvIndex( uv ) { - var shading = m.shading.toLowerCase(); + var hash = uv.x.toString() + uv.y.toString(); - if ( shading === 'phong' ) mtype = 'MeshPhongMaterial'; - else if ( shading === 'basic' ) mtype = 'MeshBasicMaterial'; + if ( uvsHash[ hash ] !== undefined ) { - } + return uvsHash[ hash ]; - if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) { + } - mpars.blending = THREE[ m.blending ]; + uvsHash[ hash ] = uvs.length / 2; + uvs.push( uv.x, uv.y ); - } + return uvsHash[ hash ]; - if ( m.transparent !== undefined ) { + } - mpars.transparent = m.transparent; + 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 ( m.opacity !== undefined && m.opacity < 1.0 ) { + return data; - mpars.transparent = true; + }, - } + clone: function () { - if ( m.depthTest !== undefined ) { + /* + // Handle primitives - mpars.depthTest = m.depthTest; + var parameters = this.parameters; - } + if ( parameters !== undefined ) { - if ( m.depthWrite !== undefined ) { + var values = []; - mpars.depthWrite = m.depthWrite; + for ( var key in parameters ) { - } + values.push( parameters[ key ] ); - if ( m.visible !== undefined ) { + } - mpars.visible = m.visible; + var geometry = Object.create( this.constructor.prototype ); + this.constructor.apply( geometry, values ); + return geometry; - } + } - if ( m.flipSided !== undefined ) { + return new this.constructor().copy( this ); + */ - mpars.side = THREE.BackSide; + return new Geometry().copy( this ); - } + }, - if ( m.doubleSided !== undefined ) { + copy: function ( source ) { - mpars.side = THREE.DoubleSide; + this.vertices = []; + this.faces = []; + this.faceVertexUvs = [ [] ]; + this.colors = []; - } + var vertices = source.vertices; - if ( m.wireframe !== undefined ) { + for ( var i = 0, il = vertices.length; i < il; i ++ ) { - mpars.wireframe = m.wireframe; + this.vertices.push( vertices[ i ].clone() ); - } + } - if ( m.vertexColors !== undefined ) { + var colors = source.colors; - if ( m.vertexColors === 'face' ) { + for ( var i = 0, il = colors.length; i < il; i ++ ) { - mpars.vertexColors = THREE.FaceColors; + this.colors.push( colors[ i ].clone() ); - } else if ( m.vertexColors ) { + } - mpars.vertexColors = THREE.VertexColors; + var faces = source.faces; - } + for ( var i = 0, il = faces.length; i < il; i ++ ) { - } + this.faces.push( faces[ i ].clone() ); - // colors + } - if ( m.colorDiffuse ) { + for ( var i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) { - mpars.color = rgb2hex( m.colorDiffuse ); + var faceVertexUvs = source.faceVertexUvs[ i ]; - } else if ( m.DbgColor ) { + if ( this.faceVertexUvs[ i ] === undefined ) { - mpars.color = m.DbgColor; + this.faceVertexUvs[ i ] = []; - } + } - if ( m.colorEmissive ) { + for ( var j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) { - mpars.emissive = rgb2hex( m.colorEmissive ); + var uvs = faceVertexUvs[ j ], uvsCopy = []; - } + for ( var k = 0, kl = uvs.length; k < kl; k ++ ) { - if ( mtype === 'MeshPhongMaterial' ) { + var uv = uvs[ k ]; - if ( m.colorSpecular ) { + uvsCopy.push( uv.clone() ); - mpars.specular = rgb2hex( m.colorSpecular ); + } - } + this.faceVertexUvs[ i ].push( uvsCopy ); - if ( m.specularCoef ) { + } - mpars.shininess = m.specularCoef; + } - } + return this; - } + }, - // modifiers + dispose: function () { - if ( m.transparency !== undefined ) { + this.dispatchEvent( { type: 'dispose' } ); - console.warn( 'THREE.Loader: transparency has been renamed to opacity' ); - m.opacity = m.transparency; + } - } + } ); - if ( m.opacity !== undefined ) { + var count$3 = 0; + function GeometryIdCount() { return count$3++; }; - mpars.opacity = m.opacity; + /** + * @author mrdoob / http://mrdoob.com/ + */ - } + function DirectGeometry() { - // textures + Object.defineProperty( this, 'id', { value: GeometryIdCount() } ); - if ( texturePath ) { + this.uuid = exports.Math.generateUUID(); - if ( m.mapDiffuse ) { + this.name = ''; + this.type = 'DirectGeometry'; - create_texture( mpars, 'map', m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy ); + this.indices = []; + this.vertices = []; + this.normals = []; + this.colors = []; + this.uvs = []; + this.uvs2 = []; - } + this.groups = []; - if ( m.mapLight ) { + this.morphTargets = {}; - create_texture( mpars, 'lightMap', m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy ); + this.skinWeights = []; + this.skinIndices = []; - } + // this.lineDistances = []; - if ( m.mapAO ) { + this.boundingBox = null; + this.boundingSphere = null; - create_texture( mpars, 'aoMap', m.mapAO, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy ); + // update flags - } + this.verticesNeedUpdate = false; + this.normalsNeedUpdate = false; + this.colorsNeedUpdate = false; + this.uvsNeedUpdate = false; + this.groupsNeedUpdate = false; - if ( m.mapBump ) { + } - create_texture( mpars, 'bumpMap', m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy ); + Object.assign( DirectGeometry.prototype, EventDispatcher.prototype, { - } + computeBoundingBox: Geometry.prototype.computeBoundingBox, + computeBoundingSphere: Geometry.prototype.computeBoundingSphere, - if ( m.mapNormal ) { + computeFaceNormals: function () { - create_texture( mpars, 'normalMap', m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy ); + console.warn( 'THREE.DirectGeometry: computeFaceNormals() is not a method of this type of geometry.' ); - } + }, - if ( m.mapSpecular ) { + computeVertexNormals: function () { - create_texture( mpars, 'specularMap', m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy ); + console.warn( 'THREE.DirectGeometry: computeVertexNormals() is not a method of this type of geometry.' ); - } + }, - if ( m.mapAlpha ) { + computeGroups: function ( geometry ) { - create_texture( mpars, 'alphaMap', m.mapAlpha, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy ); + var group; + var groups = []; + var materialIndex; - } + var faces = geometry.faces; - } + for ( var i = 0; i < faces.length; i ++ ) { - // + var face = faces[ i ]; - if ( m.mapBumpScale ) { + // materials - mpars.bumpScale = m.mapBumpScale; + if ( face.materialIndex !== materialIndex ) { - } + materialIndex = face.materialIndex; - if ( m.mapNormalFactor ) { + if ( group !== undefined ) { - mpars.normalScale = new THREE.Vector2( m.mapNormalFactor, m.mapNormalFactor ); + group.count = ( i * 3 ) - group.start; + groups.push( group ); - } + } - var material = new THREE[ mtype ]( mpars ); + group = { + start: i * 3, + materialIndex: materialIndex + }; - if ( m.DbgName !== undefined ) material.name = m.DbgName; + } - return material; + } - }; + if ( group !== undefined ) { - } )() + group.count = ( i * 3 ) - group.start; + groups.push( group ); -}; + } -THREE.Loader.Handlers = { + this.groups = groups; - handlers: [], + }, - add: function ( regex, loader ) { + fromGeometry: function ( geometry ) { - this.handlers.push( regex, loader ); + 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; - get: function ( file ) { + // morphs - for ( var i = 0, l = this.handlers.length; i < l; i += 2 ) { + var morphTargets = geometry.morphTargets; + var morphTargetsLength = morphTargets.length; - var regex = this.handlers[ i ]; - var loader = this.handlers[ i + 1 ]; + var morphTargetsPosition; - if ( regex.test( file ) ) { + if ( morphTargetsLength > 0 ) { - return loader; + morphTargetsPosition = []; - } + for ( var i = 0; i < morphTargetsLength; i ++ ) { - } + morphTargetsPosition[ i ] = []; - return null; + } - } + this.morphTargets.position = morphTargetsPosition; -}; + } -// File:src/loaders/XHRLoader.js + var morphNormals = geometry.morphNormals; + var morphNormalsLength = morphNormals.length; -/** - * @author mrdoob / http://mrdoob.com/ - */ + var morphTargetsNormal; -THREE.XHRLoader = function ( manager ) { + if ( morphNormalsLength > 0 ) { - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + morphTargetsNormal = []; -}; + for ( var i = 0; i < morphNormalsLength; i ++ ) { -THREE.XHRLoader.prototype = { + morphTargetsNormal[ i ] = []; - constructor: THREE.XHRLoader, + } - load: function ( url, onLoad, onProgress, onError ) { + this.morphTargets.normal = morphTargetsNormal; - var scope = this; + } - var cached = THREE.Cache.get( url ); + // skins - if ( cached !== undefined ) { + var skinIndices = geometry.skinIndices; + var skinWeights = geometry.skinWeights; - if ( onLoad ) { + var hasSkinIndices = skinIndices.length === vertices.length; + var hasSkinWeights = skinWeights.length === vertices.length; - setTimeout( function () { + // - onLoad( cached ); + for ( var i = 0; i < faces.length; i ++ ) { - }, 0 ); + var face = faces[ i ]; - } + this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] ); - return cached; + var vertexNormals = face.vertexNormals; - } + if ( vertexNormals.length === 3 ) { - var request = new XMLHttpRequest(); - request.open( 'GET', url, true ); + this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] ); - request.addEventListener( 'load', function ( event ) { + } else { - THREE.Cache.add( url, this.response ); + var normal = face.normal; - if ( onLoad ) onLoad( this.response ); + this.normals.push( normal, normal, normal ); - scope.manager.itemEnd( url ); + } - }, false ); + var vertexColors = face.vertexColors; - if ( onProgress !== undefined ) { + if ( vertexColors.length === 3 ) { - request.addEventListener( 'progress', function ( event ) { + this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] ); - onProgress( event ); + } else { - }, false ); + var color = face.color; - } + this.colors.push( color, color, color ); - request.addEventListener( 'error', function ( event ) { + } - if ( onError ) onError( event ); + if ( hasFaceVertexUv === true ) { - scope.manager.itemError( url ); + var vertexUvs = faceVertexUvs[ 0 ][ i ]; - }, false ); + if ( vertexUvs !== undefined ) { - if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin; - if ( this.responseType !== undefined ) request.responseType = this.responseType; - if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials; + this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] ); - request.send( null ); + } else { - scope.manager.itemStart( url ); + console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i ); - return request; + this.uvs.push( new Vector2(), new Vector2(), new Vector2() ); - }, + } - setResponseType: function ( value ) { + } - this.responseType = value; + if ( hasFaceVertexUv2 === true ) { - }, + var vertexUvs = faceVertexUvs[ 1 ][ i ]; - setCrossOrigin: function ( value ) { + if ( vertexUvs !== undefined ) { - this.crossOrigin = value; + this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] ); - }, + } else { - setWithCredentials: function ( value ) { + console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i ); - this.withCredentials = value; + this.uvs2.push( new Vector2(), new Vector2(), new Vector2() ); - } + } -}; + } -// File:src/loaders/ImageLoader.js + // morphs -/** - * @author mrdoob / http://mrdoob.com/ - */ + for ( var j = 0; j < morphTargetsLength; j ++ ) { -THREE.ImageLoader = function ( manager ) { + var morphTarget = morphTargets[ j ].vertices; - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + morphTargetsPosition[ j ].push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] ); -}; + } -THREE.ImageLoader.prototype = { + for ( var j = 0; j < morphNormalsLength; j ++ ) { - constructor: THREE.ImageLoader, + var morphNormal = morphNormals[ j ].vertexNormals[ i ]; - load: function ( url, onLoad, onProgress, onError ) { + morphTargetsNormal[ j ].push( morphNormal.a, morphNormal.b, morphNormal.c ); - var scope = this; + } - var cached = THREE.Cache.get( url ); + // skins - if ( cached !== undefined ) { + if ( hasSkinIndices ) { - if ( onLoad ) { + this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] ); - setTimeout( function () { + } - onLoad( cached ); + if ( hasSkinWeights ) { - }, 0 ); + this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] ); - } + } - return cached; + } - } + this.computeGroups( geometry ); - var image = document.createElement( 'img' ); + this.verticesNeedUpdate = geometry.verticesNeedUpdate; + this.normalsNeedUpdate = geometry.normalsNeedUpdate; + this.colorsNeedUpdate = geometry.colorsNeedUpdate; + this.uvsNeedUpdate = geometry.uvsNeedUpdate; + this.groupsNeedUpdate = geometry.groupsNeedUpdate; - image.addEventListener( 'load', function ( event ) { + return this; - THREE.Cache.add( url, this ); + }, - if ( onLoad ) onLoad( this ); + dispose: function () { - scope.manager.itemEnd( url ); + this.dispatchEvent( { type: 'dispose' } ); - }, false ); + } - if ( onProgress !== undefined ) { + } ); - image.addEventListener( 'progress', function ( event ) { + /** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + */ - onProgress( event ); + function BufferGeometry() { - }, false ); + Object.defineProperty( this, 'id', { value: GeometryIdCount() } ); - } + this.uuid = exports.Math.generateUUID(); - image.addEventListener( 'error', function ( event ) { + this.name = ''; + this.type = 'BufferGeometry'; - if ( onError ) onError( event ); + this.index = null; + this.attributes = {}; - scope.manager.itemError( url ); + this.morphAttributes = {}; - }, false ); + this.groups = []; - if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin; + this.boundingBox = null; + this.boundingSphere = null; - scope.manager.itemStart( url ); + this.drawRange = { start: 0, count: Infinity }; - image.src = url; + } - return image; + Object.assign( BufferGeometry.prototype, EventDispatcher.prototype, { - }, + isBufferGeometry: true, - setCrossOrigin: function ( value ) { + getIndex: function () { - this.crossOrigin = value; + return this.index; - } + }, -}; + setIndex: function ( index ) { -// File:src/loaders/JSONLoader.js + this.index = index; -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + }, -THREE.JSONLoader = function ( manager ) { + addAttribute: function ( name, attribute ) { - if ( typeof manager === 'boolean' ) { + if ( (attribute && attribute.isBufferAttribute) === false && (attribute && attribute.isInterleavedBufferAttribute) === false ) { - console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' ); - manager = undefined; + console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' ); - } + this.addAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) ); - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + return; - this.withCredentials = false; + } -}; + if ( name === 'index' ) { -THREE.JSONLoader.prototype = { + console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' ); + this.setIndex( attribute ); - constructor: THREE.JSONLoader, + return; - // Deprecated - - get statusDomElement () { + } - if ( this._statusDomElement === undefined ) { + this.attributes[ name ] = attribute; - this._statusDomElement = document.createElement( 'div' ); + return this; - } + }, - console.warn( 'THREE.JSONLoader: .statusDomElement has been removed.' ); - return this._statusDomElement; + getAttribute: function ( name ) { - }, + return this.attributes[ name ]; - load: function( url, onLoad, onProgress, onError ) { + }, - var scope = this; + removeAttribute: function ( name ) { - var texturePath = this.texturePath && ( typeof this.texturePath === "string" ) ? this.texturePath : THREE.Loader.prototype.extractUrlBase( url ); + delete this.attributes[ name ]; - var loader = new THREE.XHRLoader( this.manager ); - loader.setCrossOrigin( this.crossOrigin ); - loader.setWithCredentials( this.withCredentials ); - loader.load( url, function ( text ) { + return this; - var json = JSON.parse( text ); - var metadata = json.metadata; + }, - if ( metadata !== undefined ) { + addGroup: function ( start, count, materialIndex ) { - if ( metadata.type === 'object' ) { + this.groups.push( { - console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' ); - return; + start: start, + count: count, + materialIndex: materialIndex !== undefined ? materialIndex : 0 - } + } ); - if ( metadata.type === 'scene' ) { + }, - console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.SceneLoader instead.' ); - return; + clearGroups: function () { - } + this.groups = []; - } + }, - var object = scope.parse( json, texturePath ); - onLoad( object.geometry, object.materials ); + setDrawRange: function ( start, count ) { - } ); + this.drawRange.start = start; + this.drawRange.count = count; - }, + }, - setCrossOrigin: function ( value ) { + applyMatrix: function ( matrix ) { - this.crossOrigin = value; + var position = this.attributes.position; - }, + if ( position !== undefined ) { - setTexturePath: function ( value ) { + matrix.applyToVector3Array( position.array ); + position.needsUpdate = true; - this.texturePath = value; + } - }, + var normal = this.attributes.normal; - parse: function ( json, texturePath ) { + if ( normal !== undefined ) { - var geometry = new THREE.Geometry(), - scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0; + var normalMatrix = new Matrix3().getNormalMatrix( matrix ); - parseModel( scale ); + normalMatrix.applyToVector3Array( normal.array ); + normal.needsUpdate = true; - parseSkin(); - parseMorphing( scale ); + } - geometry.computeFaceNormals(); - geometry.computeBoundingSphere(); + if ( this.boundingBox !== null ) { - function parseModel( scale ) { + this.computeBoundingBox(); - function isBitSet( value, position ) { + } - return value & ( 1 << position ); + if ( this.boundingSphere !== null ) { - } + this.computeBoundingSphere(); - var i, j, fi, + } - offset, zLength, + return this; - colorIndex, normalIndex, uvIndex, materialIndex, + }, - type, - isQuad, - hasMaterial, - hasFaceVertexUv, - hasFaceNormal, hasFaceVertexNormal, - hasFaceColor, hasFaceVertexColor, + rotateX: function () { - vertex, face, faceA, faceB, hex, normal, + // rotate geometry around world x-axis - uvLayer, uv, u, v, + var m1; - faces = json.faces, - vertices = json.vertices, - normals = json.normals, - colors = json.colors, + return function rotateX( angle ) { - nUvLayers = 0; + if ( m1 === undefined ) m1 = new Matrix4(); - if ( json.uvs !== undefined ) { + m1.makeRotationX( angle ); - // disregard empty arrays + this.applyMatrix( m1 ); - for ( i = 0; i < json.uvs.length; i ++ ) { + return this; - if ( json.uvs[ i ].length ) nUvLayers ++; + }; - } + }(), - for ( i = 0; i < nUvLayers; i ++ ) { + rotateY: function () { - geometry.faceVertexUvs[ i ] = []; + // rotate geometry around world y-axis - } + var m1; - } + return function rotateY( angle ) { - offset = 0; - zLength = vertices.length; + if ( m1 === undefined ) m1 = new Matrix4(); - while ( offset < zLength ) { + m1.makeRotationY( angle ); - vertex = new THREE.Vector3(); + this.applyMatrix( m1 ); - vertex.x = vertices[ offset ++ ] * scale; - vertex.y = vertices[ offset ++ ] * scale; - vertex.z = vertices[ offset ++ ] * scale; + return this; - geometry.vertices.push( vertex ); + }; - } + }(), - offset = 0; - zLength = faces.length; + rotateZ: function () { - while ( offset < zLength ) { + // rotate geometry around world z-axis - type = faces[ offset ++ ]; + var m1; + return function rotateZ( angle ) { - isQuad = isBitSet( type, 0 ); - hasMaterial = isBitSet( type, 1 ); - hasFaceVertexUv = isBitSet( type, 3 ); - hasFaceNormal = isBitSet( type, 4 ); - hasFaceVertexNormal = isBitSet( type, 5 ); - hasFaceColor = isBitSet( type, 6 ); - hasFaceVertexColor = isBitSet( type, 7 ); + if ( m1 === undefined ) m1 = new Matrix4(); - // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor); + m1.makeRotationZ( angle ); - if ( isQuad ) { + this.applyMatrix( m1 ); - faceA = new THREE.Face3(); - faceA.a = faces[ offset ]; - faceA.b = faces[ offset + 1 ]; - faceA.c = faces[ offset + 3 ]; + return this; - faceB = new THREE.Face3(); - faceB.a = faces[ offset + 1 ]; - faceB.b = faces[ offset + 2 ]; - faceB.c = faces[ offset + 3 ]; + }; - offset += 4; + }(), - if ( hasMaterial ) { + translate: function () { - materialIndex = faces[ offset ++ ]; - faceA.materialIndex = materialIndex; - faceB.materialIndex = materialIndex; + // translate geometry - } + var m1; - // to get face <=> uv index correspondence + return function translate( x, y, z ) { - fi = geometry.faces.length; + if ( m1 === undefined ) m1 = new Matrix4(); - if ( hasFaceVertexUv ) { + m1.makeTranslation( x, y, z ); - for ( i = 0; i < nUvLayers; i ++ ) { + this.applyMatrix( m1 ); - uvLayer = json.uvs[ i ]; + return this; - geometry.faceVertexUvs[ i ][ fi ] = []; - geometry.faceVertexUvs[ i ][ fi + 1 ] = []; + }; - for ( j = 0; j < 4; j ++ ) { + }(), - uvIndex = faces[ offset ++ ]; + scale: function () { - u = uvLayer[ uvIndex * 2 ]; - v = uvLayer[ uvIndex * 2 + 1 ]; + // scale geometry - uv = new THREE.Vector2( u, v ); + var m1; - if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv ); - if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv ); + return function scale( x, y, z ) { - } + if ( m1 === undefined ) m1 = new Matrix4(); - } + m1.makeScale( x, y, z ); - } + this.applyMatrix( m1 ); - if ( hasFaceNormal ) { + return this; - normalIndex = faces[ offset ++ ] * 3; + }; - faceA.normal.set( - normals[ normalIndex ++ ], - normals[ normalIndex ++ ], - normals[ normalIndex ] - ); + }(), - faceB.normal.copy( faceA.normal ); + lookAt: function () { - } + var obj; - if ( hasFaceVertexNormal ) { + return function lookAt( vector ) { - for ( i = 0; i < 4; i ++ ) { + if ( obj === undefined ) obj = new Object3D(); - normalIndex = faces[ offset ++ ] * 3; + obj.lookAt( vector ); - normal = new THREE.Vector3( - normals[ normalIndex ++ ], - normals[ normalIndex ++ ], - normals[ normalIndex ] - ); + obj.updateMatrix(); + this.applyMatrix( obj.matrix ); - if ( i !== 2 ) faceA.vertexNormals.push( normal ); - if ( i !== 0 ) faceB.vertexNormals.push( normal ); + }; - } + }(), - } + center: function () { + this.computeBoundingBox(); - if ( hasFaceColor ) { + var offset = this.boundingBox.getCenter().negate(); - colorIndex = faces[ offset ++ ]; - hex = colors[ colorIndex ]; + this.translate( offset.x, offset.y, offset.z ); - faceA.color.setHex( hex ); - faceB.color.setHex( hex ); + return offset; - } + }, + setFromObject: function ( object ) { - if ( hasFaceVertexColor ) { + // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this ); - for ( i = 0; i < 4; i ++ ) { + var geometry = object.geometry; - colorIndex = faces[ offset ++ ]; - hex = colors[ colorIndex ]; + if ( (object && object.isPoints) || (object && object.isLine) ) { - if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) ); - if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) ); + var positions = new Float32Attribute( geometry.vertices.length * 3, 3 ); + var colors = new Float32Attribute( geometry.colors.length * 3, 3 ); - } + this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) ); + this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) ); - } + if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) { - geometry.faces.push( faceA ); - geometry.faces.push( faceB ); + var lineDistances = new Float32Attribute( geometry.lineDistances.length, 1 ); - } else { + this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) ); - face = new THREE.Face3(); - face.a = faces[ offset ++ ]; - face.b = faces[ offset ++ ]; - face.c = faces[ offset ++ ]; + } - if ( hasMaterial ) { + if ( geometry.boundingSphere !== null ) { - materialIndex = faces[ offset ++ ]; - face.materialIndex = materialIndex; + this.boundingSphere = geometry.boundingSphere.clone(); - } + } - // to get face <=> uv index correspondence + if ( geometry.boundingBox !== null ) { - fi = geometry.faces.length; + this.boundingBox = geometry.boundingBox.clone(); - if ( hasFaceVertexUv ) { + } - for ( i = 0; i < nUvLayers; i ++ ) { + } else if ( (object && object.isMesh) ) { - uvLayer = json.uvs[ i ]; + if ( (geometry && geometry.isGeometry) ) { - geometry.faceVertexUvs[ i ][ fi ] = []; + this.fromGeometry( geometry ); - for ( j = 0; j < 3; j ++ ) { + } - uvIndex = faces[ offset ++ ]; + } - u = uvLayer[ uvIndex * 2 ]; - v = uvLayer[ uvIndex * 2 + 1 ]; + return this; - uv = new THREE.Vector2( u, v ); + }, - geometry.faceVertexUvs[ i ][ fi ].push( uv ); + updateFromObject: function ( object ) { - } + var geometry = object.geometry; - } + if ( (object && object.isMesh) ) { - } + var direct = geometry.__directGeometry; - if ( hasFaceNormal ) { + if ( geometry.elementsNeedUpdate === true ) { - normalIndex = faces[ offset ++ ] * 3; + direct = undefined; + geometry.elementsNeedUpdate = false; - face.normal.set( - normals[ normalIndex ++ ], - normals[ normalIndex ++ ], - normals[ normalIndex ] - ); + } - } + if ( direct === undefined ) { - if ( hasFaceVertexNormal ) { + return this.fromGeometry( geometry ); - for ( i = 0; i < 3; i ++ ) { + } - normalIndex = faces[ offset ++ ] * 3; + direct.verticesNeedUpdate = geometry.verticesNeedUpdate; + direct.normalsNeedUpdate = geometry.normalsNeedUpdate; + direct.colorsNeedUpdate = geometry.colorsNeedUpdate; + direct.uvsNeedUpdate = geometry.uvsNeedUpdate; + direct.groupsNeedUpdate = geometry.groupsNeedUpdate; - normal = new THREE.Vector3( - normals[ normalIndex ++ ], - normals[ normalIndex ++ ], - normals[ normalIndex ] - ); + geometry.verticesNeedUpdate = false; + geometry.normalsNeedUpdate = false; + geometry.colorsNeedUpdate = false; + geometry.uvsNeedUpdate = false; + geometry.groupsNeedUpdate = false; - face.vertexNormals.push( normal ); + geometry = direct; - } + } - } + var attribute; + if ( geometry.verticesNeedUpdate === true ) { - if ( hasFaceColor ) { + attribute = this.attributes.position; - colorIndex = faces[ offset ++ ]; - face.color.setHex( colors[ colorIndex ] ); + if ( attribute !== undefined ) { - } + attribute.copyVector3sArray( geometry.vertices ); + attribute.needsUpdate = true; + } - if ( hasFaceVertexColor ) { + geometry.verticesNeedUpdate = false; - for ( i = 0; i < 3; i ++ ) { + } - colorIndex = faces[ offset ++ ]; - face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) ); + if ( geometry.normalsNeedUpdate === true ) { - } + attribute = this.attributes.normal; - } + if ( attribute !== undefined ) { - geometry.faces.push( face ); + attribute.copyVector3sArray( geometry.normals ); + attribute.needsUpdate = true; - } + } - } + geometry.normalsNeedUpdate = false; - }; + } - function parseSkin() { + if ( geometry.colorsNeedUpdate === true ) { - var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2; + attribute = this.attributes.color; - if ( json.skinWeights ) { + if ( attribute !== undefined ) { - for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) { + attribute.copyColorsArray( geometry.colors ); + attribute.needsUpdate = true; - 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 THREE.Vector4( x, y, z, w ) ); + geometry.colorsNeedUpdate = false; - } + } - } + if ( geometry.uvsNeedUpdate ) { - if ( json.skinIndices ) { + attribute = this.attributes.uv; - for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) { + if ( attribute !== undefined ) { - var a = json.skinIndices[ i ]; - var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0; - var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0; - var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0; + attribute.copyVector2sArray( geometry.uvs ); + attribute.needsUpdate = true; - geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) ); + } - } + geometry.uvsNeedUpdate = false; - } + } - geometry.bones = json.bones; + if ( geometry.lineDistancesNeedUpdate ) { - if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) { + attribute = this.attributes.lineDistance; - console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' + - geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' ); + if ( attribute !== undefined ) { - } + attribute.copyArray( geometry.lineDistances ); + attribute.needsUpdate = true; + } - // could change this to json.animations[0] or remove completely + geometry.lineDistancesNeedUpdate = false; - geometry.animation = json.animation; - geometry.animations = json.animations; + } - }; + if ( geometry.groupsNeedUpdate ) { - function parseMorphing( scale ) { + geometry.computeGroups( object.geometry ); + this.groups = geometry.groups; - if ( json.morphTargets !== undefined ) { + geometry.groupsNeedUpdate = false; - var i, l, v, vl, dstVertices, srcVertices; + } - for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) { + return this; - geometry.morphTargets[ i ] = {}; - geometry.morphTargets[ i ].name = json.morphTargets[ i ].name; - geometry.morphTargets[ i ].vertices = []; + }, - dstVertices = geometry.morphTargets[ i ].vertices; - srcVertices = json.morphTargets[ i ].vertices; + fromGeometry: function ( geometry ) { - for ( v = 0, vl = srcVertices.length; v < vl; v += 3 ) { + geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry ); - var vertex = new THREE.Vector3(); - vertex.x = srcVertices[ v ] * scale; - vertex.y = srcVertices[ v + 1 ] * scale; - vertex.z = srcVertices[ v + 2 ] * scale; + return this.fromDirectGeometry( geometry.__directGeometry ); - dstVertices.push( vertex ); + }, - } + fromDirectGeometry: function ( geometry ) { - } + var positions = new Float32Array( geometry.vertices.length * 3 ); + this.addAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) ); - } + if ( geometry.normals.length > 0 ) { - if ( json.morphColors !== undefined ) { + var normals = new Float32Array( geometry.normals.length * 3 ); + this.addAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) ); - var i, l, c, cl, dstColors, srcColors, color; + } - for ( i = 0, l = json.morphColors.length; i < l; i ++ ) { + if ( geometry.colors.length > 0 ) { - geometry.morphColors[ i ] = {}; - geometry.morphColors[ i ].name = json.morphColors[ i ].name; - geometry.morphColors[ i ].colors = []; + var colors = new Float32Array( geometry.colors.length * 3 ); + this.addAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) ); - dstColors = geometry.morphColors[ i ].colors; - srcColors = json.morphColors[ i ].colors; + } - for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) { + if ( geometry.uvs.length > 0 ) { - color = new THREE.Color( 0xffaa00 ); - color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] ); - dstColors.push( color ); + var uvs = new Float32Array( geometry.uvs.length * 2 ); + this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) ); - } + } - } + if ( geometry.uvs2.length > 0 ) { - } + var uvs2 = new Float32Array( geometry.uvs2.length * 2 ); + this.addAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) ); - }; + } - if ( json.materials === undefined || json.materials.length === 0 ) { + if ( geometry.indices.length > 0 ) { - return { geometry: geometry }; + 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 ) ); - } else { + } - var materials = THREE.Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin ); + // groups - return { geometry: geometry, materials: materials }; + this.groups = geometry.groups; - } + // morphs - } + for ( var name in geometry.morphTargets ) { -}; + var array = []; + var morphTargets = geometry.morphTargets[ name ]; -// File:src/loaders/LoadingManager.js + for ( var i = 0, l = morphTargets.length; i < l; i ++ ) { -/** - * @author mrdoob / http://mrdoob.com/ - */ + var morphTarget = morphTargets[ i ]; -THREE.LoadingManager = function ( onLoad, onProgress, onError ) { + var attribute = new Float32Attribute( morphTarget.length * 3, 3 ); - var scope = this; + array.push( attribute.copyVector3sArray( morphTarget ) ); - var isLoading = false, itemsLoaded = 0, itemsTotal = 0; + } - this.onStart = undefined; - this.onLoad = onLoad; - this.onProgress = onProgress; - this.onError = onError; + this.morphAttributes[ name ] = array; - this.itemStart = function ( url ) { + } - itemsTotal ++; + // skinning - if ( isLoading === false ) { + if ( geometry.skinIndices.length > 0 ) { - if ( scope.onStart !== undefined ) { + var skinIndices = new Float32Attribute( geometry.skinIndices.length * 4, 4 ); + this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) ); - scope.onStart( url, itemsLoaded, itemsTotal ); + } - } + if ( geometry.skinWeights.length > 0 ) { - } + var skinWeights = new Float32Attribute( geometry.skinWeights.length * 4, 4 ); + this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) ); - isLoading = true; + } - }; + // - this.itemEnd = function ( url ) { + if ( geometry.boundingSphere !== null ) { - itemsLoaded ++; + this.boundingSphere = geometry.boundingSphere.clone(); - if ( scope.onProgress !== undefined ) { + } - scope.onProgress( url, itemsLoaded, itemsTotal ); + if ( geometry.boundingBox !== null ) { - } + this.boundingBox = geometry.boundingBox.clone(); - if ( itemsLoaded === itemsTotal ) { + } - isLoading = false; + return this; - if ( scope.onLoad !== undefined ) { + }, - scope.onLoad(); + computeBoundingBox: function () { - } + if ( this.boundingBox === null ) { - } + this.boundingBox = new Box3(); - }; + } - this.itemError = function ( url ) { + var positions = this.attributes.position.array; - if ( scope.onError !== undefined ) { + if ( positions !== undefined ) { - scope.onError( url ); + this.boundingBox.setFromArray( positions ); - } + } else { - }; + this.boundingBox.makeEmpty(); -}; + } -THREE.DefaultLoadingManager = new THREE.LoadingManager(); + if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) { -// File:src/loaders/BufferGeometryLoader.js + console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this ); -/** - * @author mrdoob / http://mrdoob.com/ - */ + } -THREE.BufferGeometryLoader = function ( manager ) { + }, - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + computeBoundingSphere: function () { -}; + var box = new Box3(); + var vector = new Vector3(); -THREE.BufferGeometryLoader.prototype = { + return function computeBoundingSphere() { - constructor: THREE.BufferGeometryLoader, + if ( this.boundingSphere === null ) { - load: function ( url, onLoad, onProgress, onError ) { + this.boundingSphere = new Sphere(); - var scope = this; + } - var loader = new THREE.XHRLoader( scope.manager ); - loader.setCrossOrigin( this.crossOrigin ); - loader.load( url, function ( text ) { + var positions = this.attributes.position; - onLoad( scope.parse( JSON.parse( text ) ) ); + if ( positions ) { - }, onProgress, onError ); + var array = positions.array; + var center = this.boundingSphere.center; - }, + box.setFromArray( array ); + box.getCenter( center ); - setCrossOrigin: function ( value ) { + // hoping to find a boundingSphere with a radius smaller than the + // boundingSphere of the boundingBox: sqrt(3) smaller in the best case - this.crossOrigin = value; + var maxRadiusSq = 0; - }, + for ( var i = 0, il = array.length; i < il; i += 3 ) { - parse: function ( json ) { + vector.fromArray( array, i ); + maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) ); - var geometry = new THREE.BufferGeometry(); + } - var index = json.data.index; + this.boundingSphere.radius = Math.sqrt( maxRadiusSq ); - if ( index !== undefined ) { + if ( isNaN( this.boundingSphere.radius ) ) { - var typedArray = new self[ index.type ]( index.array ); - geometry.setIndex( new THREE.BufferAttribute( typedArray, 1 ) ); + console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this ); - } + } - var attributes = json.data.attributes; + } - for ( var key in attributes ) { + }; - var attribute = attributes[ key ]; - var typedArray = new self[ attribute.type ]( attribute.array ); + }(), - geometry.addAttribute( key, new THREE.BufferAttribute( typedArray, attribute.itemSize ) ); + computeFaceNormals: function () { - } + // backwards compatibility - var groups = json.data.groups || json.data.drawcalls || json.data.offsets; + }, - if ( groups !== undefined ) { + computeVertexNormals: function () { - for ( var i = 0, n = groups.length; i !== n; ++ i ) { + var index = this.index; + var attributes = this.attributes; + var groups = this.groups; - var group = groups[ i ]; + if ( attributes.position ) { - geometry.addGroup( group.start, group.count ); + var positions = attributes.position.array; - } + if ( attributes.normal === undefined ) { - } + this.addAttribute( 'normal', new BufferAttribute( new Float32Array( positions.length ), 3 ) ); - var boundingSphere = json.data.boundingSphere; + } else { - if ( boundingSphere !== undefined ) { + // reset existing normals to zero - var center = new THREE.Vector3(); + var array = attributes.normal.array; - if ( boundingSphere.center !== undefined ) { + for ( var i = 0, il = array.length; i < il; i ++ ) { - center.fromArray( boundingSphere.center ); + array[ i ] = 0; - } + } - geometry.boundingSphere = new THREE.Sphere( center, boundingSphere.radius ); + } - } + var normals = attributes.normal.array; - return geometry; + var vA, vB, vC, - } + pA = new Vector3(), + pB = new Vector3(), + pC = new Vector3(), -}; + cb = new Vector3(), + ab = new Vector3(); -// File:src/loaders/MaterialLoader.js + // indexed elements -/** - * @author mrdoob / http://mrdoob.com/ - */ + if ( index ) { -THREE.MaterialLoader = function ( manager ) { + var indices = index.array; - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; - this.textures = {}; + if ( groups.length === 0 ) { -}; + this.addGroup( 0, indices.length ); -THREE.MaterialLoader.prototype = { + } - constructor: THREE.MaterialLoader, + for ( var j = 0, jl = groups.length; j < jl; ++ j ) { - load: function ( url, onLoad, onProgress, onError ) { + var group = groups[ j ]; - var scope = this; + var start = group.start; + var count = group.count; - var loader = new THREE.XHRLoader( scope.manager ); - loader.setCrossOrigin( this.crossOrigin ); - loader.load( url, function ( text ) { + for ( var i = start, il = start + count; i < il; i += 3 ) { - onLoad( scope.parse( JSON.parse( text ) ) ); + vA = indices[ i + 0 ] * 3; + vB = indices[ i + 1 ] * 3; + vC = indices[ i + 2 ] * 3; - }, onProgress, onError ); + pA.fromArray( positions, vA ); + pB.fromArray( positions, vB ); + pC.fromArray( positions, vC ); - }, + cb.subVectors( pC, pB ); + ab.subVectors( pA, pB ); + cb.cross( ab ); - setCrossOrigin: function ( value ) { + normals[ vA ] += cb.x; + normals[ vA + 1 ] += cb.y; + normals[ vA + 2 ] += cb.z; - this.crossOrigin = value; + normals[ vB ] += cb.x; + normals[ vB + 1 ] += cb.y; + normals[ vB + 2 ] += cb.z; - }, + normals[ vC ] += cb.x; + normals[ vC + 1 ] += cb.y; + normals[ vC + 2 ] += cb.z; - setTextures: function ( value ) { + } - this.textures = value; + } - }, + } else { - getTexture: function ( name ) { + // non-indexed elements (unconnected triangle soup) - var textures = this.textures; + for ( var i = 0, il = positions.length; i < il; i += 9 ) { - if ( textures[ name ] === undefined ) { + pA.fromArray( positions, i ); + pB.fromArray( positions, i + 3 ); + pC.fromArray( positions, i + 6 ); - console.warn( 'THREE.MaterialLoader: Undefined texture', name ); + cb.subVectors( pC, pB ); + ab.subVectors( pA, pB ); + cb.cross( ab ); - } + normals[ i ] = cb.x; + normals[ i + 1 ] = cb.y; + normals[ i + 2 ] = cb.z; - return textures[ name ]; + 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; - parse: function ( json ) { + } - var material = new THREE[ json.type ]; - material.uuid = json.uuid; + } - if ( json.name !== undefined ) material.name = json.name; - if ( json.color !== undefined ) material.color.setHex( json.color ); - 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.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.wireframe !== undefined ) material.wireframe = json.wireframe; - if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth; + this.normalizeNormals(); - // for PointsMaterial - if ( json.size !== undefined ) material.size = json.size; - if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation; + attributes.normal.needsUpdate = true; - // maps + } - if ( json.map !== undefined ) material.map = this.getTexture( json.map ); + }, - if ( json.alphaMap !== undefined ) { + merge: function ( geometry, offset ) { - material.alphaMap = this.getTexture( json.alphaMap ); - material.transparent = true; + if ( (geometry && geometry.isBufferGeometry) === false ) { - } + console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry ); + return; - 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 ) material.normalScale = new THREE.Vector2( json.normalScale, json.normalScale ); + if ( offset === undefined ) offset = 0; - 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 attributes = this.attributes; - if ( json.specularMap !== undefined ) material.specularMap = this.getTexture( json.specularMap ); + for ( var key in attributes ) { - if ( json.envMap !== undefined ) { + if ( geometry.attributes[ key ] === undefined ) continue; - material.envMap = this.getTexture( json.envMap ); - material.combine = THREE.MultiplyOperation; + var attribute1 = attributes[ key ]; + var attributeArray1 = attribute1.array; - } + var attribute2 = geometry.attributes[ key ]; + var attributeArray2 = attribute2.array; - if ( json.reflectivity ) material.reflectivity = json.reflectivity; + var attributeSize = attribute2.itemSize; - if ( json.lightMap !== undefined ) material.lightMap = this.getTexture( json.lightMap ); - if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity; + for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) { - if ( json.aoMap !== undefined ) material.aoMap = this.getTexture( json.aoMap ); - if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity; + attributeArray1[ j ] = attributeArray2[ i ]; - // MeshFaceMaterial + } - if ( json.materials !== undefined ) { + } - for ( var i = 0, l = json.materials.length; i < l; i ++ ) { + return this; - material.materials.push( this.parse( json.materials[ i ] ) ); + }, - } + normalizeNormals: function () { - } + var normals = this.attributes.normal.array; - return material; + var x, y, z, n; - } + for ( var i = 0, il = normals.length; i < il; i += 3 ) { -}; + x = normals[ i ]; + y = normals[ i + 1 ]; + z = normals[ i + 2 ]; -// File:src/loaders/ObjectLoader.js + n = 1.0 / Math.sqrt( x * x + y * y + z * z ); -/** - * @author mrdoob / http://mrdoob.com/ - */ + normals[ i ] *= n; + normals[ i + 1 ] *= n; + normals[ i + 2 ] *= n; -THREE.ObjectLoader = function ( manager ) { + } - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; - this.texturePath = ''; + }, -}; + toNonIndexed: function () { -THREE.ObjectLoader.prototype = { + if ( this.index === null ) { - constructor: THREE.ObjectLoader, + console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' ); + return this; - load: function ( url, onLoad, onProgress, onError ) { + } - if ( this.texturePath === '' ) { + var geometry2 = new BufferGeometry(); - this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 ); + var indices = this.index.array; + var attributes = this.attributes; - } + for ( var name in attributes ) { - var scope = this; + var attribute = attributes[ name ]; - var loader = new THREE.XHRLoader( scope.manager ); - loader.setCrossOrigin( this.crossOrigin ); - loader.load( url, function ( text ) { + var array = attribute.array; + var itemSize = attribute.itemSize; - scope.parse( JSON.parse( text ), onLoad ); + var array2 = new array.constructor( indices.length * itemSize ); - }, onProgress, onError ); + var index = 0, index2 = 0; - }, + for ( var i = 0, l = indices.length; i < l; i ++ ) { - setTexturePath: function ( value ) { + index = indices[ i ] * itemSize; - this.texturePath = value; + for ( var j = 0; j < itemSize; j ++ ) { - }, + array2[ index2 ++ ] = array[ index ++ ]; - setCrossOrigin: function ( value ) { + } - this.crossOrigin = value; + } - }, + geometry2.addAttribute( name, new BufferAttribute( array2, itemSize ) ); - parse: function ( json, onLoad ) { + } - var geometries = this.parseGeometries( json.geometries ); + return geometry2; - var images = this.parseImages( json.images, function () { + }, - if ( onLoad !== undefined ) onLoad( object ); + toJSON: function () { - } ); + var data = { + metadata: { + version: 4.4, + type: 'BufferGeometry', + generator: 'BufferGeometry.toJSON' + } + }; - var textures = this.parseTextures( json.textures, images ); - var materials = this.parseMaterials( json.materials, textures ); - var object = this.parseObject( json.object, geometries, materials ); + // standard BufferGeometry serialization - if ( json.images === undefined || json.images.length === 0 ) { + data.uuid = this.uuid; + data.type = this.type; + if ( this.name !== '' ) data.name = this.name; - if ( onLoad !== undefined ) onLoad( object ); + if ( this.parameters !== undefined ) { - } + var parameters = this.parameters; - return object; + for ( var key in parameters ) { - }, + if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ]; - parseGeometries: function ( json ) { + } - var geometries = {}; + return data; - if ( json !== undefined ) { + } - var geometryLoader = new THREE.JSONLoader(); - var bufferGeometryLoader = new THREE.BufferGeometryLoader(); + data.data = { attributes: {} }; - for ( var i = 0, l = json.length; i < l; i ++ ) { + var index = this.index; - var geometry; - var data = json[ i ]; + if ( index !== null ) { - switch ( data.type ) { + var array = Array.prototype.slice.call( index.array ); - case 'PlaneGeometry': - case 'PlaneBufferGeometry': + data.data.index = { + type: index.array.constructor.name, + array: array + }; - geometry = new THREE[ data.type ]( - data.width, - data.height, - data.widthSegments, - data.heightSegments - ); + } - break; + var attributes = this.attributes; - case 'BoxGeometry': - case 'CubeGeometry': // backwards compatible + for ( var key in attributes ) { - geometry = new THREE.BoxGeometry( - data.width, - data.height, - data.depth, - data.widthSegments, - data.heightSegments, - data.depthSegments - ); + var attribute = attributes[ key ]; - break; + var array = Array.prototype.slice.call( attribute.array ); - case 'CircleBufferGeometry': + data.data.attributes[ key ] = { + itemSize: attribute.itemSize, + type: attribute.array.constructor.name, + array: array, + normalized: attribute.normalized + }; - geometry = new THREE.CircleBufferGeometry( - data.radius, - data.segments, - data.thetaStart, - data.thetaLength - ); + } - break; + var groups = this.groups; - case 'CircleGeometry': + if ( groups.length > 0 ) { - geometry = new THREE.CircleGeometry( - data.radius, - data.segments, - data.thetaStart, - data.thetaLength - ); + data.data.groups = JSON.parse( JSON.stringify( groups ) ); - break; + } - case 'CylinderGeometry': + var boundingSphere = this.boundingSphere; - geometry = new THREE.CylinderGeometry( - data.radiusTop, - data.radiusBottom, - data.height, - data.radialSegments, - data.heightSegments, - data.openEnded, - data.thetaStart, - data.thetaLength - ); + if ( boundingSphere !== null ) { - break; + data.data.boundingSphere = { + center: boundingSphere.center.toArray(), + radius: boundingSphere.radius + }; - case 'SphereGeometry': + } - geometry = new THREE.SphereGeometry( - data.radius, - data.widthSegments, - data.heightSegments, - data.phiStart, - data.phiLength, - data.thetaStart, - data.thetaLength - ); + return data; - break; + }, - case 'SphereBufferGeometry': + clone: function () { - geometry = new THREE.SphereBufferGeometry( - data.radius, - data.widthSegments, - data.heightSegments, - data.phiStart, - data.phiLength, - data.thetaStart, - data.thetaLength - ); + /* + // Handle primitives - break; + var parameters = this.parameters; - case 'DodecahedronGeometry': + if ( parameters !== undefined ) { - geometry = new THREE.DodecahedronGeometry( - data.radius, - data.detail - ); + var values = []; - break; + for ( var key in parameters ) { - case 'IcosahedronGeometry': + values.push( parameters[ key ] ); - geometry = new THREE.IcosahedronGeometry( - data.radius, - data.detail - ); + } - break; + var geometry = Object.create( this.constructor.prototype ); + this.constructor.apply( geometry, values ); + return geometry; - case 'OctahedronGeometry': + } - geometry = new THREE.OctahedronGeometry( - data.radius, - data.detail - ); + return new this.constructor().copy( this ); + */ - break; + return new BufferGeometry().copy( this ); - case 'TetrahedronGeometry': + }, - geometry = new THREE.TetrahedronGeometry( - data.radius, - data.detail - ); + copy: function ( source ) { - break; + var index = source.index; - case 'RingGeometry': + if ( index !== null ) { - geometry = new THREE.RingGeometry( - data.innerRadius, - data.outerRadius, - data.thetaSegments, - data.phiSegments, - data.thetaStart, - data.thetaLength - ); + this.setIndex( index.clone() ); - break; + } - case 'TorusGeometry': + var attributes = source.attributes; - geometry = new THREE.TorusGeometry( - data.radius, - data.tube, - data.radialSegments, - data.tubularSegments, - data.arc - ); + for ( var name in attributes ) { - break; + var attribute = attributes[ name ]; + this.addAttribute( name, attribute.clone() ); - case 'TorusKnotGeometry': + } - geometry = new THREE.TorusKnotGeometry( - data.radius, - data.tube, - data.radialSegments, - data.tubularSegments, - data.p, - data.q, - data.heightScale - ); + var groups = source.groups; - break; + for ( var i = 0, l = groups.length; i < l; i ++ ) { - case 'TextGeometry': + var group = groups[ i ]; + this.addGroup( group.start, group.count, group.materialIndex ); - geometry = new THREE.TextGeometry( - data.text, - data.data - ); + } - break; + return this; - case 'BufferGeometry': + }, - geometry = bufferGeometryLoader.parse( data ); + dispose: function () { - break; + this.dispatchEvent( { type: 'dispose' } ); - case 'Geometry': + } - geometry = geometryLoader.parse( data.data, this.texturePath ).geometry; + } ); - break; + BufferGeometry.MaxIndex = 65535; - default: + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * @author mikael emtinger / http://gomo.se/ + * @author jonobr1 / http://jonobr1.com/ + */ - console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' ); + function Mesh( geometry, material ) { - continue; + Object3D.call( this ); - } + this.type = 'Mesh'; - geometry.uuid = data.uuid; + this.geometry = geometry !== undefined ? geometry : new BufferGeometry(); + this.material = material !== undefined ? material : new MeshBasicMaterial( { color: Math.random() * 0xffffff } ); - if ( data.name !== undefined ) geometry.name = data.name; + this.drawMode = TrianglesDrawMode; - geometries[ data.uuid ] = geometry; + this.updateMorphTargets(); - } + } - } + Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), { - return geometries; + constructor: Mesh, - }, + isMesh: true, - parseMaterials: function ( json, textures ) { + setDrawMode: function ( value ) { - var materials = {}; + this.drawMode = value; - if ( json !== undefined ) { + }, - var loader = new THREE.MaterialLoader(); - loader.setTextures( textures ); + copy: function ( source ) { - for ( var i = 0, l = json.length; i < l; i ++ ) { + Object3D.prototype.copy.call( this, source ); - var material = loader.parse( json[ i ] ); - materials[ material.uuid ] = material; + this.drawMode = source.drawMode; - } + return this; - } + }, - return materials; + updateMorphTargets: function () { - }, + var morphTargets = this.geometry.morphTargets; - parseImages: function ( json, onLoad ) { + if ( morphTargets !== undefined && morphTargets.length > 0 ) { - var scope = this; - var images = {}; + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; - function loadImage( url ) { + for ( var m = 0, ml = morphTargets.length; m < ml; m ++ ) { - scope.manager.itemStart( url ); + this.morphTargetInfluences.push( 0 ); + this.morphTargetDictionary[ morphTargets[ m ].name ] = m; - return loader.load( url, function () { + } - scope.manager.itemEnd( url ); + } - } ); + }, - } + raycast: ( function () { - if ( json !== undefined && json.length > 0 ) { + var inverseMatrix = new Matrix4(); + var ray = new Ray(); + var sphere = new Sphere(); - var manager = new THREE.LoadingManager( onLoad ); + var vA = new Vector3(); + var vB = new Vector3(); + var vC = new Vector3(); - var loader = new THREE.ImageLoader( manager ); - loader.setCrossOrigin( this.crossOrigin ); + var tempA = new Vector3(); + var tempB = new Vector3(); + var tempC = new Vector3(); - for ( var i = 0, l = json.length; i < l; i ++ ) { + var uvA = new Vector2(); + var uvB = new Vector2(); + var uvC = new Vector2(); - var image = json[ i ]; - var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url; + var barycoord = new Vector3(); - images[ image.uuid ] = loadImage( path ); + var intersectionPoint = new Vector3(); + var intersectionPointWorld = new Vector3(); - } + function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) { - } + Triangle.barycoordFromPoint( point, p1, p2, p3, barycoord ); - return images; + uv1.multiplyScalar( barycoord.x ); + uv2.multiplyScalar( barycoord.y ); + uv3.multiplyScalar( barycoord.z ); - }, + uv1.add( uv2 ).add( uv3 ); - parseTextures: function ( json, images ) { + return uv1.clone(); - function parseConstant( value ) { + } - if ( typeof( value ) === 'number' ) return value; + function checkIntersection( object, raycaster, ray, pA, pB, pC, point ) { - console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value ); + var intersect; + var material = object.material; - return THREE[ value ]; + if ( material.side === BackSide ) { - } + intersect = ray.intersectTriangle( pC, pB, pA, true, point ); - var textures = {}; + } else { - if ( json !== undefined ) { + intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point ); - for ( var i = 0, l = json.length; i < l; i ++ ) { + } - var data = json[ i ]; + if ( intersect === null ) return null; - if ( data.image === undefined ) { + intersectionPointWorld.copy( point ); + intersectionPointWorld.applyMatrix4( object.matrixWorld ); - console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid ); + var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld ); - } + if ( distance < raycaster.near || distance > raycaster.far ) return null; - if ( images[ data.image ] === undefined ) { + return { + distance: distance, + point: intersectionPointWorld.clone(), + object: object + }; - console.warn( 'THREE.ObjectLoader: Undefined image', data.image ); + } - } + function checkBufferGeometryIntersection( object, raycaster, ray, positions, uvs, a, b, c ) { - var texture = new THREE.Texture( images[ data.image ] ); - texture.needsUpdate = true; + vA.fromArray( positions, a * 3 ); + vB.fromArray( positions, b * 3 ); + vC.fromArray( positions, c * 3 ); - texture.uuid = data.uuid; + var intersection = checkIntersection( object, raycaster, ray, vA, vB, vC, intersectionPoint ); - if ( data.name !== undefined ) texture.name = data.name; - if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping ); - if ( data.offset !== undefined ) texture.offset = new THREE.Vector2( data.offset[ 0 ], data.offset[ 1 ] ); - if ( data.repeat !== undefined ) texture.repeat = new THREE.Vector2( data.repeat[ 0 ], data.repeat[ 1 ] ); - 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 ( Array.isArray( data.wrap ) ) { + if ( intersection ) { - texture.wrapS = parseConstant( data.wrap[ 0 ] ); - texture.wrapT = parseConstant( data.wrap[ 1 ] ); + if ( uvs ) { - } + uvA.fromArray( uvs, a * 2 ); + uvB.fromArray( uvs, b * 2 ); + uvC.fromArray( uvs, c * 2 ); - textures[ data.uuid ] = texture; + intersection.uv = uvIntersection( intersectionPoint, vA, vB, vC, uvA, uvB, uvC ); - } + } - } + intersection.face = new Face3( a, b, c, Triangle.normal( vA, vB, vC ) ); + intersection.faceIndex = a; - return textures; + } - }, + return intersection; - parseObject: function () { + } - var matrix = new THREE.Matrix4(); + return function raycast( raycaster, intersects ) { - return function ( data, geometries, materials ) { + var geometry = this.geometry; + var material = this.material; + var matrixWorld = this.matrixWorld; - var object; + if ( material === undefined ) return; - var getGeometry = function ( name ) { + // Checking boundingSphere distance to ray - if ( geometries[ name ] === undefined ) { + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); - console.warn( 'THREE.ObjectLoader: Undefined geometry', name ); + sphere.copy( geometry.boundingSphere ); + sphere.applyMatrix4( matrixWorld ); - } + if ( raycaster.ray.intersectsSphere( sphere ) === false ) return; - return geometries[ name ]; + // - }; + inverseMatrix.getInverse( matrixWorld ); + ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); - var getMaterial = function ( name ) { + // Check boundingBox before continuing - if ( materials[ name ] === undefined ) { + if ( geometry.boundingBox !== null ) { - console.warn( 'THREE.ObjectLoader: Undefined material', name ); + if ( ray.intersectsBox( geometry.boundingBox ) === false ) return; - } + } - return materials[ name ]; + var uvs, intersection; - }; + if ( (geometry && geometry.isBufferGeometry) ) { - switch ( data.type ) { + var a, b, c; + var index = geometry.index; + var attributes = geometry.attributes; + var positions = attributes.position.array; - case 'Scene': + if ( attributes.uv !== undefined ) { - object = new THREE.Scene(); + uvs = attributes.uv.array; - break; + } - case 'PerspectiveCamera': + if ( index !== null ) { - object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far ); + var indices = index.array; - break; + for ( var i = 0, l = indices.length; i < l; i += 3 ) { - case 'OrthographicCamera': + a = indices[ i ]; + b = indices[ i + 1 ]; + c = indices[ i + 2 ]; - object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far ); + intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c ); - break; + if ( intersection ) { - case 'AmbientLight': + intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indices buffer semantics + intersects.push( intersection ); - object = new THREE.AmbientLight( data.color ); + } - break; + } - case 'DirectionalLight': + } else { - object = new THREE.DirectionalLight( data.color, data.intensity ); - break; + for ( var i = 0, l = positions.length; i < l; i += 9 ) { - case 'PointLight': + a = i / 3; + b = a + 1; + c = a + 2; - object = new THREE.PointLight( data.color, data.intensity, data.distance, data.decay ); + intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c ); - break; + if ( intersection ) { - case 'SpotLight': + intersection.index = a; // triangle number in positions buffer semantics + intersects.push( intersection ); - object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.exponent, data.decay ); + } - break; + } - case 'HemisphereLight': + } - object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity ); + } else if ( (geometry && geometry.isGeometry) ) { - break; + var fvA, fvB, fvC; + var isFaceMaterial = (material && material.isMultiMaterial); + var materials = isFaceMaterial === true ? material.materials : null; - case 'Mesh': + var vertices = geometry.vertices; + var faces = geometry.faces; + var faceVertexUvs = geometry.faceVertexUvs[ 0 ]; + if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs; - object = new THREE.Mesh( getGeometry( data.geometry ), getMaterial( data.material ) ); + for ( var f = 0, fl = faces.length; f < fl; f ++ ) { - break; + var face = faces[ f ]; + var faceMaterial = isFaceMaterial === true ? materials[ face.materialIndex ] : material; - case 'LOD': + if ( faceMaterial === undefined ) continue; - object = new THREE.LOD(); + fvA = vertices[ face.a ]; + fvB = vertices[ face.b ]; + fvC = vertices[ face.c ]; - break; + if ( faceMaterial.morphTargets === true ) { - case 'Line': + var morphTargets = geometry.morphTargets; + var morphInfluences = this.morphTargetInfluences; - object = new THREE.Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode ); + vA.set( 0, 0, 0 ); + vB.set( 0, 0, 0 ); + vC.set( 0, 0, 0 ); - break; + for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) { - case 'PointCloud': - case 'Points': + var influence = morphInfluences[ t ]; - object = new THREE.Points( getGeometry( data.geometry ), getMaterial( data.material ) ); + if ( influence === 0 ) continue; - break; + var targets = morphTargets[ t ].vertices; - case 'Sprite': + 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 ); - object = new THREE.Sprite( getMaterial( data.material ) ); + } - break; + vA.add( fvA ); + vB.add( fvB ); + vC.add( fvC ); - case 'Group': + fvA = vA; + fvB = vB; + fvC = vC; - object = new THREE.Group(); + } - break; + intersection = checkIntersection( this, raycaster, ray, fvA, fvB, fvC, intersectionPoint ); - default: + if ( intersection ) { - object = new THREE.Object3D(); + if ( uvs ) { - } + var uvs_f = uvs[ f ]; + uvA.copy( uvs_f[ 0 ] ); + uvB.copy( uvs_f[ 1 ] ); + uvC.copy( uvs_f[ 2 ] ); - object.uuid = data.uuid; + intersection.uv = uvIntersection( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC ); - if ( data.name !== undefined ) object.name = data.name; - if ( data.matrix !== undefined ) { + } - matrix.fromArray( data.matrix ); - matrix.decompose( object.position, object.quaternion, object.scale ); + intersection.face = face; + intersection.faceIndex = f; + intersects.push( intersection ); - } else { + } - if ( data.position !== undefined ) object.position.fromArray( data.position ); - if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation ); - if ( data.scale !== undefined ) object.scale.fromArray( data.scale ); + } - } + } - if ( data.castShadow !== undefined ) object.castShadow = data.castShadow; - if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow; + }; - if ( data.visible !== undefined ) object.visible = data.visible; - if ( data.userData !== undefined ) object.userData = data.userData; + }() ), - if ( data.children !== undefined ) { + clone: function () { - for ( var child in data.children ) { + return new this.constructor( this.geometry, this.material ).copy( this ); - object.add( this.parseObject( data.children[ child ], geometries, materials ) ); + } - } + } ); - } + /** + * @author Mugen87 / https://github.com/Mugen87 + */ - if ( data.type === 'LOD' ) { + function BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) { - var levels = data.levels; + BufferGeometry.call( this ); - for ( var l = 0; l < levels.length; l ++ ) { + this.type = 'BoxBufferGeometry'; - var level = levels[ l ]; - var child = object.getObjectByProperty( 'uuid', level.object ); + this.parameters = { + width: width, + height: height, + depth: depth, + widthSegments: widthSegments, + heightSegments: heightSegments, + depthSegments: depthSegments + }; - if ( child !== undefined ) { + var scope = this; - object.addLevel( child, level.distance ); + // segments + widthSegments = Math.floor( widthSegments ) || 1; + heightSegments = Math.floor( heightSegments ) || 1; + depthSegments = Math.floor( depthSegments ) || 1; - } + // these are used to calculate buffer length + var vertexCount = calculateVertexCount( widthSegments, heightSegments, depthSegments ); + var indexCount = calculateIndexCount( widthSegments, heightSegments, depthSegments ); - } + // 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 ); - } + // offset variables + var vertexBufferOffset = 0; + var uvBufferOffset = 0; + var indexBufferOffset = 0; + var numberOfVertices = 0; - return object; + // 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 - }() + // build geometry + this.setIndex( new BufferAttribute( indices, 1 ) ); + this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) ); + this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) ); + this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) ); -}; + // helper functions -// File:src/loaders/TextureLoader.js + function calculateVertexCount( w, h, d ) { -/** - * @author mrdoob / http://mrdoob.com/ - */ + var vertices = 0; -THREE.TextureLoader = function ( manager ) { + // 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 - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + return vertices; -}; + } -THREE.TextureLoader.prototype = { + function calculateIndexCount( w, h, d ) { - constructor: THREE.TextureLoader, + var index = 0; - load: function ( url, onLoad, onProgress, onError ) { + // calculate the amount of squares for each side + index += w * h * 2; // xy + index += w * d * 2; // xz + index += d * h * 2; // zy - var scope = this; + return index * 6; // two triangles per square => six vertices per square - var loader = new THREE.ImageLoader( scope.manager ); - loader.setCrossOrigin( this.crossOrigin ); - loader.load( url, function ( image ) { + } - var texture = new THREE.Texture( image ); - texture.needsUpdate = true; + function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) { - if ( onLoad !== undefined ) { + var segmentWidth = width / gridX; + var segmentHeight = height / gridY; - onLoad( texture ); + var widthHalf = width / 2; + var heightHalf = height / 2; + var depthHalf = depth / 2; - } + var gridX1 = gridX + 1; + var gridY1 = gridY + 1; - }, onProgress, onError ); + var vertexCounter = 0; + var groupCount = 0; - }, + var vector = new Vector3(); - setCrossOrigin: function ( value ) { + // generate vertices, normals and uvs - this.crossOrigin = value; + for ( var iy = 0; iy < gridY1; iy ++ ) { - } + var y = iy * segmentHeight - heightHalf; -}; + for ( var ix = 0; ix < gridX1; ix ++ ) { -// File:src/loaders/BinaryTextureLoader.js + var x = ix * segmentWidth - widthHalf; -/** - * @author Nikos M. / https://github.com/foo123/ - * - * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...) - */ + // set values to correct vector component + vector[ u ] = x * udir; + vector[ v ] = y * vdir; + vector[ w ] = depthHalf; -THREE.DataTextureLoader = THREE.BinaryTextureLoader = function ( manager ) { + // now apply vector to vertex buffer + vertices[ vertexBufferOffset ] = vector.x; + vertices[ vertexBufferOffset + 1 ] = vector.y; + vertices[ vertexBufferOffset + 2 ] = vector.z; - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + // set values to correct vector component + vector[ u ] = 0; + vector[ v ] = 0; + vector[ w ] = depth > 0 ? 1 : - 1; - // override in sub classes - this._parser = null; + // now apply vector to normal buffer + normals[ vertexBufferOffset ] = vector.x; + normals[ vertexBufferOffset + 1 ] = vector.y; + normals[ vertexBufferOffset + 2 ] = vector.z; -}; + // uvs + uvs[ uvBufferOffset ] = ix / gridX; + uvs[ uvBufferOffset + 1 ] = 1 - ( iy / gridY ); -THREE.BinaryTextureLoader.prototype = { + // update offsets and counters + vertexBufferOffset += 3; + uvBufferOffset += 2; + vertexCounter += 1; - constructor: THREE.BinaryTextureLoader, + } - load: function ( url, onLoad, onProgress, onError ) { + } - var scope = this; + // 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 - var texture = new THREE.DataTexture(); + for ( iy = 0; iy < gridY; iy ++ ) { - var loader = new THREE.XHRLoader( this.manager ); - loader.setCrossOrigin( this.crossOrigin ); - loader.setResponseType( 'arraybuffer' ); + for ( ix = 0; ix < gridX; ix ++ ) { - loader.load( url, function ( buffer ) { + // 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; - var texData = scope._parser( buffer ); + // face one + indices[ indexBufferOffset ] = a; + indices[ indexBufferOffset + 1 ] = b; + indices[ indexBufferOffset + 2 ] = d; - if ( ! texData ) return; + // face two + indices[ indexBufferOffset + 3 ] = b; + indices[ indexBufferOffset + 4 ] = c; + indices[ indexBufferOffset + 5 ] = d; - if ( undefined !== texData.image ) { + // update offsets and counters + indexBufferOffset += 6; + groupCount += 6; - texture.image = texData.image; + } - } else if ( undefined !== texData.data ) { + } - texture.image.width = texData.width; - texture.image.height = texData.height; - texture.image.data = texData.data; + // add a group to the geometry. this will ensure multi material support + scope.addGroup( groupStart, groupCount, materialIndex ); - } + // calculate new start value for groups + groupStart += groupCount; - texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : THREE.ClampToEdgeWrapping; - texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : THREE.ClampToEdgeWrapping; + // update total number of vertices + numberOfVertices += vertexCounter; - texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : THREE.LinearFilter; - texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : THREE.LinearMipMapLinearFilter; + } - texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1; + } - if ( undefined !== texData.format ) { + BoxBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + BoxBufferGeometry.prototype.constructor = BoxBufferGeometry; - texture.format = texData.format; + /** + * @author mrdoob / http://mrdoob.com/ + * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as + */ - } - if ( undefined !== texData.type ) { + function PlaneBufferGeometry( width, height, widthSegments, heightSegments ) { - texture.type = texData.type; + BufferGeometry.call( this ); - } + this.type = 'PlaneBufferGeometry'; - if ( undefined !== texData.mipmaps ) { + this.parameters = { + width: width, + height: height, + widthSegments: widthSegments, + heightSegments: heightSegments + }; - texture.mipmaps = texData.mipmaps; + var width_half = width / 2; + var height_half = height / 2; - } + var gridX = Math.floor( widthSegments ) || 1; + var gridY = Math.floor( heightSegments ) || 1; - if ( 1 === texData.mipmapCount ) { + var gridX1 = gridX + 1; + var gridY1 = gridY + 1; - texture.minFilter = THREE.LinearFilter; + 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 ); - texture.needsUpdate = true; + var offset = 0; + var offset2 = 0; - if ( onLoad ) onLoad( texture, texData ); + for ( var iy = 0; iy < gridY1; iy ++ ) { - }, onProgress, onError ); + var y = iy * segment_height - height_half; + for ( var ix = 0; ix < gridX1; ix ++ ) { - return texture; + var x = ix * segment_width - width_half; - }, + vertices[ offset ] = x; + vertices[ offset + 1 ] = - y; - setCrossOrigin: function ( value ) { + normals[ offset + 2 ] = 1; - this.crossOrigin = value; + uvs[ offset2 ] = ix / gridX; + uvs[ offset2 + 1 ] = 1 - ( iy / gridY ); - } + offset += 3; + offset2 += 2; -}; + } -// File:src/loaders/CompressedTextureLoader.js + } -/** - * @author mrdoob / http://mrdoob.com/ - * - * Abstract Base class to block based textures loader (dds, pvr, ...) - */ + offset = 0; -THREE.CompressedTextureLoader = function ( manager ) { + var indices = new ( ( vertices.length / 3 ) > 65535 ? Uint32Array : Uint16Array )( gridX * gridY * 6 ); - this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; + for ( var iy = 0; iy < gridY; iy ++ ) { - // override in sub classes - this._parser = null; + for ( var ix = 0; ix < gridX; ix ++ ) { -}; + var a = ix + gridX1 * iy; + var b = ix + gridX1 * ( iy + 1 ); + var c = ( ix + 1 ) + gridX1 * ( iy + 1 ); + var d = ( ix + 1 ) + gridX1 * iy; + indices[ offset ] = a; + indices[ offset + 1 ] = b; + indices[ offset + 2 ] = d; -THREE.CompressedTextureLoader.prototype = { + indices[ offset + 3 ] = b; + indices[ offset + 4 ] = c; + indices[ offset + 5 ] = d; - constructor: THREE.CompressedTextureLoader, + offset += 6; - load: function ( url, onLoad, onProgress, onError ) { + } - var scope = this; + } - var images = []; + 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 texture = new THREE.CompressedTexture(); - texture.image = images; + } - var loader = new THREE.XHRLoader( this.manager ); - loader.setCrossOrigin( this.crossOrigin ); - loader.setResponseType( 'arraybuffer' ); + PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry; - if ( Array.isArray( url ) ) { + /** + * @author mrdoob / http://mrdoob.com/ + * @author mikael emtinger / http://gomo.se/ + * @author WestLangley / http://github.com/WestLangley + */ - var loaded = 0; + function Camera() { - var loadTexture = function ( i ) { + Object3D.call( this ); - loader.load( url[ i ], function ( buffer ) { + this.type = 'Camera'; - var texDatas = scope._parser( buffer, true ); + this.matrixWorldInverse = new Matrix4(); + this.projectionMatrix = new Matrix4(); - images[ i ] = { - width: texDatas.width, - height: texDatas.height, - format: texDatas.format, - mipmaps: texDatas.mipmaps - }; + } - loaded += 1; + Camera.prototype = Object.create( Object3D.prototype ); + Camera.prototype.constructor = Camera; - if ( loaded === 6 ) { + Camera.prototype.isCamera = true; - if ( texDatas.mipmapCount === 1 ) - texture.minFilter = THREE.LinearFilter; + Camera.prototype.getWorldDirection = function () { - texture.format = texDatas.format; - texture.needsUpdate = true; + var quaternion = new Quaternion(); - if ( onLoad ) onLoad( texture ); + return function getWorldDirection( optionalTarget ) { - } + var result = optionalTarget || new Vector3(); - }, onProgress, onError ); + this.getWorldQuaternion( quaternion ); - }; + return result.set( 0, 0, - 1 ).applyQuaternion( quaternion ); - for ( var i = 0, il = url.length; i < il; ++ i ) { + }; - loadTexture( i ); + }(); - } + Camera.prototype.lookAt = function () { - } else { + // This routine does not support cameras with rotated and/or translated parent(s) - // compressed cubemap texture stored in a single DDS file + var m1 = new Matrix4(); - loader.load( url, function ( buffer ) { + return function lookAt( vector ) { - var texDatas = scope._parser( buffer, true ); + m1.lookAt( this.position, vector, this.up ); - if ( texDatas.isCubemap ) { + this.quaternion.setFromRotationMatrix( m1 ); - var faces = texDatas.mipmaps.length / texDatas.mipmapCount; + }; - for ( var f = 0; f < faces; f ++ ) { + }(); - images[ f ] = { mipmaps : [] }; + Camera.prototype.clone = function () { - for ( var i = 0; i < texDatas.mipmapCount; i ++ ) { + return new this.constructor().copy( this ); - 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; + }; - } + Camera.prototype.copy = function ( source ) { - } + Object3D.prototype.copy.call( this, source ); - } else { + this.matrixWorldInverse.copy( source.matrixWorldInverse ); + this.projectionMatrix.copy( source.projectionMatrix ); - texture.image.width = texDatas.width; - texture.image.height = texDatas.height; - texture.mipmaps = texDatas.mipmaps; + return this; - } + }; - if ( texDatas.mipmapCount === 1 ) { + /** + * @author mrdoob / http://mrdoob.com/ + * @author greggman / http://games.greggman.com/ + * @author zz85 / http://www.lab4games.net/zz85/blog + * @author tschw + */ - texture.minFilter = THREE.LinearFilter; + function PerspectiveCamera( fov, aspect, near, far ) { - } + Camera.call( this ); - texture.format = texDatas.format; - texture.needsUpdate = true; + this.type = 'PerspectiveCamera'; - if ( onLoad ) onLoad( texture ); + this.fov = fov !== undefined ? fov : 50; + this.zoom = 1; - }, onProgress, onError ); + 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; - return texture; + this.filmGauge = 35; // width of the film (default in millimeters) + this.filmOffset = 0; // horizontal film offset (same unit as gauge) - }, + this.updateProjectionMatrix(); - setCrossOrigin: function ( value ) { + } - this.crossOrigin = value; + PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), { - } + constructor: PerspectiveCamera, -}; + isPerspectiveCamera: true, -// File:src/materials/Material.js + copy: function ( source ) { -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + Camera.prototype.copy.call( this, source ); -THREE.Material = function () { + this.fov = source.fov; + this.zoom = source.zoom; - Object.defineProperty( this, 'id', { value: THREE.MaterialIdCount ++ } ); + this.near = source.near; + this.far = source.far; + this.focus = source.focus; - this.uuid = THREE.Math.generateUUID(); + this.aspect = source.aspect; + this.view = source.view === null ? null : Object.assign( {}, source.view ); - this.name = ''; - this.type = 'Material'; + this.filmGauge = source.filmGauge; + this.filmOffset = source.filmOffset; - this.side = THREE.FrontSide; + return this; - this.opacity = 1; - this.transparent = false; + }, - this.blending = THREE.NormalBlending; + /** + * 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.blendSrc = THREE.SrcAlphaFactor; - this.blendDst = THREE.OneMinusSrcAlphaFactor; - this.blendEquation = THREE.AddEquation; - this.blendSrcAlpha = null; - this.blendDstAlpha = null; - this.blendEquationAlpha = null; + // see http://www.bobatkins.com/photography/technical/field_of_view.html + var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength; - this.depthFunc = THREE.LessEqualDepth; - this.depthTest = true; - this.depthWrite = true; + this.fov = exports.Math.RAD2DEG * 2 * Math.atan( vExtentSlope ); + this.updateProjectionMatrix(); - this.colorWrite = true; + }, - this.precision = null; // override the renderer's default precision for this material + /** + * Calculates the focal length from the current .fov and .filmGauge. + */ + getFocalLength: function () { - this.polygonOffset = false; - this.polygonOffsetFactor = 0; - this.polygonOffsetUnits = 0; + var vExtentSlope = Math.tan( exports.Math.DEG2RAD * 0.5 * this.fov ); - this.alphaTest = 0; + return 0.5 * this.getFilmHeight() / vExtentSlope; - this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer + }, - this.visible = true; + getEffectiveFOV: function () { - this._needsUpdate = true; + return exports.Math.RAD2DEG * 2 * Math.atan( + Math.tan( exports.Math.DEG2RAD * 0.5 * this.fov ) / this.zoom ); -}; + }, -THREE.Material.prototype = { + getFilmWidth: function () { - constructor: THREE.Material, + // film not completely covered in portrait format (aspect < 1) + return this.filmGauge * Math.min( this.aspect, 1 ); - get needsUpdate () { + }, - return this._needsUpdate; + getFilmHeight: function () { - }, + // film not completely covered in landscape format (aspect > 1) + return this.filmGauge / Math.max( this.aspect, 1 ); - set needsUpdate ( value ) { + }, - if ( value === true ) this.update(); + /** + * 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._needsUpdate = value; + this.aspect = fullWidth / fullHeight; - }, + this.view = { + fullWidth: fullWidth, + fullHeight: fullHeight, + offsetX: x, + offsetY: y, + width: width, + height: height + }; - setValues: function ( values ) { + this.updateProjectionMatrix(); - if ( values === undefined ) return; + }, - for ( var key in values ) { + clearViewOffset: function() { - var newValue = values[ key ]; + this.view = null; + this.updateProjectionMatrix(); - if ( newValue === undefined ) { + }, - console.warn( "THREE.Material: '" + key + "' parameter is undefined." ); - continue; + updateProjectionMatrix: function () { - } + var near = this.near, + top = near * Math.tan( + exports.Math.DEG2RAD * 0.5 * this.fov ) / this.zoom, + height = 2 * top, + width = this.aspect * height, + left = - 0.5 * width, + view = this.view; - var currentValue = this[ key ]; + if ( view !== null ) { - if ( currentValue === undefined ) { + var fullWidth = view.fullWidth, + fullHeight = view.fullHeight; - console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." ); - continue; + left += view.offsetX * width / fullWidth; + top -= view.offsetY * height / fullHeight; + width *= view.width / fullWidth; + height *= view.height / fullHeight; - } + } - if ( currentValue instanceof THREE.Color ) { + var skew = this.filmOffset; + if ( skew !== 0 ) left += near * skew / this.getFilmWidth(); - currentValue.set( newValue ); + this.projectionMatrix.makeFrustum( + left, left + width, top - height, top, near, this.far ); - } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) { + }, - currentValue.copy( newValue ); + toJSON: function ( meta ) { - } else if ( key === 'overdraw' ) { + var data = Object3D.prototype.toJSON.call( this, meta ); - // ensure overdraw is backwards-compatible with legacy boolean type - this[ key ] = Number( newValue ); + data.object.fov = this.fov; + data.object.zoom = this.zoom; - } else { + data.object.near = this.near; + data.object.far = this.far; + data.object.focus = this.focus; - this[ key ] = newValue; + data.object.aspect = this.aspect; - } + if ( this.view !== null ) data.object.view = Object.assign( {}, this.view ); - } + data.object.filmGauge = this.filmGauge; + data.object.filmOffset = this.filmOffset; - }, + return data; - toJSON: function ( meta ) { + } - var data = { - metadata: { - version: 4.4, - type: 'Material', - generator: 'Material.toJSON' - } - }; + } ); - // standard Material serialization - data.uuid = this.uuid; - data.type = this.type; - if ( this.name !== '' ) data.name = this.name; + /** + * @author alteredq / http://alteredqualia.com/ + * @author arose / http://github.com/arose + */ - if ( this.color instanceof THREE.Color ) data.color = this.color.getHex(); - if ( this.emissive instanceof THREE.Color ) data.emissive = this.emissive.getHex(); - if ( this.specular instanceof THREE.Color ) data.specular = this.specular.getHex(); - if ( this.shininess !== undefined ) data.shininess = this.shininess; + function OrthographicCamera( left, right, top, bottom, near, far ) { - if ( this.map instanceof THREE.Texture ) data.map = this.map.toJSON( meta ).uuid; - if ( this.alphaMap instanceof THREE.Texture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid; - if ( this.lightMap instanceof THREE.Texture ) data.lightMap = this.lightMap.toJSON( meta ).uuid; - if ( this.bumpMap instanceof THREE.Texture ) { + Camera.call( this ); - data.bumpMap = this.bumpMap.toJSON( meta ).uuid; - data.bumpScale = this.bumpScale; + this.type = 'OrthographicCamera'; - } - if ( this.normalMap instanceof THREE.Texture ) { + this.zoom = 1; + this.view = null; - data.normalMap = this.normalMap.toJSON( meta ).uuid; - data.normalScale = this.normalScale; // Removed for now, causes issue in editor ui.js + this.left = left; + this.right = right; + this.top = top; + this.bottom = bottom; - } - if ( this.displacementMap instanceof THREE.Texture ) { + this.near = ( near !== undefined ) ? near : 0.1; + this.far = ( far !== undefined ) ? far : 2000; - data.displacementMap = this.displacementMap.toJSON( meta ).uuid; - data.displacementScale = this.displacementScale; - data.displacementBias = this.displacementBias; + this.updateProjectionMatrix(); - } - if ( this.specularMap instanceof THREE.Texture ) data.specularMap = this.specularMap.toJSON( meta ).uuid; - if ( this.envMap instanceof THREE.Texture ) { + } - data.envMap = this.envMap.toJSON( meta ).uuid; - data.reflectivity = this.reflectivity; // Scale behind envMap + OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), { - } + constructor: OrthographicCamera, - if ( this.size !== undefined ) data.size = this.size; - if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation; + isOrthographicCamera: true, - if ( this.vertexColors !== undefined && this.vertexColors !== THREE.NoColors ) data.vertexColors = this.vertexColors; - if ( this.shading !== undefined && this.shading !== THREE.SmoothShading ) data.shading = this.shading; - if ( this.blending !== undefined && this.blending !== THREE.NormalBlending ) data.blending = this.blending; - if ( this.side !== undefined && this.side !== THREE.FrontSide ) data.side = this.side; + copy: function ( source ) { - 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.wireframe === true ) data.wireframe = this.wireframe; - if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth; + Camera.prototype.copy.call( this, source ); - return data; + this.left = source.left; + this.right = source.right; + this.top = source.top; + this.bottom = source.bottom; + this.near = source.near; + this.far = source.far; - }, + this.zoom = source.zoom; + this.view = source.view === null ? null : Object.assign( {}, source.view ); - clone: function () { + return this; - return new this.constructor().copy( this ); + }, - }, + setViewOffset: function( fullWidth, fullHeight, x, y, width, height ) { - copy: function ( source ) { + this.view = { + fullWidth: fullWidth, + fullHeight: fullHeight, + offsetX: x, + offsetY: y, + width: width, + height: height + }; - this.name = source.name; + this.updateProjectionMatrix(); - this.side = source.side; + }, - this.opacity = source.opacity; - this.transparent = source.transparent; + clearViewOffset: function() { - this.blending = source.blending; + this.view = null; + this.updateProjectionMatrix(); - this.blendSrc = source.blendSrc; - this.blendDst = source.blendDst; - this.blendEquation = source.blendEquation; - this.blendSrcAlpha = source.blendSrcAlpha; - this.blendDstAlpha = source.blendDstAlpha; - this.blendEquationAlpha = source.blendEquationAlpha; + }, - this.depthFunc = source.depthFunc; - this.depthTest = source.depthTest; - this.depthWrite = source.depthWrite; + updateProjectionMatrix: function () { - this.precision = source.precision; + 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; - this.polygonOffset = source.polygonOffset; - this.polygonOffsetFactor = source.polygonOffsetFactor; - this.polygonOffsetUnits = source.polygonOffsetUnits; + var left = cx - dx; + var right = cx + dx; + var top = cy + dy; + var bottom = cy - dy; - this.alphaTest = source.alphaTest; + if ( this.view !== null ) { - this.overdraw = source.overdraw; + 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; - this.visible = source.visible; + 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 ); - return this; + } - }, + this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far ); - update: function () { + }, - this.dispatchEvent( { type: 'update' } ); + toJSON: function ( meta ) { - }, + var data = Object3D.prototype.toJSON.call( this, meta ); - dispose: function () { + 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; - this.dispatchEvent( { type: 'dispose' } ); + if ( this.view !== null ) data.object.view = Object.assign( {}, this.view ); - }, + return data; - // Deprecated + } - get wrapAround () { + } ); - console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' ); + /** + * @author mrdoob / http://mrdoob.com/ + */ - }, + function WebGLIndexedBufferRenderer( gl, extensions, infoRender ) { - set wrapAround ( boolean ) { + var mode; - console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' ); + function setMode( value ) { - }, + mode = value; - get wrapRGB () { + } - console.warn( 'THREE.' + this.type + ': .wrapRGB has been removed.' ); - return new THREE.Color(); + var type, size; - } + function setIndex( index ) { -}; + if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) { -THREE.EventDispatcher.prototype.apply( THREE.Material.prototype ); + type = gl.UNSIGNED_INT; + size = 4; -THREE.MaterialIdCount = 0; + } else { -// File:src/materials/LineBasicMaterial.js + type = gl.UNSIGNED_SHORT; + size = 2; -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * opacity: , - * - * blending: THREE.NormalBlending, - * depthTest: , - * depthWrite: , - * - * linewidth: , - * linecap: "round", - * linejoin: "round", - * - * vertexColors: - * - * fog: - * } - */ + } -THREE.LineBasicMaterial = function ( parameters ) { + } - THREE.Material.call( this ); + function render( start, count ) { - this.type = 'LineBasicMaterial'; + gl.drawElements( mode, count, type, start * size ); - this.color = new THREE.Color( 0xffffff ); + infoRender.calls ++; + infoRender.vertices += count; - this.linewidth = 1; - this.linecap = 'round'; - this.linejoin = 'round'; + if ( mode === gl.TRIANGLES ) infoRender.faces += count / 3; - this.vertexColors = THREE.NoColors; + } - this.fog = true; + function renderInstances( geometry, start, count ) { - this.setValues( parameters ); + var extension = extensions.get( 'ANGLE_instanced_arrays' ); -}; + if ( extension === null ) { -THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.LineBasicMaterial.prototype.constructor = THREE.LineBasicMaterial; + console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); + return; -THREE.LineBasicMaterial.prototype.copy = function ( source ) { + } - THREE.Material.prototype.copy.call( this, source ); + extension.drawElementsInstancedANGLE( mode, count, type, start * size, geometry.maxInstancedCount ); - this.color.copy( source.color ); + infoRender.calls ++; + infoRender.vertices += count * geometry.maxInstancedCount; - this.linewidth = source.linewidth; - this.linecap = source.linecap; - this.linejoin = source.linejoin; + if ( mode === gl.TRIANGLES ) infoRender.faces += geometry.maxInstancedCount * count / 3; - this.vertexColors = source.vertexColors; + } - this.fog = source.fog; + return { - return this; + setMode: setMode, + setIndex: setIndex, + render: render, + renderInstances: renderInstances -}; + }; -// File:src/materials/LineDashedMaterial.js + } -/** - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * opacity: , - * - * blending: THREE.NormalBlending, - * depthTest: , - * depthWrite: , - * - * linewidth: , - * - * scale: , - * dashSize: , - * gapSize: , - * - * vertexColors: - * - * fog: - * } - */ + /** + * @author mrdoob / http://mrdoob.com/ + */ -THREE.LineDashedMaterial = function ( parameters ) { + function WebGLBufferRenderer( gl, extensions, infoRender ) { - THREE.Material.call( this ); + var mode; - this.type = 'LineDashedMaterial'; + function setMode( value ) { - this.color = new THREE.Color( 0xffffff ); + mode = value; - this.linewidth = 1; + } - this.scale = 1; - this.dashSize = 3; - this.gapSize = 1; + function render( start, count ) { - this.vertexColors = false; + gl.drawArrays( mode, start, count ); - this.fog = true; + infoRender.calls ++; + infoRender.vertices += count; - this.setValues( parameters ); + if ( mode === gl.TRIANGLES ) infoRender.faces += count / 3; -}; + } -THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.LineDashedMaterial.prototype.constructor = THREE.LineDashedMaterial; + function renderInstances( geometry ) { -THREE.LineDashedMaterial.prototype.copy = function ( source ) { + var extension = extensions.get( 'ANGLE_instanced_arrays' ); - THREE.Material.prototype.copy.call( this, source ); + if ( extension === null ) { - this.color.copy( source.color ); - - this.linewidth = source.linewidth; + console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); + return; - this.scale = source.scale; - this.dashSize = source.dashSize; - this.gapSize = source.gapSize; + } - this.vertexColors = source.vertexColors; + var position = geometry.attributes.position; - this.fog = source.fog; + var count = 0; - return this; + if ( (position && position.isInterleavedBufferAttribute) ) { -}; + count = position.data.count; -// File:src/materials/MeshBasicMaterial.js + extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount ); -/** - * @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, - * blending: THREE.NormalBlending, - * depthTest: , - * depthWrite: , - * - * wireframe: , - * wireframeLinewidth: , - * - * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors, - * - * skinning: , - * morphTargets: , - * - * fog: - * } - */ + } else { -THREE.MeshBasicMaterial = function ( parameters ) { + count = position.count; - THREE.Material.call( this ); + extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount ); - this.type = 'MeshBasicMaterial'; + } - this.color = new THREE.Color( 0xffffff ); // emissive + infoRender.calls ++; + infoRender.vertices += count * geometry.maxInstancedCount; - this.map = null; + if ( mode === gl.TRIANGLES ) infoRender.faces += geometry.maxInstancedCount * count / 3; - this.aoMap = null; - this.aoMapIntensity = 1.0; + } - this.specularMap = null; + return { + setMode: setMode, + render: render, + renderInstances: renderInstances + }; - this.alphaMap = null; + } - this.envMap = null; - this.combine = THREE.MultiplyOperation; - this.reflectivity = 1; - this.refractionRatio = 0.98; + function WebGLLights() { - this.fog = true; + var lights = {}; - this.shading = THREE.SmoothShading; + return { - this.wireframe = false; - this.wireframeLinewidth = 1; - this.wireframeLinecap = 'round'; - this.wireframeLinejoin = 'round'; + get: function ( light ) { - this.vertexColors = THREE.NoColors; + if ( lights[ light.id ] !== undefined ) { - this.skinning = false; - this.morphTargets = false; + return lights[ light.id ]; - this.setValues( parameters ); + } -}; + var uniforms; -THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.MeshBasicMaterial.prototype.constructor = THREE.MeshBasicMaterial; + switch ( light.type ) { -THREE.MeshBasicMaterial.prototype.copy = function ( source ) { - - THREE.Material.prototype.copy.call( this, source ); + case 'DirectionalLight': + uniforms = { + direction: new Vector3(), + color: new Color(), - this.color.copy( source.color ); + shadow: false, + shadowBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2() + }; + break; - this.map = source.map; + case 'SpotLight': + uniforms = { + position: new Vector3(), + direction: new Vector3(), + color: new Color(), + distance: 0, + coneCos: 0, + penumbraCos: 0, + decay: 0, - this.aoMap = source.aoMap; - this.aoMapIntensity = source.aoMapIntensity; + shadow: false, + shadowBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2() + }; + break; - this.specularMap = source.specularMap; + case 'PointLight': + uniforms = { + position: new Vector3(), + color: new Color(), + distance: 0, + decay: 0, - this.alphaMap = source.alphaMap; + shadow: false, + shadowBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2() + }; + break; - this.envMap = source.envMap; - this.combine = source.combine; - this.reflectivity = source.reflectivity; - this.refractionRatio = source.refractionRatio; - - this.fog = source.fog; + case 'HemisphereLight': + uniforms = { + direction: new Vector3(), + skyColor: new Color(), + groundColor: new Color() + }; + break; - this.shading = source.shading; + } - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; - this.wireframeLinecap = source.wireframeLinecap; - this.wireframeLinejoin = source.wireframeLinejoin; + lights[ light.id ] = uniforms; - this.vertexColors = source.vertexColors; + return uniforms; - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; - - return this; + } -}; + }; -// File:src/materials/MeshLambertMaterial.js + } -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * emissive: , - * opacity: , - * - * map: 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: , - * - * blending: THREE.NormalBlending, - * depthTest: , - * depthWrite: , - * - * wireframe: , - * wireframeLinewidth: , - * - * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors, - * - * skinning: , - * morphTargets: , - * morphNormals: , - * - * fog: - * } - */ + /** + * @author mrdoob / http://mrdoob.com/ + */ -THREE.MeshLambertMaterial = function ( parameters ) { + function addLineNumbers( string ) { - THREE.Material.call( this ); + var lines = string.split( '\n' ); - this.type = 'MeshLambertMaterial'; + for ( var i = 0; i < lines.length; i ++ ) { - this.color = new THREE.Color( 0xffffff ); // diffuse - this.emissive = new THREE.Color( 0x000000 ); + lines[ i ] = ( i + 1 ) + ': ' + lines[ i ]; - this.map = null; + } - this.specularMap = null; - - this.alphaMap = null; - - this.envMap = null; - this.combine = THREE.MultiplyOperation; - this.reflectivity = 1; - this.refractionRatio = 0.98; - - this.fog = true; - - this.wireframe = false; - this.wireframeLinewidth = 1; - this.wireframeLinecap = 'round'; - this.wireframeLinejoin = 'round'; - - this.vertexColors = THREE.NoColors; - - this.skinning = false; - this.morphTargets = false; - this.morphNormals = false; - - this.setValues( parameters ); - -}; - -THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.MeshLambertMaterial.prototype.constructor = THREE.MeshLambertMaterial; - -THREE.MeshLambertMaterial.prototype.copy = function ( source ) { - - THREE.Material.prototype.copy.call( this, source ); - - this.color.copy( source.color ); - this.emissive.copy( source.emissive ); - - this.map = source.map; - - this.specularMap = source.specularMap; - - this.alphaMap = source.alphaMap; - - this.envMap = source.envMap; - this.combine = source.combine; - this.reflectivity = source.reflectivity; - this.refractionRatio = source.refractionRatio; - - this.fog = source.fog; - - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; - this.wireframeLinecap = source.wireframeLinecap; - this.wireframeLinejoin = source.wireframeLinejoin; - - this.vertexColors = source.vertexColors; - - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; - this.morphNormals = source.morphNormals; - - return this; - -}; - -// File:src/materials/MeshPhongMaterial.js - -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * emissive: , - * specular: , - * shininess: , - * opacity: , - * - * map: new THREE.Texture( ), - * - * lightMap: new THREE.Texture( ), - * lightMapIntensity: - * - * aoMap: new THREE.Texture( ), - * aoMapIntensity: - * - * 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: , - * - * shading: THREE.SmoothShading, - * blending: THREE.NormalBlending, - * depthTest: , - * depthWrite: , - * - * wireframe: , - * wireframeLinewidth: , - * - * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors, - * - * skinning: , - * morphTargets: , - * morphNormals: , - * - * fog: - * } - */ + return lines.join( '\n' ); -THREE.MeshPhongMaterial = function ( parameters ) { + } - THREE.Material.call( this ); + function WebGLShader( gl, type, string ) { - this.type = 'MeshPhongMaterial'; + var shader = gl.createShader( type ); - this.color = new THREE.Color( 0xffffff ); // diffuse - this.emissive = new THREE.Color( 0x000000 ); - this.specular = new THREE.Color( 0x111111 ); - this.shininess = 30; + gl.shaderSource( shader, string ); + gl.compileShader( shader ); - this.metal = false; + if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) { - this.map = null; + console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' ); - this.lightMap = null; - this.lightMapIntensity = 1.0; + } - this.aoMap = null; - this.aoMapIntensity = 1.0; + if ( gl.getShaderInfoLog( shader ) !== '' ) { - this.emissiveMap = null; + console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) ); - this.bumpMap = null; - this.bumpScale = 1; + } - this.normalMap = null; - this.normalScale = new THREE.Vector2( 1, 1 ); + // --enable-privileged-webgl-extension + // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) ); - this.displacementMap = null; - this.displacementScale = 1; - this.displacementBias = 0; + return shader; - this.specularMap = null; + } - this.alphaMap = null; - - this.envMap = null; - this.combine = THREE.MultiplyOperation; - this.reflectivity = 1; - this.refractionRatio = 0.98; - - this.fog = true; - - this.shading = THREE.SmoothShading; - - this.wireframe = false; - this.wireframeLinewidth = 1; - this.wireframeLinecap = 'round'; - this.wireframeLinejoin = 'round'; + var programIdCount = 0; - this.vertexColors = THREE.NoColors; + function getEncodingComponents( encoding ) { - this.skinning = false; - this.morphTargets = false; - this.morphNormals = false; + switch ( encoding ) { - this.setValues( parameters ); + 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 ); -}; + } -THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.MeshPhongMaterial.prototype.constructor = THREE.MeshPhongMaterial; + } -THREE.MeshPhongMaterial.prototype.copy = function ( source ) { + function getTexelDecodingFunction( functionName, encoding ) { - THREE.Material.prototype.copy.call( this, source ); + var components = getEncodingComponents( encoding ); + return "vec4 " + functionName + "( vec4 value ) { return " + components[ 0 ] + "ToLinear" + components[ 1 ] + "; }"; - this.color.copy( source.color ); - this.emissive.copy( source.emissive ); - this.specular.copy( source.specular ); - this.shininess = source.shininess; + } - this.metal = source.metal; + function getTexelEncodingFunction( functionName, encoding ) { - this.map = source.map; + var components = getEncodingComponents( encoding ); + return "vec4 " + functionName + "( vec4 value ) { return LinearTo" + components[ 0 ] + components[ 1 ] + "; }"; - this.lightMap = source.lightMap; - this.lightMapIntensity = source.lightMapIntensity; + } - this.aoMap = source.aoMap; - this.aoMapIntensity = source.aoMapIntensity; + function getToneMappingFunction( functionName, toneMapping ) { - this.emissiveMap = source.emissiveMap; + var toneMappingName; - this.bumpMap = source.bumpMap; - this.bumpScale = source.bumpScale; + switch ( toneMapping ) { - this.normalMap = source.normalMap; - this.normalScale.copy( source.normalScale ); + case LinearToneMapping: + toneMappingName = "Linear"; + break; - this.displacementMap = source.displacementMap; - this.displacementScale = source.displacementScale; - this.displacementBias = source.displacementBias; + case ReinhardToneMapping: + toneMappingName = "Reinhard"; + break; - this.specularMap = source.specularMap; + case Uncharted2ToneMapping: + toneMappingName = "Uncharted2"; + break; - this.alphaMap = source.alphaMap; + case CineonToneMapping: + toneMappingName = "OptimizedCineon"; + break; - this.envMap = source.envMap; - this.combine = source.combine; - this.reflectivity = source.reflectivity; - this.refractionRatio = source.refractionRatio; + default: + throw new Error( 'unsupported toneMapping: ' + toneMapping ); - this.fog = source.fog; + } - this.shading = source.shading; + return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }"; - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; - this.wireframeLinecap = source.wireframeLinecap; - this.wireframeLinejoin = source.wireframeLinejoin; + } - this.vertexColors = source.vertexColors; + function generateExtensions( extensions, parameters, rendererExtensions ) { - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; - this.morphNormals = source.morphNormals; + extensions = extensions || {}; - return this; + 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' : '', + ]; -}; + return chunks.filter( filterEmptyLine ).join( '\n' ); -// File:src/materials/MeshDepthMaterial.js + } -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * opacity: , - * - * blending: THREE.NormalBlending, - * depthTest: , - * depthWrite: , - * - * wireframe: , - * wireframeLinewidth: - * } - */ + function generateDefines( defines ) { -THREE.MeshDepthMaterial = function ( parameters ) { + var chunks = []; - THREE.Material.call( this ); + for ( var name in defines ) { - this.type = 'MeshDepthMaterial'; + var value = defines[ name ]; - this.morphTargets = false; - this.wireframe = false; - this.wireframeLinewidth = 1; + if ( value === false ) continue; - this.setValues( parameters ); + chunks.push( '#define ' + name + ' ' + value ); -}; + } -THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.MeshDepthMaterial.prototype.constructor = THREE.MeshDepthMaterial; + return chunks.join( '\n' ); -THREE.MeshDepthMaterial.prototype.copy = function ( source ) { + } - THREE.Material.prototype.copy.call( this, source ); + function fetchAttributeLocations( gl, program, identifiers ) { - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; + var attributes = {}; - return this; + var n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES ); -}; + for ( var i = 0; i < n; i ++ ) { -// File:src/materials/MeshNormalMaterial.js + var info = gl.getActiveAttrib( program, i ); + var name = info.name; -/** - * @author mrdoob / http://mrdoob.com/ - * - * parameters = { - * opacity: , - * - * shading: THREE.FlatShading, - * blending: THREE.NormalBlending, - * depthTest: , - * depthWrite: , - * - * wireframe: , - * wireframeLinewidth: - * } - */ + // console.log("THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:", name, i ); -THREE.MeshNormalMaterial = function ( parameters ) { + attributes[ name ] = gl.getAttribLocation( program, name ); - THREE.Material.call( this, parameters ); + } - this.type = 'MeshNormalMaterial'; + return attributes; - this.wireframe = false; - this.wireframeLinewidth = 1; + } - this.morphTargets = false; + function filterEmptyLine( string ) { - this.setValues( parameters ); + return string !== ''; -}; + } -THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.MeshNormalMaterial.prototype.constructor = THREE.MeshNormalMaterial; + function replaceLightNums( string, parameters ) { -THREE.MeshNormalMaterial.prototype.copy = function ( source ) { + 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 ); - THREE.Material.prototype.copy.call( this, source ); + } - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; + function parseIncludes( string ) { - return this; + var pattern = /#include +<([\w\d.]+)>/g; -}; + function replace( match, include ) { -// File:src/materials/MultiMaterial.js + var replace = ShaderChunk[ include ]; -/** - * @author mrdoob / http://mrdoob.com/ - */ + if ( replace === undefined ) { -THREE.MultiMaterial = function ( materials ) { + throw new Error( 'Can not resolve #include <' + include + '>' ); - this.uuid = THREE.Math.generateUUID(); + } - this.type = 'MultiMaterial'; + return parseIncludes( replace ); - this.materials = materials instanceof Array ? materials : []; + } - this.visible = true; + return string.replace( pattern, replace ); -}; + } -THREE.MultiMaterial.prototype = { + function unrollLoops( string ) { - constructor: THREE.MultiMaterial, + var pattern = /for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g; - toJSON: function () { + function replace( match, start, end, snippet ) { - var output = { - metadata: { - version: 4.2, - type: 'material', - generator: 'MaterialExporter' - }, - uuid: this.uuid, - type: this.type, - materials: [] - }; + var unroll = ''; - for ( var i = 0, l = this.materials.length; i < l; i ++ ) { + for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) { - output.materials.push( this.materials[ i ].toJSON() ); + unroll += snippet.replace( /\[ i \]/g, '[ ' + i + ' ]' ); - } + } - output.visible = this.visible; + return unroll; - return output; + } - }, + return string.replace( pattern, replace ); - clone: function () { + } - var material = new this.constructor(); + function WebGLProgram( renderer, code, material, parameters ) { - for ( var i = 0; i < this.materials.length; i ++ ) { + var gl = renderer.context; - material.materials.push( this.materials[ i ].clone() ); + var extensions = material.extensions; + var defines = material.defines; - } + var vertexShader = material.__webglShader.vertexShader; + var fragmentShader = material.__webglShader.fragmentShader; - material.visible = this.visible; + var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC'; - return material; + if ( parameters.shadowMapType === PCFShadowMap ) { - } + shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF'; -}; + } else if ( parameters.shadowMapType === PCFSoftShadowMap ) { -// backwards compatibility + shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT'; -THREE.MeshFaceMaterial = THREE.MultiMaterial; + } -// File:src/materials/PointsMaterial.js + var envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; + var envMapModeDefine = 'ENVMAP_MODE_REFLECTION'; + var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY'; -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * opacity: , - * map: new THREE.Texture( ), - * - * size: , - * sizeAttenuation: , - * - * blending: THREE.NormalBlending, - * depthTest: , - * depthWrite: , - * - * vertexColors: , - * - * fog: - * } - */ + if ( parameters.envMap ) { -THREE.PointsMaterial = function ( parameters ) { + switch ( material.envMap.mapping ) { - THREE.Material.call( this ); + case CubeReflectionMapping: + case CubeRefractionMapping: + envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; + break; - this.type = 'PointsMaterial'; + case CubeUVReflectionMapping: + case CubeUVRefractionMapping: + envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV'; + break; - this.color = new THREE.Color( 0xffffff ); + case EquirectangularReflectionMapping: + case EquirectangularRefractionMapping: + envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC'; + break; - this.map = null; + case SphericalReflectionMapping: + envMapTypeDefine = 'ENVMAP_TYPE_SPHERE'; + break; - this.size = 1; - this.sizeAttenuation = true; + } - this.vertexColors = THREE.NoColors; + switch ( material.envMap.mapping ) { - this.fog = true; + case CubeRefractionMapping: + case EquirectangularRefractionMapping: + envMapModeDefine = 'ENVMAP_MODE_REFRACTION'; + break; - this.setValues( parameters ); + } -}; + switch ( material.combine ) { -THREE.PointsMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.PointsMaterial.prototype.constructor = THREE.PointsMaterial; + case MultiplyOperation: + envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY'; + break; -THREE.PointsMaterial.prototype.copy = function ( source ) { + case MixOperation: + envMapBlendingDefine = 'ENVMAP_BLENDING_MIX'; + break; - THREE.Material.prototype.copy.call( this, source ); + case AddOperation: + envMapBlendingDefine = 'ENVMAP_BLENDING_ADD'; + break; - this.color.copy( source.color ); + } - this.map = source.map; + } - this.size = source.size; - this.sizeAttenuation = source.sizeAttenuation; + var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0; - this.vertexColors = source.vertexColors; + // console.log( 'building new program ' ); - this.fog = source.fog; + // - return this; + var customExtensions = generateExtensions( extensions, parameters, renderer.extensions ); -}; + var customDefines = generateDefines( defines ); -// backwards compatibility + // -THREE.PointCloudMaterial = function ( parameters ) { + var program = gl.createProgram(); - console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' ); - return new THREE.PointsMaterial( parameters ); + var prefixVertex, prefixFragment; -}; + if ( material.isRawShaderMaterial ) { -THREE.ParticleBasicMaterial = function ( parameters ) { + prefixVertex = [ - console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' ); - return new THREE.PointsMaterial( parameters ); + customDefines, -}; + '\n' -THREE.ParticleSystemMaterial = function ( parameters ) { + ].filter( filterEmptyLine ).join( '\n' ); - console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' ); - return new THREE.PointsMaterial( parameters ); + prefixFragment = [ -}; + customExtensions, + customDefines, -// File:src/materials/ShaderMaterial.js + '\n' -/** - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * defines: { "label" : "value" }, - * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } }, - * - * fragmentShader: , - * vertexShader: , - * - * shading: THREE.SmoothShading, - * blending: THREE.NormalBlending, - * depthTest: , - * depthWrite: , - * - * wireframe: , - * wireframeLinewidth: , - * - * lights: , - * - * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors, - * - * skinning: , - * morphTargets: , - * morphNormals: , - * - * fog: - * } - */ + ].filter( filterEmptyLine ).join( '\n' ); -THREE.ShaderMaterial = function ( parameters ) { + } else { - THREE.Material.call( this ); + prefixVertex = [ - this.type = 'ShaderMaterial'; + 'precision ' + parameters.precision + ' float;', + 'precision ' + parameters.precision + ' int;', - this.defines = {}; - this.uniforms = {}; + '#define SHADER_NAME ' + material.__webglShader.name, - 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}'; + customDefines, - this.shading = THREE.SmoothShading; + parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', - this.linewidth = 1; + '#define GAMMA_FACTOR ' + gammaFactorDefine, - this.wireframe = false; - this.wireframeLinewidth = 1; + '#define MAX_BONES ' + parameters.maxBones, - this.fog = false; // set to use scene fog + 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' : '', - this.lights = false; // set to use scene lights + parameters.flatShading ? '#define FLAT_SHADED' : '', - this.vertexColors = THREE.NoColors; // set to use "color" attribute stream + parameters.skinning ? '#define USE_SKINNING' : '', + parameters.useVertexTexture ? '#define BONE_TEXTURE' : '', - this.skinning = false; // set to use skinning attribute streams + parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', + parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', + parameters.doubleSided ? '#define DOUBLE_SIDED' : '', + parameters.flipSided ? '#define FLIP_SIDED' : '', - this.morphTargets = false; // set to use morph targets - this.morphNormals = false; // set to use morph normals + '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes, - this.derivatives = false; // set to use derivatives + parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', + parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', - // 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 ] - }; + parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '', - this.index0AttributeName = undefined; + parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', + parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '', - if ( parameters !== undefined ) { + 'uniform mat4 modelMatrix;', + 'uniform mat4 modelViewMatrix;', + 'uniform mat4 projectionMatrix;', + 'uniform mat4 viewMatrix;', + 'uniform mat3 normalMatrix;', + 'uniform vec3 cameraPosition;', - if ( parameters.attributes !== undefined ) { + 'attribute vec3 position;', + 'attribute vec3 normal;', + 'attribute vec2 uv;', - console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' ); + '#ifdef USE_COLOR', - } + ' attribute vec3 color;', - this.setValues( parameters ); + '#endif', - } + '#ifdef USE_MORPHTARGETS', -}; + ' attribute vec3 morphTarget0;', + ' attribute vec3 morphTarget1;', + ' attribute vec3 morphTarget2;', + ' attribute vec3 morphTarget3;', -THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.ShaderMaterial.prototype.constructor = THREE.ShaderMaterial; + ' #ifdef USE_MORPHNORMALS', -THREE.ShaderMaterial.prototype.copy = function ( source ) { + ' attribute vec3 morphNormal0;', + ' attribute vec3 morphNormal1;', + ' attribute vec3 morphNormal2;', + ' attribute vec3 morphNormal3;', - THREE.Material.prototype.copy.call( this, source ); + ' #else', - this.fragmentShader = source.fragmentShader; - this.vertexShader = source.vertexShader; + ' attribute vec3 morphTarget4;', + ' attribute vec3 morphTarget5;', + ' attribute vec3 morphTarget6;', + ' attribute vec3 morphTarget7;', - this.uniforms = THREE.UniformsUtils.clone( source.uniforms ); + ' #endif', - this.attributes = source.attributes; - this.defines = source.defines; + '#endif', - this.shading = source.shading; + '#ifdef USE_SKINNING', - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; + ' attribute vec4 skinIndex;', + ' attribute vec4 skinWeight;', - this.fog = source.fog; + '#endif', - this.lights = source.lights; + '\n' - this.vertexColors = source.vertexColors; + ].filter( filterEmptyLine ).join( '\n' ); - this.skinning = source.skinning; + prefixFragment = [ - this.morphTargets = source.morphTargets; - this.morphNormals = source.morphNormals; + customExtensions, - this.derivatives = source.derivatives; + 'precision ' + parameters.precision + ' float;', + 'precision ' + parameters.precision + ' int;', - return this; + '#define SHADER_NAME ' + material.__webglShader.name, -}; + customDefines, -THREE.ShaderMaterial.prototype.toJSON = function ( meta ) { + parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '', - var data = THREE.Material.prototype.toJSON.call( this, meta ); + '#define GAMMA_FACTOR ' + gammaFactorDefine, - data.uniforms = this.uniforms; - data.attributes = this.attributes; - data.vertexShader = this.vertexShader; - data.fragmentShader = this.fragmentShader; + ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '', + ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '', - return data; + 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' : '', -// File:src/materials/RawShaderMaterial.js + parameters.doubleSided ? '#define DOUBLE_SIDED' : '', + parameters.flipSided ? '#define FLIP_SIDED' : '', -/** - * @author mrdoob / http://mrdoob.com/ - */ + '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes, -THREE.RawShaderMaterial = function ( parameters ) { + parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', + parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', - THREE.ShaderMaterial.call( this, parameters ); + parameters.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : '', - this.type = 'RawShaderMaterial'; + parameters.physicallyCorrectLights ? "#define PHYSICALLY_CORRECT_LIGHTS" : '', -}; + parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', + parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '', -THREE.RawShaderMaterial.prototype = Object.create( THREE.ShaderMaterial.prototype ); -THREE.RawShaderMaterial.prototype.constructor = THREE.RawShaderMaterial; -// File:src/materials/SpriteMaterial.js + parameters.envMap && renderer.extensions.get( 'EXT_shader_texture_lod' ) ? '#define TEXTURE_LOD_EXT' : '', -/** - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * opacity: , - * map: new THREE.Texture( ), - * - * blending: THREE.NormalBlending, - * depthTest: , - * depthWrite: , - * - * uvOffset: new THREE.Vector2(), - * uvScale: new THREE.Vector2(), - * - * fog: - * } - */ + 'uniform mat4 viewMatrix;', + 'uniform vec3 cameraPosition;', -THREE.SpriteMaterial = function ( parameters ) { + ( 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 ) : '', - THREE.Material.call( this ); + ( 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 ) : '', - this.type = 'SpriteMaterial'; + parameters.depthPacking ? "#define DEPTH_PACKING " + material.depthPacking : '', - this.color = new THREE.Color( 0xffffff ); - this.map = null; + '\n' - this.rotation = 0; + ].filter( filterEmptyLine ).join( '\n' ); - this.fog = false; + } - // set parameters + vertexShader = parseIncludes( vertexShader, parameters ); + vertexShader = replaceLightNums( vertexShader, parameters ); - this.setValues( parameters ); + fragmentShader = parseIncludes( fragmentShader, parameters ); + fragmentShader = replaceLightNums( fragmentShader, parameters ); -}; + if ( ! material.isShaderMaterial ) { -THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype ); -THREE.SpriteMaterial.prototype.constructor = THREE.SpriteMaterial; + vertexShader = unrollLoops( vertexShader ); + fragmentShader = unrollLoops( fragmentShader ); -THREE.SpriteMaterial.prototype.copy = function ( source ) { + } - THREE.Material.prototype.copy.call( this, source ); + var vertexGlsl = prefixVertex + vertexShader; + var fragmentGlsl = prefixFragment + fragmentShader; - this.color.copy( source.color ); - this.map = source.map; + // console.log( '*VERTEX*', vertexGlsl ); + // console.log( '*FRAGMENT*', fragmentGlsl ); - this.rotation = source.rotation; + var glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl ); + var glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl ); - this.fog = source.fog; + gl.attachShader( program, glVertexShader ); + gl.attachShader( program, glFragmentShader ); - return this; + // Force a particular attribute to index 0. -}; + if ( material.index0AttributeName !== undefined ) { -// File:src/textures/Texture.js + gl.bindAttribLocation( program, 0, material.index0AttributeName ); -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * @author szimek / https://github.com/szimek/ - */ + } else if ( parameters.morphTargets === true ) { -THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { + // programs with morphTargets displace position out of attribute 0 + gl.bindAttribLocation( program, 0, 'position' ); - Object.defineProperty( this, 'id', { value: THREE.TextureIdCount ++ } ); + } - this.uuid = THREE.Math.generateUUID(); + gl.linkProgram( program ); - this.name = ''; - this.sourceFile = ''; + var programLog = gl.getProgramInfoLog( program ); + var vertexLog = gl.getShaderInfoLog( glVertexShader ); + var fragmentLog = gl.getShaderInfoLog( glFragmentShader ); - this.image = image !== undefined ? image : THREE.Texture.DEFAULT_IMAGE; - this.mipmaps = []; + var runnable = true; + var haveDiagnostics = true; - this.mapping = mapping !== undefined ? mapping : THREE.Texture.DEFAULT_MAPPING; + // console.log( '**VERTEX**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glVertexShader ) ); + // console.log( '**FRAGMENT**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glFragmentShader ) ); - this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping; - this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping; + if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) { - this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter; - this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter; + runnable = false; - this.anisotropy = anisotropy !== undefined ? anisotropy : 1; + console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter( program, gl.VALIDATE_STATUS ), 'gl.getProgramInfoLog', programLog, vertexLog, fragmentLog ); - this.format = format !== undefined ? format : THREE.RGBAFormat; - this.type = type !== undefined ? type : THREE.UnsignedByteType; + } else if ( programLog !== '' ) { - this.offset = new THREE.Vector2( 0, 0 ); - this.repeat = new THREE.Vector2( 1, 1 ); + console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog ); - 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) + } else if ( vertexLog === '' || fragmentLog === '' ) { - this.version = 0; - this.onUpdate = null; + haveDiagnostics = false; -}; + } -THREE.Texture.DEFAULT_IMAGE = undefined; -THREE.Texture.DEFAULT_MAPPING = THREE.UVMapping; + if ( haveDiagnostics ) { -THREE.Texture.prototype = { + this.diagnostics = { - constructor: THREE.Texture, + runnable: runnable, + material: material, - set needsUpdate ( value ) { + programLog: programLog, - if ( value === true ) this.version ++; + vertexShader: { - }, + log: vertexLog, + prefix: prefixVertex - clone: function () { + }, - return new this.constructor().copy( this ); + fragmentShader: { - }, + log: fragmentLog, + prefix: prefixFragment - copy: function ( source ) { + } - this.image = source.image; - this.mipmaps = source.mipmaps.slice( 0 ); + }; - this.mapping = source.mapping; + } - this.wrapS = source.wrapS; - this.wrapT = source.wrapT; + // clean up - this.magFilter = source.magFilter; - this.minFilter = source.minFilter; + gl.deleteShader( glVertexShader ); + gl.deleteShader( glFragmentShader ); - this.anisotropy = source.anisotropy; + // set up caching for uniform locations - this.format = source.format; - this.type = source.type; + var cachedUniforms; - this.offset.copy( source.offset ); - this.repeat.copy( source.repeat ); + this.getUniforms = function() { - this.generateMipmaps = source.generateMipmaps; - this.premultiplyAlpha = source.premultiplyAlpha; - this.flipY = source.flipY; - this.unpackAlignment = source.unpackAlignment; + if ( cachedUniforms === undefined ) { - return this; + cachedUniforms = + new WebGLUniforms( gl, program, renderer ); - }, + } - toJSON: function ( meta ) { + return cachedUniforms; - if ( meta.textures[ this.uuid ] !== undefined ) { + }; - return meta.textures[ this.uuid ]; + // set up caching for attribute locations - } + var cachedAttributes; - function getDataURL( image ) { + this.getAttributes = function() { - var canvas; + if ( cachedAttributes === undefined ) { - if ( image.toDataURL !== undefined ) { + cachedAttributes = fetchAttributeLocations( gl, program ); - canvas = image; + } - } else { + return cachedAttributes; - canvas = document.createElement( 'canvas' ); - canvas.width = image.width; - canvas.height = image.height; + }; - canvas.getContext( '2d' ).drawImage( image, 0, 0, image.width, image.height ); + // free resource - } + this.destroy = function() { - if ( canvas.width > 2048 || canvas.height > 2048 ) { + gl.deleteProgram( program ); + this.program = undefined; - return canvas.toDataURL( 'image/jpeg', 0.6 ); + }; - } else { + // DEPRECATED - return canvas.toDataURL( 'image/png' ); + Object.defineProperties( this, { - } + uniforms: { + get: function() { - } + console.warn( 'THREE.WebGLProgram: .uniforms is now .getUniforms().' ); + return this.getUniforms(); - var output = { - metadata: { - version: 4.4, - type: 'Texture', - generator: 'Texture.toJSON' - }, + } + }, - uuid: this.uuid, - name: this.name, + attributes: { + get: function() { - mapping: this.mapping, + console.warn( 'THREE.WebGLProgram: .attributes is now .getAttributes().' ); + return this.getAttributes(); - repeat: [ this.repeat.x, this.repeat.y ], - offset: [ this.offset.x, this.offset.y ], - wrap: [ this.wrapS, this.wrapT ], + } + } - minFilter: this.minFilter, - magFilter: this.magFilter, - anisotropy: this.anisotropy - }; + } ); - if ( this.image !== undefined ) { - // TODO: Move to THREE.Image + // - var image = this.image; + this.id = programIdCount ++; + this.code = code; + this.usedTimes = 1; + this.program = program; + this.vertexShader = glVertexShader; + this.fragmentShader = glFragmentShader; - if ( image.uuid === undefined ) { + return this; - image.uuid = THREE.Math.generateUUID(); // UGH + } - } + function WebGLPrograms( renderer, capabilities ) { - if ( meta.images[ image.uuid ] === undefined ) { + var programs = []; - meta.images[ image.uuid ] = { - uuid: image.uuid, - url: getDataURL( image ) - }; + var shaderIDs = { + MeshDepthMaterial: 'depth', + MeshNormalMaterial: 'normal', + MeshBasicMaterial: 'basic', + MeshLambertMaterial: 'lambert', + MeshPhongMaterial: 'phong', + MeshStandardMaterial: 'physical', + MeshPhysicalMaterial: 'physical', + LineBasicMaterial: 'basic', + LineDashedMaterial: 'dashed', + PointsMaterial: 'points' + }; - } + 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" + ]; - output.image = image.uuid; - } + function allocateBones( object ) { - meta.textures[ this.uuid ] = output; + if ( capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture ) { - return output; + return 1024; - }, + } else { - dispose: function () { + // 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) - this.dispatchEvent( { type: 'dispose' } ); + var nVertexUniforms = capabilities.maxVertexUniforms; + var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 ); - }, + var maxBones = nVertexMatrices; - transformUv: function ( uv ) { + if ( object !== undefined && (object && object.isSkinnedMesh) ) { - if ( this.mapping !== THREE.UVMapping ) return; + maxBones = Math.min( object.skeleton.bones.length, maxBones ); - uv.multiply( this.repeat ); - uv.add( this.offset ); + if ( maxBones < object.skeleton.bones.length ) { - if ( uv.x < 0 || uv.x > 1 ) { + console.warn( 'WebGLRenderer: too many bones - ' + object.skeleton.bones.length + ', this GPU supports just ' + maxBones + ' (try OpenGL instead of ANGLE)' ); - switch ( this.wrapS ) { + } - case THREE.RepeatWrapping: + } - uv.x = uv.x - Math.floor( uv.x ); - break; + return maxBones; - case THREE.ClampToEdgeWrapping: + } - uv.x = uv.x < 0 ? 0 : 1; - break; + } - case THREE.MirroredRepeatWrapping: + function getTextureEncodingFromMap( map, gammaOverrideLinear ) { - if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) { + var encoding; - uv.x = Math.ceil( uv.x ) - uv.x; + if ( ! map ) { - } else { + encoding = LinearEncoding; - uv.x = uv.x - Math.floor( uv.x ); + } else if ( (map && map.isTexture) ) { - } - break; + encoding = map.encoding; - } + } else if ( (map && map.isWebGLRenderTarget) ) { - } + console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." ); + encoding = map.texture.encoding; - if ( uv.y < 0 || uv.y > 1 ) { + } - switch ( this.wrapT ) { + // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point. + if ( encoding === LinearEncoding && gammaOverrideLinear ) { - case THREE.RepeatWrapping: + encoding = GammaEncoding; - uv.y = uv.y - Math.floor( uv.y ); - break; + } - case THREE.ClampToEdgeWrapping: + return encoding; - uv.y = uv.y < 0 ? 0 : 1; - break; + } - case THREE.MirroredRepeatWrapping: + this.getParameters = function ( material, lights, fog, nClipPlanes, object ) { - if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) { + var shaderID = shaderIDs[ material.type ]; - uv.y = Math.ceil( uv.y ) - uv.y; + // heuristics to create shader parameters according to lights in the scene + // (not to blow over maxLights budget) - } else { + var maxBones = allocateBones( object ); + var precision = renderer.getPrecision(); - uv.y = uv.y - Math.floor( uv.y ); + if ( material.precision !== null ) { - } - break; + precision = capabilities.getMaxPrecision( material.precision ); - } + if ( precision !== material.precision ) { - } + console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' ); - if ( this.flipY ) { + } - uv.y = 1 - uv.y; + } - } + var currentRenderTarget = renderer.getCurrentRenderTarget(); - } + var parameters = { -}; + shaderID: shaderID, -THREE.EventDispatcher.prototype.apply( THREE.Texture.prototype ); + 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, -THREE.TextureIdCount = 0; + combine: material.combine, -// File:src/textures/CanvasTexture.js + vertexColors: material.vertexColors, -/** - * @author mrdoob / http://mrdoob.com/ - */ + fog: !! fog, + useFog: material.fog, + fogExp: (fog && fog.isFogExp2), -THREE.CanvasTexture = function ( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { + flatShading: material.shading === FlatShading, - THREE.Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + sizeAttenuation: material.sizeAttenuation, + logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer, - this.needsUpdate = true; + 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, -THREE.CanvasTexture.prototype = Object.create( THREE.Texture.prototype ); -THREE.CanvasTexture.prototype.constructor = THREE.CanvasTexture; + numDirLights: lights.directional.length, + numPointLights: lights.point.length, + numSpotLights: lights.spot.length, + numHemiLights: lights.hemi.length, -// File:src/textures/CubeTexture.js + numClippingPlanes: nClipPlanes, -/** - * @author mrdoob / http://mrdoob.com/ - */ + shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && lights.shadows.length > 0, + shadowMapType: renderer.shadowMap.type, -THREE.CubeTexture = function ( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { + toneMapping: renderer.toneMapping, + physicallyCorrectLights: renderer.physicallyCorrectLights, - mapping = mapping !== undefined ? mapping : THREE.CubeReflectionMapping; + premultipliedAlpha: material.premultipliedAlpha, - THREE.Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + alphaTest: material.alphaTest, + doubleSided: material.side === DoubleSide, + flipSided: material.side === BackSide, - this.images = images; - this.flipY = false; + depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false -}; + }; -THREE.CubeTexture.prototype = Object.create( THREE.Texture.prototype ); -THREE.CubeTexture.prototype.constructor = THREE.CubeTexture; + return parameters; -THREE.CubeTexture.prototype.copy = function ( source ) { + }; - THREE.Texture.prototype.copy.call( this, source ); - - this.images = source.images; - - return this; + this.getProgramCode = function ( material, parameters ) { -}; -// File:src/textures/CompressedTexture.js + var array = []; -/** - * @author alteredq / http://alteredqualia.com/ - */ + if ( parameters.shaderID ) { -THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) { + array.push( parameters.shaderID ); - THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + } else { - this.image = { width: width, height: height }; - this.mipmaps = mipmaps; + array.push( material.fragmentShader ); + array.push( material.vertexShader ); - // no flipping for cube textures - // (also flipping doesn't work for compressed textures ) + } - this.flipY = false; + if ( material.defines !== undefined ) { - // can't generate mipmaps for compressed textures - // mips must be embedded in DDS files + for ( var name in material.defines ) { - this.generateMipmaps = false; + array.push( name ); + array.push( material.defines[ name ] ); -}; + } -THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype ); -THREE.CompressedTexture.prototype.constructor = THREE.CompressedTexture; + } -// File:src/textures/DataTexture.js + for ( var i = 0; i < parameterNames.length; i ++ ) { -/** - * @author alteredq / http://alteredqualia.com/ - */ + array.push( parameters[ parameterNames[ i ] ] ); -THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) { + } - THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + return array.join(); - this.image = { data: data, width: width, height: height }; + }; - this.magFilter = magFilter !== undefined ? magFilter : THREE.NearestFilter; - this.minFilter = minFilter !== undefined ? minFilter : THREE.NearestFilter; - - this.flipY = false; - this.generateMipmaps = false; + this.acquireProgram = function ( material, parameters, code ) { -}; + var program; -THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype ); -THREE.DataTexture.prototype.constructor = THREE.DataTexture; + // Check if code has been already compiled + for ( var p = 0, pl = programs.length; p < pl; p ++ ) { -// File:src/textures/VideoTexture.js + var programInfo = programs[ p ]; -/** - * @author mrdoob / http://mrdoob.com/ - */ + if ( programInfo.code === code ) { -THREE.VideoTexture = function ( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { + program = programInfo; + ++ program.usedTimes; - THREE.Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + break; - this.generateMipmaps = false; + } - var scope = this; + } - var update = function () { + if ( program === undefined ) { - requestAnimationFrame( update ); + program = new WebGLProgram( renderer, code, material, parameters ); + programs.push( program ); - if ( video.readyState === video.HAVE_ENOUGH_DATA ) { + } - scope.needsUpdate = true; + return program; - } + }; - }; + this.releaseProgram = function( program ) { - update(); + if ( -- program.usedTimes === 0 ) { -}; + // Remove from unordered set + var i = programs.indexOf( program ); + programs[ i ] = programs[ programs.length - 1 ]; + programs.pop(); -THREE.VideoTexture.prototype = Object.create( THREE.Texture.prototype ); -THREE.VideoTexture.prototype.constructor = THREE.VideoTexture; + // Free WebGL resources + program.destroy(); -// File:src/objects/Group.js + } -/** - * @author mrdoob / http://mrdoob.com/ - */ + }; -THREE.Group = function () { + // Exposed for resource monitoring & error feedback via renderer.info: + this.programs = programs; - THREE.Object3D.call( this ); + } - this.type = 'Group'; + function WebGLGeometries( gl, properties, info ) { -}; + var geometries = {}; -THREE.Group.prototype = Object.create( THREE.Object3D.prototype ); -THREE.Group.prototype.constructor = THREE.Group; -// File:src/objects/Points.js + function onGeometryDispose( event ) { -/** - * @author alteredq / http://alteredqualia.com/ - */ + var geometry = event.target; + var buffergeometry = geometries[ geometry.id ]; -THREE.Points = function ( geometry, material ) { + if ( buffergeometry.index !== null ) { - THREE.Object3D.call( this ); + deleteAttribute( buffergeometry.index ); - this.type = 'Points'; + } - this.geometry = geometry !== undefined ? geometry : new THREE.Geometry(); - this.material = material !== undefined ? material : new THREE.PointsMaterial( { color: Math.random() * 0xffffff } ); + deleteAttributes( buffergeometry.attributes ); -}; + geometry.removeEventListener( 'dispose', onGeometryDispose ); -THREE.Points.prototype = Object.create( THREE.Object3D.prototype ); -THREE.Points.prototype.constructor = THREE.Points; + delete geometries[ geometry.id ]; -THREE.Points.prototype.raycast = ( function () { + // TODO - var inverseMatrix = new THREE.Matrix4(); - var ray = new THREE.Ray(); + var property = properties.get( geometry ); - return function raycast( raycaster, intersects ) { + if ( property.wireframe ) { - var object = this; - var geometry = object.geometry; - var threshold = raycaster.params.Points.threshold; + deleteAttribute( property.wireframe ); - inverseMatrix.getInverse( this.matrixWorld ); - ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); + } - if ( geometry.boundingBox !== null ) { + properties.delete( geometry ); - if ( ray.isIntersectionBox( geometry.boundingBox ) === false ) { + var bufferproperty = properties.get( buffergeometry ); - return; + if ( bufferproperty.wireframe ) { - } + deleteAttribute( bufferproperty.wireframe ); - } + } - var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 ); - var localThresholdSq = localThreshold * localThreshold; - var position = new THREE.Vector3(); + properties.delete( buffergeometry ); - function testPoint( point, index ) { + // - var rayPointDistanceSq = ray.distanceSqToPoint( point ); + info.memory.geometries --; - if ( rayPointDistanceSq < localThresholdSq ) { + } - var intersectPoint = ray.closestPointToPoint( point ); - intersectPoint.applyMatrix4( object.matrixWorld ); + function getAttributeBuffer( attribute ) { - var distance = raycaster.ray.origin.distanceTo( intersectPoint ); + if ( attribute.isInterleavedBufferAttribute ) { - if ( distance < raycaster.near || distance > raycaster.far ) return; + return properties.get( attribute.data ).__webglBuffer; - intersects.push( { + } - distance: distance, - distanceToRay: Math.sqrt( rayPointDistanceSq ), - point: intersectPoint.clone(), - index: index, - face: null, - object: object + return properties.get( attribute ).__webglBuffer; - } ); + } - } + function deleteAttribute( attribute ) { - } + var buffer = getAttributeBuffer( attribute ); - if ( geometry instanceof THREE.BufferGeometry ) { + if ( buffer !== undefined ) { - var index = geometry.index; - var attributes = geometry.attributes; - var positions = attributes.position.array; + gl.deleteBuffer( buffer ); + removeAttributeBuffer( attribute ); - if ( index !== null ) { + } - var indices = index.array; + } - for ( var i = 0, il = indices.length; i < il; i ++ ) { + function deleteAttributes( attributes ) { - var a = indices[ i ]; + for ( var name in attributes ) { - position.fromArray( positions, a * 3 ); + deleteAttribute( attributes[ name ] ); - testPoint( position, a ); + } - } + } - } else { + function removeAttributeBuffer( attribute ) { - for ( var i = 0, l = positions.length / 3; i < l; i ++ ) { + if ( attribute.isInterleavedBufferAttribute ) { - position.fromArray( positions, i * 3 ); + properties.delete( attribute.data ); - testPoint( position, i ); + } else { - } + properties.delete( attribute ); - } + } - } else { + } - var vertices = geometry.vertices; + return { - for ( var i = 0, l = vertices.length; i < l; i ++ ) { + get: function ( object ) { - testPoint( vertices[ i ], i ); + var geometry = object.geometry; - } + if ( geometries[ geometry.id ] !== undefined ) { - } + return geometries[ geometry.id ]; - }; + } -}() ); + geometry.addEventListener( 'dispose', onGeometryDispose ); -THREE.Points.prototype.clone = function () { + var buffergeometry; - return new this.constructor( this.geometry, this.material ).copy( this ); + if ( geometry.isBufferGeometry ) { -}; + buffergeometry = geometry; -THREE.Points.prototype.toJSON = function ( meta ) { + } else if ( geometry.isGeometry ) { - var data = THREE.Object3D.prototype.toJSON.call( this, meta ); + if ( geometry._bufferGeometry === undefined ) { - // only serialize if not in meta geometries cache - if ( meta.geometries[ this.geometry.uuid ] === undefined ) { + geometry._bufferGeometry = new BufferGeometry().setFromObject( object ); - meta.geometries[ this.geometry.uuid ] = this.geometry.toJSON(); + } - } + buffergeometry = geometry._bufferGeometry; - // only serialize if not in meta materials cache - if ( meta.materials[ this.material.uuid ] === undefined ) { + } - meta.materials[ this.material.uuid ] = this.material.toJSON(); + geometries[ geometry.id ] = buffergeometry; - } + info.memory.geometries ++; - data.object.geometry = this.geometry.uuid; - data.object.material = this.material.uuid; + return buffergeometry; - return data; + } -}; + }; -// Backwards compatibility + } -THREE.PointCloud = function ( geometry, material ) { + function WebGLObjects( gl, properties, info ) { - console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' ); - return new THREE.Points( geometry, material ); + var geometries = new WebGLGeometries( gl, properties, info ); -}; + // -THREE.ParticleSystem = function ( geometry, material ) { + function update( object ) { - console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' ); - return new THREE.Points( geometry, material ); + // TODO: Avoid updating twice (when using shadowMap). Maybe add frame counter. -}; + var geometry = geometries.get( object ); -// File:src/objects/Line.js + if ( object.geometry.isGeometry ) { -/** - * @author mrdoob / http://mrdoob.com/ - */ + geometry.updateFromObject( object ); -THREE.Line = function ( geometry, material, mode ) { + } - if ( mode === 1 ) { + var index = geometry.index; + var attributes = geometry.attributes; - console.warn( 'THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.' ); - return new THREE.LineSegments( geometry, material ); + if ( index !== null ) { - } + updateAttribute( index, gl.ELEMENT_ARRAY_BUFFER ); - THREE.Object3D.call( this ); + } - this.type = 'Line'; + for ( var name in attributes ) { - this.geometry = geometry !== undefined ? geometry : new THREE.Geometry(); - this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } ); + updateAttribute( attributes[ name ], gl.ARRAY_BUFFER ); -}; + } -THREE.Line.prototype = Object.create( THREE.Object3D.prototype ); -THREE.Line.prototype.constructor = THREE.Line; + // morph targets -THREE.Line.prototype.raycast = ( function () { + var morphAttributes = geometry.morphAttributes; - var inverseMatrix = new THREE.Matrix4(); - var ray = new THREE.Ray(); - var sphere = new THREE.Sphere(); + for ( var name in morphAttributes ) { - return function raycast( raycaster, intersects ) { + var array = morphAttributes[ name ]; - var precision = raycaster.linePrecision; - var precisionSq = precision * precision; + for ( var i = 0, l = array.length; i < l; i ++ ) { - var geometry = this.geometry; + updateAttribute( array[ i ], gl.ARRAY_BUFFER ); - if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + } - // Checking boundingSphere distance to ray + } - sphere.copy( geometry.boundingSphere ); - sphere.applyMatrix4( this.matrixWorld ); + return geometry; - if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) { + } - return; + function updateAttribute( attribute, bufferType ) { - } + var data = ( attribute.isInterleavedBufferAttribute ) ? attribute.data : attribute; - inverseMatrix.getInverse( this.matrixWorld ); - ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); + var attributeProperties = properties.get( data ); - var vStart = new THREE.Vector3(); - var vEnd = new THREE.Vector3(); - var interSegment = new THREE.Vector3(); - var interRay = new THREE.Vector3(); - var step = this instanceof THREE.LineSegments ? 2 : 1; + if ( attributeProperties.__webglBuffer === undefined ) { - if ( geometry instanceof THREE.BufferGeometry ) { + createBuffer( attributeProperties, data, bufferType ); - var index = geometry.index; - var attributes = geometry.attributes; + } else if ( attributeProperties.version !== data.version ) { - if ( index !== null ) { + updateBuffer( attributeProperties, data, bufferType ); - var indices = index.array; - var positions = attributes.position.array; + } - for ( var i = 0, l = indices.length - 1; i < l; i += step ) { + } - var a = indices[ i ]; - var b = indices[ i + 1 ]; + function createBuffer( attributeProperties, data, bufferType ) { - vStart.fromArray( positions, a * 3 ); - vEnd.fromArray( positions, b * 3 ); + attributeProperties.__webglBuffer = gl.createBuffer(); + gl.bindBuffer( bufferType, attributeProperties.__webglBuffer ); - var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); + var usage = data.dynamic ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW; - if ( distSq > precisionSq ) continue; + gl.bufferData( bufferType, data.array, usage ); - interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation + attributeProperties.version = data.version; - var distance = raycaster.ray.origin.distanceTo( interRay ); + } - if ( distance < raycaster.near || distance > raycaster.far ) continue; + function updateBuffer( attributeProperties, data, bufferType ) { - intersects.push( { + gl.bindBuffer( bufferType, attributeProperties.__webglBuffer ); - 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 + if ( data.dynamic === false || data.updateRange.count === - 1 ) { - } ); + // Not using update ranges - } + gl.bufferSubData( bufferType, 0, data.array ); - } else { + } else if ( data.updateRange.count === 0 ) { - var positions = attributes.position.array; + 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.' ); - for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) { + } else { - vStart.fromArray( positions, 3 * i ); - vEnd.fromArray( positions, 3 * i + 3 ); + gl.bufferSubData( bufferType, data.updateRange.offset * data.array.BYTES_PER_ELEMENT, + data.array.subarray( data.updateRange.offset, data.updateRange.offset + data.updateRange.count ) ); - var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); + data.updateRange.count = 0; // reset range - if ( distSq > precisionSq ) continue; + } - interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation + attributeProperties.version = data.version; - var distance = raycaster.ray.origin.distanceTo( interRay ); + } - if ( distance < raycaster.near || distance > raycaster.far ) continue; + function getAttributeBuffer( attribute ) { - intersects.push( { + if ( attribute.isInterleavedBufferAttribute ) { - distance: distance, - // What do we want? intersection point on the ray or on the segment?? - // point: raycaster.ray.at( distance ), - point: interSegment.clone().applyMatrix4( this.matrixWorld ), - index: i, - face: null, - faceIndex: null, - object: this + return properties.get( attribute.data ).__webglBuffer; - } ); + } - } + return properties.get( attribute ).__webglBuffer; - } + } - } else if ( geometry instanceof THREE.Geometry ) { + function getWireframeAttribute( geometry ) { - var vertices = geometry.vertices; - var nbVertices = vertices.length; + var property = properties.get( geometry ); - for ( var i = 0; i < nbVertices - 1; i += step ) { + if ( property.wireframe !== undefined ) { - var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment ); + return property.wireframe; - if ( distSq > precisionSq ) continue; + } - interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation + var indices = []; - var distance = raycaster.ray.origin.distanceTo( interRay ); + var index = geometry.index; + var attributes = geometry.attributes; + var position = attributes.position; - if ( distance < raycaster.near || distance > raycaster.far ) continue; + // console.time( 'wireframe' ); - 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 edges = {}; + var array = index.array; - } ); + 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 ]; - } + indices.push( a, b, b, c, c, a ); - }; + } -}() ); + } else { -THREE.Line.prototype.clone = function () { + var array = attributes.position.array; - return new this.constructor( this.geometry, this.material ).copy( this ); + for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) { -}; + var a = i + 0; + var b = i + 1; + var c = i + 2; -THREE.Line.prototype.toJSON = function ( meta ) { + indices.push( a, b, b, c, c, a ); - var data = THREE.Object3D.prototype.toJSON.call( this, meta ); + } - // only serialize if not in meta geometries cache - if ( meta.geometries[ this.geometry.uuid ] === undefined ) { + } - meta.geometries[ this.geometry.uuid ] = this.geometry.toJSON(); + // console.timeEnd( 'wireframe' ); - } + var TypeArray = position.count > 65535 ? Uint32Array : Uint16Array; + var attribute = new BufferAttribute( new TypeArray( indices ), 1 ); - // only serialize if not in meta materials cache - if ( meta.materials[ this.material.uuid ] === undefined ) { + updateAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER ); - meta.materials[ this.material.uuid ] = this.material.toJSON(); + property.wireframe = attribute; - } + return attribute; - data.object.geometry = this.geometry.uuid; - data.object.material = this.material.uuid; + } - return data; + return { -}; + getAttributeBuffer: getAttributeBuffer, + getWireframeAttribute: getWireframeAttribute, -// DEPRECATED + update: update -THREE.LineStrip = 0; -THREE.LinePieces = 1; + }; -// File:src/objects/LineSegments.js + } -/** - * @author mrdoob / http://mrdoob.com/ - */ + function WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, info ) { -THREE.LineSegments = function ( geometry, material ) { + var _infoMemory = info.memory; + var _isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && _gl instanceof WebGL2RenderingContext ); - THREE.Line.call( this, geometry, material ); + // - this.type = 'LineSegments'; + function clampToMaxSize( image, maxSize ) { -}; + if ( image.width > maxSize || image.height > maxSize ) { -THREE.LineSegments.prototype = Object.create( THREE.Line.prototype ); -THREE.LineSegments.prototype.constructor = THREE.LineSegments; + // Warning: Scaling through the canvas will only work with images that use + // premultiplied alpha. -// File:src/objects/Mesh.js + var scale = maxSize / Math.max( image.width, image.height ); -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * @author mikael emtinger / http://gomo.se/ - * @author jonobr1 / http://jonobr1.com/ - */ + 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 ); -THREE.Mesh = function ( geometry, material ) { + var context = canvas.getContext( '2d' ); + context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height ); - THREE.Object3D.call( this ); + console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image ); - this.type = 'Mesh'; + return canvas; - this.geometry = geometry !== undefined ? geometry : new THREE.Geometry(); - this.material = material !== undefined ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } ); + } - this.updateMorphTargets(); + return image; -}; + } -THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype ); -THREE.Mesh.prototype.constructor = THREE.Mesh; + function isPowerOfTwo( image ) { -THREE.Mesh.prototype.updateMorphTargets = function () { + return exports.Math.isPowerOfTwo( image.width ) && exports.Math.isPowerOfTwo( image.height ); - if ( this.geometry.morphTargets !== undefined && this.geometry.morphTargets.length > 0 ) { + } - this.morphTargetBase = - 1; - this.morphTargetInfluences = []; - this.morphTargetDictionary = {}; + function makePowerOfTwo( image ) { - for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) { + if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement ) { - this.morphTargetInfluences.push( 0 ); - this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m; + var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); + canvas.width = exports.Math.nearestPowerOfTwo( image.width ); + canvas.height = exports.Math.nearestPowerOfTwo( image.height ); - } + var context = canvas.getContext( '2d' ); + context.drawImage( image, 0, 0, canvas.width, canvas.height ); - } + 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; -THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) { + } - if ( this.morphTargetDictionary[ name ] !== undefined ) { + return image; - return this.morphTargetDictionary[ name ]; + } - } + function textureNeedsPowerOfTwo( texture ) { - console.warn( 'THREE.Mesh.getMorphTargetIndexByName: morph target ' + name + ' does not exist. Returning 0.' ); + if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) return true; + if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) return true; - return 0; + return false; -}; + } + // Fallback filters for non-power-of-2 textures -THREE.Mesh.prototype.raycast = ( function () { + function filterFallback( f ) { - var inverseMatrix = new THREE.Matrix4(); - var ray = new THREE.Ray(); - var sphere = new THREE.Sphere(); + if ( f === NearestFilter || f === NearestMipMapNearestFilter || f === NearestMipMapLinearFilter ) { - var vA = new THREE.Vector3(); - var vB = new THREE.Vector3(); - var vC = new THREE.Vector3(); + return _gl.NEAREST; - var tempA = new THREE.Vector3(); - var tempB = new THREE.Vector3(); - var tempC = new THREE.Vector3(); + } - var uvA = new THREE.Vector2(); - var uvB = new THREE.Vector2(); - var uvC = new THREE.Vector2(); + return _gl.LINEAR; - var barycoord = new THREE.Vector3(); + } - var intersectionPoint = new THREE.Vector3(); - var intersectionPointWorld = new THREE.Vector3(); + // - function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) { + function onTextureDispose( event ) { - THREE.Triangle.barycoordFromPoint( point, p1, p2, p3, barycoord ); + var texture = event.target; - uv1.multiplyScalar( barycoord.x ); - uv2.multiplyScalar( barycoord.y ); - uv3.multiplyScalar( barycoord.z ); + texture.removeEventListener( 'dispose', onTextureDispose ); - uv1.add( uv2 ).add( uv3 ); + deallocateTexture( texture ); - return uv1.clone(); + _infoMemory.textures --; - } - return function raycast( raycaster, intersects ) { + } - var geometry = this.geometry; - var material = this.material; + function onRenderTargetDispose( event ) { - if ( material === undefined ) return; + var renderTarget = event.target; - // Checking boundingSphere distance to ray + renderTarget.removeEventListener( 'dispose', onRenderTargetDispose ); - if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + deallocateRenderTarget( renderTarget ); - sphere.copy( geometry.boundingSphere ); - sphere.applyMatrix4( this.matrixWorld ); + _infoMemory.textures --; - if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) { + } - return; + // - } + function deallocateTexture( texture ) { - // Check boundingBox before continuing + var textureProperties = properties.get( texture ); - inverseMatrix.getInverse( this.matrixWorld ); - ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); + if ( texture.image && textureProperties.__image__webglTextureCube ) { - if ( geometry.boundingBox !== null ) { + // cube texture - if ( ray.isIntersectionBox( geometry.boundingBox ) === false ) { + _gl.deleteTexture( textureProperties.__image__webglTextureCube ); - return; + } else { - } + // 2D texture - } + if ( textureProperties.__webglInit === undefined ) return; - var a, b, c; + _gl.deleteTexture( textureProperties.__webglTexture ); - if ( geometry instanceof THREE.BufferGeometry ) { + } - var index = geometry.index; - var attributes = geometry.attributes; + // remove all webgl properties + properties.delete( texture ); - if ( index !== null ) { + } - var indices = index.array; - var positions = attributes.position.array; + function deallocateRenderTarget( renderTarget ) { - for ( var i = 0, l = indices.length; i < l; i += 3 ) { + var renderTargetProperties = properties.get( renderTarget ); + var textureProperties = properties.get( renderTarget.texture ); - a = indices[ i ]; - b = indices[ i + 1 ]; - c = indices[ i + 2 ]; + if ( ! renderTarget ) return; - vA.fromArray( positions, a * 3 ); - vB.fromArray( positions, b * 3 ); - vC.fromArray( positions, c * 3 ); + if ( textureProperties.__webglTexture !== undefined ) { - if ( material.side === THREE.BackSide ) { + _gl.deleteTexture( textureProperties.__webglTexture ); - if ( ray.intersectTriangle( vC, vB, vA, true, intersectionPoint ) === null ) continue; + } - } else { + if ( renderTarget.depthTexture ) { - if ( ray.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide, intersectionPoint ) === null ) continue; + renderTarget.depthTexture.dispose(); - } + } - intersectionPointWorld.copy( intersectionPoint ); - intersectionPointWorld.applyMatrix4( this.matrixWorld ); + if ( (renderTarget && renderTarget.isWebGLRenderTargetCube) ) { - var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld ); + for ( var i = 0; i < 6; i ++ ) { - if ( distance < raycaster.near || distance > raycaster.far ) continue; + _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] ); + if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] ); - var uv; + } - if ( attributes.uv !== undefined ) { + } else { - var uvs = attributes.uv.array; - uvA.fromArray( uvs, a * 2 ); - uvB.fromArray( uvs, b * 2 ); - uvC.fromArray( uvs, c * 2 ); - uv = uvIntersection( intersectionPoint, vA, vB, vC, uvA, uvB, uvC ); + _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer ); + if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer ); - } + } - intersects.push( { + properties.delete( renderTarget.texture ); + properties.delete( renderTarget ); - distance: distance, - point: intersectionPointWorld.clone(), - uv: uv, - face: new THREE.Face3( a, b, c, THREE.Triangle.normal( vA, vB, vC ) ), - faceIndex: Math.floor( i / 3 ), // triangle number in indices buffer semantics - object: this + } - } ); + // - } - } else { - var positions = attributes.position.array; + function setTexture2D( texture, slot ) { - for ( var i = 0, l = positions.length; i < l; i += 9 ) { + var textureProperties = properties.get( texture ); - vA.fromArray( positions, i ); - vB.fromArray( positions, i + 3 ); - vC.fromArray( positions, i + 6 ); + if ( texture.version > 0 && textureProperties.__version !== texture.version ) { - if ( material.side === THREE.BackSide ) { + var image = texture.image; - if ( ray.intersectTriangle( vC, vB, vA, true, intersectionPoint ) === null ) continue; + if ( image === undefined ) { - } else { + console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture ); - if ( ray.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide, intersectionPoint ) === null ) continue; + } else if ( image.complete === false ) { - } + console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture ); - intersectionPointWorld.copy( intersectionPoint ); - intersectionPointWorld.applyMatrix4( this.matrixWorld ); + } else { - var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld ); + uploadTexture( textureProperties, texture, slot ); + return; - if ( distance < raycaster.near || distance > raycaster.far ) continue; + } - var uv; + } - if ( attributes.uv !== undefined ) { + state.activeTexture( _gl.TEXTURE0 + slot ); + state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture ); - var uvs = attributes.uv.array; - uvA.fromArray( uvs, i ); - uvB.fromArray( uvs, i + 2 ); - uvC.fromArray( uvs, i + 4 ); - uv = uvIntersection( intersectionPoint, vA, vB, vC, uvA, uvB, uvC ); + } - } + function setTextureCube( texture, slot ) { - a = i / 3; - b = a + 1; - c = a + 2; + var textureProperties = properties.get( texture ); - intersects.push( { + if ( texture.image.length === 6 ) { - distance: distance, - point: intersectionPointWorld.clone(), - uv: uv, - face: new THREE.Face3( a, b, c, THREE.Triangle.normal( vA, vB, vC ) ), - index: a, // triangle number in positions buffer semantics - object: this + if ( texture.version > 0 && textureProperties.__version !== texture.version ) { - } ); + if ( ! textureProperties.__image__webglTextureCube ) { - } + texture.addEventListener( 'dispose', onTextureDispose ); - } + textureProperties.__image__webglTextureCube = _gl.createTexture(); - } else if ( geometry instanceof THREE.Geometry ) { + _infoMemory.textures ++; - var isFaceMaterial = material instanceof THREE.MeshFaceMaterial; - var materials = isFaceMaterial === true ? material.materials : null; + } - var vertices = geometry.vertices; - var faces = geometry.faces; + state.activeTexture( _gl.TEXTURE0 + slot ); + state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube ); - for ( var f = 0, fl = faces.length; f < fl; f ++ ) { + _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY ); - var face = faces[ f ]; - var faceMaterial = isFaceMaterial === true ? materials[ face.materialIndex ] : material; + var isCompressed = (texture && texture.isCompressedTexture); + var isDataTexture = (texture.image[ 0 ] && texture.image[ 0 ].isDataTexture); - if ( faceMaterial === undefined ) continue; + var cubeImage = []; - a = vertices[ face.a ]; - b = vertices[ face.b ]; - c = vertices[ face.c ]; + for ( var i = 0; i < 6; i ++ ) { - if ( faceMaterial.morphTargets === true ) { + if ( ! isCompressed && ! isDataTexture ) { - var morphTargets = geometry.morphTargets; - var morphInfluences = this.morphTargetInfluences; + cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize ); - vA.set( 0, 0, 0 ); - vB.set( 0, 0, 0 ); - vC.set( 0, 0, 0 ); + } else { - for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) { + cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ]; - var influence = morphInfluences[ t ]; + } - if ( influence === 0 ) continue; + } - var targets = morphTargets[ t ].vertices; + var image = cubeImage[ 0 ], + isPowerOfTwoImage = isPowerOfTwo( image ), + glFormat = paramThreeToGL( texture.format ), + glType = paramThreeToGL( texture.type ); - vA.addScaledVector( tempA.subVectors( targets[ face.a ], a ), influence ); - vB.addScaledVector( tempB.subVectors( targets[ face.b ], b ), influence ); - vC.addScaledVector( tempC.subVectors( targets[ face.c ], c ), influence ); + setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isPowerOfTwoImage ); - } + for ( var i = 0; i < 6; i ++ ) { - vA.add( a ); - vB.add( b ); - vC.add( c ); + if ( ! isCompressed ) { - a = vA; - b = vB; - c = vC; + if ( isDataTexture ) { - } + state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data ); - if ( faceMaterial.side === THREE.BackSide ) { + } else { - if ( ray.intersectTriangle( c, b, a, true, intersectionPoint ) === null ) continue; + state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] ); - } else { + } - if ( ray.intersectTriangle( a, b, c, faceMaterial.side !== THREE.DoubleSide, intersectionPoint ) === null ) continue; + } else { - } + var mipmap, mipmaps = cubeImage[ i ].mipmaps; - intersectionPointWorld.copy( intersectionPoint ); - intersectionPointWorld.applyMatrix4( this.matrixWorld ); + for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) { - var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld ); + mipmap = mipmaps[ j ]; - if ( distance < raycaster.near || distance > raycaster.far ) continue; + if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) { - var uv; + if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) { - if ( geometry.faceVertexUvs[ 0 ].length > 0 ) { + state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data ); - var uvs = geometry.faceVertexUvs[ 0 ][ f ]; - uvA.copy( uvs[ 0 ] ); - uvB.copy( uvs[ 1 ] ); - uvC.copy( uvs[ 2 ] ); - uv = uvIntersection( intersectionPoint, a, b, c, uvA, uvB, uvC ); + } else { - } + console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()" ); - intersects.push( { + } - distance: distance, - point: intersectionPointWorld.clone(), - uv: uv, - face: face, - faceIndex: f, - object: this + } else { - } ); + state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); - } + } - } + } - }; + } -}() ); + } -THREE.Mesh.prototype.clone = function () { + if ( texture.generateMipmaps && isPowerOfTwoImage ) { - return new this.constructor( this.geometry, this.material ).copy( this ); + _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP ); -}; + } -THREE.Mesh.prototype.toJSON = function ( meta ) { + textureProperties.__version = texture.version; - var data = THREE.Object3D.prototype.toJSON.call( this, meta ); + if ( texture.onUpdate ) texture.onUpdate( texture ); - // only serialize if not in meta geometries cache - if ( meta.geometries[ this.geometry.uuid ] === undefined ) { + } else { - meta.geometries[ this.geometry.uuid ] = this.geometry.toJSON( meta ); + state.activeTexture( _gl.TEXTURE0 + slot ); + state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube ); - } + } - // only serialize if not in meta materials cache - if ( meta.materials[ this.material.uuid ] === undefined ) { + } - meta.materials[ this.material.uuid ] = this.material.toJSON( meta ); + } - } + function setTextureCubeDynamic( texture, slot ) { - data.object.geometry = this.geometry.uuid; - data.object.material = this.material.uuid; + state.activeTexture( _gl.TEXTURE0 + slot ); + state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture ); - return data; + } -}; + function setTextureParameters( textureType, texture, isPowerOfTwoImage ) { -// File:src/objects/Bone.js + var extension; -/** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author ikerr / http://verold.com - */ + if ( isPowerOfTwoImage ) { -THREE.Bone = function ( skin ) { + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) ); + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) ); - THREE.Object3D.call( this ); + _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) ); + _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) ); - this.type = 'Bone'; + } else { - this.skin = skin; + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE ); + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE ); -}; + if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) { -THREE.Bone.prototype = Object.create( THREE.Object3D.prototype ); -THREE.Bone.prototype.constructor = THREE.Bone; + console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture ); -THREE.Bone.prototype.copy = function ( source ) { - - THREE.Object3D.prototype.copy.call( this, source ); - - this.skin = source.skin; - - return this; + } -}; + _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) ); + _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) ); -// File:src/objects/Skeleton.js + if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) { -/** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author michael guerrero / http://realitymeltdown.com - * @author ikerr / http://verold.com - */ + console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture ); -THREE.Skeleton = function ( bones, boneInverses, useVertexTexture ) { + } - this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true; + } - this.identityMatrix = new THREE.Matrix4(); + extension = extensions.get( 'EXT_texture_filter_anisotropic' ); - // copy the bone array + if ( extension ) { - bones = bones || []; + 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; - this.bones = bones.slice( 0 ); + if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) { - // create a bone texture or an array of floats + _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) ); + properties.get( texture ).__currentAnisotropy = texture.anisotropy; - if ( this.useVertexTexture ) { + } - // layout (1 matrix = 4 pixels) - // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4) - // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8) - // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16) - // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32) - // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64) + } - - var size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix - size = THREE.Math.nextPowerOfTwo( Math.ceil( size ) ); - size = Math.max( size, 4 ); + } - this.boneTextureWidth = size; - this.boneTextureHeight = size; + function uploadTexture( textureProperties, texture, slot ) { - this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel - this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType ); + if ( textureProperties.__webglInit === undefined ) { - } else { + textureProperties.__webglInit = true; - this.boneMatrices = new Float32Array( 16 * this.bones.length ); + texture.addEventListener( 'dispose', onTextureDispose ); - } + textureProperties.__webglTexture = _gl.createTexture(); - // use the supplied bone inverses or calculate the inverses + _infoMemory.textures ++; - if ( boneInverses === undefined ) { + } - this.calculateInverses(); + state.activeTexture( _gl.TEXTURE0 + slot ); + state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture ); - } else { + _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 ( this.bones.length === boneInverses.length ) { + var image = clampToMaxSize( texture.image, capabilities.maxTextureSize ); - this.boneInverses = boneInverses.slice( 0 ); + if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( image ) === false ) { - } else { + image = makePowerOfTwo( image ); - console.warn( 'THREE.Skeleton bonInverses is the wrong length.' ); + } - this.boneInverses = []; + var isPowerOfTwoImage = isPowerOfTwo( image ), + glFormat = paramThreeToGL( texture.format ), + glType = paramThreeToGL( texture.type ); - for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { + setTextureParameters( _gl.TEXTURE_2D, texture, isPowerOfTwoImage ); - this.boneInverses.push( new THREE.Matrix4() ); + var mipmap, mipmaps = texture.mipmaps; - } + if ( (texture && texture.isDepthTexture) ) { - } + // populate depth texture with dummy data - } + var internalFormat = _gl.DEPTH_COMPONENT; -}; + if ( texture.type === FloatType ) { -THREE.Skeleton.prototype.calculateInverses = function () { + if ( !_isWebGL2 ) throw new Error('Float Depth Texture only supported in WebGL2.0'); + internalFormat = _gl.DEPTH_COMPONENT32F; - this.boneInverses = []; + } else if ( _isWebGL2 ) { - for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { + // WebGL 2.0 requires signed internalformat for glTexImage2D + internalFormat = _gl.DEPTH_COMPONENT16; - var inverse = new THREE.Matrix4(); + } - if ( this.bones[ b ] ) { + // Depth stencil textures need the DEPTH_STENCIL internal format + // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) + if ( texture.format === DepthStencilFormat ) { - inverse.getInverse( this.bones[ b ].matrixWorld ); + internalFormat = _gl.DEPTH_STENCIL; - } + } - this.boneInverses.push( inverse ); + 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 -THREE.Skeleton.prototype.pose = function () { + if ( mipmaps.length > 0 && isPowerOfTwoImage ) { - var bone; + for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { - // recover the bind-time world matrices + mipmap = mipmaps[ i ]; + state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); - for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { + } - bone = this.bones[ b ]; + texture.generateMipmaps = false; - if ( bone ) { + } else { - bone.matrixWorld.getInverse( this.boneInverses[ b ] ); + state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data ); - } + } - } + } else if ( (texture && texture.isCompressedTexture) ) { - // compute the local matrices, positions, rotations and scales + for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { - for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { + mipmap = mipmaps[ i ]; - bone = this.bones[ b ]; + if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) { - if ( bone ) { + if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) { - if ( bone.parent ) { + state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data ); - bone.matrix.getInverse( bone.parent.matrixWorld ); - bone.matrix.multiply( bone.matrixWorld ); + } else { - } else { + console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" ); - bone.matrix.copy( bone.matrixWorld ); + } - } + } else { - bone.matrix.decompose( bone.position, bone.quaternion, bone.scale ); + state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); - } + } - } + } -}; + } else { -THREE.Skeleton.prototype.update = ( function () { + // regular Texture (image, video, canvas) - var offsetMatrix = new THREE.Matrix4(); + // 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 function update() { + if ( mipmaps.length > 0 && isPowerOfTwoImage ) { - // flatten bone matrices to array + for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { - for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) { + mipmap = mipmaps[ i ]; + state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap ); - // compute the offset between the current and the original transform + } - var matrix = this.bones[ b ] ? this.bones[ b ].matrixWorld : this.identityMatrix; + texture.generateMipmaps = false; - offsetMatrix.multiplyMatrices( matrix, this.boneInverses[ b ] ); - offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 ); + } else { - } + state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, image ); - if ( this.useVertexTexture ) { + } - this.boneTexture.needsUpdate = true; + } - } + if ( texture.generateMipmaps && isPowerOfTwoImage ) _gl.generateMipmap( _gl.TEXTURE_2D ); - }; + textureProperties.__version = texture.version; -} )(); + if ( texture.onUpdate ) texture.onUpdate( texture ); -THREE.Skeleton.prototype.clone = function () { + } - return new THREE.Skeleton( this.bones, this.boneInverses, this.useVertexTexture ); + // Render targets -}; + // Setup storage for target texture and bind it to correct framebuffer + function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) { -// File:src/objects/SkinnedMesh.js + 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 ); -/** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author ikerr / http://verold.com - */ + } -THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) { + // Setup storage for internal depth/stencil buffers and bind to correct framebuffer + function setupRenderBufferStorage( renderbuffer, renderTarget ) { - THREE.Mesh.call( this, geometry, material ); + _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer ); - this.type = 'SkinnedMesh'; + if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) { - this.bindMode = "attached"; - this.bindMatrix = new THREE.Matrix4(); - this.bindMatrixInverse = new THREE.Matrix4(); + _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height ); + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); - // init bones + } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) { - // TODO: remove bone creation as there is no reason (other than - // convenience) for THREE.SkinnedMesh to do this. + _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height ); + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); - var bones = []; + } else { - if ( this.geometry && this.geometry.bones !== undefined ) { + // FIXME: We don't support !depth !stencil + _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height ); - var bone, gbone; + } - for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) { + _gl.bindRenderbuffer( _gl.RENDERBUFFER, null ); - gbone = this.geometry.bones[ b ]; + } - bone = new THREE.Bone( this ); - bones.push( bone ); + // Setup resources for a Depth Texture for a FBO (needs an extension) + function setupDepthTexture( framebuffer, renderTarget ) { - bone.name = gbone.name; - bone.position.fromArray( gbone.pos ); - bone.quaternion.fromArray( gbone.rotq ); - if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl ); + var isCube = ( (renderTarget && renderTarget.isWebGLRenderTargetCube) ); + if ( isCube ) throw new Error('Depth Texture with cube render targets is not supported!'); - } + _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); - for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) { + if ( !( (renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture) ) ) { - gbone = this.geometry.bones[ b ]; + throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture'); - if ( gbone.parent !== - 1 ) { + } - bones[ gbone.parent ].add( bones[ b ] ); + // 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; + } - } else { + setTexture2D( renderTarget.depthTexture, 0 ); - this.add( bones[ b ] ); + var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture; - } + if ( renderTarget.depthTexture.format === DepthFormat ) { - } + _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 ); - } + } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) { - this.normalizeSkinWeights(); + _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 ); - this.updateMatrixWorld( true ); - this.bind( new THREE.Skeleton( bones, undefined, useVertexTexture ), this.matrixWorld ); + } else { -}; + throw new Error('Unknown depthTexture format') + } -THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype ); -THREE.SkinnedMesh.prototype.constructor = THREE.SkinnedMesh; + } -THREE.SkinnedMesh.prototype.bind = function( skeleton, bindMatrix ) { + // Setup GL resources for a non-texture depth buffer + function setupDepthRenderbuffer( renderTarget ) { - this.skeleton = skeleton; + var renderTargetProperties = properties.get( renderTarget ); - if ( bindMatrix === undefined ) { + var isCube = ( (renderTarget && renderTarget.isWebGLRenderTargetCube) ); - this.updateMatrixWorld( true ); - - this.skeleton.calculateInverses(); + if ( renderTarget.depthTexture ) { - bindMatrix = this.matrixWorld; + if ( isCube ) throw new Error('target.depthTexture not supported in Cube render targets'); - } + setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget ); - this.bindMatrix.copy( bindMatrix ); - this.bindMatrixInverse.getInverse( bindMatrix ); + } else { -}; + if ( isCube ) { -THREE.SkinnedMesh.prototype.pose = function () { + renderTargetProperties.__webglDepthbuffer = []; - this.skeleton.pose(); + for ( var i = 0; i < 6; i ++ ) { -}; + _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] ); + renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer(); + setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget ); -THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () { + } - if ( this.geometry instanceof THREE.Geometry ) { + } else { - for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) { + _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer ); + renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer(); + setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget ); - var sw = this.geometry.skinWeights[ i ]; + } - var scale = 1.0 / sw.lengthManhattan(); + } - if ( scale !== Infinity ) { + _gl.bindFramebuffer( _gl.FRAMEBUFFER, null ); - sw.multiplyScalar( scale ); + } - } else { + // Set up GL resources for the render target + function setupRenderTarget( renderTarget ) { - sw.set( 1 ); // this will be normalized by the shader anyway + var renderTargetProperties = properties.get( renderTarget ); + var textureProperties = properties.get( renderTarget.texture ); - } + renderTarget.addEventListener( 'dispose', onRenderTargetDispose ); - } + textureProperties.__webglTexture = _gl.createTexture(); - } else { + _infoMemory.textures ++; - // skinning weights assumed to be normalized for THREE.BufferGeometry + var isCube = ( (renderTarget && renderTarget.isWebGLRenderTargetCube) ); + var isTargetPowerOfTwo = isPowerOfTwo( renderTarget ); - } + // Setup framebuffer -}; + if ( isCube ) { -THREE.SkinnedMesh.prototype.updateMatrixWorld = function( force ) { + renderTargetProperties.__webglFramebuffer = []; - THREE.Mesh.prototype.updateMatrixWorld.call( this, true ); + for ( var i = 0; i < 6; i ++ ) { - if ( this.bindMode === "attached" ) { + renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer(); - this.bindMatrixInverse.getInverse( this.matrixWorld ); + } - } else if ( this.bindMode === "detached" ) { + } else { - this.bindMatrixInverse.getInverse( this.bindMatrix ); + renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer(); - } else { + } - console.warn( 'THREE.SkinnedMesh unrecognized bindMode: ' + this.bindMode ); + // Setup color buffer - } + if ( isCube ) { -}; + state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture ); + setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo ); -THREE.SkinnedMesh.prototype.clone = function() { + for ( var i = 0; i < 6; i ++ ) { - return new this.constructor( this.geometry, this.material, this.useVertexTexture ).copy( this ); + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i ); -}; + } -// File:src/objects/MorphAnimMesh.js + if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP ); + state.bindTexture( _gl.TEXTURE_CUBE_MAP, null ); -/** - * @author alteredq / http://alteredqualia.com/ - */ + } else { -THREE.MorphAnimMesh = function ( geometry, material ) { + state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture ); + setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo ); + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D ); - THREE.Mesh.call( this, geometry, material ); + if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D ); + state.bindTexture( _gl.TEXTURE_2D, null ); - this.type = 'MorphAnimMesh'; + } - // API + // Setup depth and stencil buffers - this.duration = 1000; // milliseconds - this.mirroredLoop = false; - this.time = 0; + if ( renderTarget.depthBuffer ) { - // internals + setupDepthRenderbuffer( renderTarget ); - this.lastKeyframe = 0; - this.currentKeyframe = 0; + } - this.direction = 1; - this.directionBackwards = false; + } - this.setFrameRange( 0, geometry.morphTargets.length - 1 ); + function updateRenderTargetMipmap( renderTarget ) { -}; + var texture = renderTarget.texture; -THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype ); -THREE.MorphAnimMesh.prototype.constructor = THREE.MorphAnimMesh; + if ( texture.generateMipmaps && isPowerOfTwo( renderTarget ) && + texture.minFilter !== NearestFilter && + texture.minFilter !== LinearFilter ) { -THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) { + var target = (renderTarget && renderTarget.isWebGLRenderTargetCube) ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D; + var webglTexture = properties.get( texture ).__webglTexture; - this.startKeyframe = start; - this.endKeyframe = end; + state.bindTexture( target, webglTexture ); + _gl.generateMipmap( target ); + state.bindTexture( target, null ); - this.length = this.endKeyframe - this.startKeyframe + 1; + } -}; + } -THREE.MorphAnimMesh.prototype.setDirectionForward = function () { + this.setTexture2D = setTexture2D; + this.setTextureCube = setTextureCube; + this.setTextureCubeDynamic = setTextureCubeDynamic; + this.setupRenderTarget = setupRenderTarget; + this.updateRenderTargetMipmap = updateRenderTargetMipmap; - this.direction = 1; - this.directionBackwards = false; + } -}; + /** + * @author fordacious / fordacious.github.io + */ -THREE.MorphAnimMesh.prototype.setDirectionBackward = function () { + function WebGLProperties() { - this.direction = - 1; - this.directionBackwards = true; + var properties = {}; -}; + return { -THREE.MorphAnimMesh.prototype.parseAnimations = function () { + get: function ( object ) { - var geometry = this.geometry; + var uuid = object.uuid; + var map = properties[ uuid ]; - if ( ! geometry.animations ) geometry.animations = {}; + if ( map === undefined ) { - var firstAnimation, animations = geometry.animations; + map = {}; + properties[ uuid ] = map; - var pattern = /([a-z]+)_?(\d+)/; + } - for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) { + return map; - var morph = geometry.morphTargets[ i ]; - var parts = morph.name.match( pattern ); + }, - if ( parts && parts.length > 1 ) { + delete: function ( object ) { - var label = parts[ 1 ]; + delete properties[ object.uuid ]; - if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: - Infinity }; + }, - var animation = animations[ label ]; + clear: function () { - if ( i < animation.start ) animation.start = i; - if ( i > animation.end ) animation.end = i; + properties = {}; - if ( ! firstAnimation ) firstAnimation = label; + } - } + }; - } + } - geometry.firstAnimation = firstAnimation; + function WebGLState( gl, extensions, paramThreeToGL ) { -}; + function ColorBuffer() { -THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) { + var locked = false; - if ( ! this.geometry.animations ) this.geometry.animations = {}; + var color = new Vector4(); + var currentColorMask = null; + var currentColorClear = new Vector4(); - this.geometry.animations[ label ] = { start: start, end: end }; + return { -}; + setMask: function ( colorMask ) { -THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) { + if ( currentColorMask !== colorMask && ! locked ) { - var animation = this.geometry.animations[ label ]; + gl.colorMask( colorMask, colorMask, colorMask, colorMask ); + currentColorMask = colorMask; - if ( animation ) { + } - this.setFrameRange( animation.start, animation.end ); - this.duration = 1000 * ( ( animation.end - animation.start ) / fps ); - this.time = 0; + }, - } else { + setLocked: function ( lock ) { - console.warn( 'THREE.MorphAnimMesh: animation[' + label + '] undefined in .playAnimation()' ); + locked = lock; - } + }, -}; + setClear: function ( r, g, b, a ) { -THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) { + color.set( r, g, b, a ); - var frameTime = this.duration / this.length; + if ( currentColorClear.equals( color ) === false ) { - this.time += this.direction * delta; + gl.clearColor( r, g, b, a ); + currentColorClear.copy( color ); - if ( this.mirroredLoop ) { + } - if ( this.time > this.duration || this.time < 0 ) { + }, - this.direction *= - 1; + reset: function () { - if ( this.time > this.duration ) { + locked = false; - this.time = this.duration; - this.directionBackwards = true; + currentColorMask = null; + currentColorClear.set( 0, 0, 0, 1 ); - } + } - if ( this.time < 0 ) { + }; - this.time = 0; - this.directionBackwards = false; + } - } + function DepthBuffer() { - } + var locked = false; - } else { + var currentDepthMask = null; + var currentDepthFunc = null; + var currentDepthClear = null; - this.time = this.time % this.duration; + return { - if ( this.time < 0 ) this.time += this.duration; + setTest: function ( depthTest ) { - } + if ( depthTest ) { - var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 ); + enable( gl.DEPTH_TEST ); - var influences = this.morphTargetInfluences; + } else { - if ( keyframe !== this.currentKeyframe ) { + disable( gl.DEPTH_TEST ); - influences[ this.lastKeyframe ] = 0; - influences[ this.currentKeyframe ] = 1; - influences[ keyframe ] = 0; + } - this.lastKeyframe = this.currentKeyframe; - this.currentKeyframe = keyframe; + }, - } + setMask: function ( depthMask ) { - var mix = ( this.time % frameTime ) / frameTime; + if ( currentDepthMask !== depthMask && ! locked ) { - if ( this.directionBackwards ) { + gl.depthMask( depthMask ); + currentDepthMask = depthMask; - mix = 1 - mix; + } - } + }, - influences[ this.currentKeyframe ] = mix; - influences[ this.lastKeyframe ] = 1 - mix; + setFunc: function ( depthFunc ) { -}; + if ( currentDepthFunc !== depthFunc ) { -THREE.MorphAnimMesh.prototype.interpolateTargets = function ( a, b, t ) { + if ( depthFunc ) { - var influences = this.morphTargetInfluences; + switch ( depthFunc ) { - for ( var i = 0, l = influences.length; i < l; i ++ ) { + case NeverDepth: - influences[ i ] = 0; + gl.depthFunc( gl.NEVER ); + break; - } + case AlwaysDepth: - if ( a > - 1 ) influences[ a ] = 1 - t; - if ( b > - 1 ) influences[ b ] = t; + gl.depthFunc( gl.ALWAYS ); + break; -}; + case LessDepth: -THREE.MorphAnimMesh.prototype.copy = function ( source ) { + gl.depthFunc( gl.LESS ); + break; - THREE.Mesh.prototype.copy.call( this, source ); + case LessEqualDepth: - this.duration = source.duration; - this.mirroredLoop = source.mirroredLoop; - this.time = source.time; + gl.depthFunc( gl.LEQUAL ); + break; - this.lastKeyframe = source.lastKeyframe; - this.currentKeyframe = source.currentKeyframe; + case EqualDepth: - this.direction = source.direction; - this.directionBackwards = source.directionBackwards; + gl.depthFunc( gl.EQUAL ); + break; - return this; + case GreaterEqualDepth: -}; + gl.depthFunc( gl.GEQUAL ); + break; -// File:src/objects/LOD.js + case GreaterDepth: -/** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - */ + gl.depthFunc( gl.GREATER ); + break; -THREE.LOD = function () { + case NotEqualDepth: - THREE.Object3D.call( this ); + gl.depthFunc( gl.NOTEQUAL ); + break; - this.type = 'LOD'; + default: - Object.defineProperties( this, { - levels: { - enumerable: true, - value: [] - }, - objects: { - get: function () { + gl.depthFunc( gl.LEQUAL ); - console.warn( 'THREE.LOD: .objects has been renamed to .levels.' ); - return this.levels; + } - } - } - } ); + } else { -}; + gl.depthFunc( gl.LEQUAL ); + } -THREE.LOD.prototype = Object.create( THREE.Object3D.prototype ); -THREE.LOD.prototype.constructor = THREE.LOD; + currentDepthFunc = depthFunc; -THREE.LOD.prototype.addLevel = function ( object, distance ) { + } - if ( distance === undefined ) distance = 0; + }, - distance = Math.abs( distance ); + setLocked: function ( lock ) { - var levels = this.levels; + locked = lock; - for ( var l = 0; l < levels.length; l ++ ) { + }, - if ( distance < levels[ l ].distance ) { + setClear: function ( depth ) { - break; + if ( currentDepthClear !== depth ) { - } + gl.clearDepth( depth ); + currentDepthClear = depth; - } + } - levels.splice( l, 0, { distance: distance, object: object } ); + }, - this.add( object ); + reset: function () { -}; + locked = false; -THREE.LOD.prototype.getObjectForDistance = function ( distance ) { + currentDepthMask = null; + currentDepthFunc = null; + currentDepthClear = null; - var levels = this.levels; + } - for ( var i = 1, l = levels.length; i < l; i ++ ) { + }; - if ( distance < levels[ i ].distance ) { + } - break; + function StencilBuffer() { - } + 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; - return levels[ i - 1 ].object; + return { -}; + setTest: function ( stencilTest ) { -THREE.LOD.prototype.raycast = ( function () { + if ( stencilTest ) { - var matrixPosition = new THREE.Vector3(); + enable( gl.STENCIL_TEST ); - return function raycast( raycaster, intersects ) { + } else { - matrixPosition.setFromMatrixPosition( this.matrixWorld ); + disable( gl.STENCIL_TEST ); - var distance = raycaster.ray.origin.distanceTo( matrixPosition ); + } - this.getObjectForDistance( distance ).raycast( raycaster, intersects ); + }, - }; + setMask: function ( stencilMask ) { -}() ); + if ( currentStencilMask !== stencilMask && ! locked ) { -THREE.LOD.prototype.update = function () { + gl.stencilMask( stencilMask ); + currentStencilMask = stencilMask; - var v1 = new THREE.Vector3(); - var v2 = new THREE.Vector3(); + } - return function update( camera ) { + }, - var levels = this.levels; + setFunc: function ( stencilFunc, stencilRef, stencilMask ) { - if ( levels.length > 1 ) { + if ( currentStencilFunc !== stencilFunc || + currentStencilRef !== stencilRef || + currentStencilFuncMask !== stencilMask ) { - v1.setFromMatrixPosition( camera.matrixWorld ); - v2.setFromMatrixPosition( this.matrixWorld ); + gl.stencilFunc( stencilFunc, stencilRef, stencilMask ); - var distance = v1.distanceTo( v2 ); + currentStencilFunc = stencilFunc; + currentStencilRef = stencilRef; + currentStencilFuncMask = stencilMask; - levels[ 0 ].object.visible = true; + } - for ( var i = 1, l = levels.length; i < l; i ++ ) { + }, - if ( distance >= levels[ i ].distance ) { + setOp: function ( stencilFail, stencilZFail, stencilZPass ) { - levels[ i - 1 ].object.visible = false; - levels[ i ].object.visible = true; + if ( currentStencilFail !== stencilFail || + currentStencilZFail !== stencilZFail || + currentStencilZPass !== stencilZPass ) { - } else { + gl.stencilOp( stencilFail, stencilZFail, stencilZPass ); - break; + currentStencilFail = stencilFail; + currentStencilZFail = stencilZFail; + currentStencilZPass = stencilZPass; - } + } - } + }, - for ( ; i < l; i ++ ) { + setLocked: function ( lock ) { - levels[ i ].object.visible = false; + locked = lock; - } + }, - } + setClear: function ( stencil ) { - }; + if ( currentStencilClear !== stencil ) { -}(); + gl.clearStencil( stencil ); + currentStencilClear = stencil; -THREE.LOD.prototype.copy = function ( source ) { + } - THREE.Object3D.prototype.copy.call( this, source, false ); + }, - var levels = source.levels; + reset: function () { - for ( var i = 0, l = levels.length; i < l; i ++ ) { + locked = false; - var level = levels[ i ]; + currentStencilMask = null; + currentStencilFunc = null; + currentStencilRef = null; + currentStencilFuncMask = null; + currentStencilFail = null; + currentStencilZFail = null; + currentStencilZPass = null; + currentStencilClear = null; - this.addLevel( level.object.clone(), level.distance ); + } - } + }; - return this; + } -}; + // -THREE.LOD.prototype.toJSON = function ( meta ) { + var colorBuffer = new ColorBuffer(); + var depthBuffer = new DepthBuffer(); + var stencilBuffer = new StencilBuffer(); - var data = THREE.Object3D.prototype.toJSON.call( this, meta ); + var maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS ); + var newAttributes = new Uint8Array( maxVertexAttributes ); + var enabledAttributes = new Uint8Array( maxVertexAttributes ); + var attributeDivisors = new Uint8Array( maxVertexAttributes ); - data.object.levels = []; + var capabilities = {}; - var levels = this.levels; + var compressedTextureFormats = null; - for ( var i = 0, l = levels.length; i < l; i ++ ) { + var currentBlending = null; + var currentBlendEquation = null; + var currentBlendSrc = null; + var currentBlendDst = null; + var currentBlendEquationAlpha = null; + var currentBlendSrcAlpha = null; + var currentBlendDstAlpha = null; + var currentPremultipledAlpha = false; - var level = levels[ i ]; + var currentFlipSided = null; + var currentCullFace = null; - data.object.levels.push( { - object: level.object.uuid, - distance: level.distance - } ); + var currentLineWidth = null; - } + var currentPolygonOffsetFactor = null; + var currentPolygonOffsetUnits = null; - return data; + var currentScissorTest = null; -}; + var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS ); -// File:src/objects/Sprite.js + var currentTextureSlot = null; + var currentBoundTextures = {}; -/** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - */ + var currentScissor = new Vector4(); + var currentViewport = new Vector4(); -THREE.Sprite = ( function () { + function createTexture( type, target, count ) { - var indices = new Uint16Array( [ 0, 1, 2, 0, 2, 3 ] ); - var vertices = new Float32Array( [ - 0.5, - 0.5, 0, 0.5, - 0.5, 0, 0.5, 0.5, 0, - 0.5, 0.5, 0 ] ); - var uvs = new Float32Array( [ 0, 0, 1, 0, 1, 1, 0, 1 ] ); + var data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4. + var texture = gl.createTexture(); - var geometry = new THREE.BufferGeometry(); - geometry.setIndex( new THREE.BufferAttribute( indices, 1 ) ); - geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) ); - geometry.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) ); + gl.bindTexture( type, texture ); + gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST ); + gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST ); - return function Sprite( material ) { + for ( var i = 0; i < count; i ++ ) { - THREE.Object3D.call( this ); + gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data ); - this.type = 'Sprite'; + } - this.geometry = geometry; - this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial(); + return texture; - }; + } -} )(); + 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 ); -THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype ); -THREE.Sprite.prototype.constructor = THREE.Sprite; + // -THREE.Sprite.prototype.raycast = ( function () { + function init() { - var matrixPosition = new THREE.Vector3(); + clearColor( 0, 0, 0, 1 ); + clearDepth( 1 ); + clearStencil( 0 ); - return function raycast( raycaster, intersects ) { + enable( gl.DEPTH_TEST ); + setDepthFunc( LessEqualDepth ); - matrixPosition.setFromMatrixPosition( this.matrixWorld ); + setFlipSided( false ); + setCullFace( CullFaceBack ); + enable( gl.CULL_FACE ); - var distanceSq = raycaster.ray.distanceSqToPoint( matrixPosition ); - var guessSizeSq = this.scale.x * this.scale.y; + enable( gl.BLEND ); + setBlending( NormalBlending ); - if ( distanceSq > guessSizeSq ) { + } - return; + function initAttributes() { - } + for ( var i = 0, l = newAttributes.length; i < l; i ++ ) { - intersects.push( { + newAttributes[ i ] = 0; - distance: Math.sqrt( distanceSq ), - point: this.position, - face: null, - object: this + } - } ); + } - }; + function enableAttribute( attribute ) { -}() ); + newAttributes[ attribute ] = 1; -THREE.Sprite.prototype.clone = function () { + if ( enabledAttributes[ attribute ] === 0 ) { - return new this.constructor( this.material ).copy( this ); + gl.enableVertexAttribArray( attribute ); + enabledAttributes[ attribute ] = 1; -}; + } -THREE.Sprite.prototype.toJSON = function ( meta ) { + if ( attributeDivisors[ attribute ] !== 0 ) { - var data = THREE.Object3D.prototype.toJSON.call( this, meta ); + var extension = extensions.get( 'ANGLE_instanced_arrays' ); - // only serialize if not in meta materials cache - if ( meta.materials[ this.material.uuid ] === undefined ) { + extension.vertexAttribDivisorANGLE( attribute, 0 ); + attributeDivisors[ attribute ] = 0; - meta.materials[ this.material.uuid ] = this.material.toJSON(); + } - } + } - data.object.material = this.material.uuid; + function enableAttributeAndDivisor( attribute, meshPerAttribute, extension ) { - return data; + newAttributes[ attribute ] = 1; -}; + if ( enabledAttributes[ attribute ] === 0 ) { -// Backwards compatibility + gl.enableVertexAttribArray( attribute ); + enabledAttributes[ attribute ] = 1; -THREE.Particle = THREE.Sprite; + } -// File:src/objects/LensFlare.js + if ( attributeDivisors[ attribute ] !== meshPerAttribute ) { -/** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - */ + extension.vertexAttribDivisorANGLE( attribute, meshPerAttribute ); + attributeDivisors[ attribute ] = meshPerAttribute; -THREE.LensFlare = function ( texture, size, distance, blending, color ) { + } - THREE.Object3D.call( this ); + } - this.lensFlares = []; + function disableUnusedAttributes() { - this.positionScreen = new THREE.Vector3(); - this.customUpdateCallback = undefined; + for ( var i = 0, l = enabledAttributes.length; i !== l; ++ i ) { - if ( texture !== undefined ) { + if ( enabledAttributes[ i ] !== newAttributes[ i ] ) { - this.add( texture, size, distance, blending, color ); + gl.disableVertexAttribArray( i ); + enabledAttributes[ i ] = 0; - } + } -}; + } -THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype ); -THREE.LensFlare.prototype.constructor = THREE.LensFlare; + } + function enable( id ) { -/* - * Add: adds another flare - */ + if ( capabilities[ id ] !== true ) { -THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) { + gl.enable( id ); + capabilities[ id ] = true; - if ( size === undefined ) size = - 1; - if ( distance === undefined ) distance = 0; - if ( opacity === undefined ) opacity = 1; - if ( color === undefined ) color = new THREE.Color( 0xffffff ); - if ( blending === undefined ) blending = THREE.NormalBlending; + } - distance = Math.min( distance, Math.max( 0, distance ) ); + } - 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 - } ); + function disable( id ) { -}; + if ( capabilities[ id ] !== false ) { -/* - * 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. - */ + gl.disable( id ); + capabilities[ id ] = false; -THREE.LensFlare.prototype.updateLensFlares = function () { + } - var f, fl = this.lensFlares.length; - var flare; - var vecX = - this.positionScreen.x * 2; - var vecY = - this.positionScreen.y * 2; + } - for ( f = 0; f < fl; f ++ ) { + function getCompressedTextureFormats() { - flare = this.lensFlares[ f ]; + if ( compressedTextureFormats === null ) { - flare.x = this.positionScreen.x + vecX * flare.distance; - flare.y = this.positionScreen.y + vecY * flare.distance; + compressedTextureFormats = []; - flare.wantedRotation = flare.x * Math.PI * 0.25; - flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25; + 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 ++ ) { -THREE.LensFlare.prototype.copy = function ( source ) { + compressedTextureFormats.push( formats[ i ] ); - THREE.Object3D.prototype.copy.call( this, source ); + } - this.positionScreen.copy( source.positionScreen ); - this.customUpdateCallback = source.customUpdateCallback; + } - for ( var i = 0, l = source.lensFlares.length; i < l; i ++ ) { + } - this.lensFlares.push( source.lensFlares[ i ] ); + return compressedTextureFormats; - } + } - return this; + function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) { -}; + if ( blending !== NoBlending ) { -// File:src/scenes/Scene.js + enable( gl.BLEND ); -/** - * @author mrdoob / http://mrdoob.com/ - */ + } else { -THREE.Scene = function () { + disable( gl.BLEND ); + currentBlending = blending; // no blending, that is + return; - THREE.Object3D.call( this ); + } - this.type = 'Scene'; + if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) { - this.fog = null; - this.overrideMaterial = null; + if ( blending === AdditiveBlending ) { - this.autoUpdate = true; // checked by the renderer + if ( premultipliedAlpha ) { -}; + gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); + gl.blendFuncSeparate( gl.ONE, gl.ONE, gl.ONE, gl.ONE ); -THREE.Scene.prototype = Object.create( THREE.Object3D.prototype ); -THREE.Scene.prototype.constructor = THREE.Scene; + } else { -THREE.Scene.prototype.copy = function ( source ) { + gl.blendEquation( gl.FUNC_ADD ); + gl.blendFunc( gl.SRC_ALPHA, gl.ONE ); - THREE.Object3D.prototype.copy.call( this, source ); + } - if ( source.fog !== null ) this.fog = source.fog.clone(); - if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone(); + } else if ( blending === SubtractiveBlending ) { - this.autoUpdate = source.autoUpdate; - this.matrixAutoUpdate = source.matrixAutoUpdate; + if ( premultipliedAlpha ) { - return this; + gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); + gl.blendFuncSeparate( gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA ); -}; + } else { -// File:src/scenes/Fog.js + gl.blendEquation( gl.FUNC_ADD ); + gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR ); -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + } -THREE.Fog = function ( color, near, far ) { + } else if ( blending === MultiplyBlending ) { - this.name = ''; + if ( premultipliedAlpha ) { - this.color = new THREE.Color( color ); + gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); + gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA ); - this.near = ( near !== undefined ) ? near : 1; - this.far = ( far !== undefined ) ? far : 1000; + } else { -}; + gl.blendEquation( gl.FUNC_ADD ); + gl.blendFunc( gl.ZERO, gl.SRC_COLOR ); -THREE.Fog.prototype.clone = function () { + } - return new THREE.Fog( this.color.getHex(), this.near, this.far ); + } else { -}; + if ( premultipliedAlpha ) { -// File:src/scenes/FogExp2.js + gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); + gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA ); -/** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + } else { -THREE.FogExp2 = function ( color, density ) { + 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.name = ''; + } - this.color = new THREE.Color( color ); - this.density = ( density !== undefined ) ? density : 0.00025; + } -}; + currentBlending = blending; + currentPremultipledAlpha = premultipliedAlpha; -THREE.FogExp2.prototype.clone = function () { + } - return new THREE.FogExp2( this.color.getHex(), this.density ); + if ( blending === CustomBlending ) { -}; + blendEquationAlpha = blendEquationAlpha || blendEquation; + blendSrcAlpha = blendSrcAlpha || blendSrc; + blendDstAlpha = blendDstAlpha || blendDst; -// File:src/renderers/shaders/ShaderChunk.js + if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) { -THREE.ShaderChunk = {}; + gl.blendEquationSeparate( paramThreeToGL( blendEquation ), paramThreeToGL( blendEquationAlpha ) ); -// File:src/renderers/shaders/ShaderChunk/alphamap_fragment.glsl + currentBlendEquation = blendEquation; + currentBlendEquationAlpha = blendEquationAlpha; -THREE.ShaderChunk[ 'alphamap_fragment'] = "#ifdef USE_ALPHAMAP\n\n diffuseColor.a *= texture2D( alphaMap, vUv ).g;\n\n#endif\n"; + } -// File:src/renderers/shaders/ShaderChunk/alphamap_pars_fragment.glsl + if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) { -THREE.ShaderChunk[ 'alphamap_pars_fragment'] = "#ifdef USE_ALPHAMAP\n\n uniform sampler2D alphaMap;\n\n#endif\n"; + gl.blendFuncSeparate( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ), paramThreeToGL( blendSrcAlpha ), paramThreeToGL( blendDstAlpha ) ); -// File:src/renderers/shaders/ShaderChunk/alphatest_fragment.glsl + currentBlendSrc = blendSrc; + currentBlendDst = blendDst; + currentBlendSrcAlpha = blendSrcAlpha; + currentBlendDstAlpha = blendDstAlpha; -THREE.ShaderChunk[ 'alphatest_fragment'] = "#ifdef ALPHATEST\n\n if ( diffuseColor.a < ALPHATEST ) discard;\n\n#endif\n"; + } -// File:src/renderers/shaders/ShaderChunk/aomap_fragment.glsl + } else { -THREE.ShaderChunk[ 'aomap_fragment'] = "#ifdef USE_AOMAP\n\n totalAmbientLight *= ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\n#endif\n"; + currentBlendEquation = null; + currentBlendSrc = null; + currentBlendDst = null; + currentBlendEquationAlpha = null; + currentBlendSrcAlpha = null; + currentBlendDstAlpha = null; -// File:src/renderers/shaders/ShaderChunk/aomap_pars_fragment.glsl + } -THREE.ShaderChunk[ 'aomap_pars_fragment'] = "#ifdef USE_AOMAP\n\n uniform sampler2D aoMap;\n uniform float aoMapIntensity;\n\n#endif"; + } -// File:src/renderers/shaders/ShaderChunk/begin_vertex.glsl + // TODO Deprecate -THREE.ShaderChunk[ 'begin_vertex'] = "\nvec3 transformed = vec3( position );\n"; + function setColorWrite( colorWrite ) { -// File:src/renderers/shaders/ShaderChunk/beginnormal_vertex.glsl + colorBuffer.setMask( colorWrite ); -THREE.ShaderChunk[ 'beginnormal_vertex'] = "\nvec3 objectNormal = vec3( normal );\n"; + } -// File:src/renderers/shaders/ShaderChunk/bumpmap_pars_fragment.glsl + function setDepthTest( depthTest ) { -THREE.ShaderChunk[ 'bumpmap_pars_fragment'] = "#ifdef USE_BUMPMAP\n\n uniform sampler2D bumpMap;\n uniform float bumpScale;\n\n // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen\n // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html\n\n // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)\n\n vec2 dHdxy_fwd() {\n\n vec2 dSTdx = dFdx( vUv );\n vec2 dSTdy = dFdy( vUv );\n\n float Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\n return vec2( dBx, dBy );\n\n }\n\n vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\n vec3 vSigmaX = dFdx( surf_pos );\n vec3 vSigmaY = dFdy( surf_pos );\n vec3 vN = surf_norm; // normalized\n\n vec3 R1 = cross( vSigmaY, vN );\n vec3 R2 = cross( vN, vSigmaX );\n\n float fDet = dot( vSigmaX, R1 );\n\n vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n return normalize( abs( fDet ) * surf_norm - vGrad );\n\n }\n\n#endif\n"; + depthBuffer.setTest( depthTest ); -// File:src/renderers/shaders/ShaderChunk/color_fragment.glsl + } -THREE.ShaderChunk[ 'color_fragment'] = "#ifdef USE_COLOR\n\n diffuseColor.rgb *= vColor;\n\n#endif"; + function setDepthWrite( depthWrite ) { -// File:src/renderers/shaders/ShaderChunk/color_pars_fragment.glsl + depthBuffer.setMask( depthWrite ); -THREE.ShaderChunk[ 'color_pars_fragment'] = "#ifdef USE_COLOR\n\n varying vec3 vColor;\n\n#endif\n"; + } -// File:src/renderers/shaders/ShaderChunk/color_pars_vertex.glsl + function setDepthFunc( depthFunc ) { -THREE.ShaderChunk[ 'color_pars_vertex'] = "#ifdef USE_COLOR\n\n varying vec3 vColor;\n\n#endif"; + depthBuffer.setFunc( depthFunc ); -// File:src/renderers/shaders/ShaderChunk/color_vertex.glsl + } -THREE.ShaderChunk[ 'color_vertex'] = "#ifdef USE_COLOR\n\n vColor.xyz = color.xyz;\n\n#endif"; + function setStencilTest( stencilTest ) { -// File:src/renderers/shaders/ShaderChunk/common.glsl + stencilBuffer.setTest( stencilTest ); -THREE.ShaderChunk[ 'common'] = "#define PI 3.14159\n#define PI2 6.28318\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define whiteCompliment(a) ( 1.0 - saturate( a ) )\n\nvec3 transformDirection( in vec3 normal, in mat4 matrix ) {\n\n return normalize( ( matrix * vec4( normal, 0.0 ) ).xyz );\n\n}\n\n// http://en.wikibooks.org/wiki/GLSL_Programming/Applying_Matrix_Transformations\nvec3 inverseTransformDirection( in vec3 normal, in mat4 matrix ) {\n\n return normalize( ( vec4( normal, 0.0 ) * matrix ).xyz );\n\n}\n\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\n float distance = dot( planeNormal, point - pointOnPlane );\n\n return - distance * planeNormal + point;\n\n}\n\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\n return sign( dot( point - pointOnPlane, planeNormal ) );\n\n}\n\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\n return lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n\n}\n\nfloat calcLightAttenuation( float lightDistance, float cutoffDistance, float decayExponent ) {\n\n if ( decayExponent > 0.0 ) {\n\n return pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\n }\n\n return 1.0;\n\n}\n\nvec3 F_Schlick( in vec3 specularColor, in float dotLH ) {\n\n // Original approximation by Christophe Schlick '94\n //;float fresnel = pow( 1.0 - dotLH, 5.0 );\n\n // Optimized variant (presented by Epic at SIGGRAPH '13)\n float fresnel = exp2( ( -5.55437 * dotLH - 6.98316 ) * dotLH );\n\n return ( 1.0 - specularColor ) * fresnel + specularColor;\n\n}\n\nfloat G_BlinnPhong_Implicit( /* in float dotNL, in float dotNV */ ) {\n\n // geometry term is (nâ‹…l)(nâ‹…v) / 4(nâ‹…l)(nâ‹…v)\n\n return 0.25;\n\n}\n\nfloat D_BlinnPhong( in float shininess, in float dotNH ) {\n\n // factor of 1/PI in distribution term omitted\n\n return ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n\n}\n\nvec3 BRDF_BlinnPhong( in vec3 specularColor, in float shininess, in vec3 normal, in vec3 lightDir, in vec3 viewDir ) {\n\n vec3 halfDir = normalize( lightDir + viewDir );\n\n //float dotNL = saturate( dot( normal, lightDir ) );\n //float dotNV = saturate( dot( normal, viewDir ) );\n float dotNH = saturate( dot( normal, halfDir ) );\n float dotLH = saturate( dot( lightDir, halfDir ) );\n\n vec3 F = F_Schlick( specularColor, dotLH );\n\n float G = G_BlinnPhong_Implicit( /* dotNL, dotNV */ );\n\n float D = D_BlinnPhong( shininess, dotNH );\n\n return F * G * D;\n\n}\n\nvec3 inputToLinear( in vec3 a ) {\n\n #ifdef GAMMA_INPUT\n\n return pow( a, vec3( float( GAMMA_FACTOR ) ) );\n\n #else\n\n return a;\n\n #endif\n\n}\n\nvec3 linearToOutput( in vec3 a ) {\n\n #ifdef GAMMA_OUTPUT\n\n return pow( a, vec3( 1.0 / float( GAMMA_FACTOR ) ) );\n\n #else\n\n return a;\n\n #endif\n\n}\n"; + } -// File:src/renderers/shaders/ShaderChunk/defaultnormal_vertex.glsl + function setStencilWrite( stencilWrite ) { -THREE.ShaderChunk[ 'defaultnormal_vertex'] = "#ifdef FLIP_SIDED\n\n objectNormal = -objectNormal;\n\n#endif\n\nvec3 transformedNormal = normalMatrix * objectNormal;\n"; + stencilBuffer.setMask( stencilWrite ); -// File:src/renderers/shaders/ShaderChunk/displacementmap_vertex.glsl + } -THREE.ShaderChunk[ 'displacementmap_vertex'] = "#ifdef USE_DISPLACEMENTMAP\n\n transformed += normal * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n\n#endif\n"; + function setStencilFunc( stencilFunc, stencilRef, stencilMask ) { -// File:src/renderers/shaders/ShaderChunk/displacementmap_pars_vertex.glsl + stencilBuffer.setFunc( stencilFunc, stencilRef, stencilMask ); -THREE.ShaderChunk[ 'displacementmap_pars_vertex'] = "#ifdef USE_DISPLACEMENTMAP\n\n uniform sampler2D displacementMap;\n uniform float displacementScale;\n uniform float displacementBias;\n\n#endif\n"; + } -// File:src/renderers/shaders/ShaderChunk/emissivemap_fragment.glsl + function setStencilOp( stencilFail, stencilZFail, stencilZPass ) { -THREE.ShaderChunk[ 'emissivemap_fragment'] = "#ifdef USE_EMISSIVEMAP\n\n vec4 emissiveColor = texture2D( emissiveMap, vUv );\n\n emissiveColor.rgb = inputToLinear( emissiveColor.rgb );\n\n totalEmissiveLight *= emissiveColor.rgb;\n\n#endif\n"; + stencilBuffer.setOp( stencilFail, stencilZFail, stencilZPass ); -// File:src/renderers/shaders/ShaderChunk/emissivemap_pars_fragment.glsl + } -THREE.ShaderChunk[ 'emissivemap_pars_fragment'] = "#ifdef USE_EMISSIVEMAP\n\n uniform sampler2D emissiveMap;\n\n#endif\n"; + // -// File:src/renderers/shaders/ShaderChunk/envmap_fragment.glsl + function setFlipSided( flipSided ) { -THREE.ShaderChunk[ 'envmap_fragment'] = "#ifdef USE_ENVMAP\n\n #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\n vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\n // Transforming Normal Vectors with the Inverse Transformation\n vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\n #ifdef ENVMAP_MODE_REFLECTION\n\n vec3 reflectVec = reflect( cameraToVertex, worldNormal );\n\n #else\n\n vec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n\n #endif\n\n #else\n\n vec3 reflectVec = vReflect;\n\n #endif\n\n #ifdef DOUBLE_SIDED\n float flipNormal = ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n #else\n float flipNormal = 1.0;\n #endif\n\n #ifdef ENVMAP_TYPE_CUBE\n vec4 envColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\n #elif defined( ENVMAP_TYPE_EQUIREC )\n vec2 sampleUV;\n sampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n sampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n vec4 envColor = texture2D( envMap, sampleUV );\n\n #elif defined( ENVMAP_TYPE_SPHERE )\n vec3 reflectView = flipNormal * normalize((viewMatrix * vec4( reflectVec, 0.0 )).xyz + vec3(0.0,0.0,1.0));\n vec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n #endif\n\n envColor.xyz = inputToLinear( envColor.xyz );\n\n #ifdef ENVMAP_BLENDING_MULTIPLY\n\n outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\n #elif defined( ENVMAP_BLENDING_MIX )\n\n outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\n #elif defined( ENVMAP_BLENDING_ADD )\n\n outgoingLight += envColor.xyz * specularStrength * reflectivity;\n\n #endif\n\n#endif\n"; + if ( currentFlipSided !== flipSided ) { -// File:src/renderers/shaders/ShaderChunk/envmap_pars_fragment.glsl + if ( flipSided ) { -THREE.ShaderChunk[ 'envmap_pars_fragment'] = "#ifdef USE_ENVMAP\n\n uniform float reflectivity;\n #ifdef ENVMAP_TYPE_CUBE\n uniform samplerCube envMap;\n #else\n uniform sampler2D envMap;\n #endif\n uniform float flipEnvMap;\n\n #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\n uniform float refractionRatio;\n\n #else\n\n varying vec3 vReflect;\n\n #endif\n\n#endif\n"; + gl.frontFace( gl.CW ); -// File:src/renderers/shaders/ShaderChunk/envmap_pars_vertex.glsl + } else { -THREE.ShaderChunk[ 'envmap_pars_vertex'] = "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP ) && ! defined( PHONG )\n\n varying vec3 vReflect;\n\n uniform float refractionRatio;\n\n#endif\n"; + gl.frontFace( gl.CCW ); -// File:src/renderers/shaders/ShaderChunk/envmap_vertex.glsl + } -THREE.ShaderChunk[ 'envmap_vertex'] = "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP ) && ! defined( PHONG )\n\n vec3 worldNormal = transformDirection( objectNormal, modelMatrix );\n\n vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\n #ifdef ENVMAP_MODE_REFLECTION\n\n vReflect = reflect( cameraToVertex, worldNormal );\n\n #else\n\n vReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\n #endif\n\n#endif\n"; + currentFlipSided = flipSided; -// File:src/renderers/shaders/ShaderChunk/fog_fragment.glsl + } -THREE.ShaderChunk[ 'fog_fragment'] = "#ifdef USE_FOG\n\n #ifdef USE_LOGDEPTHBUF_EXT\n\n float depth = gl_FragDepthEXT / gl_FragCoord.w;\n\n #else\n\n float depth = gl_FragCoord.z / gl_FragCoord.w;\n\n #endif\n\n #ifdef FOG_EXP2\n\n float fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * depth * depth * LOG2 ) );\n\n #else\n\n float fogFactor = smoothstep( fogNear, fogFar, depth );\n\n #endif\n \n outgoingLight = mix( outgoingLight, fogColor, fogFactor );\n\n#endif"; + } -// File:src/renderers/shaders/ShaderChunk/fog_pars_fragment.glsl + function setCullFace( cullFace ) { -THREE.ShaderChunk[ 'fog_pars_fragment'] = "#ifdef USE_FOG\n\n uniform vec3 fogColor;\n\n #ifdef FOG_EXP2\n\n uniform float fogDensity;\n\n #else\n\n uniform float fogNear;\n uniform float fogFar;\n #endif\n\n#endif"; + if ( cullFace !== CullFaceNone ) { -// File:src/renderers/shaders/ShaderChunk/lightmap_fragment.glsl + enable( gl.CULL_FACE ); -THREE.ShaderChunk[ 'lightmap_fragment'] = "#ifdef USE_LIGHTMAP\n\n totalAmbientLight += texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\n#endif\n"; + if ( cullFace !== currentCullFace ) { -// File:src/renderers/shaders/ShaderChunk/lightmap_pars_fragment.glsl + if ( cullFace === CullFaceBack ) { -THREE.ShaderChunk[ 'lightmap_pars_fragment'] = "#ifdef USE_LIGHTMAP\n\n uniform sampler2D lightMap;\n uniform float lightMapIntensity;\n\n#endif"; + gl.cullFace( gl.BACK ); -// File:src/renderers/shaders/ShaderChunk/lights_lambert_pars_vertex.glsl + } else if ( cullFace === CullFaceFront ) { -THREE.ShaderChunk[ 'lights_lambert_pars_vertex'] = "uniform vec3 ambientLightColor;\n\n#if MAX_DIR_LIGHTS > 0\n\n uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];\n uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];\n\n#endif\n\n#if MAX_HEMI_LIGHTS > 0\n\n uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];\n uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];\n uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];\n\n#endif\n\n#if MAX_POINT_LIGHTS > 0\n\n uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];\n uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];\n uniform float pointLightDistance[ MAX_POINT_LIGHTS ];\n uniform float pointLightDecay[ MAX_POINT_LIGHTS ];\n\n#endif\n\n#if MAX_SPOT_LIGHTS > 0\n\n uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];\n uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];\n uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];\n uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];\n uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];\n uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];\n uniform float spotLightDecay[ MAX_SPOT_LIGHTS ];\n\n#endif\n"; + gl.cullFace( gl.FRONT ); -// File:src/renderers/shaders/ShaderChunk/lights_lambert_vertex.glsl + } else { -THREE.ShaderChunk[ 'lights_lambert_vertex'] = "vLightFront = vec3( 0.0 );\n\n#ifdef DOUBLE_SIDED\n\n vLightBack = vec3( 0.0 );\n\n#endif\n\nvec3 normal = normalize( transformedNormal );\n\n#if MAX_POINT_LIGHTS > 0\n\n for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {\n\n vec3 lightColor = pointLightColor[ i ];\n\n vec3 lVector = pointLightPosition[ i ] - mvPosition.xyz;\n vec3 lightDir = normalize( lVector );\n\n // attenuation\n\n float attenuation = calcLightAttenuation( length( lVector ), pointLightDistance[ i ], pointLightDecay[ i ] );\n\n // diffuse\n\n float dotProduct = dot( normal, lightDir );\n\n vLightFront += lightColor * attenuation * saturate( dotProduct );\n\n #ifdef DOUBLE_SIDED\n\n vLightBack += lightColor * attenuation * saturate( - dotProduct );\n\n #endif\n\n }\n\n#endif\n\n#if MAX_SPOT_LIGHTS > 0\n\n for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {\n\n vec3 lightColor = spotLightColor[ i ];\n\n vec3 lightPosition = spotLightPosition[ i ];\n vec3 lVector = lightPosition - mvPosition.xyz;\n vec3 lightDir = normalize( lVector );\n\n float spotEffect = dot( spotLightDirection[ i ], lightDir );\n\n if ( spotEffect > spotLightAngleCos[ i ] ) {\n\n spotEffect = saturate( pow( saturate( spotEffect ), spotLightExponent[ i ] ) );\n\n // attenuation\n\n float attenuation = calcLightAttenuation( length( lVector ), spotLightDistance[ i ], spotLightDecay[ i ] );\n\n attenuation *= spotEffect;\n\n // diffuse\n\n float dotProduct = dot( normal, lightDir );\n\n vLightFront += lightColor * attenuation * saturate( dotProduct );\n\n #ifdef DOUBLE_SIDED\n\n vLightBack += lightColor * attenuation * saturate( - dotProduct );\n\n #endif\n\n }\n\n }\n\n#endif\n\n#if MAX_DIR_LIGHTS > 0\n\n for ( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {\n\n vec3 lightColor = directionalLightColor[ i ];\n\n vec3 lightDir = directionalLightDirection[ i ];\n\n // diffuse\n\n float dotProduct = dot( normal, lightDir );\n\n vLightFront += lightColor * saturate( dotProduct );\n\n #ifdef DOUBLE_SIDED\n\n vLightBack += lightColor * saturate( - dotProduct );\n\n #endif\n\n }\n\n#endif\n\n#if MAX_HEMI_LIGHTS > 0\n\n for ( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {\n\n vec3 lightDir = hemisphereLightDirection[ i ];\n\n // diffuse\n\n float dotProduct = dot( normal, lightDir );\n\n float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;\n\n vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );\n\n #ifdef DOUBLE_SIDED\n\n float hemiDiffuseWeightBack = - 0.5 * dotProduct + 0.5;\n\n vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );\n\n #endif\n\n }\n\n#endif\n\nvLightFront += ambientLightColor;\n\n#ifdef DOUBLE_SIDED\n\n vLightBack += ambientLightColor;\n\n#endif\n"; + gl.cullFace( gl.FRONT_AND_BACK ); -// File:src/renderers/shaders/ShaderChunk/lights_phong_fragment.glsl + } -THREE.ShaderChunk[ 'lights_phong_fragment'] = "#ifndef FLAT_SHADED\n\n vec3 normal = normalize( vNormal );\n\n #ifdef DOUBLE_SIDED\n\n normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );\n\n #endif\n\n#else\n\n vec3 fdx = dFdx( vViewPosition );\n vec3 fdy = dFdy( vViewPosition );\n vec3 normal = normalize( cross( fdx, fdy ) );\n\n#endif\n\n#ifdef USE_NORMALMAP\n\n normal = perturbNormal2Arb( -vViewPosition, normal );\n\n#elif defined( USE_BUMPMAP )\n\n normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n\n#endif\n\nvec3 viewDir = normalize( vViewPosition );\n\nvec3 totalDiffuseLight = vec3( 0.0 );\nvec3 totalSpecularLight = vec3( 0.0 );\n\n#if MAX_POINT_LIGHTS > 0\n\n for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {\n\n vec3 lightColor = pointLightColor[ i ];\n\n vec3 lightPosition = pointLightPosition[ i ];\n vec3 lVector = lightPosition + vViewPosition.xyz;\n vec3 lightDir = normalize( lVector );\n\n // attenuation\n\n float attenuation = calcLightAttenuation( length( lVector ), pointLightDistance[ i ], pointLightDecay[ i ] );\n\n // diffuse\n\n float cosineTerm = saturate( dot( normal, lightDir ) );\n\n totalDiffuseLight += lightColor * attenuation * cosineTerm;\n\n // specular\n\n vec3 brdf = BRDF_BlinnPhong( specular, shininess, normal, lightDir, viewDir );\n\n totalSpecularLight += brdf * specularStrength * lightColor * attenuation * cosineTerm;\n\n\n }\n\n#endif\n\n#if MAX_SPOT_LIGHTS > 0\n\n for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {\n\n vec3 lightColor = spotLightColor[ i ];\n\n vec3 lightPosition = spotLightPosition[ i ];\n vec3 lVector = lightPosition + vViewPosition.xyz;\n vec3 lightDir = normalize( lVector );\n\n float spotEffect = dot( spotLightDirection[ i ], lightDir );\n\n if ( spotEffect > spotLightAngleCos[ i ] ) {\n\n spotEffect = saturate( pow( saturate( spotEffect ), spotLightExponent[ i ] ) );\n\n // attenuation\n\n float attenuation = calcLightAttenuation( length( lVector ), spotLightDistance[ i ], spotLightDecay[ i ] );\n\n attenuation *= spotEffect;\n\n // diffuse\n\n float cosineTerm = saturate( dot( normal, lightDir ) );\n\n totalDiffuseLight += lightColor * attenuation * cosineTerm;\n\n // specular\n\n vec3 brdf = BRDF_BlinnPhong( specular, shininess, normal, lightDir, viewDir );\n\n totalSpecularLight += brdf * specularStrength * lightColor * attenuation * cosineTerm;\n\n }\n\n }\n\n#endif\n\n#if MAX_DIR_LIGHTS > 0\n\n for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {\n\n vec3 lightColor = directionalLightColor[ i ];\n\n vec3 lightDir = directionalLightDirection[ i ];\n\n // diffuse\n\n float cosineTerm = saturate( dot( normal, lightDir ) );\n\n totalDiffuseLight += lightColor * cosineTerm;\n\n // specular\n\n vec3 brdf = BRDF_BlinnPhong( specular, shininess, normal, lightDir, viewDir );\n\n totalSpecularLight += brdf * specularStrength * lightColor * cosineTerm;\n\n }\n\n#endif\n\n#if MAX_HEMI_LIGHTS > 0\n\n for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {\n\n vec3 lightDir = hemisphereLightDirection[ i ];\n\n // diffuse\n\n float dotProduct = dot( normal, lightDir );\n\n float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;\n\n vec3 lightColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );\n\n totalDiffuseLight += lightColor;\n\n // specular (sky term only)\n\n vec3 brdf = BRDF_BlinnPhong( specular, shininess, normal, lightDir, viewDir );\n\n totalSpecularLight += brdf * specularStrength * lightColor * max( dotProduct, 0.0 );\n\n }\n\n#endif\n\n#ifdef METAL\n\n outgoingLight += diffuseColor.rgb * ( totalDiffuseLight + totalAmbientLight ) * specular + totalSpecularLight + totalEmissiveLight;\n\n#else\n\n outgoingLight += diffuseColor.rgb * ( totalDiffuseLight + totalAmbientLight ) + totalSpecularLight + totalEmissiveLight;\n\n#endif\n"; + } -// File:src/renderers/shaders/ShaderChunk/lights_phong_pars_fragment.glsl + } else { -THREE.ShaderChunk[ 'lights_phong_pars_fragment'] = "uniform vec3 ambientLightColor;\n\n#if MAX_DIR_LIGHTS > 0\n\n uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];\n uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];\n\n#endif\n\n#if MAX_HEMI_LIGHTS > 0\n\n uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];\n uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];\n uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];\n\n#endif\n\n#if MAX_POINT_LIGHTS > 0\n\n uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];\n\n uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];\n uniform float pointLightDistance[ MAX_POINT_LIGHTS ];\n uniform float pointLightDecay[ MAX_POINT_LIGHTS ];\n\n#endif\n\n#if MAX_SPOT_LIGHTS > 0\n\n uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];\n uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];\n uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];\n uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];\n uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];\n uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];\n uniform float spotLightDecay[ MAX_SPOT_LIGHTS ];\n\n#endif\n\n#if MAX_SPOT_LIGHTS > 0 || defined( USE_ENVMAP )\n\n varying vec3 vWorldPosition;\n\n#endif\n\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n\n varying vec3 vNormal;\n\n#endif\n"; + disable( gl.CULL_FACE ); -// File:src/renderers/shaders/ShaderChunk/lights_phong_pars_vertex.glsl + } -THREE.ShaderChunk[ 'lights_phong_pars_vertex'] = "#if MAX_SPOT_LIGHTS > 0 || defined( USE_ENVMAP )\n\n varying vec3 vWorldPosition;\n\n#endif\n"; + currentCullFace = cullFace; -// File:src/renderers/shaders/ShaderChunk/lights_phong_vertex.glsl + } -THREE.ShaderChunk[ 'lights_phong_vertex'] = "#if MAX_SPOT_LIGHTS > 0 || defined( USE_ENVMAP )\n\n vWorldPosition = worldPosition.xyz;\n\n#endif\n"; + function setLineWidth( width ) { -// File:src/renderers/shaders/ShaderChunk/linear_to_gamma_fragment.glsl + if ( width !== currentLineWidth ) { -THREE.ShaderChunk[ 'linear_to_gamma_fragment'] = "\n outgoingLight = linearToOutput( outgoingLight );\n"; + gl.lineWidth( width ); -// File:src/renderers/shaders/ShaderChunk/logdepthbuf_fragment.glsl + currentLineWidth = width; -THREE.ShaderChunk[ 'logdepthbuf_fragment'] = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\n gl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n\n#endif"; + } -// File:src/renderers/shaders/ShaderChunk/logdepthbuf_pars_fragment.glsl + } -THREE.ShaderChunk[ 'logdepthbuf_pars_fragment'] = "#ifdef USE_LOGDEPTHBUF\n\n uniform float logDepthBufFC;\n\n #ifdef USE_LOGDEPTHBUF_EXT\n\n varying float vFragDepth;\n\n #endif\n\n#endif\n"; + function setPolygonOffset( polygonOffset, factor, units ) { -// File:src/renderers/shaders/ShaderChunk/logdepthbuf_pars_vertex.glsl + if ( polygonOffset ) { -THREE.ShaderChunk[ 'logdepthbuf_pars_vertex'] = "#ifdef USE_LOGDEPTHBUF\n\n #ifdef USE_LOGDEPTHBUF_EXT\n\n varying float vFragDepth;\n\n #endif\n\n uniform float logDepthBufFC;\n\n#endif"; + enable( gl.POLYGON_OFFSET_FILL ); -// File:src/renderers/shaders/ShaderChunk/logdepthbuf_vertex.glsl + if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) { -THREE.ShaderChunk[ 'logdepthbuf_vertex'] = "#ifdef USE_LOGDEPTHBUF\n\n gl_Position.z = log2(max( EPSILON, gl_Position.w + 1.0 )) * logDepthBufFC;\n\n #ifdef USE_LOGDEPTHBUF_EXT\n\n vFragDepth = 1.0 + gl_Position.w;\n\n#else\n\n gl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;\n\n #endif\n\n#endif"; + gl.polygonOffset( factor, units ); -// File:src/renderers/shaders/ShaderChunk/map_fragment.glsl + currentPolygonOffsetFactor = factor; + currentPolygonOffsetUnits = units; -THREE.ShaderChunk[ 'map_fragment'] = "#ifdef USE_MAP\n\n vec4 texelColor = texture2D( map, vUv );\n\n texelColor.xyz = inputToLinear( texelColor.xyz );\n\n diffuseColor *= texelColor;\n\n#endif\n"; + } -// File:src/renderers/shaders/ShaderChunk/map_pars_fragment.glsl + } else { -THREE.ShaderChunk[ 'map_pars_fragment'] = "#ifdef USE_MAP\n\n uniform sampler2D map;\n\n#endif"; + disable( gl.POLYGON_OFFSET_FILL ); -// File:src/renderers/shaders/ShaderChunk/map_particle_fragment.glsl + } -THREE.ShaderChunk[ 'map_particle_fragment'] = "#ifdef USE_MAP\n\n diffuseColor *= texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) * offsetRepeat.zw + offsetRepeat.xy );\n\n#endif\n"; + } -// File:src/renderers/shaders/ShaderChunk/map_particle_pars_fragment.glsl + function getScissorTest() { -THREE.ShaderChunk[ 'map_particle_pars_fragment'] = "#ifdef USE_MAP\n\n uniform vec4 offsetRepeat;\n uniform sampler2D map;\n\n#endif\n"; + return currentScissorTest; -// File:src/renderers/shaders/ShaderChunk/morphnormal_vertex.glsl + } -THREE.ShaderChunk[ 'morphnormal_vertex'] = "#ifdef USE_MORPHNORMALS\n\n objectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n objectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n objectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n objectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n\n#endif\n"; + function setScissorTest( scissorTest ) { -// File:src/renderers/shaders/ShaderChunk/morphtarget_pars_vertex.glsl + currentScissorTest = scissorTest; -THREE.ShaderChunk[ 'morphtarget_pars_vertex'] = "#ifdef USE_MORPHTARGETS\n\n #ifndef USE_MORPHNORMALS\n\n uniform float morphTargetInfluences[ 8 ];\n\n #else\n\n uniform float morphTargetInfluences[ 4 ];\n\n #endif\n\n#endif"; + if ( scissorTest ) { -// File:src/renderers/shaders/ShaderChunk/morphtarget_vertex.glsl + enable( gl.SCISSOR_TEST ); -THREE.ShaderChunk[ 'morphtarget_vertex'] = "#ifdef USE_MORPHTARGETS\n\n transformed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n transformed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n transformed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n transformed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n\n #ifndef USE_MORPHNORMALS\n\n transformed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n transformed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n transformed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n transformed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n\n #endif\n\n#endif\n"; + } else { -// File:src/renderers/shaders/ShaderChunk/normalmap_pars_fragment.glsl + disable( gl.SCISSOR_TEST ); -THREE.ShaderChunk[ 'normalmap_pars_fragment'] = "#ifdef USE_NORMALMAP\n\n uniform sampler2D normalMap;\n uniform vec2 normalScale;\n\n // Per-Pixel Tangent Space Normal Mapping\n // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html\n\n vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n\n vec3 q0 = dFdx( eye_pos.xyz );\n vec3 q1 = dFdy( eye_pos.xyz );\n vec2 st0 = dFdx( vUv.st );\n vec2 st1 = dFdy( vUv.st );\n\n vec3 S = normalize( q0 * st1.t - q1 * st0.t );\n vec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n vec3 N = normalize( surf_norm );\n\n vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n mapN.xy = normalScale * mapN.xy;\n mat3 tsn = mat3( S, T, N );\n return normalize( tsn * mapN );\n\n }\n\n#endif\n"; + } -// File:src/renderers/shaders/ShaderChunk/project_vertex.glsl + } -THREE.ShaderChunk[ 'project_vertex'] = "#ifdef USE_SKINNING\n\n vec4 mvPosition = modelViewMatrix * skinned;\n\n#else\n\n vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\n\n#endif\n\ngl_Position = projectionMatrix * mvPosition;\n"; + // texture -// File:src/renderers/shaders/ShaderChunk/shadowmap_fragment.glsl + function activeTexture( webglSlot ) { -THREE.ShaderChunk[ 'shadowmap_fragment'] = "#ifdef USE_SHADOWMAP\n\n #ifdef SHADOWMAP_DEBUG\n\n vec3 frustumColors[3];\n frustumColors[0] = vec3( 1.0, 0.5, 0.0 );\n frustumColors[1] = vec3( 0.0, 1.0, 0.8 );\n frustumColors[2] = vec3( 0.0, 0.5, 1.0 );\n\n #endif\n\n float fDepth;\n vec3 shadowColor = vec3( 1.0 );\n\n for( int i = 0; i < MAX_SHADOWS; i ++ ) {\n\n vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;\n\n // if ( something && something ) breaks ATI OpenGL shader compiler\n // if ( all( something, something ) ) using this instead\n\n bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n bool inFrustum = all( inFrustumVec );\n\n bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\n bool frustumTest = all( frustumTestVec );\n\n if ( frustumTest ) {\n\n shadowCoord.z += shadowBias[ i ];\n\n #if defined( SHADOWMAP_TYPE_PCF )\n\n // Percentage-close filtering\n // (9 pixel kernel)\n // http://fabiensanglard.net/shadowmappingPCF/\n\n float shadow = 0.0;\n\n /*\n // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL\n // must enroll loop manually\n\n for ( float y = -1.25; y <= 1.25; y += 1.25 )\n for ( float x = -1.25; x <= 1.25; x += 1.25 ) {\n\n vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );\n\n // doesn't seem to produce any noticeable visual difference compared to simple texture2D lookup\n //vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );\n\n float fDepth = unpackDepth( rgbaDepth );\n\n if ( fDepth < shadowCoord.z )\n shadow += 1.0;\n\n }\n\n shadow /= 9.0;\n\n */\n\n const float shadowDelta = 1.0 / 9.0;\n\n float xPixelOffset = 1.0 / shadowMapSize[ i ].x;\n float yPixelOffset = 1.0 / shadowMapSize[ i ].y;\n\n float dx0 = -1.25 * xPixelOffset;\n float dy0 = -1.25 * yPixelOffset;\n float dx1 = 1.25 * xPixelOffset;\n float dy1 = 1.25 * yPixelOffset;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );\n\n #elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\n // Percentage-close filtering\n // (9 pixel kernel)\n // http://fabiensanglard.net/shadowmappingPCF/\n\n float shadow = 0.0;\n\n float xPixelOffset = 1.0 / shadowMapSize[ i ].x;\n float yPixelOffset = 1.0 / shadowMapSize[ i ].y;\n\n float dx0 = -1.0 * xPixelOffset;\n float dy0 = -1.0 * yPixelOffset;\n float dx1 = 1.0 * xPixelOffset;\n float dy1 = 1.0 * yPixelOffset;\n\n mat3 shadowKernel;\n mat3 depthKernel;\n\n depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );\n depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );\n depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );\n depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );\n depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );\n depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );\n depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );\n depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );\n depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );\n\n vec3 shadowZ = vec3( shadowCoord.z );\n shadowKernel[0] = vec3(lessThan(depthKernel[0], shadowZ ));\n shadowKernel[0] *= vec3(0.25);\n\n shadowKernel[1] = vec3(lessThan(depthKernel[1], shadowZ ));\n shadowKernel[1] *= vec3(0.25);\n\n shadowKernel[2] = vec3(lessThan(depthKernel[2], shadowZ ));\n shadowKernel[2] *= vec3(0.25);\n\n vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );\n\n shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );\n shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );\n\n vec4 shadowValues;\n shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );\n shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );\n shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );\n shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );\n\n shadow = dot( shadowValues, vec4( 1.0 ) );\n\n shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );\n\n #else\n\n vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );\n float fDepth = unpackDepth( rgbaDepth );\n\n if ( fDepth < shadowCoord.z )\n\n // spot with multiple shadows is darker\n\n shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );\n\n // spot with multiple shadows has the same color as single shadow spot\n\n // shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );\n\n #endif\n\n }\n\n\n #ifdef SHADOWMAP_DEBUG\n\n if ( inFrustum ) outgoingLight *= frustumColors[ i ];\n\n #endif\n\n }\n\n outgoingLight = outgoingLight * shadowColor;\n\n#endif\n"; + if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1; -// File:src/renderers/shaders/ShaderChunk/shadowmap_pars_fragment.glsl + if ( currentTextureSlot !== webglSlot ) { -THREE.ShaderChunk[ 'shadowmap_pars_fragment'] = "#ifdef USE_SHADOWMAP\n\n uniform sampler2D shadowMap[ MAX_SHADOWS ];\n uniform vec2 shadowMapSize[ MAX_SHADOWS ];\n\n uniform float shadowDarkness[ MAX_SHADOWS ];\n uniform float shadowBias[ MAX_SHADOWS ];\n\n varying vec4 vShadowCoord[ MAX_SHADOWS ];\n\n float unpackDepth( const in vec4 rgba_depth ) {\n\n const vec4 bit_shift = vec4( 1.0 / ( 256.0 * 256.0 * 256.0 ), 1.0 / ( 256.0 * 256.0 ), 1.0 / 256.0, 1.0 );\n float depth = dot( rgba_depth, bit_shift );\n return depth;\n\n }\n\n#endif"; + gl.activeTexture( webglSlot ); + currentTextureSlot = webglSlot; -// File:src/renderers/shaders/ShaderChunk/shadowmap_pars_vertex.glsl + } -THREE.ShaderChunk[ 'shadowmap_pars_vertex'] = "#ifdef USE_SHADOWMAP\n\n varying vec4 vShadowCoord[ MAX_SHADOWS ];\n uniform mat4 shadowMatrix[ MAX_SHADOWS ];\n\n#endif"; + } -// File:src/renderers/shaders/ShaderChunk/shadowmap_vertex.glsl + function bindTexture( webglType, webglTexture ) { -THREE.ShaderChunk[ 'shadowmap_vertex'] = "#ifdef USE_SHADOWMAP\n\n for( int i = 0; i < MAX_SHADOWS; i ++ ) {\n\n vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;\n\n }\n\n#endif"; + if ( currentTextureSlot === null ) { -// File:src/renderers/shaders/ShaderChunk/skinbase_vertex.glsl + activeTexture(); -THREE.ShaderChunk[ 'skinbase_vertex'] = "#ifdef USE_SKINNING\n\n mat4 boneMatX = getBoneMatrix( skinIndex.x );\n mat4 boneMatY = getBoneMatrix( skinIndex.y );\n mat4 boneMatZ = getBoneMatrix( skinIndex.z );\n mat4 boneMatW = getBoneMatrix( skinIndex.w );\n\n#endif"; + } -// File:src/renderers/shaders/ShaderChunk/skinning_pars_vertex.glsl + var boundTexture = currentBoundTextures[ currentTextureSlot ]; -THREE.ShaderChunk[ 'skinning_pars_vertex'] = "#ifdef USE_SKINNING\n\n uniform mat4 bindMatrix;\n uniform mat4 bindMatrixInverse;\n\n #ifdef BONE_TEXTURE\n\n uniform sampler2D boneTexture;\n uniform int boneTextureWidth;\n uniform int boneTextureHeight;\n\n mat4 getBoneMatrix( const in float i ) {\n\n float j = i * 4.0;\n float x = mod( j, float( boneTextureWidth ) );\n float y = floor( j / float( boneTextureWidth ) );\n\n float dx = 1.0 / float( boneTextureWidth );\n float dy = 1.0 / float( boneTextureHeight );\n\n y = dy * ( y + 0.5 );\n\n vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\n mat4 bone = mat4( v1, v2, v3, v4 );\n\n return bone;\n\n }\n\n #else\n\n uniform mat4 boneGlobalMatrices[ MAX_BONES ];\n\n mat4 getBoneMatrix( const in float i ) {\n\n mat4 bone = boneGlobalMatrices[ int(i) ];\n return bone;\n\n }\n\n #endif\n\n#endif\n"; + if ( boundTexture === undefined ) { -// File:src/renderers/shaders/ShaderChunk/skinning_vertex.glsl + boundTexture = { type: undefined, texture: undefined }; + currentBoundTextures[ currentTextureSlot ] = boundTexture; -THREE.ShaderChunk[ 'skinning_vertex'] = "#ifdef USE_SKINNING\n\n vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\n vec4 skinned = vec4( 0.0 );\n skinned += boneMatX * skinVertex * skinWeight.x;\n skinned += boneMatY * skinVertex * skinWeight.y;\n skinned += boneMatZ * skinVertex * skinWeight.z;\n skinned += boneMatW * skinVertex * skinWeight.w;\n skinned = bindMatrixInverse * skinned;\n\n#endif\n"; + } -// File:src/renderers/shaders/ShaderChunk/skinnormal_vertex.glsl + if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) { -THREE.ShaderChunk[ 'skinnormal_vertex'] = "#ifdef USE_SKINNING\n\n mat4 skinMatrix = mat4( 0.0 );\n skinMatrix += skinWeight.x * boneMatX;\n skinMatrix += skinWeight.y * boneMatY;\n skinMatrix += skinWeight.z * boneMatZ;\n skinMatrix += skinWeight.w * boneMatW;\n skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\n objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\n#endif\n"; + gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] ); -// File:src/renderers/shaders/ShaderChunk/specularmap_fragment.glsl + boundTexture.type = webglType; + boundTexture.texture = webglTexture; -THREE.ShaderChunk[ 'specularmap_fragment'] = "float specularStrength;\n\n#ifdef USE_SPECULARMAP\n\n vec4 texelSpecular = texture2D( specularMap, vUv );\n specularStrength = texelSpecular.r;\n\n#else\n\n specularStrength = 1.0;\n\n#endif"; + } -// File:src/renderers/shaders/ShaderChunk/specularmap_pars_fragment.glsl + } -THREE.ShaderChunk[ 'specularmap_pars_fragment'] = "#ifdef USE_SPECULARMAP\n\n uniform sampler2D specularMap;\n\n#endif"; + function compressedTexImage2D() { -// File:src/renderers/shaders/ShaderChunk/uv2_pars_fragment.glsl + try { -THREE.ShaderChunk[ 'uv2_pars_fragment'] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\n varying vec2 vUv2;\n\n#endif"; + gl.compressedTexImage2D.apply( gl, arguments ); -// File:src/renderers/shaders/ShaderChunk/uv2_pars_vertex.glsl + } catch ( error ) { -THREE.ShaderChunk[ 'uv2_pars_vertex'] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\n attribute vec2 uv2;\n varying vec2 vUv2;\n\n#endif"; + console.error( error ); -// File:src/renderers/shaders/ShaderChunk/uv2_vertex.glsl + } -THREE.ShaderChunk[ 'uv2_vertex'] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\n vUv2 = uv2;\n\n#endif"; + } -// File:src/renderers/shaders/ShaderChunk/uv_pars_fragment.glsl + function texImage2D() { -THREE.ShaderChunk[ 'uv_pars_fragment'] = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP )\n\n varying vec2 vUv;\n\n#endif"; + try { -// File:src/renderers/shaders/ShaderChunk/uv_pars_vertex.glsl + gl.texImage2D.apply( gl, arguments ); -THREE.ShaderChunk[ 'uv_pars_vertex'] = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP )\n\n varying vec2 vUv;\n uniform vec4 offsetRepeat;\n\n#endif\n"; + } catch ( error ) { -// File:src/renderers/shaders/ShaderChunk/uv_vertex.glsl + console.error( error ); -THREE.ShaderChunk[ 'uv_vertex'] = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP )\n\n vUv = uv * offsetRepeat.zw + offsetRepeat.xy;\n\n#endif"; + } -// File:src/renderers/shaders/ShaderChunk/worldpos_vertex.glsl + } -THREE.ShaderChunk[ 'worldpos_vertex'] = "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )\n\n #ifdef USE_SKINNING\n\n vec4 worldPosition = modelMatrix * skinned;\n\n #else\n\n vec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n\n #endif\n\n#endif\n"; + // TODO Deprecate -// File:src/renderers/shaders/UniformsUtils.js + function clearColor( r, g, b, a ) { -/** - * Uniform Utilities - */ + colorBuffer.setClear( r, g, b, a ); -THREE.UniformsUtils = { + } - merge: function ( uniforms ) { + function clearDepth( depth ) { - var merged = {}; + depthBuffer.setClear( depth ); - for ( var u = 0; u < uniforms.length; u ++ ) { + } - var tmp = this.clone( uniforms[ u ] ); + function clearStencil( stencil ) { - for ( var p in tmp ) { + stencilBuffer.setClear( stencil ); - merged[ p ] = tmp[ p ]; + } - } + // - } + function scissor( scissor ) { - return merged; + if ( currentScissor.equals( scissor ) === false ) { - }, + gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w ); + currentScissor.copy( scissor ); - clone: function ( uniforms_src ) { + } - var uniforms_dst = {}; + } - for ( var u in uniforms_src ) { + function viewport( viewport ) { - uniforms_dst[ u ] = {}; + if ( currentViewport.equals( viewport ) === false ) { - for ( var p in uniforms_src[ u ] ) { + gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w ); + currentViewport.copy( viewport ); - var parameter_src = uniforms_src[ u ][ p ]; + } - if ( parameter_src instanceof THREE.Color || - parameter_src instanceof THREE.Vector2 || - parameter_src instanceof THREE.Vector3 || - parameter_src instanceof THREE.Vector4 || - parameter_src instanceof THREE.Matrix3 || - parameter_src instanceof THREE.Matrix4 || - parameter_src instanceof THREE.Texture ) { + } - uniforms_dst[ u ][ p ] = parameter_src.clone(); + // - } else if ( Array.isArray( parameter_src ) ) { + function reset() { - uniforms_dst[ u ][ p ] = parameter_src.slice(); + for ( var i = 0; i < enabledAttributes.length; i ++ ) { - } else { + if ( enabledAttributes[ i ] === 1 ) { - uniforms_dst[ u ][ p ] = parameter_src; + gl.disableVertexAttribArray( i ); + enabledAttributes[ i ] = 0; - } + } - } + } - } + capabilities = {}; - return uniforms_dst; + compressedTextureFormats = null; - } + currentTextureSlot = null; + currentBoundTextures = {}; -}; + currentBlending = null; -// File:src/renderers/shaders/UniformsLib.js + currentFlipSided = null; + currentCullFace = null; -/** - * Uniforms library for shared webgl shaders - */ + colorBuffer.reset(); + depthBuffer.reset(); + stencilBuffer.reset(); -THREE.UniformsLib = { + } - common: { + return { - "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) }, - "opacity" : { type: "f", value: 1.0 }, + buffers: { + color: colorBuffer, + depth: depthBuffer, + stencil: stencilBuffer + }, - "map" : { type: "t", value: null }, - "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) }, + init: init, + initAttributes: initAttributes, + enableAttribute: enableAttribute, + enableAttributeAndDivisor: enableAttributeAndDivisor, + disableUnusedAttributes: disableUnusedAttributes, + enable: enable, + disable: disable, + getCompressedTextureFormats: getCompressedTextureFormats, - "specularMap" : { type: "t", value: null }, - "alphaMap" : { type: "t", value: null }, + setBlending: setBlending, - "envMap" : { type: "t", value: null }, - "flipEnvMap" : { type: "f", value: - 1 }, - "reflectivity" : { type: "f", value: 1.0 }, - "refractionRatio" : { type: "f", value: 0.98 } + setColorWrite: setColorWrite, + setDepthTest: setDepthTest, + setDepthWrite: setDepthWrite, + setDepthFunc: setDepthFunc, + setStencilTest: setStencilTest, + setStencilWrite: setStencilWrite, + setStencilFunc: setStencilFunc, + setStencilOp: setStencilOp, - }, + setFlipSided: setFlipSided, + setCullFace: setCullFace, - aomap: { + setLineWidth: setLineWidth, + setPolygonOffset: setPolygonOffset, - "aoMap" : { type: "t", value: null }, - "aoMapIntensity" : { type: "f", value: 1 }, + getScissorTest: getScissorTest, + setScissorTest: setScissorTest, - }, + activeTexture: activeTexture, + bindTexture: bindTexture, + compressedTexImage2D: compressedTexImage2D, + texImage2D: texImage2D, - lightmap: { + clearColor: clearColor, + clearDepth: clearDepth, + clearStencil: clearStencil, - "lightMap" : { type: "t", value: null }, - "lightMapIntensity" : { type: "f", value: 1 }, + scissor: scissor, + viewport: viewport, - }, + reset: reset - emissivemap: { + }; - "emissiveMap" : { type: "t", value: null }, + } - }, + /** + * @author mrdoob / http://mrdoob.com/ + */ - bumpmap: { + function WebGLCapabilities( gl, extensions, parameters ) { - "bumpMap" : { type: "t", value: null }, - "bumpScale" : { type: "f", value: 1 } + var maxAnisotropy; - }, + function getMaxAnisotropy() { - normalmap: { + if ( maxAnisotropy !== undefined ) return maxAnisotropy; - "normalMap" : { type: "t", value: null }, - "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) } + var extension = extensions.get( 'EXT_texture_filter_anisotropic' ); - }, + if ( extension !== null ) { - displacementmap: { + maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT ); - "displacementMap" : { type: "t", value: null }, - "displacementScale" : { type: "f", value: 1 }, - "displacementBias" : { type: "f", value: 0 } + } else { - }, + maxAnisotropy = 0; - fog : { + } - "fogDensity" : { type: "f", value: 0.00025 }, - "fogNear" : { type: "f", value: 1 }, - "fogFar" : { type: "f", value: 2000 }, - "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) } + return maxAnisotropy; - }, + } - lights: { + function getMaxPrecision( precision ) { - "ambientLightColor" : { type: "fv", value: [] }, + if ( precision === 'highp' ) { - "directionalLightDirection" : { type: "fv", value: [] }, - "directionalLightColor" : { type: "fv", value: [] }, + if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 && + gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) { - "hemisphereLightDirection" : { type: "fv", value: [] }, - "hemisphereLightSkyColor" : { type: "fv", value: [] }, - "hemisphereLightGroundColor" : { type: "fv", value: [] }, + return 'highp'; - "pointLightColor" : { type: "fv", value: [] }, - "pointLightPosition" : { type: "fv", value: [] }, - "pointLightDistance" : { type: "fv1", value: [] }, - "pointLightDecay" : { type: "fv1", value: [] }, + } - "spotLightColor" : { type: "fv", value: [] }, - "spotLightPosition" : { type: "fv", value: [] }, - "spotLightDirection" : { type: "fv", value: [] }, - "spotLightDistance" : { type: "fv1", value: [] }, - "spotLightAngleCos" : { type: "fv1", value: [] }, - "spotLightExponent" : { type: "fv1", value: [] }, - "spotLightDecay" : { type: "fv1", value: [] } + precision = 'mediump'; - }, + } - points: { + if ( precision === 'mediump' ) { - "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) }, - "opacity" : { type: "f", value: 1.0 }, - "size" : { type: "f", value: 1.0 }, - "scale" : { type: "f", value: 1.0 }, - "map" : { type: "t", value: null }, - "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) }, + if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 && + gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) { - "fogDensity" : { type: "f", value: 0.00025 }, - "fogNear" : { type: "f", value: 1 }, - "fogFar" : { type: "f", value: 2000 }, - "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) } + return 'mediump'; - }, + } - shadowmap: { + } - "shadowMap": { type: "tv", value: [] }, - "shadowMapSize": { type: "v2v", value: [] }, + return 'lowp'; - "shadowBias" : { type: "fv1", value: [] }, - "shadowDarkness": { type: "fv1", value: [] }, + } - "shadowMatrix" : { type: "m4v", value: [] } + var precision = parameters.precision !== undefined ? parameters.precision : 'highp'; + var maxPrecision = getMaxPrecision( precision ); - } + if ( maxPrecision !== precision ) { -}; + console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' ); + precision = maxPrecision; -// File:src/renderers/shaders/ShaderLib.js + } -/** - * Webgl Shader Library for three.js - * - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - * @author mikael emtinger / http://gomo.se/ - */ + var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true && !! extensions.get( 'EXT_frag_depth' ); + var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS ); + var maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ); + var maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE ); + var maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE ); -THREE.ShaderLib = { + var maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS ); + var maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS ); + var maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS ); + var maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS ); - 'basic': { + var vertexTextures = maxVertexTextures > 0; + var floatFragmentTextures = !! extensions.get( 'OES_texture_float' ); + var floatVertexTextures = vertexTextures && floatFragmentTextures; - uniforms: THREE.UniformsUtils.merge( [ + return { - THREE.UniformsLib[ "common" ], - THREE.UniformsLib[ "aomap" ], - THREE.UniformsLib[ "fog" ], - THREE.UniformsLib[ "shadowmap" ] + getMaxAnisotropy: getMaxAnisotropy, + getMaxPrecision: getMaxPrecision, - ] ), + precision: precision, + logarithmicDepthBuffer: logarithmicDepthBuffer, - vertexShader: [ + maxTextures: maxTextures, + maxVertexTextures: maxVertexTextures, + maxTextureSize: maxTextureSize, + maxCubemapSize: maxCubemapSize, - THREE.ShaderChunk[ "common" ], - THREE.ShaderChunk[ "uv_pars_vertex" ], - THREE.ShaderChunk[ "uv2_pars_vertex" ], - THREE.ShaderChunk[ "envmap_pars_vertex" ], - THREE.ShaderChunk[ "color_pars_vertex" ], - THREE.ShaderChunk[ "morphtarget_pars_vertex" ], - THREE.ShaderChunk[ "skinning_pars_vertex" ], - THREE.ShaderChunk[ "shadowmap_pars_vertex" ], - THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], + maxAttributes: maxAttributes, + maxVertexUniforms: maxVertexUniforms, + maxVaryings: maxVaryings, + maxFragmentUniforms: maxFragmentUniforms, - "void main() {", + vertexTextures: vertexTextures, + floatFragmentTextures: floatFragmentTextures, + floatVertexTextures: floatVertexTextures - THREE.ShaderChunk[ "uv_vertex" ], - THREE.ShaderChunk[ "uv2_vertex" ], - THREE.ShaderChunk[ "color_vertex" ], - THREE.ShaderChunk[ "skinbase_vertex" ], + }; - " #ifdef USE_ENVMAP", + } - THREE.ShaderChunk[ "beginnormal_vertex" ], - THREE.ShaderChunk[ "morphnormal_vertex" ], - THREE.ShaderChunk[ "skinnormal_vertex" ], - THREE.ShaderChunk[ "defaultnormal_vertex" ], + /** + * @author mrdoob / http://mrdoob.com/ + */ - " #endif", + function WebGLExtensions( gl ) { - THREE.ShaderChunk[ "begin_vertex" ], - THREE.ShaderChunk[ "morphtarget_vertex" ], - THREE.ShaderChunk[ "skinning_vertex" ], - THREE.ShaderChunk[ "project_vertex" ], - THREE.ShaderChunk[ "logdepthbuf_vertex" ], + var extensions = {}; - THREE.ShaderChunk[ "worldpos_vertex" ], - THREE.ShaderChunk[ "envmap_vertex" ], - THREE.ShaderChunk[ "shadowmap_vertex" ], + return { - "}" + get: function ( name ) { - ].join( "\n" ), + if ( extensions[ name ] !== undefined ) { - fragmentShader: [ + return extensions[ name ]; - "uniform vec3 diffuse;", - "uniform float opacity;", + } - THREE.ShaderChunk[ "common" ], - THREE.ShaderChunk[ "color_pars_fragment" ], - THREE.ShaderChunk[ "uv_pars_fragment" ], - THREE.ShaderChunk[ "uv2_pars_fragment" ], - THREE.ShaderChunk[ "map_pars_fragment" ], - THREE.ShaderChunk[ "alphamap_pars_fragment" ], - THREE.ShaderChunk[ "aomap_pars_fragment" ], - THREE.ShaderChunk[ "envmap_pars_fragment" ], - THREE.ShaderChunk[ "fog_pars_fragment" ], - THREE.ShaderChunk[ "shadowmap_pars_fragment" ], - THREE.ShaderChunk[ "specularmap_pars_fragment" ], - THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], + var extension; - "void main() {", + switch ( name ) { - " vec3 outgoingLight = vec3( 0.0 );", - " vec4 diffuseColor = vec4( diffuse, opacity );", - " vec3 totalAmbientLight = vec3( 1.0 );", // hardwired + case 'WEBGL_depth_texture': + extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' ); + break; - THREE.ShaderChunk[ "logdepthbuf_fragment" ], - THREE.ShaderChunk[ "map_fragment" ], - THREE.ShaderChunk[ "color_fragment" ], - THREE.ShaderChunk[ "alphamap_fragment" ], - THREE.ShaderChunk[ "alphatest_fragment" ], - THREE.ShaderChunk[ "specularmap_fragment" ], - THREE.ShaderChunk[ "aomap_fragment" ], + 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; - " outgoingLight = diffuseColor.rgb * totalAmbientLight;", // simple shader + 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; - THREE.ShaderChunk[ "envmap_fragment" ], - THREE.ShaderChunk[ "shadowmap_fragment" ], // TODO: Shadows on an otherwise unlit surface doesn't make sense. + case 'WEBGL_compressed_texture_pvrtc': + extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' ); + break; - THREE.ShaderChunk[ "linear_to_gamma_fragment" ], + case 'WEBGL_compressed_texture_etc1': + extension = gl.getExtension( 'WEBGL_compressed_texture_etc1' ); + break; - THREE.ShaderChunk[ "fog_fragment" ], + default: + extension = gl.getExtension( name ); - " gl_FragColor = vec4( outgoingLight, diffuseColor.a );", + } - "}" + if ( extension === null ) { - ].join( "\n" ) + console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' ); - }, + } - 'lambert': { + extensions[ name ] = extension; - uniforms: THREE.UniformsUtils.merge( [ + return extension; - THREE.UniformsLib[ "common" ], - THREE.UniformsLib[ "fog" ], - THREE.UniformsLib[ "lights" ], - THREE.UniformsLib[ "shadowmap" ], + } - { - "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) } - } + }; - ] ), + } - vertexShader: [ + function WebGLClipping() { - "#define LAMBERT", + var scope = this, - "varying vec3 vLightFront;", + globalState = null, + numGlobalPlanes = 0, + localClippingEnabled = false, + renderingShadows = false, - "#ifdef DOUBLE_SIDED", + plane = new Plane(), + viewNormalMatrix = new Matrix3(), - " varying vec3 vLightBack;", + uniform = { value: null, needsUpdate: false }; - "#endif", + this.uniform = uniform; + this.numPlanes = 0; - THREE.ShaderChunk[ "common" ], - THREE.ShaderChunk[ "uv_pars_vertex" ], - THREE.ShaderChunk[ "uv2_pars_vertex" ], - THREE.ShaderChunk[ "envmap_pars_vertex" ], - THREE.ShaderChunk[ "lights_lambert_pars_vertex" ], - THREE.ShaderChunk[ "color_pars_vertex" ], - THREE.ShaderChunk[ "morphtarget_pars_vertex" ], - THREE.ShaderChunk[ "skinning_pars_vertex" ], - THREE.ShaderChunk[ "shadowmap_pars_vertex" ], - THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], + this.init = function( planes, enableLocalClipping, camera ) { - "void main() {", + 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; - THREE.ShaderChunk[ "uv_vertex" ], - THREE.ShaderChunk[ "uv2_vertex" ], - THREE.ShaderChunk[ "color_vertex" ], + localClippingEnabled = enableLocalClipping; - THREE.ShaderChunk[ "beginnormal_vertex" ], - THREE.ShaderChunk[ "morphnormal_vertex" ], - THREE.ShaderChunk[ "skinbase_vertex" ], - THREE.ShaderChunk[ "skinnormal_vertex" ], - THREE.ShaderChunk[ "defaultnormal_vertex" ], + globalState = projectPlanes( planes, camera, 0 ); + numGlobalPlanes = planes.length; - THREE.ShaderChunk[ "begin_vertex" ], - THREE.ShaderChunk[ "morphtarget_vertex" ], - THREE.ShaderChunk[ "skinning_vertex" ], - THREE.ShaderChunk[ "project_vertex" ], - THREE.ShaderChunk[ "logdepthbuf_vertex" ], + return enabled; - THREE.ShaderChunk[ "worldpos_vertex" ], - THREE.ShaderChunk[ "envmap_vertex" ], - THREE.ShaderChunk[ "lights_lambert_vertex" ], - THREE.ShaderChunk[ "shadowmap_vertex" ], + }; - "}" + this.beginShadows = function() { - ].join( "\n" ), + renderingShadows = true; + projectPlanes( null ); - fragmentShader: [ + }; - "uniform vec3 diffuse;", - "uniform vec3 emissive;", - "uniform float opacity;", + this.endShadows = function() { - "varying vec3 vLightFront;", + renderingShadows = false; + resetGlobalState(); - "#ifdef DOUBLE_SIDED", + }; - " varying vec3 vLightBack;", + this.setState = function( planes, clipShadows, camera, cache, fromCache ) { - "#endif", + if ( ! localClippingEnabled || + planes === null || planes.length === 0 || + renderingShadows && ! clipShadows ) { + // there's no local clipping - THREE.ShaderChunk[ "common" ], - THREE.ShaderChunk[ "color_pars_fragment" ], - THREE.ShaderChunk[ "uv_pars_fragment" ], - THREE.ShaderChunk[ "uv2_pars_fragment" ], - THREE.ShaderChunk[ "map_pars_fragment" ], - THREE.ShaderChunk[ "alphamap_pars_fragment" ], - THREE.ShaderChunk[ "envmap_pars_fragment" ], - THREE.ShaderChunk[ "fog_pars_fragment" ], - THREE.ShaderChunk[ "shadowmap_pars_fragment" ], - THREE.ShaderChunk[ "specularmap_pars_fragment" ], - THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], + if ( renderingShadows ) { + // there's no global clipping - "void main() {", + projectPlanes( null ); - " vec3 outgoingLight = vec3( 0.0 );", // outgoing light does not have an alpha, the surface does - " vec4 diffuseColor = vec4( diffuse, opacity );", + } else { - THREE.ShaderChunk[ "logdepthbuf_fragment" ], - THREE.ShaderChunk[ "map_fragment" ], - THREE.ShaderChunk[ "color_fragment" ], - THREE.ShaderChunk[ "alphamap_fragment" ], - THREE.ShaderChunk[ "alphatest_fragment" ], - THREE.ShaderChunk[ "specularmap_fragment" ], + resetGlobalState(); + } - " #ifdef DOUBLE_SIDED", + } else { - " if ( gl_FrontFacing )", - " outgoingLight += diffuseColor.rgb * vLightFront + emissive;", - " else", - " outgoingLight += diffuseColor.rgb * vLightBack + emissive;", + var nGlobal = renderingShadows ? 0 : numGlobalPlanes, + lGlobal = nGlobal * 4, - " #else", + dstArray = cache.clippingState || null; - " outgoingLight += diffuseColor.rgb * vLightFront + emissive;", + uniform.value = dstArray; // ensure unique state - " #endif", + dstArray = projectPlanes( planes, camera, lGlobal, fromCache ); - THREE.ShaderChunk[ "envmap_fragment" ], - THREE.ShaderChunk[ "shadowmap_fragment" ], + for ( var i = 0; i !== lGlobal; ++ i ) { - THREE.ShaderChunk[ "linear_to_gamma_fragment" ], + dstArray[ i ] = globalState[ i ]; - THREE.ShaderChunk[ "fog_fragment" ], + } - " gl_FragColor = vec4( outgoingLight, diffuseColor.a );", + cache.clippingState = dstArray; + this.numPlanes += nGlobal; - "}" + } - ].join( "\n" ) - }, + }; - 'phong': { + function resetGlobalState() { - uniforms: THREE.UniformsUtils.merge( [ + if ( uniform.value !== globalState ) { - THREE.UniformsLib[ "common" ], - THREE.UniformsLib[ "aomap" ], - THREE.UniformsLib[ "lightmap" ], - THREE.UniformsLib[ "emissivemap" ], - THREE.UniformsLib[ "bumpmap" ], - THREE.UniformsLib[ "normalmap" ], - THREE.UniformsLib[ "displacementmap" ], - THREE.UniformsLib[ "fog" ], - THREE.UniformsLib[ "lights" ], - THREE.UniformsLib[ "shadowmap" ], + uniform.value = globalState; + uniform.needsUpdate = numGlobalPlanes > 0; - { - "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) }, - "specular" : { type: "c", value: new THREE.Color( 0x111111 ) }, - "shininess": { type: "f", value: 30 } - } + } - ] ), + scope.numPlanes = numGlobalPlanes; - vertexShader: [ + } - "#define PHONG", + function projectPlanes( planes, camera, dstOffset, skipTransform ) { - "varying vec3 vViewPosition;", + var nPlanes = planes !== null ? planes.length : 0, + dstArray = null; - "#ifndef FLAT_SHADED", + if ( nPlanes !== 0 ) { - " varying vec3 vNormal;", + dstArray = uniform.value; - "#endif", + if ( skipTransform !== true || dstArray === null ) { - THREE.ShaderChunk[ "common" ], - THREE.ShaderChunk[ "uv_pars_vertex" ], - THREE.ShaderChunk[ "uv2_pars_vertex" ], - THREE.ShaderChunk[ "displacementmap_pars_vertex" ], - THREE.ShaderChunk[ "envmap_pars_vertex" ], - THREE.ShaderChunk[ "lights_phong_pars_vertex" ], - THREE.ShaderChunk[ "color_pars_vertex" ], - THREE.ShaderChunk[ "morphtarget_pars_vertex" ], - THREE.ShaderChunk[ "skinning_pars_vertex" ], - THREE.ShaderChunk[ "shadowmap_pars_vertex" ], - THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], + var flatSize = dstOffset + nPlanes * 4, + viewMatrix = camera.matrixWorldInverse; - "void main() {", + viewNormalMatrix.getNormalMatrix( viewMatrix ); - THREE.ShaderChunk[ "uv_vertex" ], - THREE.ShaderChunk[ "uv2_vertex" ], - THREE.ShaderChunk[ "color_vertex" ], + if ( dstArray === null || dstArray.length < flatSize ) { - THREE.ShaderChunk[ "beginnormal_vertex" ], - THREE.ShaderChunk[ "morphnormal_vertex" ], - THREE.ShaderChunk[ "skinbase_vertex" ], - THREE.ShaderChunk[ "skinnormal_vertex" ], - THREE.ShaderChunk[ "defaultnormal_vertex" ], + dstArray = new Float32Array( flatSize ); - "#ifndef FLAT_SHADED", // Normal computed with derivatives when FLAT_SHADED + } - " vNormal = normalize( transformedNormal );", + for ( var i = 0, i4 = dstOffset; + i !== nPlanes; ++ i, i4 += 4 ) { - "#endif", + plane.copy( planes[ i ] ). + applyMatrix4( viewMatrix, viewNormalMatrix ); - THREE.ShaderChunk[ "begin_vertex" ], - THREE.ShaderChunk[ "displacementmap_vertex" ], - THREE.ShaderChunk[ "morphtarget_vertex" ], - THREE.ShaderChunk[ "skinning_vertex" ], - THREE.ShaderChunk[ "project_vertex" ], - THREE.ShaderChunk[ "logdepthbuf_vertex" ], + plane.normal.toArray( dstArray, i4 ); + dstArray[ i4 + 3 ] = plane.constant; - " vViewPosition = - mvPosition.xyz;", + } - THREE.ShaderChunk[ "worldpos_vertex" ], - THREE.ShaderChunk[ "envmap_vertex" ], - THREE.ShaderChunk[ "lights_phong_vertex" ], - THREE.ShaderChunk[ "shadowmap_vertex" ], + } - "}" + uniform.value = dstArray; + uniform.needsUpdate = true; - ].join( "\n" ), + } - fragmentShader: [ + scope.numPlanes = nPlanes; + return dstArray; - "#define PHONG", + } - "uniform vec3 diffuse;", - "uniform vec3 emissive;", - "uniform vec3 specular;", - "uniform float shininess;", - "uniform float opacity;", + } - THREE.ShaderChunk[ "common" ], - THREE.ShaderChunk[ "color_pars_fragment" ], - THREE.ShaderChunk[ "uv_pars_fragment" ], - THREE.ShaderChunk[ "uv2_pars_fragment" ], - THREE.ShaderChunk[ "map_pars_fragment" ], - THREE.ShaderChunk[ "alphamap_pars_fragment" ], - THREE.ShaderChunk[ "aomap_pars_fragment" ], - THREE.ShaderChunk[ "lightmap_pars_fragment" ], - THREE.ShaderChunk[ "emissivemap_pars_fragment" ], - THREE.ShaderChunk[ "envmap_pars_fragment" ], - THREE.ShaderChunk[ "fog_pars_fragment" ], - THREE.ShaderChunk[ "lights_phong_pars_fragment" ], - THREE.ShaderChunk[ "shadowmap_pars_fragment" ], - THREE.ShaderChunk[ "bumpmap_pars_fragment" ], - THREE.ShaderChunk[ "normalmap_pars_fragment" ], - THREE.ShaderChunk[ "specularmap_pars_fragment" ], - THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], + /** + * @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 + */ - "void main() {", + function WebGLRenderer( parameters ) { - " vec3 outgoingLight = vec3( 0.0 );", - " vec4 diffuseColor = vec4( diffuse, opacity );", - " vec3 totalAmbientLight = ambientLightColor;", - " vec3 totalEmissiveLight = emissive;", + console.log( 'THREE.WebGLRenderer', REVISION ); - THREE.ShaderChunk[ "logdepthbuf_fragment" ], - THREE.ShaderChunk[ "map_fragment" ], - THREE.ShaderChunk[ "color_fragment" ], - THREE.ShaderChunk[ "alphamap_fragment" ], - THREE.ShaderChunk[ "alphatest_fragment" ], - THREE.ShaderChunk[ "specularmap_fragment" ], - THREE.ShaderChunk[ "lightmap_fragment" ], - THREE.ShaderChunk[ "aomap_fragment" ], - THREE.ShaderChunk[ "emissivemap_fragment" ], + parameters = parameters || {}; - THREE.ShaderChunk[ "lights_phong_fragment" ], + var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ), + _context = parameters.context !== undefined ? parameters.context : null, - THREE.ShaderChunk[ "envmap_fragment" ], - THREE.ShaderChunk[ "shadowmap_fragment" ], + _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; - THREE.ShaderChunk[ "linear_to_gamma_fragment" ], + var lights = []; - THREE.ShaderChunk[ "fog_fragment" ], + var opaqueObjects = []; + var opaqueObjectsLastIndex = - 1; + var transparentObjects = []; + var transparentObjectsLastIndex = - 1; - " gl_FragColor = vec4( outgoingLight, diffuseColor.a );", + var morphInfluences = new Float32Array( 8 ); - "}" + var sprites = []; + var lensFlares = []; - ].join( "\n" ) + // public properties - }, + this.domElement = _canvas; + this.context = null; - 'points': { + // clearing - uniforms: THREE.UniformsUtils.merge( [ + this.autoClear = true; + this.autoClearColor = true; + this.autoClearDepth = true; + this.autoClearStencil = true; - THREE.UniformsLib[ "points" ], - THREE.UniformsLib[ "shadowmap" ] + // scene graph - ] ), + this.sortObjects = true; - vertexShader: [ + // user-defined clipping - "uniform float size;", - "uniform float scale;", + this.clippingPlanes = []; + this.localClippingEnabled = false; - THREE.ShaderChunk[ "common" ], - THREE.ShaderChunk[ "color_pars_vertex" ], - THREE.ShaderChunk[ "shadowmap_pars_vertex" ], - THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], + // physically based shading - "void main() {", + this.gammaFactor = 2.0; // for backwards compatibility + this.gammaInput = false; + this.gammaOutput = false; - THREE.ShaderChunk[ "color_vertex" ], + // physical lights - " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );", + this.physicallyCorrectLights = false; - " #ifdef USE_SIZEATTENUATION", - " gl_PointSize = size * ( scale / length( mvPosition.xyz ) );", - " #else", - " gl_PointSize = size;", - " #endif", + // tone mapping - " gl_Position = projectionMatrix * mvPosition;", + this.toneMapping = LinearToneMapping; + this.toneMappingExposure = 1.0; + this.toneMappingWhitePoint = 1.0; - THREE.ShaderChunk[ "logdepthbuf_vertex" ], - THREE.ShaderChunk[ "worldpos_vertex" ], - THREE.ShaderChunk[ "shadowmap_vertex" ], + // morphs - "}" + this.maxMorphTargets = 8; + this.maxMorphNormals = 4; - ].join( "\n" ), + // internal properties - fragmentShader: [ + var _this = this, - "uniform vec3 psColor;", - "uniform float opacity;", + // internal state cache - THREE.ShaderChunk[ "common" ], - THREE.ShaderChunk[ "color_pars_fragment" ], - THREE.ShaderChunk[ "map_particle_pars_fragment" ], - THREE.ShaderChunk[ "fog_pars_fragment" ], - THREE.ShaderChunk[ "shadowmap_pars_fragment" ], - THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], + _currentProgram = null, + _currentRenderTarget = null, + _currentFramebuffer = null, + _currentMaterialId = - 1, + _currentGeometryProgram = '', + _currentCamera = null, - "void main() {", + _currentScissor = new Vector4(), + _currentScissorTest = null, - " vec3 outgoingLight = vec3( 0.0 );", - " vec4 diffuseColor = vec4( psColor, opacity );", + _currentViewport = new Vector4(), - THREE.ShaderChunk[ "logdepthbuf_fragment" ], - THREE.ShaderChunk[ "map_particle_fragment" ], - THREE.ShaderChunk[ "color_fragment" ], - THREE.ShaderChunk[ "alphatest_fragment" ], + // - " outgoingLight = diffuseColor.rgb;", // simple shader + _usedTextureUnits = 0, - THREE.ShaderChunk[ "shadowmap_fragment" ], - THREE.ShaderChunk[ "fog_fragment" ], + // - " gl_FragColor = vec4( outgoingLight, diffuseColor.a );", + _clearColor = new Color( 0x000000 ), + _clearAlpha = 0, - "}" + _width = _canvas.width, + _height = _canvas.height, - ].join( "\n" ) + _pixelRatio = 1, - }, + _scissor = new Vector4( 0, 0, _width, _height ), + _scissorTest = false, - 'dashed': { + _viewport = new Vector4( 0, 0, _width, _height ), - uniforms: THREE.UniformsUtils.merge( [ + // frustum - THREE.UniformsLib[ "common" ], - THREE.UniformsLib[ "fog" ], + _frustum = new Frustum(), - { - "scale" : { type: "f", value: 1 }, - "dashSize" : { type: "f", value: 1 }, - "totalSize": { type: "f", value: 2 } - } + // clipping - ] ), + _clipping = new WebGLClipping(), + _clippingEnabled = false, + _localClippingEnabled = false, - vertexShader: [ + _sphere = new Sphere(), - "uniform float scale;", - "attribute float lineDistance;", + // camera matrices cache - "varying float vLineDistance;", + _projScreenMatrix = new Matrix4(), - THREE.ShaderChunk[ "common" ], - THREE.ShaderChunk[ "color_pars_vertex" ], - THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], + _vector3 = new Vector3(), - "void main() {", + // light arrays cache - THREE.ShaderChunk[ "color_vertex" ], + _lights = { - " vLineDistance = scale * lineDistance;", + hash: '', - " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );", - " gl_Position = projectionMatrix * mvPosition;", + ambient: [ 0, 0, 0 ], + directional: [], + directionalShadowMap: [], + directionalShadowMatrix: [], + spot: [], + spotShadowMap: [], + spotShadowMatrix: [], + point: [], + pointShadowMap: [], + pointShadowMatrix: [], + hemi: [], - THREE.ShaderChunk[ "logdepthbuf_vertex" ], + shadows: [] - "}" + }, - ].join( "\n" ), + // info - fragmentShader: [ + _infoRender = { - "uniform vec3 diffuse;", - "uniform float opacity;", + calls: 0, + vertices: 0, + faces: 0, + points: 0 - "uniform float dashSize;", - "uniform float totalSize;", + }; - "varying float vLineDistance;", + this.info = { - THREE.ShaderChunk[ "common" ], - THREE.ShaderChunk[ "color_pars_fragment" ], - THREE.ShaderChunk[ "fog_pars_fragment" ], - THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], + render: _infoRender, + memory: { - "void main() {", + geometries: 0, + textures: 0 - " if ( mod( vLineDistance, totalSize ) > dashSize ) {", + }, + programs: null - " discard;", + }; - " }", - " vec3 outgoingLight = vec3( 0.0 );", - " vec4 diffuseColor = vec4( diffuse, opacity );", + // initialize - THREE.ShaderChunk[ "logdepthbuf_fragment" ], - THREE.ShaderChunk[ "color_fragment" ], + var _gl; - " outgoingLight = diffuseColor.rgb;", // simple shader + try { - THREE.ShaderChunk[ "fog_fragment" ], + var attributes = { + alpha: _alpha, + depth: _depth, + stencil: _stencil, + antialias: _antialias, + premultipliedAlpha: _premultipliedAlpha, + preserveDrawingBuffer: _preserveDrawingBuffer + }; - " gl_FragColor = vec4( outgoingLight, diffuseColor.a );", + _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes ); - "}" + if ( _gl === null ) { - ].join( "\n" ) + if ( _canvas.getContext( 'webgl' ) !== null ) { - }, + throw 'Error creating WebGL context with your selected attributes.'; - 'depth': { + } else { - uniforms: { + throw 'Error creating WebGL context.'; - "mNear": { type: "f", value: 1.0 }, - "mFar" : { type: "f", value: 2000.0 }, - "opacity" : { type: "f", value: 1.0 } + } - }, + } - vertexShader: [ + // Some experimental-webgl implementations do not have getShaderPrecisionFormat - THREE.ShaderChunk[ "common" ], - THREE.ShaderChunk[ "morphtarget_pars_vertex" ], - THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], + if ( _gl.getShaderPrecisionFormat === undefined ) { - "void main() {", + _gl.getShaderPrecisionFormat = function () { - THREE.ShaderChunk[ "begin_vertex" ], - THREE.ShaderChunk[ "morphtarget_vertex" ], - THREE.ShaderChunk[ "project_vertex" ], - THREE.ShaderChunk[ "logdepthbuf_vertex" ], + return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 }; - "}" + }; - ].join( "\n" ), + } - fragmentShader: [ + _canvas.addEventListener( 'webglcontextlost', onContextLost, false ); - "uniform float mNear;", - "uniform float mFar;", - "uniform float opacity;", + } catch ( error ) { - THREE.ShaderChunk[ "common" ], - THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], + console.error( 'THREE.WebGLRenderer: ' + error ); - "void main() {", + } - THREE.ShaderChunk[ "logdepthbuf_fragment" ], + var extensions = new WebGLExtensions( _gl ); - " #ifdef USE_LOGDEPTHBUF_EXT", + 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' ); - " float depth = gl_FragDepthEXT / gl_FragCoord.w;", + if ( extensions.get( 'OES_element_index_uint' ) ) { - " #else", + BufferGeometry.MaxIndex = 4294967296; - " float depth = gl_FragCoord.z / gl_FragCoord.w;", + } - " #endif", + var capabilities = new WebGLCapabilities( _gl, extensions, parameters ); - " float color = 1.0 - smoothstep( mNear, mFar, depth );", - " gl_FragColor = vec4( vec3( color ), opacity );", + 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; - ].join( "\n" ) + var bufferRenderer = new WebGLBufferRenderer( _gl, extensions, _infoRender ); + var indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, _infoRender ); - }, + // - 'normal': { + 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 = 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 + } ) + ); - uniforms: { + // - "opacity" : { type: "f", value: 1.0 } + function getTargetPixelRatio() { - }, + return _currentRenderTarget === null ? _pixelRatio : 1; - vertexShader: [ + } - "varying vec3 vNormal;", + function glClearColor( r, g, b, a ) { - THREE.ShaderChunk[ "common" ], - THREE.ShaderChunk[ "morphtarget_pars_vertex" ], - THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], + if ( _premultipliedAlpha === true ) { - "void main() {", + r *= a; g *= a; b *= a; - " vNormal = normalize( normalMatrix * normal );", + } - THREE.ShaderChunk[ "begin_vertex" ], - THREE.ShaderChunk[ "morphtarget_vertex" ], - THREE.ShaderChunk[ "project_vertex" ], - THREE.ShaderChunk[ "logdepthbuf_vertex" ], + state.clearColor( r, g, b, a ); - "}" + } - ].join( "\n" ), + function setDefaultGLState() { - fragmentShader: [ + state.init(); - "uniform float opacity;", - "varying vec3 vNormal;", + state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) ); + state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) ); - THREE.ShaderChunk[ "common" ], - THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], + glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); - "void main() {", + } - " gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );", + function resetGLState() { - THREE.ShaderChunk[ "logdepthbuf_fragment" ], + _currentProgram = null; + _currentCamera = null; - "}" + _currentGeometryProgram = ''; + _currentMaterialId = - 1; - ].join( "\n" ) + state.reset(); - }, + } - /* ------------------------------------------------------------------------- - // Cube map shader - ------------------------------------------------------------------------- */ + setDefaultGLState(); - 'cube': { + this.context = _gl; + this.capabilities = capabilities; + this.extensions = extensions; + this.properties = properties; + this.state = state; - uniforms: { "tCube": { type: "t", value: null }, - "tFlip": { type: "f", value: - 1 } }, + // shadow map - vertexShader: [ + var shadowMap = new WebGLShadowMap( this, _lights, objects, capabilities ); - "varying vec3 vWorldPosition;", + this.shadowMap = shadowMap; - THREE.ShaderChunk[ "common" ], - THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], - "void main() {", + // Plugins - " vWorldPosition = transformDirection( position, modelMatrix );", + var spritePlugin = new SpritePlugin( this, sprites ); + var lensFlarePlugin = new LensFlarePlugin( this, lensFlares ); - " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );", + // API - THREE.ShaderChunk[ "logdepthbuf_vertex" ], + this.getContext = function () { - "}" + return _gl; - ].join( "\n" ), + }; - fragmentShader: [ + this.getContextAttributes = function () { - "uniform samplerCube tCube;", - "uniform float tFlip;", + return _gl.getContextAttributes(); - "varying vec3 vWorldPosition;", + }; - THREE.ShaderChunk[ "common" ], - THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], + this.forceContextLoss = function () { - "void main() {", + extensions.get( 'WEBGL_lose_context' ).loseContext(); - " gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );", + }; - THREE.ShaderChunk[ "logdepthbuf_fragment" ], + this.getMaxAnisotropy = function () { - "}" + return capabilities.getMaxAnisotropy(); - ].join( "\n" ) + }; - }, + this.getPrecision = function () { - /* ------------------------------------------------------------------------- - // Cube map shader - ------------------------------------------------------------------------- */ + return capabilities.precision; - 'equirect': { + }; - uniforms: { "tEquirect": { type: "t", value: null }, - "tFlip": { type: "f", value: - 1 } }, + this.getPixelRatio = function () { - vertexShader: [ + return _pixelRatio; - "varying vec3 vWorldPosition;", + }; - THREE.ShaderChunk[ "common" ], - THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], + this.setPixelRatio = function ( value ) { - "void main() {", + if ( value === undefined ) return; - " vWorldPosition = transformDirection( position, modelMatrix );", + _pixelRatio = value; - " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );", + this.setSize( _viewport.z, _viewport.w, false ); - THREE.ShaderChunk[ "logdepthbuf_vertex" ], + }; - "}" + this.getSize = function () { - ].join( "\n" ), + return { + width: _width, + height: _height + }; - fragmentShader: [ + }; - "uniform sampler2D tEquirect;", - "uniform float tFlip;", + this.setSize = function ( width, height, updateStyle ) { - "varying vec3 vWorldPosition;", + _width = width; + _height = height; - THREE.ShaderChunk[ "common" ], - THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], + _canvas.width = width * _pixelRatio; + _canvas.height = height * _pixelRatio; - "void main() {", + if ( updateStyle !== false ) { - // " gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );", - "vec3 direction = normalize( vWorldPosition );", - "vec2 sampleUV;", - "sampleUV.y = saturate( tFlip * direction.y * -0.5 + 0.5 );", - "sampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;", - "gl_FragColor = texture2D( tEquirect, sampleUV );", + _canvas.style.width = width + 'px'; + _canvas.style.height = height + 'px'; - THREE.ShaderChunk[ "logdepthbuf_fragment" ], + } - "}" + this.setViewport( 0, 0, width, height ); - ].join( "\n" ) + }; - }, + this.setViewport = function ( x, y, width, height ) { - /* Depth encoding into RGBA texture - * - * based on SpiderGL shadow map example - * http://spidergl.org/example.php?id=6 - * - * originally from - * http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD - * - * see also - * http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/ - */ + state.viewport( _viewport.set( x, y, width, height ) ); - 'depthRGBA': { + }; - uniforms: {}, + this.setScissor = function ( x, y, width, height ) { - vertexShader: [ + state.scissor( _scissor.set( x, y, width, height ) ); - THREE.ShaderChunk[ "common" ], - THREE.ShaderChunk[ "morphtarget_pars_vertex" ], - THREE.ShaderChunk[ "skinning_pars_vertex" ], - THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ], + }; - "void main() {", + this.setScissorTest = function ( boolean ) { - THREE.ShaderChunk[ "skinbase_vertex" ], + state.setScissorTest( _scissorTest = boolean ); - THREE.ShaderChunk[ "begin_vertex" ], - THREE.ShaderChunk[ "morphtarget_vertex" ], - THREE.ShaderChunk[ "skinning_vertex" ], - THREE.ShaderChunk[ "project_vertex" ], - THREE.ShaderChunk[ "logdepthbuf_vertex" ], + }; - "}" + // Clearing - ].join( "\n" ), + this.getClearColor = function () { - fragmentShader: [ + return _clearColor; - THREE.ShaderChunk[ "common" ], - THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ], + }; - "vec4 pack_depth( const in float depth ) {", + this.setClearColor = function ( color, alpha ) { - " const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );", - " const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );", - " vec4 res = mod( depth * bit_shift * vec4( 255 ), vec4( 256 ) ) / vec4( 255 );", // " vec4 res = fract( depth * bit_shift );", - " res -= res.xxyz * bit_mask;", - " return res;", + _clearColor.set( color ); - "}", + _clearAlpha = alpha !== undefined ? alpha : 1; - "void main() {", + glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); - THREE.ShaderChunk[ "logdepthbuf_fragment" ], + }; - " #ifdef USE_LOGDEPTHBUF_EXT", + this.getClearAlpha = function () { - " gl_FragData[ 0 ] = pack_depth( gl_FragDepthEXT );", + return _clearAlpha; - " #else", + }; - " gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );", + this.setClearAlpha = function ( alpha ) { - " #endif", + _clearAlpha = alpha; - //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );", - //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );", - //"gl_FragData[ 0 ] = pack_depth( z );", - //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );", + glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); - "}" + }; - ].join( "\n" ) + this.clear = function ( color, depth, stencil ) { - } + 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; -// File:src/renderers/WebGLRenderer.js + _gl.clear( bits ); -/** - * @author supereggbert / http://www.paulbrunt.co.uk/ - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * @author szimek / https://github.com/szimek/ - */ + }; -THREE.WebGLRenderer = function ( parameters ) { + this.clearColor = function () { - console.log( 'THREE.WebGLRenderer', THREE.REVISION ); + this.clear( true, false, false ); - parameters = parameters || {}; + }; - var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ), - _context = parameters.context !== undefined ? parameters.context : null, + this.clearDepth = function () { - _width = _canvas.width, - _height = _canvas.height, + this.clear( false, true, false ); - pixelRatio = 1, + }; - _alpha = parameters.alpha !== undefined ? parameters.alpha : false, - _depth = parameters.depth !== undefined ? parameters.depth : true, - _stencil = parameters.stencil !== undefined ? parameters.stencil : true, - _antialias = parameters.antialias !== undefined ? parameters.antialias : false, - _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true, - _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false, + this.clearStencil = function () { - _clearColor = new THREE.Color( 0x000000 ), - _clearAlpha = 0; + this.clear( false, false, true ); - var lights = []; + }; - var opaqueObjects = []; - var opaqueObjectsLastIndex = -1; - var transparentObjects = []; - var transparentObjectsLastIndex = -1; + this.clearTarget = function ( renderTarget, color, depth, stencil ) { - var opaqueImmediateObjects = []; - var opaqueImmediateObjectsLastIndex = -1; - var transparentImmediateObjects = []; - var transparentImmediateObjectsLastIndex = -1; + this.setRenderTarget( renderTarget ); + this.clear( color, depth, stencil ); - var morphInfluences = new Float32Array( 8 ); + }; + // Reset - var sprites = []; - var lensFlares = []; + this.resetGLState = resetGLState; - // public properties + this.dispose = function() { - this.domElement = _canvas; - this.context = null; + transparentObjects = []; + transparentObjectsLastIndex = -1; + opaqueObjects = []; + opaqueObjectsLastIndex = -1; - // clearing + _canvas.removeEventListener( 'webglcontextlost', onContextLost, false ); - this.autoClear = true; - this.autoClearColor = true; - this.autoClearDepth = true; - this.autoClearStencil = true; + }; - // scene graph + // Events - this.sortObjects = true; + function onContextLost( event ) { - // physically based shading + event.preventDefault(); - this.gammaFactor = 2.0; // for backwards compatibility - this.gammaInput = false; - this.gammaOutput = false; + resetGLState(); + setDefaultGLState(); - // morphs + properties.clear(); - this.maxMorphTargets = 8; - this.maxMorphNormals = 4; + } - // flags + function onMaterialDispose( event ) { - this.autoScaleCubemaps = true; + var material = event.target; - // internal properties + material.removeEventListener( 'dispose', onMaterialDispose ); - var _this = this, + deallocateMaterial( material ); - // internal state cache + } - _currentProgram = null, - _currentFramebuffer = null, - _currentMaterialId = - 1, - _currentGeometryProgram = '', - _currentCamera = null, + // Buffer deallocation - _usedTextureUnits = 0, + function deallocateMaterial( material ) { - _viewportX = 0, - _viewportY = 0, - _viewportWidth = _canvas.width, - _viewportHeight = _canvas.height, - _currentWidth = 0, - _currentHeight = 0, + releaseMaterialProgramReference( material ); - // frustum + properties.delete( material ); - _frustum = new THREE.Frustum(), + } - // camera matrices cache - _projScreenMatrix = new THREE.Matrix4(), + function releaseMaterialProgramReference( material ) { - _vector3 = new THREE.Vector3(), + var programInfo = properties.get( material ).program; - // light arrays cache + material.program = undefined; - _direction = new THREE.Vector3(), + if ( programInfo !== undefined ) { - _lightsNeedUpdate = true, + programCache.releaseProgram( programInfo ); - _lights = { + } - ambient: [ 0, 0, 0 ], - directional: { length: 0, colors: [], positions: [] }, - point: { length: 0, colors: [], positions: [], distances: [], decays: [] }, - spot: { length: 0, colors: [], positions: [], distances: [], directions: [], anglesCos: [], exponents: [], decays: [] }, - hemi: { length: 0, skyColors: [], groundColors: [], positions: [] } + } - }, + // Buffer rendering - // info + this.renderBufferImmediate = function ( object, program, material ) { - _infoMemory = { + state.initAttributes(); - geometries: 0, - textures: 0 + var buffers = properties.get( object ); - }, + if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer(); + if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer(); + if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer(); + if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer(); - _infoRender = { + var attributes = program.getAttributes(); - calls: 0, - vertices: 0, - faces: 0, - points: 0 + if ( object.hasPositions ) { - }; + _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position ); + _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW ); - this.info = { + state.enableAttribute( attributes.position ); + _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 ); - render: _infoRender, - memory: _infoMemory, - programs: null + } - }; + if ( object.hasNormals ) { + _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal ); - // initialize + if ( ! material.isMeshPhongMaterial && + ! material.isMeshStandardMaterial && + material.shading === FlatShading ) { - var _gl; + for ( var i = 0, l = object.count * 3; i < l; i += 9 ) { - try { + var array = object.normalArray; - var attributes = { - alpha: _alpha, - depth: _depth, - stencil: _stencil, - antialias: _antialias, - premultipliedAlpha: _premultipliedAlpha, - preserveDrawingBuffer: _preserveDrawingBuffer - }; + 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; - _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes ); + array[ i + 0 ] = nx; + array[ i + 1 ] = ny; + array[ i + 2 ] = nz; - if ( _gl === null ) { + array[ i + 3 ] = nx; + array[ i + 4 ] = ny; + array[ i + 5 ] = nz; - if ( _canvas.getContext( 'webgl' ) !== null ) { + array[ i + 6 ] = nx; + array[ i + 7 ] = ny; + array[ i + 8 ] = nz; - throw 'Error creating WebGL context with your selected attributes.'; + } - } else { + } - throw 'Error creating WebGL context.'; + _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW ); - } + state.enableAttribute( attributes.normal ); - } + _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 ); - _canvas.addEventListener( 'webglcontextlost', onContextLost, false ); + } - } catch ( error ) { + if ( object.hasUvs && material.map ) { - console.error( 'THREE.WebGLRenderer: ' + error ); + _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv ); + _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW ); - } + state.enableAttribute( attributes.uv ); - var extensions = new THREE.WebGLExtensions( _gl ); + _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 ); - 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' ) ) { + if ( object.hasColors && material.vertexColors !== NoColors ) { - THREE.BufferGeometry.MaxIndex = 4294967296; + _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color ); + _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW ); - } + state.enableAttribute( attributes.color ); - var capabilities = new THREE.WebGLCapabilities( _gl, extensions, parameters ); + _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 ); - var state = new THREE.WebGLState( _gl, extensions, paramThreeToGL ); - var properties = new THREE.WebGLProperties(); - var objects = new THREE.WebGLObjects( _gl, properties, this.info ); - var programCache = new THREE.WebGLPrograms( this, capabilities ); + } - this.info.programs = programCache.programs; + state.disableUnusedAttributes(); - var bufferRenderer = new THREE.WebGLBufferRenderer( _gl, extensions, _infoRender ); - var indexedBufferRenderer = new THREE.WebGLIndexedBufferRenderer( _gl, extensions, _infoRender ); + _gl.drawArrays( _gl.TRIANGLES, 0, object.count ); - // + object.count = 0; - function glClearColor( r, g, b, a ) { + }; - if ( _premultipliedAlpha === true ) { + this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) { - r *= a; g *= a; b *= a; + setMaterial( material ); - } + var program = setProgram( camera, fog, material, object ); - _gl.clearColor( r, g, b, a ); + var updateBuffers = false; + var geometryProgram = geometry.id + '_' + program.id + '_' + material.wireframe; - } + if ( geometryProgram !== _currentGeometryProgram ) { - function setDefaultGLState() { + _currentGeometryProgram = geometryProgram; + updateBuffers = true; - state.init(); + } - _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight ); + // morph targets - glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); + var morphTargetInfluences = object.morphTargetInfluences; - } + if ( morphTargetInfluences !== undefined ) { - function resetGLState() { + var activeInfluences = []; - _currentProgram = null; - _currentCamera = null; + for ( var i = 0, l = morphTargetInfluences.length; i < l; i ++ ) { - _currentGeometryProgram = ''; - _currentMaterialId = - 1; + var influence = morphTargetInfluences[ i ]; + activeInfluences.push( [ influence, i ] ); - _lightsNeedUpdate = true; + } - state.reset(); + activeInfluences.sort( absNumericalSort ); - } + if ( activeInfluences.length > 8 ) { - setDefaultGLState(); + activeInfluences.length = 8; - this.context = _gl; - this.capabilities = capabilities; - this.extensions = extensions; - this.state = state; + } - // shadow map + var morphAttributes = geometry.morphAttributes; - var shadowMap = new THREE.WebGLShadowMap( this, lights, objects ); + for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) { - this.shadowMap = shadowMap; + var influence = activeInfluences[ i ]; + morphInfluences[ i ] = influence[ 0 ]; + if ( influence[ 0 ] !== 0 ) { - // Plugins + var index = influence[ 1 ]; - var spritePlugin = new THREE.SpritePlugin( this, sprites ); - var lensFlarePlugin = new THREE.LensFlarePlugin( this, lensFlares ); + 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 ] ); - // API + } else { - this.getContext = function () { + if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i ); + if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i ); - return _gl; + } - }; + } - this.getContextAttributes = function () { + for ( var i = activeInfluences.length, il = morphInfluences.length; i < il; i ++ ) { - return _gl.getContextAttributes(); + morphInfluences[ i ] = 0.0; - }; + } - this.forceContextLoss = function () { + program.getUniforms().setValue( + _gl, 'morphTargetInfluences', morphInfluences ); - extensions.get( 'WEBGL_lose_context' ).loseContext(); + updateBuffers = true; - }; + } - this.getMaxAnisotropy = ( function () { + // - var value; + var index = geometry.index; + var position = geometry.attributes.position; + var rangeFactor = 1; - return function getMaxAnisotropy() { + if ( material.wireframe === true ) { - if ( value !== undefined ) return value; + index = objects.getWireframeAttribute( geometry ); + rangeFactor = 2; - var extension = extensions.get( 'EXT_texture_filter_anisotropic' ); + } - if ( extension !== null ) { + var renderer; - value = _gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT ); + if ( index !== null ) { - } else { + renderer = indexedBufferRenderer; + renderer.setIndex( index ); - value = 0; + } else { - } + renderer = bufferRenderer; - return value; + } - } + if ( updateBuffers ) { - } )(); + setupVertexAttributes( material, program, geometry ); - this.getPrecision = function () { + if ( index !== null ) { - return capabilities.precision; + _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, objects.getAttributeBuffer( index ) ); - }; + } - this.getPixelRatio = function () { + } - return pixelRatio; + // - }; + var dataCount = 0; - this.setPixelRatio = function ( value ) { + if ( index !== null ) { - if ( value !== undefined ) pixelRatio = value; + dataCount = index.count; - }; + } else if ( position !== undefined ) { - this.getSize = function () { + dataCount = position.count; - return { - width: _width, - height: _height - }; + } - }; + var rangeStart = geometry.drawRange.start * rangeFactor; + var rangeCount = geometry.drawRange.count * rangeFactor; - this.setSize = function ( width, height, updateStyle ) { + var groupStart = group !== null ? group.start * rangeFactor : 0; + var groupCount = group !== null ? group.count * rangeFactor : Infinity; - _width = width; - _height = height; + var drawStart = Math.max( rangeStart, groupStart ); + var drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1; - _canvas.width = width * pixelRatio; - _canvas.height = height * pixelRatio; + var drawCount = Math.max( 0, drawEnd - drawStart + 1 ); - if ( updateStyle !== false ) { + if ( drawCount === 0 ) return; - _canvas.style.width = width + 'px'; - _canvas.style.height = height + 'px'; + // - } + if ( object.isMesh ) { - this.setViewport( 0, 0, width, height ); + if ( material.wireframe === true ) { - }; + state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() ); + renderer.setMode( _gl.LINES ); - this.setViewport = function ( x, y, width, height ) { + } else { - _viewportX = x * pixelRatio; - _viewportY = y * pixelRatio; + switch ( object.drawMode ) { - _viewportWidth = width * pixelRatio; - _viewportHeight = height * pixelRatio; + case TrianglesDrawMode: + renderer.setMode( _gl.TRIANGLES ); + break; - _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight ); + case TriangleStripDrawMode: + renderer.setMode( _gl.TRIANGLE_STRIP ); + break; - }; + case TriangleFanDrawMode: + renderer.setMode( _gl.TRIANGLE_FAN ); + break; - this.setScissor = function ( x, y, width, height ) { + } - _gl.scissor( - x * pixelRatio, - y * pixelRatio, - width * pixelRatio, - height * pixelRatio - ); + } - }; - this.enableScissorTest = function ( boolean ) { + } else if ( object.isLine ) { - state.setScissorTest( boolean ); + var lineWidth = material.linewidth; - }; + if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material - // Clearing + state.setLineWidth( lineWidth * getTargetPixelRatio() ); - this.getClearColor = function () { + if ( object.isLineSegments ) { - return _clearColor; + renderer.setMode( _gl.LINES ); - }; + } else { - this.setClearColor = function ( color, alpha ) { + renderer.setMode( _gl.LINE_STRIP ); - _clearColor.set( color ); + } - _clearAlpha = alpha !== undefined ? alpha : 1; + } else if ( object.isPoints ) { - glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); + renderer.setMode( _gl.POINTS ); - }; + } - this.getClearAlpha = function () { + if ( geometry && geometry.isInstancedBufferGeometry ) { - return _clearAlpha; + if ( geometry.maxInstancedCount > 0 ) { - }; + renderer.renderInstances( geometry, drawStart, drawCount ); - this.setClearAlpha = function ( alpha ) { + } - _clearAlpha = alpha; + } else { - glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); + renderer.render( drawStart, drawCount ); - }; + } - this.clear = function ( color, depth, stencil ) { + }; - var bits = 0; + function setupVertexAttributes( material, program, geometry, startIndex ) { - 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 extension; - _gl.clear( bits ); + if ( geometry && geometry.isInstancedBufferGeometry ) { - }; + extension = extensions.get( 'ANGLE_instanced_arrays' ); - this.clearColor = function () { + if ( extension === null ) { - _gl.clear( _gl.COLOR_BUFFER_BIT ); + console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); + return; - }; + } - this.clearDepth = function () { + } - _gl.clear( _gl.DEPTH_BUFFER_BIT ); + if ( startIndex === undefined ) startIndex = 0; - }; + state.initAttributes(); - this.clearStencil = function () { + var geometryAttributes = geometry.attributes; - _gl.clear( _gl.STENCIL_BUFFER_BIT ); + var programAttributes = program.getAttributes(); - }; + var materialDefaultAttributeValues = material.defaultAttributeValues; - this.clearTarget = function ( renderTarget, color, depth, stencil ) { + for ( var name in programAttributes ) { - this.setRenderTarget( renderTarget ); - this.clear( color, depth, stencil ); + var programAttribute = programAttributes[ name ]; - }; + if ( programAttribute >= 0 ) { - // Reset + var geometryAttribute = geometryAttributes[ name ]; - this.resetGLState = resetGLState; + if ( geometryAttribute !== undefined ) { - this.dispose = function() { + var type = _gl.FLOAT; + var array = geometryAttribute.array; + var normalized = geometryAttribute.normalized; - _canvas.removeEventListener( 'webglcontextlost', onContextLost, false ); + if ( array instanceof Float32Array ) { - }; + type = _gl.FLOAT; - // Events + } else if ( array instanceof Float64Array ) { - function onContextLost( event ) { + console.warn( "Unsupported data buffer format: Float64Array" ); - event.preventDefault(); + } else if ( array instanceof Uint16Array ) { - resetGLState(); - setDefaultGLState(); + type = _gl.UNSIGNED_SHORT; - properties.clear(); + } else if ( array instanceof Int16Array ) { - }; + type = _gl.SHORT; - function onTextureDispose( event ) { + } else if ( array instanceof Uint32Array ) { - var texture = event.target; + type = _gl.UNSIGNED_INT; - texture.removeEventListener( 'dispose', onTextureDispose ); + } else if ( array instanceof Int32Array ) { - deallocateTexture( texture ); + type = _gl.INT; - _infoMemory.textures --; + } else if ( array instanceof Int8Array ) { + type = _gl.BYTE; - } + } else if ( array instanceof Uint8Array ) { - function onRenderTargetDispose( event ) { + type = _gl.UNSIGNED_BYTE; - var renderTarget = event.target; + } - renderTarget.removeEventListener( 'dispose', onRenderTargetDispose ); + var size = geometryAttribute.itemSize; + var buffer = objects.getAttributeBuffer( geometryAttribute ); - deallocateRenderTarget( renderTarget ); + if ( geometryAttribute && geometryAttribute.isInterleavedBufferAttribute ) { - _infoMemory.textures --; + var data = geometryAttribute.data; + var stride = data.stride; + var offset = geometryAttribute.offset; - } + if ( data && data.isInstancedInterleavedBuffer ) { - function onMaterialDispose( event ) { + state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute, extension ); - var material = event.target; + if ( geometry.maxInstancedCount === undefined ) { - material.removeEventListener( 'dispose', onMaterialDispose ); + geometry.maxInstancedCount = data.meshPerAttribute * data.count; - deallocateMaterial( material ); + } - } + } else { - // Buffer deallocation + state.enableAttribute( programAttribute ); - function deallocateTexture( texture ) { + } - var textureProperties = properties.get( texture ); + _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 ( texture.image && textureProperties.__image__webglTextureCube ) { + } else { - // cube texture + if ( geometryAttribute && geometryAttribute.isInstancedBufferAttribute ) { - _gl.deleteTexture( textureProperties.__image__webglTextureCube ); + state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute, extension ); - } else { + if ( geometry.maxInstancedCount === undefined ) { - // 2D texture + geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count; - if ( textureProperties.__webglInit === undefined ) return; + } - _gl.deleteTexture( textureProperties.__webglTexture ); + } else { - } + state.enableAttribute( programAttribute ); - // remove all webgl properties - properties.delete( texture ); + } - } + _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer ); + _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, startIndex * size * geometryAttribute.array.BYTES_PER_ELEMENT ); - function deallocateRenderTarget( renderTarget ) { + } - var renderTargetProperties = properties.get( renderTarget ); + } else if ( materialDefaultAttributeValues !== undefined ) { - if ( ! renderTarget || renderTargetProperties.__webglTexture === undefined ) return; + var value = materialDefaultAttributeValues[ name ]; - _gl.deleteTexture( renderTargetProperties.__webglTexture ); + if ( value !== undefined ) { - if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) { + switch ( value.length ) { - for ( var i = 0; i < 6; i ++ ) { + case 2: + _gl.vertexAttrib2fv( programAttribute, value ); + break; - _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] ); - _gl.deleteRenderbuffer( renderTargetProperties.__webglRenderbuffer[ i ] ); + case 3: + _gl.vertexAttrib3fv( programAttribute, value ); + break; - } + case 4: + _gl.vertexAttrib4fv( programAttribute, value ); + break; - } else { + default: + _gl.vertexAttrib1fv( programAttribute, value ); - _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer ); - _gl.deleteRenderbuffer( renderTargetProperties.__webglRenderbuffer ); + } - } + } - properties.delete( renderTarget ); + } - } + } - function deallocateMaterial( material ) { + } - releaseMaterialProgramReference( material ); + state.disableUnusedAttributes(); - properties.delete( material ); + } - } + // Sorting + function absNumericalSort( a, b ) { - function releaseMaterialProgramReference( material ) { + return Math.abs( b[ 0 ] ) - Math.abs( a[ 0 ] ); - var programInfo = properties.get( material ).program; + } - material.program = undefined; + function painterSortStable( a, b ) { - if ( programInfo !== undefined ) { + if ( a.object.renderOrder !== b.object.renderOrder ) { - programCache.releaseProgram( programInfo ); - } + return a.object.renderOrder - b.object.renderOrder; - } + } else if ( a.material.program && b.material.program && a.material.program !== b.material.program ) { - // Buffer rendering + return a.material.program.id - b.material.program.id; - this.renderBufferImmediate = function ( object, program, material ) { + } else if ( a.material.id !== b.material.id ) { - state.initAttributes(); + return a.material.id - b.material.id; - var buffers = properties.get( object ); + } else if ( a.z !== b.z ) { - 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(); + return a.z - b.z; - var attributes = program.getAttributes(); + } else { - if ( object.hasPositions ) { + return a.id - b.id; - _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 ); + } - } + function reversePainterSortStable( a, b ) { - if ( object.hasNormals ) { + if ( a.object.renderOrder !== b.object.renderOrder ) { - _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal ); + return a.object.renderOrder - b.object.renderOrder; - if ( material.type !== 'MeshPhongMaterial' && material.shading === THREE.FlatShading ) { + } if ( a.z !== b.z ) { - for ( var i = 0, l = object.count * 3; i < l; i += 9 ) { + return b.z - a.z; - var array = object.normalArray; + } else { - 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; + return a.id - b.id; - array[ i + 0 ] = nx; - array[ i + 1 ] = ny; - array[ i + 2 ] = nz; + } - array[ i + 3 ] = nx; - array[ i + 4 ] = ny; - array[ i + 5 ] = nz; + } - array[ i + 6 ] = nx; - array[ i + 7 ] = ny; - array[ i + 8 ] = nz; + // Rendering - } + this.render = function ( scene, camera, renderTarget, forceClear ) { - } + if ( camera !== undefined && camera.isCamera !== true ) { - _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW ); + console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' ); + return; - state.enableAttribute( attributes.normal ); + } - _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 ); + var fog = scene.fog; - } + // reset caching for this frame - if ( object.hasUvs && material.map ) { + _currentGeometryProgram = ''; + _currentMaterialId = - 1; + _currentCamera = null; - _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv ); - _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW ); + // update scene graph - state.enableAttribute( attributes.uv ); + if ( scene.autoUpdate === true ) scene.updateMatrixWorld(); - _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 ); + // update camera matrices and frustum - } + if ( camera.parent === null ) camera.updateMatrixWorld(); - if ( object.hasColors && material.vertexColors !== THREE.NoColors ) { + camera.matrixWorldInverse.getInverse( camera.matrixWorld ); - _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color ); - _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW ); + _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); + _frustum.setFromMatrix( _projScreenMatrix ); - state.enableAttribute( attributes.color ); + lights.length = 0; - _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 ); + opaqueObjectsLastIndex = - 1; + transparentObjectsLastIndex = - 1; - } + sprites.length = 0; + lensFlares.length = 0; - state.disableUnusedAttributes(); + _localClippingEnabled = this.localClippingEnabled; + _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera ); - _gl.drawArrays( _gl.TRIANGLES, 0, object.count ); + projectObject( scene, camera ); - object.count = 0; + opaqueObjects.length = opaqueObjectsLastIndex + 1; + transparentObjects.length = transparentObjectsLastIndex + 1; - }; + if ( _this.sortObjects === true ) { - this.renderBufferDirect = function ( camera, lights, fog, geometry, material, object, group ) { + opaqueObjects.sort( painterSortStable ); + transparentObjects.sort( reversePainterSortStable ); - setMaterial( material ); + } - var program = setProgram( camera, lights, fog, material, object ); + // - var updateBuffers = false; - var geometryProgram = geometry.id + '_' + program.id + '_' + material.wireframe; + if ( _clippingEnabled ) _clipping.beginShadows(); - if ( geometryProgram !== _currentGeometryProgram ) { + setupShadows( lights ); - _currentGeometryProgram = geometryProgram; - updateBuffers = true; + shadowMap.render( scene, camera ); - } + setupLights( lights, camera ); - // morph targets + if ( _clippingEnabled ) _clipping.endShadows(); - var morphTargetInfluences = object.morphTargetInfluences; + // - if ( morphTargetInfluences !== undefined ) { + _infoRender.calls = 0; + _infoRender.vertices = 0; + _infoRender.faces = 0; + _infoRender.points = 0; - var activeInfluences = []; + if ( renderTarget === undefined ) { - for ( var i = 0, l = morphTargetInfluences.length; i < l; i ++ ) { + renderTarget = null; - var influence = morphTargetInfluences[ i ]; - activeInfluences.push( [ influence, i ] ); + } - } + this.setRenderTarget( renderTarget ); - activeInfluences.sort( numericalSort ); + // - if ( activeInfluences.length > 8 ) { + var background = scene.background; - activeInfluences.length = 8; + if ( background === null ) { - } + glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); - var morphAttributes = geometry.morphAttributes; + } else if ( background && background.isColor ) { - for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) { + glClearColor( background.r, background.g, background.b, 1 ); + forceClear = true; - var influence = activeInfluences[ i ]; - morphInfluences[ i ] = influence[ 0 ]; + } - if ( influence[ 0 ] !== 0 ) { + if ( this.autoClear || forceClear ) { - var index = influence[ 1 ]; + this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil ); - 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 ( background && background.isCubeTexture ) { - if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i ); - if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i ); + backgroundCamera2.projectionMatrix.copy( camera.projectionMatrix ); - } + backgroundCamera2.matrixWorld.extractRotation( camera.matrixWorld ); + backgroundCamera2.matrixWorldInverse.getInverse( backgroundCamera2.matrixWorld ); - } + backgroundBoxMesh.material.uniforms[ "tCube" ].value = background; + backgroundBoxMesh.modelViewMatrix.multiplyMatrices( backgroundCamera2.matrixWorldInverse, backgroundBoxMesh.matrixWorld ); - var uniforms = program.getUniforms(); + objects.update( backgroundBoxMesh ); - if ( uniforms.morphTargetInfluences !== null ) { + _this.renderBufferDirect( backgroundCamera2, null, backgroundBoxMesh.geometry, backgroundBoxMesh.material, backgroundBoxMesh, null ); - _gl.uniform1fv( uniforms.morphTargetInfluences, morphInfluences ); + } else if ( background && background.isTexture ) { - } + backgroundPlaneMesh.material.map = background; - updateBuffers = true; + objects.update( backgroundPlaneMesh ); - } + _this.renderBufferDirect( backgroundCamera, null, backgroundPlaneMesh.geometry, backgroundPlaneMesh.material, backgroundPlaneMesh, null ); - // + } - var index = geometry.index; - var position = geometry.attributes.position; + // - if ( material.wireframe === true ) { + if ( scene.overrideMateri