瀏覽代碼

Merge pull request #5 from mrdoob/dev

Update
Temdog007 6 年之前
父節點
當前提交
79f772152e

+ 0 - 0
examples/js/TypedArrayUtils.js → examples/js/utils/TypedArrayUtils.js


+ 8 - 8
examples/jsm/controls/MapControls.js

@@ -7,14 +7,6 @@
  * @author moroine / https://github.com/moroine
  */
 
-// This set of controls performs orbiting, dollying (zooming), and panning.
-// Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
-// This is very similar to OrbitControls, another set of touch behavior
-//
-//    Orbit - right mouse, or left mouse + ctrl/meta/shiftKey / touch: two-finger rotate
-//    Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
-//    Pan - left mouse, or arrow keys / touch: one-finger move
-
 import {
 	EventDispatcher,
 	MOUSE,
@@ -24,6 +16,14 @@ import {
 	Vector3
 } from "../../../build/three.module.js";
 
+// This set of controls performs orbiting, dollying (zooming), and panning.
+// Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
+// This is very similar to OrbitControls, another set of touch behavior
+//
+//    Orbit - right mouse, or left mouse + ctrl/meta/shiftKey / touch: two-finger rotate
+//    Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
+//    Pan - left mouse, or arrow keys / touch: one-finger move
+
 var MapControls = function ( object, domElement ) {
 
 	this.object = object;

+ 7 - 7
examples/jsm/controls/OrbitControls.js

@@ -6,13 +6,6 @@
  * @author erich666 / http://erichaines.com
  */
 
-// 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 left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move
-
 import {
 	EventDispatcher,
 	MOUSE,
@@ -22,6 +15,13 @@ import {
 	Vector3
 } from "../../../build/three.module.js";
 
+// 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 left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move
+
 var OrbitControls = function ( object, domElement ) {
 
 	this.object = object;

+ 635 - 0
examples/jsm/exporters/ColladaExporter.js

@@ -0,0 +1,635 @@
+/**
+ * @author Garrett Johnson / http://gkjohnson.github.io/
+ * https://github.com/gkjohnson/collada-exporter-js
+ *
+ * Usage:
+ *  var exporter = new ColladaExporter();
+ *
+ *  var data = exporter.parse(mesh);
+ *
+ * Format Definition:
+ *  https://www.khronos.org/collada/
+ */
+
+import {
+	BufferGeometry,
+	Color,
+	DoubleSide,
+	Geometry,
+	Matrix4,
+	Mesh,
+	MeshBasicMaterial,
+	MeshLambertMaterial
+} from "../../../build/three.module.js";
+
+var ColladaExporter = function () {};
+
+ColladaExporter.prototype = {
+
+	constructor: ColladaExporter,
+
+	parse: function ( object, onDone, options = {} ) {
+
+		options = Object.assign( {
+			version: '1.4.1',
+			author: null,
+			textureDirectory: '',
+		}, options );
+
+		if ( options.textureDirectory !== '' ) {
+
+			options.textureDirectory = `${ options.textureDirectory }/`
+				.replace( /\\/g, '/' )
+				.replace( /\/+/g, '/' );
+
+		}
+
+		var version = options.version;
+		if ( version !== '1.4.1' && version !== '1.5.0' ) {
+
+			console.warn( `ColladaExporter : Version ${ version } not supported for export. Only 1.4.1 and 1.5.0.` );
+			return null;
+
+		}
+
+		// Convert the urdf xml into a well-formatted, indented format
+		function format( urdf ) {
+
+			var IS_END_TAG = /^<\//;
+			var IS_SELF_CLOSING = /(\?>$)|(\/>$)/;
+			var HAS_TEXT = /<[^>]+>[^<]*<\/[^<]+>/;
+
+			var pad = ( ch, num ) => ( num > 0 ? ch + pad( ch, num - 1 ) : '' );
+
+			var tagnum = 0;
+			return urdf
+				.match( /(<[^>]+>[^<]+<\/[^<]+>)|(<[^>]+>)/g )
+				.map( tag => {
+
+					if ( ! HAS_TEXT.test( tag ) && ! IS_SELF_CLOSING.test( tag ) && IS_END_TAG.test( tag ) ) {
+
+						tagnum --;
+
+					}
+
+					var res = `${ pad( '  ', tagnum ) }${ tag }`;
+
+					if ( ! HAS_TEXT.test( tag ) && ! IS_SELF_CLOSING.test( tag ) && ! IS_END_TAG.test( tag ) ) {
+
+						tagnum ++;
+
+					}
+
+					return res;
+
+				} )
+				.join( '\n' );
+
+		}
+
+		// Convert an image into a png format for saving
+		function base64ToBuffer( str ) {
+
+			var b = atob( str );
+			var buf = new Uint8Array( b.length );
+
+			for ( var i = 0, l = buf.length; i < l; i ++ ) {
+
+				buf[ i ] = b.charCodeAt( i );
+
+			}
+
+			return buf;
+
+		}
+
+		var canvas, ctx;
+		function imageToData( image, ext ) {
+
+			canvas = canvas || document.createElement( 'canvas' );
+			ctx = ctx || canvas.getContext( '2d' );
+
+			canvas.width = image.naturalWidth;
+			canvas.height = image.naturalHeight;
+
+			ctx.drawImage( image, 0, 0 );
+
+			// Get the base64 encoded data
+			var base64data = canvas
+				.toDataURL( `image/${ ext }`, 1 )
+				.replace( /^data:image\/(png|jpg);base64,/, '' );
+
+			// Convert to a uint8 array
+			return base64ToBuffer( base64data );
+
+		}
+
+		// gets the attribute array. Generate a new array if the attribute is interleaved
+		var getFuncs = [ 'getX', 'getY', 'getZ', 'getW' ];
+		function attrBufferToArray( attr ) {
+
+			if ( attr.isInterleavedBufferAttribute ) {
+
+				// use the typed array constructor to save on memory
+				var arr = new attr.array.constructor( attr.count * attr.itemSize );
+				var size = attr.itemSize;
+				for ( var i = 0, l = attr.count; i < l; i ++ ) {
+
+					for ( var j = 0; j < size; j ++ ) {
+
+						arr[ i * size + j ] = attr[ getFuncs[ j ] ]( i );
+
+					}
+
+				}
+
+				return arr;
+
+			} else {
+
+				return attr.array;
+
+			}
+
+		}
+
+		// Returns an array of the same type starting at the `st` index,
+		// and `ct` length
+		function subArray( arr, st, ct ) {
+
+			if ( Array.isArray( arr ) ) return arr.slice( st, st + ct );
+			else return new arr.constructor( arr.buffer, st * arr.BYTES_PER_ELEMENT, ct );
+
+		}
+
+		// Returns the string for a geometry's attribute
+		function getAttribute( attr, name, params, type ) {
+
+			var array = attrBufferToArray( attr );
+			var res =
+					`<source id="${ name }">` +
+
+					`<float_array id="${ name }-array" count="${ array.length }">` +
+					array.join( ' ' ) +
+					'</float_array>' +
+
+					'<technique_common>' +
+					`<accessor source="#${ name }-array" count="${ Math.floor( array.length / attr.itemSize ) }" stride="${ attr.itemSize }">` +
+
+					params.map( n => `<param name="${ n }" type="${ type }" />` ).join( '' ) +
+
+					'</accessor>' +
+					'</technique_common>' +
+					'</source>';
+
+			return res;
+
+		}
+
+		// Returns the string for a node's transform information
+		var transMat;
+		function getTransform( o ) {
+
+			// ensure the object's matrix is up to date
+			// before saving the transform
+			o.updateMatrix();
+
+			transMat = transMat || new Matrix4();
+			transMat.copy( o.matrix );
+			transMat.transpose();
+			return `<matrix>${ transMat.toArray().join( ' ' ) }</matrix>`;
+
+		}
+
+		// Process the given piece of geometry into the geometry library
+		// Returns the mesh id
+		function processGeometry( g ) {
+
+			var info = geometryInfo.get( g );
+
+			if ( ! info ) {
+
+				// convert the geometry to bufferGeometry if it isn't already
+				var bufferGeometry = g;
+				if ( bufferGeometry instanceof Geometry ) {
+
+					bufferGeometry = ( new BufferGeometry() ).fromGeometry( bufferGeometry );
+
+				}
+
+				var meshid = `Mesh${ libraryGeometries.length + 1 }`;
+
+				var indexCount =
+					bufferGeometry.index ?
+						bufferGeometry.index.count * bufferGeometry.index.itemSize :
+						bufferGeometry.attributes.position.count;
+
+				var groups =
+					bufferGeometry.groups != null && bufferGeometry.groups.length !== 0 ?
+						bufferGeometry.groups :
+						[ { start: 0, count: indexCount, materialIndex: 0 } ];
+
+				var gnode = `<geometry id="${ meshid }" name="${ g.name }"><mesh>`;
+
+				// define the geometry node and the vertices for the geometry
+				var posName = `${ meshid }-position`;
+				var vertName = `${ meshid }-vertices`;
+				gnode += getAttribute( bufferGeometry.attributes.position, posName, [ 'X', 'Y', 'Z' ], 'float' );
+				gnode += `<vertices id="${ vertName }"><input semantic="POSITION" source="#${ posName }" /></vertices>`;
+
+				// NOTE: We're not optimizing the attribute arrays here, so they're all the same length and
+				// can therefore share the same triangle indices. However, MeshLab seems to have trouble opening
+				// models with attributes that share an offset.
+				// MeshLab Bug#424: https://sourceforge.net/p/meshlab/bugs/424/
+
+				// serialize normals
+				var triangleInputs = `<input semantic="VERTEX" source="#${ vertName }" offset="0" />`;
+				if ( 'normal' in bufferGeometry.attributes ) {
+
+					var normName = `${ meshid }-normal`;
+					gnode += getAttribute( bufferGeometry.attributes.normal, normName, [ 'X', 'Y', 'Z' ], 'float' );
+					triangleInputs += `<input semantic="NORMAL" source="#${ normName }" offset="0" />`;
+
+				}
+
+				// serialize uvs
+				if ( 'uv' in bufferGeometry.attributes ) {
+
+					var uvName = `${ meshid }-texcoord`;
+					gnode += getAttribute( bufferGeometry.attributes.uv, uvName, [ 'S', 'T' ], 'float' );
+					triangleInputs += `<input semantic="TEXCOORD" source="#${ uvName }" offset="0" set="0" />`;
+
+				}
+
+				// serialize colors
+				if ( 'color' in bufferGeometry.attributes ) {
+
+					var colName = `${ meshid }-color`;
+					gnode += getAttribute( bufferGeometry.attributes.color, colName, [ 'X', 'Y', 'Z' ], 'uint8' );
+					triangleInputs += `<input semantic="COLOR" source="#${ colName }" offset="0" />`;
+
+				}
+
+				var indexArray = null;
+				if ( bufferGeometry.index ) {
+
+					indexArray = attrBufferToArray( bufferGeometry.index );
+
+				} else {
+
+					indexArray = new Array( indexCount );
+					for ( var i = 0, l = indexArray.length; i < l; i ++ ) indexArray[ i ] = i;
+
+				}
+
+				for ( var i = 0, l = groups.length; i < l; i ++ ) {
+
+					var group = groups[ i ];
+					var subarr = subArray( indexArray, group.start, group.count );
+					var polycount = subarr.length / 3;
+					gnode += `<triangles material="MESH_MATERIAL_${ group.materialIndex }" count="${ polycount }">`;
+					gnode += triangleInputs;
+
+					gnode += `<p>${ subarr.join( ' ' ) }</p>`;
+					gnode += '</triangles>';
+
+				}
+
+				gnode += `</mesh></geometry>`;
+
+				libraryGeometries.push( gnode );
+
+				info = { meshid: meshid, bufferGeometry: bufferGeometry };
+				geometryInfo.set( g, info );
+
+			}
+
+			return info;
+
+		}
+
+		// Process the given texture into the image library
+		// Returns the image library
+		function processTexture( tex ) {
+
+			var texid = imageMap.get( tex );
+			if ( texid == null ) {
+
+				texid = `image-${ libraryImages.length + 1 }`;
+
+				var ext = 'png';
+				var name = tex.name || texid;
+				var imageNode = `<image id="${ texid }" name="${ name }">`;
+
+				if ( version === '1.5.0' ) {
+
+					imageNode += `<init_from><ref>${ options.textureDirectory }${ name }.${ ext }</ref></init_from>`;
+
+				} else {
+
+					// version image node 1.4.1
+					imageNode += `<init_from>${ options.textureDirectory }${ name }.${ ext }</init_from>`;
+
+				}
+
+				imageNode += '</image>';
+
+				libraryImages.push( imageNode );
+				imageMap.set( tex, texid );
+				textures.push( {
+					directory: options.textureDirectory,
+					name,
+					ext,
+					data: imageToData( tex.image, ext ),
+					original: tex
+				} );
+
+			}
+
+			return texid;
+
+		}
+
+		// Process the given material into the material and effect libraries
+		// Returns the material id
+		function processMaterial( m ) {
+
+			var matid = materialMap.get( m );
+
+			if ( matid == null ) {
+
+				matid = `Mat${ libraryEffects.length + 1 }`;
+
+				var type = 'phong';
+
+				if ( m instanceof MeshLambertMaterial ) {
+
+					type = 'lambert';
+
+				} else if ( m instanceof MeshBasicMaterial ) {
+
+					type = 'constant';
+
+					if ( m.map !== null ) {
+
+						// The Collada spec does not support diffuse texture maps with the
+						// constant shader type.
+						// mrdoob/three.js#15469
+						console.warn( 'ColladaExporter: Texture maps not supported with MeshBasicMaterial.' );
+
+					}
+
+				}
+
+				var emissive = m.emissive ? m.emissive : new Color( 0, 0, 0 );
+				var diffuse = m.color ? m.color : new Color( 0, 0, 0 );
+				var specular = m.specular ? m.specular : new Color( 1, 1, 1 );
+				var shininess = m.shininess || 0;
+				var reflectivity = m.reflectivity || 0;
+
+				// Do not export and alpha map for the reasons mentioned in issue (#13792)
+				// in THREE.js alpha maps are black and white, but collada expects the alpha
+				// channel to specify the transparency
+				var transparencyNode = '';
+				if ( m.transparent === true ) {
+
+					transparencyNode +=
+						`<transparent>` +
+						(
+							m.map ?
+								`<texture texture="diffuse-sampler"></texture>` :
+								'<float>1</float>'
+						) +
+						'</transparent>';
+
+					if ( m.opacity < 1 ) {
+
+						transparencyNode += `<transparency><float>${ m.opacity }</float></transparency>`;
+
+					}
+
+				}
+
+				var techniqueNode = `<technique sid="common"><${ type }>` +
+
+					'<emission>' +
+
+					(
+						m.emissiveMap ?
+							'<texture texture="emissive-sampler" texcoord="TEXCOORD" />' :
+							`<color sid="emission">${ emissive.r } ${ emissive.g } ${ emissive.b } 1</color>`
+					) +
+
+					'</emission>' +
+
+					(
+						type !== 'constant' ?
+						'<diffuse>' +
+
+						(
+							m.map ?
+								'<texture texture="diffuse-sampler" texcoord="TEXCOORD" />' :
+								`<color sid="diffuse">${ diffuse.r } ${ diffuse.g } ${ diffuse.b } 1</color>`
+						) +
+						'</diffuse>'
+						: ''
+					) +
+
+					(
+						type === 'phong' ?
+						`<specular><color sid="specular">${ specular.r } ${ specular.g } ${ specular.b } 1</color></specular>` +
+
+						'<shininess>' +
+
+						(
+							m.specularMap ?
+								'<texture texture="specular-sampler" texcoord="TEXCOORD" />' :
+								`<float sid="shininess">${ shininess }</float>`
+						) +
+
+						'</shininess>'
+						: ''
+					) +
+
+					`<reflective><color>${ diffuse.r } ${ diffuse.g } ${ diffuse.b } 1</color></reflective>` +
+
+					`<reflectivity><float>${ reflectivity }</float></reflectivity>` +
+
+					transparencyNode +
+
+					`</${ type }></technique>`;
+
+				var effectnode =
+					`<effect id="${ matid }-effect">` +
+					'<profile_COMMON>' +
+
+					(
+						m.map ?
+							'<newparam sid="diffuse-surface"><surface type="2D">' +
+							`<init_from>${ processTexture( m.map ) }</init_from>` +
+							'</surface></newparam>' +
+							'<newparam sid="diffuse-sampler"><sampler2D><source>diffuse-surface</source></sampler2D></newparam>' :
+							''
+					) +
+
+					(
+						m.specularMap ?
+							'<newparam sid="specular-surface"><surface type="2D">' +
+							`<init_from>${ processTexture( m.specularMap ) }</init_from>` +
+							'</surface></newparam>' +
+							'<newparam sid="specular-sampler"><sampler2D><source>specular-surface</source></sampler2D></newparam>' :
+							''
+					) +
+
+					(
+						m.emissiveMap ?
+							'<newparam sid="emissive-surface"><surface type="2D">' +
+							`<init_from>${ processTexture( m.emissiveMap ) }</init_from>` +
+							'</surface></newparam>' +
+							'<newparam sid="emissive-sampler"><sampler2D><source>emissive-surface</source></sampler2D></newparam>' :
+							''
+					) +
+
+					techniqueNode +
+
+					(
+						m.side === DoubleSide ?
+							`<extra><technique><double_sided sid="double_sided" type="int">1</double_sided></technique></extra>` :
+							''
+					) +
+
+					'</profile_COMMON>' +
+
+					'</effect>';
+
+				libraryMaterials.push( `<material id="${ matid }" name="${ m.name }"><instance_effect url="#${ matid }-effect" /></material>` );
+				libraryEffects.push( effectnode );
+				materialMap.set( m, matid );
+
+			}
+
+			return matid;
+
+		}
+
+		// Recursively process the object into a scene
+		function processObject( o ) {
+
+			var node = `<node name="${ o.name }">`;
+
+			node += getTransform( o );
+
+			if ( o instanceof Mesh && o.geometry != null ) {
+
+				// function returns the id associated with the mesh and a "BufferGeometry" version
+				// of the geometry in case it's not a geometry.
+				var geomInfo = processGeometry( o.geometry );
+				var meshid = geomInfo.meshid;
+				var geometry = geomInfo.bufferGeometry;
+
+				// ids of the materials to bind to the geometry
+				var matids = null;
+				var matidsArray = [];
+
+				// get a list of materials to bind to the sub groups of the geometry.
+				// If the amount of subgroups is greater than the materials, than reuse
+				// the materials.
+				var mat = o.material || new MeshBasicMaterial();
+				var materials = Array.isArray( mat ) ? mat : [ mat ];
+				if ( geometry.groups.length > materials.length ) {
+					matidsArray = new Array( geometry.groups.length );
+				} else {
+					matidsArray = new Array( materials.length )
+				}
+				matids = matidsArray.fill()
+					.map( ( v, i ) => processMaterial( materials[ i % materials.length ] ) );
+
+				node +=
+					`<instance_geometry url="#${ meshid }">` +
+
+					(
+						matids != null ?
+							'<bind_material><technique_common>' +
+							matids.map( ( id, i ) =>
+
+								`<instance_material symbol="MESH_MATERIAL_${ i }" target="#${ id }" >` +
+
+								'<bind_vertex_input semantic="TEXCOORD" input_semantic="TEXCOORD" input_set="0" />' +
+
+								'</instance_material>'
+							).join( '' ) +
+							'</technique_common></bind_material>' :
+							''
+					) +
+
+					'</instance_geometry>';
+
+			}
+
+			o.children.forEach( c => node += processObject( c ) );
+
+			node += '</node>';
+
+			return node;
+
+		}
+
+		var geometryInfo = new WeakMap();
+		var materialMap = new WeakMap();
+		var imageMap = new WeakMap();
+		var textures = [];
+
+		var libraryImages = [];
+		var libraryGeometries = [];
+		var libraryEffects = [];
+		var libraryMaterials = [];
+		var libraryVisualScenes = processObject( object );
+
+		var specLink = version === '1.4.1' ? 'http://www.collada.org/2005/11/COLLADASchema' : 'https://www.khronos.org/collada/';
+		var dae =
+			'<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' +
+			`<COLLADA xmlns="${ specLink }" version="${ version }">` +
+			'<asset>' +
+			(
+				'<contributor>' +
+				'<authoring_tool>THREE.js Collada Exporter</authoring_tool>' +
+				( options.author !== null ? `<author>${ options.author }</author>` : '' ) +
+				'</contributor>' +
+				`<created>${ ( new Date() ).toISOString() }</created>` +
+				`<modified>${ ( new Date() ).toISOString() }</modified>` +
+				'<up_axis>Y_UP</up_axis>'
+			) +
+			'</asset>';
+
+		dae += `<library_images>${ libraryImages.join( '' ) }</library_images>`;
+
+		dae += `<library_effects>${ libraryEffects.join( '' ) }</library_effects>`;
+
+		dae += `<library_materials>${ libraryMaterials.join( '' ) }</library_materials>`;
+
+		dae += `<library_geometries>${ libraryGeometries.join( '' ) }</library_geometries>`;
+
+		dae += `<library_visual_scenes><visual_scene id="Scene" name="scene">${ libraryVisualScenes }</visual_scene></library_visual_scenes>`;
+
+		dae += '<scene><instance_visual_scene url="#Scene"/></scene>';
+
+		dae += '</COLLADA>';
+
+		var res = {
+			data: format( dae ),
+			textures
+		};
+
+		if ( typeof onDone === 'function' ) {
+
+			requestAnimationFrame( () => onDone( res ) );
+
+		}
+
+		return res;
+
+	}
+
+};
+
+export { ColladaExporter };

+ 39 - 49
examples/jsm/exporters/GLTFExporter.js

@@ -4,6 +4,29 @@
  * @author Takahiro / https://github.com/takahirox
  */
 
+import {
+	BufferAttribute,
+	BufferGeometry,
+	ClampToEdgeWrapping,
+	DoubleSide,
+	InterpolateDiscrete,
+	LinearFilter,
+	LinearMipMapLinearFilter,
+	LinearMipMapNearestFilter,
+	Math as _Math,
+	MirroredRepeatWrapping,
+	NearestFilter,
+	NearestMipMapLinearFilter,
+	NearestMipMapNearestFilter,
+	PropertyBinding,
+	RGBAFormat,
+	RepeatWrapping,
+	Scene,
+	TriangleFanDrawMode,
+	TriangleStripDrawMode,
+	Vector3
+} from "../../../build/three.module.js";
+
 //------------------------------------------------------------------------------
 // Constants
 //------------------------------------------------------------------------------
@@ -58,39 +81,6 @@ var PATH_PROPERTIES = {
 //------------------------------------------------------------------------------
 // GLTF Exporter
 //------------------------------------------------------------------------------
-import {
-	AnimationClip,
-	BufferAttribute,
-	BufferGeometry,
-	Camera,
-	ClampToEdgeWrapping,
-	DoubleSide,
-	Geometry,
-	InterpolateDiscrete,
-	LinearFilter,
-	LinearMipMapLinearFilter,
-	LinearMipMapNearestFilter,
-	Material,
-	Math,
-	Mesh,
-	MirroredRepeatWrapping,
-	NearestFilter,
-	NearestMipMapLinearFilter,
-	NearestMipMapNearestFilter,
-	Object3D,
-	PropertyBinding,
-	RGBAFormat,
-	RGBFormat,
-	RepeatWrapping,
-	Scene,
-	Scenes,
-	ShaderMaterial,
-	TriangleFanDrawMode,
-	TriangleStripDrawMode,
-	Vector3,
-	VertexColors
-} from "../../../build/three.module.js";
-
 var GLTFExporter = function () {};
 
 GLTFExporter.prototype = {
@@ -99,7 +89,7 @@ GLTFExporter.prototype = {
 
 	/**
 	 * Parse scenes and generate GLTF output
-	 * @param  {Scene or [Scenes]} input   Scene or Array of Scenes
+	 * @param  {Scene or [THREE.Scenes]} input   Scene or Array of THREE.Scenes
 	 * @param  {Function} onDone  Callback on completed
 	 * @param  {Object} options options
 	 */
@@ -244,7 +234,7 @@ GLTFExporter.prototype = {
 		 */
 		function isPowerOfTwo( image ) {
 
-			return Math.isPowerOfTwo( image.width ) && Math.isPowerOfTwo( image.height );
+			return _Math.isPowerOfTwo( image.width ) && _Math.isPowerOfTwo( image.height );
 
 		}
 
@@ -373,7 +363,7 @@ GLTFExporter.prototype = {
 		/**
 		 * Serializes a userData.
 		 *
-		 * @param {Object3D|Material} object
+		 * @param {THREE.Object3D|THREE.Material} object
 		 * @param {Object} gltfProperty
 		 */
 		function serializeUserData( object, gltfProperty ) {
@@ -736,7 +726,7 @@ GLTFExporter.prototype = {
 		/**
 		 * Process image
 		 * @param  {Image} image to process
-		 * @param  {Integer} format of the image (e.g. RGBFormat, RGBAFormat etc)
+		 * @param  {Integer} format of the image (e.g. THREE.RGBFormat, RGBAFormat etc)
 		 * @param  {Boolean} flipY before writing out the image
 		 * @return {Integer}     Index of the processed texture in the "images" array
 		 */
@@ -777,8 +767,8 @@ GLTFExporter.prototype = {
 
 					console.warn( 'GLTFExporter: Resized non-power-of-two image.', image );
 
-					canvas.width = Math.floorPowerOfTwo( canvas.width );
-					canvas.height = Math.floorPowerOfTwo( canvas.height );
+					canvas.width = _Math.floorPowerOfTwo( canvas.width );
+					canvas.height = _Math.floorPowerOfTwo( canvas.height );
 
 				}
 
@@ -897,7 +887,7 @@ GLTFExporter.prototype = {
 
 		/**
 		 * Process material
-		 * @param  {Material} material Material to process
+		 * @param  {THREE.Material} material Material to process
 		 * @return {Integer}      Index of the processed material in the "materials" array
 		 */
 		function processMaterial( material ) {
@@ -916,7 +906,7 @@ GLTFExporter.prototype = {
 
 			if ( material.isShaderMaterial ) {
 
-				console.warn( 'GLTFExporter: ShaderMaterial not supported.' );
+				console.warn( 'GLTFExporter: THREE.ShaderMaterial not supported.' );
 				return null;
 
 			}
@@ -1101,7 +1091,7 @@ GLTFExporter.prototype = {
 
 		/**
 		 * Process mesh
-		 * @param  {Mesh} mesh Mesh to process
+		 * @param  {THREE.Mesh} mesh Mesh to process
 		 * @return {Integer}      Index of the processed mesh in the "meshes" array
 		 */
 		function processMesh( mesh ) {
@@ -1138,7 +1128,7 @@ GLTFExporter.prototype = {
 
 				if ( ! geometry.isBufferGeometry ) {
 
-					console.warn( 'GLTFExporter: Exporting Geometry will increase file size. Use BufferGeometry instead.' );
+					console.warn( 'GLTFExporter: Exporting THREE.Geometry will increase file size. Use BufferGeometry instead.' );
 
 					var geometryTemp = new BufferGeometry();
 					geometryTemp.fromGeometry( geometry );
@@ -1190,7 +1180,7 @@ GLTFExporter.prototype = {
 
 			}
 
-			// @QUESTION Detect if .vertexColors = VertexColors?
+			// @QUESTION Detect if .vertexColors = THREE.VertexColors?
 			// For every attribute create an accessor
 			var modifiedAttribute = null;
 			for ( var attributeName in geometry.attributes ) {
@@ -1432,7 +1422,7 @@ GLTFExporter.prototype = {
 
 		/**
 		 * Process camera
-		 * @param  {Camera} camera Camera to process
+		 * @param  {THREE.Camera} camera Camera to process
 		 * @return {Integer}      Index of the processed mesh in the "camera" array
 		 */
 		function processCamera( camera ) {
@@ -1467,7 +1457,7 @@ GLTFExporter.prototype = {
 				gltfCamera.perspective = {
 
 					aspectRatio: camera.aspect,
-					yfov: Math.degToRad( camera.fov ),
+					yfov: _Math.degToRad( camera.fov ),
 					zfar: camera.far <= 0 ? 0.001 : camera.far,
 					znear: camera.near < 0 ? 0 : camera.near
 
@@ -1493,8 +1483,8 @@ GLTFExporter.prototype = {
 		 * Status:
 		 * - Only properties listed in PATH_PROPERTIES may be animated.
 		 *
-		 * @param {AnimationClip} clip
-		 * @param {Object3D} root
+		 * @param {THREE.AnimationClip} clip
+		 * @param {THREE.Object3D} root
 		 * @return {number}
 		 */
 		function processAnimation( clip, root ) {
@@ -1701,7 +1691,7 @@ GLTFExporter.prototype = {
 
 		/**
 		 * Process Object3D node
-		 * @param  {Object3D} node Object3D to processNode
+		 * @param  {THREE.Object3D} node Object3D to processNode
 		 * @return {Integer}      Index of the node in the nodes list
 		 */
 		function processNode( object ) {

+ 218 - 0
examples/jsm/exporters/MMDExporter.js

@@ -0,0 +1,218 @@
+/**
+ * @author takahiro / http://github.com/takahirox
+ *
+ * Dependencies
+ *  - mmd-parser https://github.com/takahirox/mmd-parser
+ */
+
+import {
+	Matrix4,
+	Quaternion,
+	Vector3
+} from "../../../build/three.module.js";
+
+var MMDExporter = function () {
+
+	// Unicode to Shift_JIS table
+	var u2sTable;
+
+	function unicodeToShiftjis( str ) {
+
+		if ( u2sTable === undefined ) {
+
+			var encoder = new MMDParser.CharsetEncoder();
+			var table = encoder.s2uTable;
+			u2sTable = {};
+
+			var keys = Object.keys( table );
+
+			for ( var i = 0, il = keys.length; i < il; i ++ ) {
+
+				var key = keys[ i ];
+
+				var value = table[ key ];
+				key = parseInt( key );
+
+				u2sTable[ value ] = key;
+
+			}
+
+		}
+
+		var array = [];
+
+		for ( var i = 0, il = str.length; i < il; i ++ ) {
+
+			var code = str.charCodeAt( i );
+
+			var value = u2sTable[ code ];
+
+			if ( value === undefined ) {
+
+				throw 'cannot convert charcode 0x' + code.toString( 16 );
+
+			} else if ( value > 0xff ) {
+
+				array.push( ( value >> 8 ) & 0xff );
+				array.push( value & 0xff );
+
+			} else {
+
+				array.push( value & 0xff );
+
+			}
+
+		}
+
+		return new Uint8Array( array );
+
+	}
+
+	function getBindBones( skin ) {
+
+		// any more efficient ways?
+		var poseSkin = skin.clone();
+		poseSkin.pose();
+		return poseSkin.skeleton.bones;
+
+	}
+
+	/* TODO: implement
+	// mesh -> pmd
+	this.parsePmd = function ( object ) {
+
+	};
+	*/
+
+	/* TODO: implement
+	// mesh -> pmx
+	this.parsePmx = function ( object ) {
+
+	};
+	*/
+
+	/*
+	 * skeleton -> vpd
+	 * Returns Shift_JIS encoded Uint8Array. Otherwise return strings.
+	 */
+	this.parseVpd = function ( skin, outputShiftJis, useOriginalBones ) {
+
+		if ( skin.isSkinnedMesh !== true ) {
+
+			console.warn( 'THREE.MMDExporter: parseVpd() requires SkinnedMesh instance.' );
+			return null;
+
+		}
+
+		function toStringsFromNumber( num ) {
+
+			if ( Math.abs( num ) < 1e-6 ) num = 0;
+
+			var a = num.toString();
+
+			if ( a.indexOf( '.' ) === - 1 ) {
+
+				a += '.';
+
+			}
+
+			a += '000000';
+
+			var index = a.indexOf( '.' );
+
+			var d = a.slice( 0, index );
+			var p = a.slice( index + 1, index + 7 );
+
+			return d + '.' + p;
+
+		}
+
+		function toStringsFromArray( array ) {
+
+			var a = [];
+
+			for ( var i = 0, il = array.length; i < il; i ++ ) {
+
+				a.push( toStringsFromNumber( array[ i ] ) );
+
+			}
+
+			return a.join( ',' );
+
+		}
+
+		skin.updateMatrixWorld( true );
+
+		var bones = skin.skeleton.bones;
+		var bones2 = getBindBones( skin );
+
+		var position = new Vector3();
+		var quaternion = new Quaternion();
+		var quaternion2 = new Quaternion();
+		var matrix = new Matrix4();
+
+		var array = [];
+		array.push( 'Vocaloid Pose Data file' );
+		array.push( '' );
+		array.push( ( skin.name !== '' ? skin.name.replace( /\s/g, '_' ) : 'skin' ) + '.osm;' );
+		array.push( bones.length + ';' );
+		array.push( '' );
+
+		for ( var i = 0, il = bones.length; i < il; i ++ ) {
+
+			var bone = bones[ i ];
+			var bone2 = bones2[ i ];
+
+			/*
+			 * use the bone matrix saved before solving IK.
+			 * see CCDIKSolver for the detail.
+			 */
+			if ( useOriginalBones === true &&
+				bone.userData.ik !== undefined &&
+				bone.userData.ik.originalMatrix !== undefined ) {
+
+				matrix.fromArray( bone.userData.ik.originalMatrix );
+
+			} else {
+
+				matrix.copy( bone.matrix );
+
+			}
+
+			position.setFromMatrixPosition( matrix );
+			quaternion.setFromRotationMatrix( matrix );
+
+			var pArray = position.sub( bone2.position ).toArray();
+			var qArray = quaternion2.copy( bone2.quaternion ).conjugate().multiply( quaternion ).toArray();
+
+			// right to left
+			pArray[ 2 ] = - pArray[ 2 ];
+			qArray[ 0 ] = - qArray[ 0 ];
+			qArray[ 1 ] = - qArray[ 1 ];
+
+			array.push( 'Bone' + i + '{' + bone.name );
+			array.push( '  ' + toStringsFromArray( pArray ) + ';' );
+			array.push( '  ' + toStringsFromArray( qArray ) + ';' );
+			array.push( '}' );
+			array.push( '' );
+
+		}
+
+		array.push( '' );
+
+		var lines = array.join( '\n' );
+
+		return ( outputShiftJis === true ) ? unicodeToShiftjis( lines ) : lines;
+
+	};
+
+	/* TODO: implement
+	// animation + skeleton -> vmd
+	this.parseVmd = function ( object ) {
+
+	};
+	*/
+
+};
+
+export { MMDExporter };

+ 274 - 0
examples/jsm/exporters/OBJExporter.js

@@ -0,0 +1,274 @@
+/**
+ * @author mrdoob / http://mrdoob.com/
+ */
+
+import {
+	BufferGeometry,
+	Geometry,
+	Line,
+	Matrix3,
+	Mesh,
+	Vector2,
+	Vector3
+} from "../../../build/three.module.js";
+
+var OBJExporter = function () {};
+
+OBJExporter.prototype = {
+
+	constructor: OBJExporter,
+
+	parse: function ( object ) {
+
+		var output = '';
+
+		var indexVertex = 0;
+		var indexVertexUvs = 0;
+		var indexNormals = 0;
+
+		var vertex = new Vector3();
+		var normal = new Vector3();
+		var uv = new Vector2();
+
+		var i, j, k, l, m, face = [];
+
+		var parseMesh = function ( mesh ) {
+
+			var nbVertex = 0;
+			var nbNormals = 0;
+			var nbVertexUvs = 0;
+
+			var geometry = mesh.geometry;
+
+			var normalMatrixWorld = new Matrix3();
+
+			if ( geometry instanceof Geometry ) {
+
+				geometry = new BufferGeometry().setFromObject( mesh );
+
+			}
+
+			if ( geometry instanceof BufferGeometry ) {
+
+				// shortcuts
+				var vertices = geometry.getAttribute( 'position' );
+				var normals = geometry.getAttribute( 'normal' );
+				var uvs = geometry.getAttribute( 'uv' );
+				var indices = geometry.getIndex();
+
+				// name of the mesh object
+				output += 'o ' + mesh.name + '\n';
+
+				// name of the mesh material
+				if ( mesh.material && mesh.material.name ) {
+
+					output += 'usemtl ' + mesh.material.name + '\n';
+
+				}
+
+				// vertices
+
+				if ( vertices !== undefined ) {
+
+					for ( i = 0, l = vertices.count; i < l; i ++, nbVertex ++ ) {
+
+						vertex.x = vertices.getX( i );
+						vertex.y = vertices.getY( i );
+						vertex.z = vertices.getZ( i );
+
+						// transfrom the vertex to world space
+						vertex.applyMatrix4( mesh.matrixWorld );
+
+						// transform the vertex to export format
+						output += 'v ' + vertex.x + ' ' + vertex.y + ' ' + vertex.z + '\n';
+
+					}
+
+				}
+
+				// uvs
+
+				if ( uvs !== undefined ) {
+
+					for ( i = 0, l = uvs.count; i < l; i ++, nbVertexUvs ++ ) {
+
+						uv.x = uvs.getX( i );
+						uv.y = uvs.getY( i );
+
+						// transform the uv to export format
+						output += 'vt ' + uv.x + ' ' + uv.y + '\n';
+
+					}
+
+				}
+
+				// normals
+
+				if ( normals !== undefined ) {
+
+					normalMatrixWorld.getNormalMatrix( mesh.matrixWorld );
+
+					for ( i = 0, l = normals.count; i < l; i ++, nbNormals ++ ) {
+
+						normal.x = normals.getX( i );
+						normal.y = normals.getY( i );
+						normal.z = normals.getZ( i );
+
+						// transfrom the normal to world space
+						normal.applyMatrix3( normalMatrixWorld );
+
+						// transform the normal to export format
+						output += 'vn ' + normal.x + ' ' + normal.y + ' ' + normal.z + '\n';
+
+					}
+
+				}
+
+				// faces
+
+				if ( indices !== null ) {
+
+					for ( i = 0, l = indices.count; i < l; i += 3 ) {
+
+						for ( m = 0; m < 3; m ++ ) {
+
+							j = indices.getX( i + m ) + 1;
+
+							face[ m ] = ( indexVertex + j ) + ( normals || uvs ? '/' + ( uvs ? ( indexVertexUvs + j ) : '' ) + ( normals ? '/' + ( indexNormals + j ) : '' ) : '' );
+
+						}
+
+						// transform the face to export format
+						output += 'f ' + face.join( ' ' ) + "\n";
+
+					}
+
+				} else {
+
+					for ( i = 0, l = vertices.count; i < l; i += 3 ) {
+
+						for ( m = 0; m < 3; m ++ ) {
+
+							j = i + m + 1;
+
+							face[ m ] = ( indexVertex + j ) + ( normals || uvs ? '/' + ( uvs ? ( indexVertexUvs + j ) : '' ) + ( normals ? '/' + ( indexNormals + j ) : '' ) : '' );
+
+						}
+
+						// transform the face to export format
+						output += 'f ' + face.join( ' ' ) + "\n";
+
+					}
+
+				}
+
+			} else {
+
+				console.warn( 'THREE.OBJExporter.parseMesh(): geometry type unsupported', geometry );
+
+			}
+
+			// update index
+			indexVertex += nbVertex;
+			indexVertexUvs += nbVertexUvs;
+			indexNormals += nbNormals;
+
+		};
+
+		var parseLine = function ( line ) {
+
+			var nbVertex = 0;
+
+			var geometry = line.geometry;
+			var type = line.type;
+
+			if ( geometry instanceof Geometry ) {
+
+				geometry = new BufferGeometry().setFromObject( line );
+
+			}
+
+			if ( geometry instanceof BufferGeometry ) {
+
+				// shortcuts
+				var vertices = geometry.getAttribute( 'position' );
+
+				// name of the line object
+				output += 'o ' + line.name + '\n';
+
+				if ( vertices !== undefined ) {
+
+					for ( i = 0, l = vertices.count; i < l; i ++, nbVertex ++ ) {
+
+						vertex.x = vertices.getX( i );
+						vertex.y = vertices.getY( i );
+						vertex.z = vertices.getZ( i );
+
+						// transfrom the vertex to world space
+						vertex.applyMatrix4( line.matrixWorld );
+
+						// transform the vertex to export format
+						output += 'v ' + vertex.x + ' ' + vertex.y + ' ' + vertex.z + '\n';
+
+					}
+
+				}
+
+				if ( type === 'Line' ) {
+
+					output += 'l ';
+
+					for ( j = 1, l = vertices.count; j <= l; j ++ ) {
+
+						output += ( indexVertex + j ) + ' ';
+
+					}
+
+					output += '\n';
+
+				}
+
+				if ( type === 'LineSegments' ) {
+
+					for ( j = 1, k = j + 1, l = vertices.count; j < l; j += 2, k = j + 1 ) {
+
+						output += 'l ' + ( indexVertex + j ) + ' ' + ( indexVertex + k ) + '\n';
+
+					}
+
+				}
+
+			} else {
+
+				console.warn( 'THREE.OBJExporter.parseLine(): geometry type unsupported', geometry );
+
+			}
+
+			// update index
+			indexVertex += nbVertex;
+
+		};
+
+		object.traverse( function ( child ) {
+
+			if ( child instanceof Mesh ) {
+
+				parseMesh( child );
+
+			}
+
+			if ( child instanceof Line ) {
+
+				parseLine( child );
+
+			}
+
+		} );
+
+		return output;
+
+	}
+
+};
+
+export { OBJExporter };

+ 557 - 0
examples/jsm/exporters/PLYExporter.js

@@ -0,0 +1,557 @@
+/**
+ * @author Garrett Johnson / http://gkjohnson.github.io/
+ * https://github.com/gkjohnson/ply-exporter-js
+ *
+ * Usage:
+ *  var exporter = new PLYExporter();
+ *
+ *  // second argument is a list of options
+ *  exporter.parse(mesh, data => console.log(data), { binary: true, excludeAttributes: [ 'color' ] });
+ *
+ * Format Definition:
+ * http://paulbourke.net/dataformats/ply/
+ */
+
+import {
+	BufferGeometry,
+	Matrix3,
+	Vector3
+} from "../../../build/three.module.js";
+
+var PLYExporter = function () {};
+
+PLYExporter.prototype = {
+
+	constructor: PLYExporter,
+
+	parse: function ( object, onDone, options ) {
+
+		if ( onDone && typeof onDone === 'object' ) {
+
+			console.warn( 'THREE.PLYExporter: The options parameter is now the third argument to the "parse" function. See the documentation for the new API.' );
+			options = onDone;
+			onDone = undefined;
+
+		}
+
+		// Iterate over the valid meshes in the object
+		function traverseMeshes( cb ) {
+
+			object.traverse( function ( child ) {
+
+				if ( child.isMesh === true ) {
+
+					var mesh = child;
+					var geometry = mesh.geometry;
+
+					if ( geometry.isGeometry === true ) {
+
+						geometry = geomToBufferGeom.get( geometry );
+
+					}
+
+					if ( geometry.isBufferGeometry === true ) {
+
+						if ( geometry.getAttribute( 'position' ) !== undefined ) {
+
+							cb( mesh, geometry );
+
+						}
+
+					}
+
+				}
+
+			} );
+
+		}
+
+		// Default options
+		var defaultOptions = {
+			binary: false,
+			excludeAttributes: [] // normal, uv, color, index
+		};
+
+		options = Object.assign( defaultOptions, options );
+
+		var excludeAttributes = options.excludeAttributes;
+		var geomToBufferGeom = new WeakMap();
+		var includeNormals = false;
+		var includeColors = false;
+		var includeUVs = false;
+
+		// count the vertices, check which properties are used,
+		// and cache the BufferGeometry
+		var vertexCount = 0;
+		var faceCount = 0;
+		object.traverse( function ( child ) {
+
+			if ( child.isMesh === true ) {
+
+				var mesh = child;
+				var geometry = mesh.geometry;
+
+				if ( geometry.isGeometry === true ) {
+
+					var bufferGeometry = geomToBufferGeom.get( geometry ) || new BufferGeometry().setFromObject( mesh );
+					geomToBufferGeom.set( geometry, bufferGeometry );
+					geometry = bufferGeometry;
+
+				}
+
+				if ( geometry.isBufferGeometry === true ) {
+
+					var vertices = geometry.getAttribute( 'position' );
+					var normals = geometry.getAttribute( 'normal' );
+					var uvs = geometry.getAttribute( 'uv' );
+					var colors = geometry.getAttribute( 'color' );
+					var indices = geometry.getIndex();
+
+					if ( vertices === undefined ) {
+
+						return;
+
+					}
+
+					vertexCount += vertices.count;
+					faceCount += indices ? indices.count / 3 : vertices.count / 3;
+
+					if ( normals !== undefined ) includeNormals = true;
+
+					if ( uvs !== undefined ) includeUVs = true;
+
+					if ( colors !== undefined ) includeColors = true;
+
+				}
+
+			}
+
+		} );
+
+		var includeIndices = excludeAttributes.indexOf( 'index' ) === - 1;
+		includeNormals = includeNormals && excludeAttributes.indexOf( 'normal' ) === - 1;
+		includeColors = includeColors && excludeAttributes.indexOf( 'color' ) === - 1;
+		includeUVs = includeUVs && excludeAttributes.indexOf( 'uv' ) === - 1;
+
+
+		if ( includeIndices && faceCount !== Math.floor( faceCount ) ) {
+
+			// point cloud meshes will not have an index array and may not have a
+			// number of vertices that is divisble by 3 (and therefore representable
+			// as triangles)
+			console.error(
+
+				'PLYExporter: Failed to generate a valid PLY file with triangle indices because the ' +
+				'number of indices is not divisible by 3.'
+
+			);
+
+			return null;
+
+		}
+
+		// get how many bytes will be needed to save out the faces
+		// so we can use a minimal amount of memory / data
+		var indexByteCount = 1;
+
+		if ( vertexCount > 256 ) { // 2^8 bits
+
+			indexByteCount = 2;
+
+		}
+
+		if ( vertexCount > 65536 ) { // 2^16 bits
+
+			indexByteCount = 4;
+
+		}
+
+
+		var header =
+			'ply\n' +
+			`format ${ options.binary ? 'binary_big_endian' : 'ascii' } 1.0\n` +
+			`element vertex ${vertexCount}\n` +
+
+			// position
+			'property float x\n' +
+			'property float y\n' +
+			'property float z\n';
+
+		if ( includeNormals === true ) {
+
+			// normal
+			header +=
+				'property float nx\n' +
+				'property float ny\n' +
+				'property float nz\n';
+
+		}
+
+		if ( includeUVs === true ) {
+
+			// uvs
+			header +=
+				'property float s\n' +
+				'property float t\n';
+
+		}
+
+		if ( includeColors === true ) {
+
+			// colors
+			header +=
+				'property uchar red\n' +
+				'property uchar green\n' +
+				'property uchar blue\n';
+
+		}
+
+		if ( includeIndices === true ) {
+
+			// faces
+			header +=
+				`element face ${faceCount}\n` +
+				`property list uchar uint${ indexByteCount * 8 } vertex_index\n`;
+
+		}
+
+		header += 'end_header\n';
+
+
+		// Generate attribute data
+		var vertex = new Vector3();
+		var normalMatrixWorld = new Matrix3();
+		var result = null;
+
+		if ( options.binary === true ) {
+
+			// Binary File Generation
+			var headerBin = new TextEncoder().encode( header );
+
+			// 3 position values at 4 bytes
+			// 3 normal values at 4 bytes
+			// 3 color channels with 1 byte
+			// 2 uv values at 4 bytes
+			var vertexListLength = vertexCount * ( 4 * 3 + ( includeNormals ? 4 * 3 : 0 ) + ( includeColors ? 3 : 0 ) + ( includeUVs ? 4 * 2 : 0 ) );
+
+			// 1 byte shape desciptor
+			// 3 vertex indices at ${indexByteCount} bytes
+			var faceListLength = includeIndices ? faceCount * ( indexByteCount * 3 + 1 ) : 0;
+			var output = new DataView( new ArrayBuffer( headerBin.length + vertexListLength + faceListLength ) );
+			new Uint8Array( output.buffer ).set( headerBin, 0 );
+
+
+			var vOffset = headerBin.length;
+			var fOffset = headerBin.length + vertexListLength;
+			var writtenVertices = 0;
+			traverseMeshes( function ( mesh, geometry ) {
+
+				var vertices = geometry.getAttribute( 'position' );
+				var normals = geometry.getAttribute( 'normal' );
+				var uvs = geometry.getAttribute( 'uv' );
+				var colors = geometry.getAttribute( 'color' );
+				var indices = geometry.getIndex();
+
+				normalMatrixWorld.getNormalMatrix( mesh.matrixWorld );
+
+				for ( var i = 0, l = vertices.count; i < l; i ++ ) {
+
+					vertex.x = vertices.getX( i );
+					vertex.y = vertices.getY( i );
+					vertex.z = vertices.getZ( i );
+
+					vertex.applyMatrix4( mesh.matrixWorld );
+
+
+					// Position information
+					output.setFloat32( vOffset, vertex.x );
+					vOffset += 4;
+
+					output.setFloat32( vOffset, vertex.y );
+					vOffset += 4;
+
+					output.setFloat32( vOffset, vertex.z );
+					vOffset += 4;
+
+					// Normal information
+					if ( includeNormals === true ) {
+
+						if ( normals != null ) {
+
+							vertex.x = normals.getX( i );
+							vertex.y = normals.getY( i );
+							vertex.z = normals.getZ( i );
+
+							vertex.applyMatrix3( normalMatrixWorld );
+
+							output.setFloat32( vOffset, vertex.x );
+							vOffset += 4;
+
+							output.setFloat32( vOffset, vertex.y );
+							vOffset += 4;
+
+							output.setFloat32( vOffset, vertex.z );
+							vOffset += 4;
+
+						} else {
+
+							output.setFloat32( vOffset, 0 );
+							vOffset += 4;
+
+							output.setFloat32( vOffset, 0 );
+							vOffset += 4;
+
+							output.setFloat32( vOffset, 0 );
+							vOffset += 4;
+
+						}
+
+					}
+
+					// UV information
+					if ( includeUVs === true ) {
+
+						if ( uvs != null ) {
+
+							output.setFloat32( vOffset, uvs.getX( i ) );
+							vOffset += 4;
+
+							output.setFloat32( vOffset, uvs.getY( i ) );
+							vOffset += 4;
+
+						} else if ( includeUVs !== false ) {
+
+							output.setFloat32( vOffset, 0 );
+							vOffset += 4;
+
+							output.setFloat32( vOffset, 0 );
+							vOffset += 4;
+
+						}
+
+					}
+
+					// Color information
+					if ( includeColors === true ) {
+
+						if ( colors != null ) {
+
+							output.setUint8( vOffset, Math.floor( colors.getX( i ) * 255 ) );
+							vOffset += 1;
+
+							output.setUint8( vOffset, Math.floor( colors.getY( i ) * 255 ) );
+							vOffset += 1;
+
+							output.setUint8( vOffset, Math.floor( colors.getZ( i ) * 255 ) );
+							vOffset += 1;
+
+						} else {
+
+							output.setUint8( vOffset, 255 );
+							vOffset += 1;
+
+							output.setUint8( vOffset, 255 );
+							vOffset += 1;
+
+							output.setUint8( vOffset, 255 );
+							vOffset += 1;
+
+						}
+
+					}
+
+				}
+
+				if ( includeIndices === true ) {
+
+					// Create the face list
+					var faceIndexFunc = `setUint${indexByteCount * 8}`;
+					if ( indices !== null ) {
+
+						for ( var i = 0, l = indices.count; i < l; i += 3 ) {
+
+							output.setUint8( fOffset, 3 );
+							fOffset += 1;
+
+							output[ faceIndexFunc ]( fOffset, indices.getX( i + 0 ) + writtenVertices );
+							fOffset += indexByteCount;
+
+							output[ faceIndexFunc ]( fOffset, indices.getX( i + 1 ) + writtenVertices );
+							fOffset += indexByteCount;
+
+							output[ faceIndexFunc ]( fOffset, indices.getX( i + 2 ) + writtenVertices );
+							fOffset += indexByteCount;
+
+						}
+
+					} else {
+
+						for ( var i = 0, l = vertices.count; i < l; i += 3 ) {
+
+							output.setUint8( fOffset, 3 );
+							fOffset += 1;
+
+							output[ faceIndexFunc ]( fOffset, writtenVertices + i );
+							fOffset += indexByteCount;
+
+							output[ faceIndexFunc ]( fOffset, writtenVertices + i + 1 );
+							fOffset += indexByteCount;
+
+							output[ faceIndexFunc ]( fOffset, writtenVertices + i + 2 );
+							fOffset += indexByteCount;
+
+						}
+
+					}
+
+				}
+
+
+				// Save the amount of verts we've already written so we can offset
+				// the face index on the next mesh
+				writtenVertices += vertices.count;
+
+			} );
+
+			result = output.buffer;
+
+		} else {
+
+			// Ascii File Generation
+			// count the number of vertices
+			var writtenVertices = 0;
+			var vertexList = '';
+			var faceList = '';
+
+			traverseMeshes( function ( mesh, geometry ) {
+
+				var vertices = geometry.getAttribute( 'position' );
+				var normals = geometry.getAttribute( 'normal' );
+				var uvs = geometry.getAttribute( 'uv' );
+				var colors = geometry.getAttribute( 'color' );
+				var indices = geometry.getIndex();
+
+				normalMatrixWorld.getNormalMatrix( mesh.matrixWorld );
+
+				// form each line
+				for ( var i = 0, l = vertices.count; i < l; i ++ ) {
+
+					vertex.x = vertices.getX( i );
+					vertex.y = vertices.getY( i );
+					vertex.z = vertices.getZ( i );
+
+					vertex.applyMatrix4( mesh.matrixWorld );
+
+
+					// Position information
+					var line =
+						vertex.x + ' ' +
+						vertex.y + ' ' +
+						vertex.z;
+
+					// Normal information
+					if ( includeNormals === true ) {
+
+						if ( normals != null ) {
+
+							vertex.x = normals.getX( i );
+							vertex.y = normals.getY( i );
+							vertex.z = normals.getZ( i );
+
+							vertex.applyMatrix3( normalMatrixWorld );
+
+							line += ' ' +
+								vertex.x + ' ' +
+								vertex.y + ' ' +
+								vertex.z;
+
+						} else {
+
+							line += ' 0 0 0';
+
+						}
+
+					}
+
+					// UV information
+					if ( includeUVs === true ) {
+
+						if ( uvs != null ) {
+
+							line += ' ' +
+								uvs.getX( i ) + ' ' +
+								uvs.getY( i );
+
+						} else if ( includeUVs !== false ) {
+
+							line += ' 0 0';
+
+						}
+
+					}
+
+					// Color information
+					if ( includeColors === true ) {
+
+						if ( colors != null ) {
+
+							line += ' ' +
+								Math.floor( colors.getX( i ) * 255 ) + ' ' +
+								Math.floor( colors.getY( i ) * 255 ) + ' ' +
+								Math.floor( colors.getZ( i ) * 255 );
+
+						} else {
+
+							line += ' 255 255 255';
+
+						}
+
+					}
+
+					vertexList += line + '\n';
+
+				}
+
+				// Create the face list
+				if ( includeIndices === true ) {
+
+					if ( indices !== null ) {
+
+						for ( var i = 0, l = indices.count; i < l; i += 3 ) {
+
+							faceList += `3 ${ indices.getX( i + 0 ) + writtenVertices }`;
+							faceList += ` ${ indices.getX( i + 1 ) + writtenVertices }`;
+							faceList += ` ${ indices.getX( i + 2 ) + writtenVertices }\n`;
+
+						}
+
+					} else {
+
+						for ( var i = 0, l = vertices.count; i < l; i += 3 ) {
+
+							faceList += `3 ${ writtenVertices + i } ${ writtenVertices + i + 1 } ${ writtenVertices + i + 2 }\n`;
+
+						}
+
+					}
+
+					faceCount += indices ? indices.count / 3 : vertices.count / 3;
+
+				}
+
+				writtenVertices += vertices.count;
+
+			} );
+
+			result = `${ header }${vertexList}\n${ includeIndices ? `${faceList}\n` : '' }`;
+
+		}
+
+		if ( typeof onDone === 'function' ) requestAnimationFrame( () => onDone( result ) );
+		return result;
+
+	}
+
+};
+
+export { PLYExporter };

+ 174 - 0
examples/jsm/exporters/STLExporter.js

@@ -0,0 +1,174 @@
+/**
+ * @author kovacsv / http://kovacsv.hu/
+ * @author mrdoob / http://mrdoob.com/
+ * @author mudcube / http://mudcu.be/
+ * @author Mugen87 / https://github.com/Mugen87
+ *
+ * Usage:
+ *  var exporter = new STLExporter();
+ *
+ *  // second argument is a list of options
+ *  var data = exporter.parse( mesh, { binary: true } );
+ *
+ */
+
+import {
+	Geometry,
+	Matrix3,
+	Vector3
+} from "../../../build/three.module.js";
+
+var STLExporter = function () {};
+
+STLExporter.prototype = {
+
+	constructor: STLExporter,
+
+	parse: ( function () {
+
+		var vector = new Vector3();
+		var normalMatrixWorld = new Matrix3();
+
+		return function parse( scene, options ) {
+
+			if ( options === undefined ) options = {};
+
+			var binary = options.binary !== undefined ? options.binary : false;
+
+			//
+
+			var objects = [];
+			var triangles = 0;
+
+			scene.traverse( function ( object ) {
+
+				if ( object.isMesh ) {
+
+					var geometry = object.geometry;
+
+					if ( geometry.isBufferGeometry ) {
+
+						geometry = new Geometry().fromBufferGeometry( geometry );
+
+					}
+
+					if ( geometry.isGeometry ) {
+
+						triangles += geometry.faces.length;
+
+						objects.push( {
+
+							geometry: geometry,
+							matrixWorld: object.matrixWorld
+
+						} );
+
+					}
+
+				}
+
+			} );
+
+			if ( binary ) {
+
+				var offset = 80; // skip header
+				var bufferLength = triangles * 2 + triangles * 3 * 4 * 4 + 80 + 4;
+				var arrayBuffer = new ArrayBuffer( bufferLength );
+				var output = new DataView( arrayBuffer );
+				output.setUint32( offset, triangles, true ); offset += 4;
+
+				for ( var i = 0, il = objects.length; i < il; i ++ ) {
+
+					var object = objects[ i ];
+
+					var vertices = object.geometry.vertices;
+					var faces = object.geometry.faces;
+					var matrixWorld = object.matrixWorld;
+
+					normalMatrixWorld.getNormalMatrix( matrixWorld );
+
+					for ( var j = 0, jl = faces.length; j < jl; j ++ ) {
+
+						var face = faces[ j ];
+
+						vector.copy( face.normal ).applyMatrix3( normalMatrixWorld ).normalize();
+
+						output.setFloat32( offset, vector.x, true ); offset += 4; // normal
+						output.setFloat32( offset, vector.y, true ); offset += 4;
+						output.setFloat32( offset, vector.z, true ); offset += 4;
+
+						var indices = [ face.a, face.b, face.c ];
+
+						for ( var k = 0; k < 3; k ++ ) {
+
+							vector.copy( vertices[ indices[ k ] ] ).applyMatrix4( matrixWorld );
+
+							output.setFloat32( offset, vector.x, true ); offset += 4; // vertices
+							output.setFloat32( offset, vector.y, true ); offset += 4;
+							output.setFloat32( offset, vector.z, true ); offset += 4;
+
+						}
+
+						output.setUint16( offset, 0, true ); offset += 2; // attribute byte count
+
+					}
+
+				}
+
+				return output;
+
+			} else {
+
+				var output = '';
+
+				output += 'solid exported\n';
+
+				for ( var i = 0, il = objects.length; i < il; i ++ ) {
+
+					var object = objects[ i ];
+
+					var vertices = object.geometry.vertices;
+					var faces = object.geometry.faces;
+					var matrixWorld = object.matrixWorld;
+
+					normalMatrixWorld.getNormalMatrix( matrixWorld );
+
+					for ( var j = 0, jl = faces.length; j < jl; j ++ ) {
+
+						var face = faces[ j ];
+
+						vector.copy( face.normal ).applyMatrix3( normalMatrixWorld ).normalize();
+
+						output += '\tfacet normal ' + vector.x + ' ' + vector.y + ' ' + vector.z + '\n';
+						output += '\t\touter loop\n';
+
+						var indices = [ face.a, face.b, face.c ];
+
+						for ( var k = 0; k < 3; k ++ ) {
+
+							vector.copy( vertices[ indices[ k ] ] ).applyMatrix4( matrixWorld );
+
+							output += '\t\t\tvertex ' + vector.x + ' ' + vector.y + ' ' + vector.z + '\n';
+
+						}
+
+						output += '\t\tendloop\n';
+						output += '\tendfacet\n';
+
+					}
+
+				}
+
+				output += 'endsolid exported\n';
+
+				return output;
+
+			}
+
+		};
+
+	}() )
+
+};
+
+export { STLExporter };

+ 59 - 0
examples/jsm/exporters/TypedGeometryExporter.js

@@ -0,0 +1,59 @@
+/**
+ * @author mrdoob / http://mrdoob.com/
+ */
+
+
+
+var TypedGeometryExporter = function () {};
+
+TypedGeometryExporter.prototype = {
+
+	constructor: TypedGeometryExporter,
+
+	parse: function ( geometry ) {
+
+		var output = {
+			metadata: {
+				version: 4.0,
+				type: 'TypedGeometry',
+				generator: 'TypedGeometryExporter'
+			}
+		};
+
+		var attributes = [ 'vertices', 'normals', 'uvs' ];
+
+		for ( var key in attributes ) {
+
+			var attribute = attributes[ key ];
+
+			var typedArray = geometry[ attribute ];
+			var array = [];
+
+			for ( var i = 0, l = typedArray.length; i < l; i ++ ) {
+
+				array[ i ] = typedArray[ i ];
+
+			}
+
+			output[ attribute ] = array;
+
+		}
+
+		var boundingSphere = geometry.boundingSphere;
+
+		if ( boundingSphere !== null ) {
+
+			output.boundingSphere = {
+				center: boundingSphere.center.toArray(),
+				radius: boundingSphere.radius
+			};
+
+		}
+
+		return output;
+
+	}
+
+};
+
+export { TypedGeometryExporter };

+ 2 - 2
examples/jsm/loaders/GLTFLoader.js

@@ -44,7 +44,7 @@ import {
 	Loader,
 	LoaderUtils,
 	Material,
-	Math,
+	Math as _Math,
 	Matrix3,
 	Matrix4,
 	Mesh,
@@ -2793,7 +2793,7 @@ var GLTFLoader = ( function () {
 
 		if ( cameraDef.type === 'perspective' ) {
 
-			camera = new PerspectiveCamera( Math.radToDeg( params.yfov ), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6 );
+			camera = new PerspectiveCamera( _Math.radToDeg( params.yfov ), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6 );
 
 		} else if ( cameraDef.type === 'orthographic' ) {
 

+ 7 - 0
examples/jsm/utils/BufferGeometryUtils.d.ts

@@ -0,0 +1,7 @@
+import { BufferAttribute, BufferGeometry } from '../../../src/Three';
+
+export namespace BufferGeometryUtils {
+    export function mergeBufferGeometries(geometries: BufferGeometry[]): BufferGeometry;
+    export function computeTangents(geometry: BufferGeometry): null;
+    export function mergeBufferAttributes(attributes: BufferAttribute[]): BufferAttribute;
+}

+ 657 - 0
examples/jsm/utils/BufferGeometryUtils.js

@@ -0,0 +1,657 @@
+/**
+ * @author mrdoob / http://mrdoob.com/
+ */
+
+import {
+	BufferAttribute,
+	BufferGeometry,
+	InterleavedBuffer,
+	InterleavedBufferAttribute,
+	Vector2,
+	Vector3
+} from "../../../build/three.module.js";
+
+var BufferGeometryUtils = {
+
+	computeTangents: function ( geometry ) {
+
+		var index = geometry.index;
+		var attributes = geometry.attributes;
+
+		// based on http://www.terathon.com/code/tangent.html
+		// (per vertex tangents)
+
+		if ( index === null ||
+			 attributes.position === undefined ||
+			 attributes.normal === undefined ||
+			 attributes.uv === undefined ) {
+
+			console.warn( 'THREE.BufferGeometry: Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()' );
+			return;
+
+		}
+
+		var indices = index.array;
+		var positions = attributes.position.array;
+		var normals = attributes.normal.array;
+		var uvs = attributes.uv.array;
+
+		var nVertices = positions.length / 3;
+
+		if ( attributes.tangent === undefined ) {
+
+			geometry.addAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) );
+
+		}
+
+		var tangents = attributes.tangent.array;
+
+		var tan1 = [], tan2 = [];
+
+		for ( var i = 0; i < nVertices; i ++ ) {
+
+			tan1[ i ] = new Vector3();
+			tan2[ i ] = new Vector3();
+
+		}
+
+		var vA = new Vector3(),
+			vB = new Vector3(),
+			vC = new Vector3(),
+
+			uvA = new Vector2(),
+			uvB = new Vector2(),
+			uvC = new Vector2(),
+
+			sdir = new Vector3(),
+			tdir = new Vector3();
+
+		function handleTriangle( a, b, c ) {
+
+			vA.fromArray( positions, a * 3 );
+			vB.fromArray( positions, b * 3 );
+			vC.fromArray( positions, c * 3 );
+
+			uvA.fromArray( uvs, a * 2 );
+			uvB.fromArray( uvs, b * 2 );
+			uvC.fromArray( uvs, c * 2 );
+
+			var x1 = vB.x - vA.x;
+			var x2 = vC.x - vA.x;
+
+			var y1 = vB.y - vA.y;
+			var y2 = vC.y - vA.y;
+
+			var z1 = vB.z - vA.z;
+			var z2 = vC.z - vA.z;
+
+			var s1 = uvB.x - uvA.x;
+			var s2 = uvC.x - uvA.x;
+
+			var t1 = uvB.y - uvA.y;
+			var t2 = uvC.y - uvA.y;
+
+			var r = 1.0 / ( s1 * t2 - s2 * t1 );
+
+			sdir.set(
+				( t2 * x1 - t1 * x2 ) * r,
+				( t2 * y1 - t1 * y2 ) * r,
+				( t2 * z1 - t1 * z2 ) * r
+			);
+
+			tdir.set(
+				( s1 * x2 - s2 * x1 ) * r,
+				( s1 * y2 - s2 * y1 ) * r,
+				( s1 * z2 - s2 * z1 ) * r
+			);
+
+			tan1[ a ].add( sdir );
+			tan1[ b ].add( sdir );
+			tan1[ c ].add( sdir );
+
+			tan2[ a ].add( tdir );
+			tan2[ b ].add( tdir );
+			tan2[ c ].add( tdir );
+
+		}
+
+		var groups = geometry.groups;
+
+		if ( groups.length === 0 ) {
+
+			groups = [ {
+				start: 0,
+				count: indices.length
+			} ];
+
+		}
+
+		for ( var i = 0, il = groups.length; i < il; ++ i ) {
+
+			var group = groups[ i ];
+
+			var start = group.start;
+			var count = group.count;
+
+			for ( var j = start, jl = start + count; j < jl; j += 3 ) {
+
+				handleTriangle(
+					indices[ j + 0 ],
+					indices[ j + 1 ],
+					indices[ j + 2 ]
+				);
+
+			}
+
+		}
+
+		var tmp = new Vector3(), tmp2 = new Vector3();
+		var n = new Vector3(), n2 = new Vector3();
+		var w, t, test;
+
+		function handleVertex( v ) {
+
+			n.fromArray( normals, v * 3 );
+			n2.copy( n );
+
+			t = tan1[ v ];
+
+			// Gram-Schmidt orthogonalize
+
+			tmp.copy( t );
+			tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
+
+			// Calculate handedness
+
+			tmp2.crossVectors( n2, t );
+			test = tmp2.dot( tan2[ v ] );
+			w = ( test < 0.0 ) ? - 1.0 : 1.0;
+
+			tangents[ v * 4 ] = tmp.x;
+			tangents[ v * 4 + 1 ] = tmp.y;
+			tangents[ v * 4 + 2 ] = tmp.z;
+			tangents[ v * 4 + 3 ] = w;
+
+		}
+
+		for ( var i = 0, il = groups.length; i < il; ++ i ) {
+
+			var group = groups[ i ];
+
+			var start = group.start;
+			var count = group.count;
+
+			for ( var j = start, jl = start + count; j < jl; j += 3 ) {
+
+				handleVertex( indices[ j + 0 ] );
+				handleVertex( indices[ j + 1 ] );
+				handleVertex( indices[ j + 2 ] );
+
+			}
+
+		}
+
+	},
+
+	/**
+	 * @param  {Array<BufferGeometry>} geometries
+	 * @param  {Boolean} useGroups
+	 * @return {BufferGeometry}
+	 */
+	mergeBufferGeometries: function ( geometries, useGroups ) {
+
+		var isIndexed = geometries[ 0 ].index !== null;
+
+		var attributesUsed = new Set( Object.keys( geometries[ 0 ].attributes ) );
+		var morphAttributesUsed = new Set( Object.keys( geometries[ 0 ].morphAttributes ) );
+
+		var attributes = {};
+		var morphAttributes = {};
+
+		var mergedGeometry = new BufferGeometry();
+
+		var offset = 0;
+
+		for ( var i = 0; i < geometries.length; ++ i ) {
+
+			var geometry = geometries[ i ];
+
+			// ensure that all geometries are indexed, or none
+
+			if ( isIndexed !== ( geometry.index !== null ) ) return null;
+
+			// gather attributes, exit early if they're different
+
+			for ( var name in geometry.attributes ) {
+
+				if ( ! attributesUsed.has( name ) ) return null;
+
+				if ( attributes[ name ] === undefined ) attributes[ name ] = [];
+
+				attributes[ name ].push( geometry.attributes[ name ] );
+
+			}
+
+			// gather morph attributes, exit early if they're different
+
+			for ( var name in geometry.morphAttributes ) {
+
+				if ( ! morphAttributesUsed.has( name ) ) return null;
+
+				if ( morphAttributes[ name ] === undefined ) morphAttributes[ name ] = [];
+
+				morphAttributes[ name ].push( geometry.morphAttributes[ name ] );
+
+			}
+
+			// gather .userData
+
+			mergedGeometry.userData.mergedUserData = mergedGeometry.userData.mergedUserData || [];
+			mergedGeometry.userData.mergedUserData.push( geometry.userData );
+
+			if ( useGroups ) {
+
+				var count;
+
+				if ( isIndexed ) {
+
+					count = geometry.index.count;
+
+				} else if ( geometry.attributes.position !== undefined ) {
+
+					count = geometry.attributes.position.count;
+
+				} else {
+
+					return null;
+
+				}
+
+				mergedGeometry.addGroup( offset, count, i );
+
+				offset += count;
+
+			}
+
+		}
+
+		// merge indices
+
+		if ( isIndexed ) {
+
+			var indexOffset = 0;
+			var mergedIndex = [];
+
+			for ( var i = 0; i < geometries.length; ++ i ) {
+
+				var index = geometries[ i ].index;
+
+				for ( var j = 0; j < index.count; ++ j ) {
+
+					mergedIndex.push( index.getX( j ) + indexOffset );
+
+				}
+
+				indexOffset += geometries[ i ].attributes.position.count;
+
+			}
+
+			mergedGeometry.setIndex( mergedIndex );
+
+		}
+
+		// merge attributes
+
+		for ( var name in attributes ) {
+
+			var mergedAttribute = this.mergeBufferAttributes( attributes[ name ] );
+
+			if ( ! mergedAttribute ) return null;
+
+			mergedGeometry.addAttribute( name, mergedAttribute );
+
+		}
+
+		// merge morph attributes
+
+		for ( var name in morphAttributes ) {
+
+			var numMorphTargets = morphAttributes[ name ][ 0 ].length;
+
+			if ( numMorphTargets === 0 ) break;
+
+			mergedGeometry.morphAttributes = mergedGeometry.morphAttributes || {};
+			mergedGeometry.morphAttributes[ name ] = [];
+
+			for ( var i = 0; i < numMorphTargets; ++ i ) {
+
+				var morphAttributesToMerge = [];
+
+				for ( var j = 0; j < morphAttributes[ name ].length; ++ j ) {
+
+					morphAttributesToMerge.push( morphAttributes[ name ][ j ][ i ] );
+
+				}
+
+				var mergedMorphAttribute = this.mergeBufferAttributes( morphAttributesToMerge );
+
+				if ( ! mergedMorphAttribute ) return null;
+
+				mergedGeometry.morphAttributes[ name ].push( mergedMorphAttribute );
+
+			}
+
+		}
+
+		return mergedGeometry;
+
+	},
+
+	/**
+	 * @param {Array<BufferAttribute>} attributes
+	 * @return {BufferAttribute}
+	 */
+	mergeBufferAttributes: function ( attributes ) {
+
+		var TypedArray;
+		var itemSize;
+		var normalized;
+		var arrayLength = 0;
+
+		for ( var i = 0; i < attributes.length; ++ i ) {
+
+			var attribute = attributes[ i ];
+
+			if ( attribute.isInterleavedBufferAttribute ) return null;
+
+			if ( TypedArray === undefined ) TypedArray = attribute.array.constructor;
+			if ( TypedArray !== attribute.array.constructor ) return null;
+
+			if ( itemSize === undefined ) itemSize = attribute.itemSize;
+			if ( itemSize !== attribute.itemSize ) return null;
+
+			if ( normalized === undefined ) normalized = attribute.normalized;
+			if ( normalized !== attribute.normalized ) return null;
+
+			arrayLength += attribute.array.length;
+
+		}
+
+		var array = new TypedArray( arrayLength );
+		var offset = 0;
+
+		for ( var i = 0; i < attributes.length; ++ i ) {
+
+			array.set( attributes[ i ].array, offset );
+
+			offset += attributes[ i ].array.length;
+
+		}
+
+		return new BufferAttribute( array, itemSize, normalized );
+
+	},
+
+	/**
+	 * @param {Array<BufferAttribute>} attributes
+	 * @return {Array<InterleavedBufferAttribute>}
+	 */
+	interleaveAttributes: function ( attributes ) {
+
+		// Interleaves the provided attributes into an InterleavedBuffer and returns
+		// a set of InterleavedBufferAttributes for each attribute
+		var TypedArray;
+		var arrayLength = 0;
+		var stride = 0;
+
+		// calculate the the length and type of the interleavedBuffer
+		for ( var i = 0, l = attributes.length; i < l; ++ i ) {
+
+			var attribute = attributes[ i ];
+
+			if ( TypedArray === undefined ) TypedArray = attribute.array.constructor;
+			if ( TypedArray !== attribute.array.constructor ) {
+
+				console.warn( 'AttributeBuffers of different types cannot be interleaved' );
+				return null;
+
+			}
+
+			arrayLength += attribute.array.length;
+			stride += attribute.itemSize;
+
+		}
+
+		// Create the set of buffer attributes
+		var interleavedBuffer = new InterleavedBuffer( new TypedArray( arrayLength ), stride );
+		var offset = 0;
+		var res = [];
+		var getters = [ 'getX', 'getY', 'getZ', 'getW' ];
+		var setters = [ 'setX', 'setY', 'setZ', 'setW' ];
+
+		for ( var j = 0, l = attributes.length; j < l; j ++ ) {
+
+			var attribute = attributes[ j ];
+			var itemSize = attribute.itemSize;
+			var count = attribute.count;
+			var iba = new InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, attribute.normalized );
+			res.push( iba );
+
+			offset += itemSize;
+
+			// Move the data for each attribute into the new interleavedBuffer
+			// at the appropriate offset
+			for ( var c = 0; c < count; c ++ ) {
+
+				for ( var k = 0; k < itemSize; k ++ ) {
+
+					iba[ setters[ k ] ]( c, attribute[ getters[ k ] ]( c ) );
+
+				}
+
+			}
+
+		}
+
+		return res;
+
+	},
+
+	/**
+	 * @param {Array<BufferGeometry>} geometry
+	 * @return {number}
+	 */
+	estimateBytesUsed: function ( geometry ) {
+
+		// Return the estimated memory used by this geometry in bytes
+		// Calculate using itemSize, count, and BYTES_PER_ELEMENT to account
+		// for InterleavedBufferAttributes.
+		var mem = 0;
+		for ( var name in geometry.attributes ) {
+
+			var attr = geometry.getAttribute( name );
+			mem += attr.count * attr.itemSize * attr.array.BYTES_PER_ELEMENT;
+
+		}
+
+		var indices = geometry.getIndex();
+		mem += indices ? indices.count * indices.itemSize * indices.array.BYTES_PER_ELEMENT : 0;
+		return mem;
+
+	},
+
+	/**
+	 * @param {BufferGeometry} geometry
+	 * @param {number} tolerance
+	 * @return {BufferGeometry>}
+	 */
+	mergeVertices: function ( geometry, tolerance = 1e-4 ) {
+
+		tolerance = Math.max( tolerance, Number.EPSILON );
+
+		// Generate an index buffer if the geometry doesn't have one, or optimize it
+		// if it's already available.
+		var hashToIndex = {};
+		var indices = geometry.getIndex();
+		var positions = geometry.getAttribute( 'position' );
+		var vertexCount = indices ? indices.count : positions.count;
+
+		// next value for triangle indices
+		var nextIndex = 0;
+
+		// attributes and new attribute arrays
+		var attributeNames = Object.keys( geometry.attributes );
+		var attrArrays = {};
+		var morphAttrsArrays = {};
+		var newIndices = [];
+		var getters = [ 'getX', 'getY', 'getZ', 'getW' ];
+
+		// initialize the arrays
+		for ( var i = 0, l = attributeNames.length; i < l; i ++ ) {
+			var name = attributeNames[ i ];
+
+			attrArrays[ name ] = [];
+
+			var morphAttr = geometry.morphAttributes[ name ];
+			if ( morphAttr ) {
+
+				morphAttrsArrays[ name ] = new Array( morphAttr.length ).fill().map( () => [] );
+
+			}
+
+		}
+
+		// convert the error tolerance to an amount of decimal places to truncate to
+		var decimalShift = Math.log10( 1 / tolerance );
+		var shiftMultiplier = Math.pow( 10, decimalShift );
+		for ( var i = 0; i < vertexCount; i ++ ) {
+
+			var index = indices ? indices.getX( i ) : i;
+
+			// Generate a hash for the vertex attributes at the current index 'i'
+			var hash = '';
+			for ( var j = 0, l = attributeNames.length; j < l; j ++ ) {
+
+				var name = attributeNames[ j ];
+				var attribute = geometry.getAttribute( name );
+				var itemSize = attribute.itemSize;
+
+				for ( var k = 0; k < itemSize; k ++ ) {
+
+					// double tilde truncates the decimal value
+					hash += `${ ~ ~ ( attribute[ getters[ k ] ]( index ) * shiftMultiplier ) },`;
+
+				}
+
+			}
+
+			// Add another reference to the vertex if it's already
+			// used by another index
+			if ( hash in hashToIndex ) {
+
+				newIndices.push( hashToIndex[ hash ] );
+
+			} else {
+
+				// copy data to the new index in the attribute arrays
+				for ( var j = 0, l = attributeNames.length; j < l; j ++ ) {
+
+					var name = attributeNames[ j ];
+					var attribute = geometry.getAttribute( name );
+					var morphAttr = geometry.morphAttributes[ name ];
+					var itemSize = attribute.itemSize;
+					var newarray = attrArrays[ name ];
+					var newMorphArrays = morphAttrsArrays[ name ];
+
+					for ( var k = 0; k < itemSize; k ++ ) {
+
+						var getterFunc = getters[ k ];
+						newarray.push( attribute[ getterFunc ]( index ) );
+
+						if ( morphAttr ) {
+
+							for ( var m = 0, ml = morphAttr.length; m < ml; m ++ ) {
+
+								newMorphArrays[ m ].push( morphAttr[ m ][ getterFunc ]( index ) );
+
+							}
+
+						}
+
+					}
+
+				}
+
+				hashToIndex[ hash ] = nextIndex;
+				newIndices.push( nextIndex );
+				nextIndex ++;
+
+			}
+
+		}
+
+		// Generate typed arrays from new attribute arrays and update
+		// the attributeBuffers
+		const result = geometry.clone();
+		for ( var i = 0, l = attributeNames.length; i < l; i ++ ) {
+
+			var name = attributeNames[ i ];
+			var oldAttribute = geometry.getAttribute( name );
+			var attribute;
+
+			var buffer = new oldAttribute.array.constructor( attrArrays[ name ] );
+			if ( oldAttribute.isInterleavedBufferAttribute ) {
+
+				attribute = new BufferAttribute( buffer, oldAttribute.itemSize, oldAttribute.itemSize );
+
+			} else {
+
+				attribute = geometry.getAttribute( name ).clone();
+				attribute.setArray( buffer );
+
+			}
+
+			result.addAttribute( name, attribute );
+
+			// Update the attribute arrays
+			if ( name in morphAttrsArrays ) {
+
+				for ( var j = 0; j < morphAttrsArrays[ name ].length; j ++ ) {
+
+					var morphAttribute = geometry.morphAttributes[ name ][ j ].clone();
+					morphAttribute.setArray( new morphAttribute.array.constructor( morphAttrsArrays[ name ][ j ] ) );
+					result.morphAttributes[ name ][ j ] = morphAttribute;
+
+				}
+
+			}
+
+		}
+
+		// Generate an index buffer typed array
+		var cons = Uint8Array;
+		if ( newIndices.length >= Math.pow( 2, 8 ) ) cons = Uint16Array;
+		if ( newIndices.length >= Math.pow( 2, 16 ) ) cons = Uint32Array;
+
+		var newIndexBuffer = new cons( newIndices );
+		var newIndices = null;
+		if ( indices === null ) {
+
+			newIndices = new BufferAttribute( newIndexBuffer, 1 );
+
+		} else {
+
+			newIndices = geometry.getIndex().clone();
+			newIndices.setArray( newIndexBuffer );
+
+		}
+
+		result.setIndex( newIndices );
+
+		return result;
+
+	}
+
+};
+
+export { BufferGeometryUtils };

+ 13 - 0
examples/jsm/utils/GeometryUtils.d.ts

@@ -0,0 +1,13 @@
+/**
+ * @deprecated
+ */
+export namespace GeometryUtils {
+    /**
+     * @deprecated Use {@link Geometry#merge geometry.merge( geometry2, matrix, materialIndexOffset )} instead.
+     */
+    export function merge(geometry1: any, geometry2: any, materialIndexOffset?: any): any;
+    /**
+     * @deprecated Use {@link Geometry#center geometry.center()} instead.
+     */
+    export function center(geometry: any): any;
+}

+ 307 - 0
examples/jsm/utils/GeometryUtils.js

@@ -0,0 +1,307 @@
+/**
+ * @author mrdoob / http://mrdoob.com/
+ * @author alteredq / http://alteredqualia.com/
+ */
+
+import {
+	Mesh,
+	Vector3
+} from "../../../build/three.module.js";
+
+var GeometryUtils = {
+
+	// Merge two geometries or geometry and geometry from object (using object's transform)
+
+	merge: function ( geometry1, geometry2, materialIndexOffset ) {
+
+		console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
+
+		var matrix;
+
+		if ( geometry2 instanceof Mesh ) {
+
+			geometry2.matrixAutoUpdate && geometry2.updateMatrix();
+
+			matrix = geometry2.matrix;
+			geometry2 = geometry2.geometry;
+
+		}
+
+		geometry1.merge( geometry2, matrix, materialIndexOffset );
+
+	},
+
+	// Get random point in triangle (via barycentric coordinates)
+	// 	(uniform distribution)
+	// 	http://www.cgafaq.info/wiki/Random_Point_In_Triangle
+
+	randomPointInTriangle: function () {
+
+		var vector = new Vector3();
+
+		return function ( vectorA, vectorB, vectorC ) {
+
+			var point = new Vector3();
+
+			var a = Math.random();
+			var b = Math.random();
+
+			if ( ( a + b ) > 1 ) {
+
+				a = 1 - a;
+				b = 1 - b;
+
+			}
+
+			var c = 1 - a - b;
+
+			point.copy( vectorA );
+			point.multiplyScalar( a );
+
+			vector.copy( vectorB );
+			vector.multiplyScalar( b );
+
+			point.add( vector );
+
+			vector.copy( vectorC );
+			vector.multiplyScalar( c );
+
+			point.add( vector );
+
+			return point;
+
+		};
+
+	}(),
+
+	// Get random point in face (triangle)
+	// (uniform distribution)
+
+	randomPointInFace: function ( face, geometry ) {
+
+		var vA, vB, vC;
+
+		vA = geometry.vertices[ face.a ];
+		vB = geometry.vertices[ face.b ];
+		vC = geometry.vertices[ face.c ];
+
+		return GeometryUtils.randomPointInTriangle( vA, vB, vC );
+
+	},
+
+	// Get uniformly distributed random points in mesh
+	// 	- create array with cumulative sums of face areas
+	//  - pick random number from 0 to total area
+	//  - find corresponding place in area array by binary search
+	//	- get random point in face
+
+	randomPointsInGeometry: function ( geometry, n ) {
+
+		var face, i,
+			faces = geometry.faces,
+			vertices = geometry.vertices,
+			il = faces.length,
+			totalArea = 0,
+			cumulativeAreas = [],
+			vA, vB, vC;
+
+		// precompute face areas
+
+		for ( i = 0; i < il; i ++ ) {
+
+			face = faces[ i ];
+
+			vA = vertices[ face.a ];
+			vB = vertices[ face.b ];
+			vC = vertices[ face.c ];
+
+			face._area = GeometryUtils.triangleArea( vA, vB, vC );
+
+			totalArea += face._area;
+
+			cumulativeAreas[ i ] = totalArea;
+
+		}
+
+		// binary search cumulative areas array
+
+		function binarySearchIndices( value ) {
+
+			function binarySearch( start, end ) {
+
+				// return closest larger index
+				// if exact number is not found
+
+				if ( end < start )
+					return start;
+
+				var mid = start + Math.floor( ( end - start ) / 2 );
+
+				if ( cumulativeAreas[ mid ] > value ) {
+
+					return binarySearch( start, mid - 1 );
+
+				} else if ( cumulativeAreas[ mid ] < value ) {
+
+					return binarySearch( mid + 1, end );
+
+				} else {
+
+					return mid;
+
+				}
+
+			}
+
+			var result = binarySearch( 0, cumulativeAreas.length - 1 );
+			return result;
+
+		}
+
+		// pick random face weighted by face area
+
+		var r, index,
+			result = [];
+
+		var stats = {};
+
+		for ( i = 0; i < n; i ++ ) {
+
+			r = Math.random() * totalArea;
+
+			index = binarySearchIndices( r );
+
+			result[ i ] = GeometryUtils.randomPointInFace( faces[ index ], geometry );
+
+			if ( ! stats[ index ] ) {
+
+				stats[ index ] = 1;
+
+			} else {
+
+				stats[ index ] += 1;
+
+			}
+
+		}
+
+		return result;
+
+	},
+
+	randomPointsInBufferGeometry: function ( geometry, n ) {
+
+		var i,
+			vertices = geometry.attributes.position.array,
+			totalArea = 0,
+			cumulativeAreas = [],
+			vA, vB, vC;
+
+		// precompute face areas
+		vA = new Vector3();
+		vB = new Vector3();
+		vC = new Vector3();
+
+		// geometry._areas = [];
+		var il = vertices.length / 9;
+
+		for ( i = 0; i < il; i ++ ) {
+
+			vA.set( vertices[ i * 9 + 0 ], vertices[ i * 9 + 1 ], vertices[ i * 9 + 2 ] );
+			vB.set( vertices[ i * 9 + 3 ], vertices[ i * 9 + 4 ], vertices[ i * 9 + 5 ] );
+			vC.set( vertices[ i * 9 + 6 ], vertices[ i * 9 + 7 ], vertices[ i * 9 + 8 ] );
+
+			totalArea += GeometryUtils.triangleArea( vA, vB, vC );
+
+			cumulativeAreas.push( totalArea );
+
+		}
+
+		// binary search cumulative areas array
+
+		function binarySearchIndices( value ) {
+
+			function binarySearch( start, end ) {
+
+				// return closest larger index
+				// if exact number is not found
+
+				if ( end < start )
+					return start;
+
+				var mid = start + Math.floor( ( end - start ) / 2 );
+
+				if ( cumulativeAreas[ mid ] > value ) {
+
+					return binarySearch( start, mid - 1 );
+
+				} else if ( cumulativeAreas[ mid ] < value ) {
+
+					return binarySearch( mid + 1, end );
+
+				} else {
+
+					return mid;
+
+				}
+
+			}
+
+			var result = binarySearch( 0, cumulativeAreas.length - 1 );
+			return result;
+
+		}
+
+		// pick random face weighted by face area
+
+		var r, index,
+			result = [];
+
+		for ( i = 0; i < n; i ++ ) {
+
+			r = Math.random() * totalArea;
+
+			index = binarySearchIndices( r );
+
+			// result[ i ] = GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
+			vA.set( vertices[ index * 9 + 0 ], vertices[ index * 9 + 1 ], vertices[ index * 9 + 2 ] );
+			vB.set( vertices[ index * 9 + 3 ], vertices[ index * 9 + 4 ], vertices[ index * 9 + 5 ] );
+			vC.set( vertices[ index * 9 + 6 ], vertices[ index * 9 + 7 ], vertices[ index * 9 + 8 ] );
+			result[ i ] = GeometryUtils.randomPointInTriangle( vA, vB, vC );
+
+		}
+
+		return result;
+
+	},
+
+	// Get triangle area (half of parallelogram)
+	// http://mathworld.wolfram.com/TriangleArea.html
+
+	triangleArea: function () {
+
+		var vector1 = new Vector3();
+		var vector2 = new Vector3();
+
+		return function ( vectorA, vectorB, vectorC ) {
+
+			vector1.subVectors( vectorB, vectorA );
+			vector2.subVectors( vectorC, vectorA );
+			vector1.cross( vector2 );
+
+			return 0.5 * vector1.length();
+
+		};
+
+	}(),
+
+	center: function ( geometry ) {
+
+		console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
+		return geometry.center();
+
+	}
+
+};
+
+export { GeometryUtils };

+ 67 - 0
examples/jsm/utils/MathUtils.js

@@ -0,0 +1,67 @@
+/**
+ * @author WestLangley / http://github.com/WestLangley
+ * @author thezwap / http://github.com/thezwap
+ */
+
+
+
+var MathUtils = {
+
+    setQuaternionFromProperEuler: function ( q, a, b, c, order ) {
+
+        // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
+
+        // rotations are applied to the axes in the order specified by 'order'
+        // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
+        // angles are in radians
+
+        var cos = Math.cos;
+        var sin = Math.sin;
+
+        var c2 = cos( b / 2 );
+        var s2 = sin( b / 2 );
+
+        var c13 = cos( ( a + c ) / 2 );
+        var s13 = sin( ( a + c ) / 2 );
+
+        var c1_3 = cos( ( a - c ) / 2 );
+        var s1_3 = sin( ( a - c ) / 2 );
+
+        var c3_1 = cos( ( c - a ) / 2 );
+        var s3_1 = sin( ( c - a ) / 2 );
+
+        if ( order === 'XYX' ) {
+
+            q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
+
+        } else if ( order === 'YZY' ) {
+
+            q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
+
+        } else if ( order === 'ZXZ' ) {
+
+            q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
+
+        } else if ( order === 'XZX' ) {
+
+            q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
+
+        } else if ( order === 'YXY' ) {
+
+            q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
+
+        } else if ( order === 'ZYZ' ) {
+
+            q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
+
+        } else {
+
+            console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order.' );
+
+        }
+
+    }
+
+};
+
+export { MathUtils };

+ 7 - 0
examples/jsm/utils/SceneUtils.d.ts

@@ -0,0 +1,7 @@
+import { Geometry, Material, Object3D, Scene } from '../../../src/Three';
+
+export namespace SceneUtils {
+    export function createMultiMaterialObject(geometry: Geometry, materials: Material[]): Object3D;
+    export function detach(child: Object3D, parent: Object3D, scene: Scene): void;
+    export function attach(child: Object3D, scene: Scene, parent: Object3D): void;
+}

+ 46 - 0
examples/jsm/utils/SceneUtils.js

@@ -0,0 +1,46 @@
+/**
+ * @author alteredq / http://alteredqualia.com/
+ */
+
+import {
+	Group,
+	Matrix4,
+	Mesh
+} from "../../../build/three.module.js";
+
+var SceneUtils = {
+
+	createMultiMaterialObject: function ( geometry, materials ) {
+
+		var group = new Group();
+
+		for ( var i = 0, l = materials.length; i < l; i ++ ) {
+
+			group.add( new Mesh( geometry, materials[ i ] ) );
+
+		}
+
+		return group;
+
+	},
+
+	detach: function ( child, parent, scene ) {
+
+		child.applyMatrix( parent.matrixWorld );
+		parent.remove( child );
+		scene.add( child );
+
+	},
+
+	attach: function ( child, scene, parent ) {
+
+		child.applyMatrix( new Matrix4().getInverse( parent.matrixWorld ) );
+
+		scene.remove( child );
+		parent.add( child );
+
+	}
+
+};
+
+export { SceneUtils };

+ 208 - 0
examples/jsm/utils/ShadowMapViewer.js

@@ -0,0 +1,208 @@
+/**
+ * @author arya-s / https://github.com/arya-s
+ *
+ * This is a helper for visualising a given light's shadow map.
+ * It works for shadow casting lights: THREE.DirectionalLight and THREE.SpotLight.
+ * It renders out the shadow map and displays it on a HUD.
+ *
+ * Example usage:
+ *	1) Include <script src='examples/js/utils/ShadowMapViewer.js'><script> in your html file
+ *
+ *	2) Create a shadow casting light and name it optionally:
+ *		var light = new THREE.DirectionalLight( 0xffffff, 1 );
+ *		light.castShadow = true;
+ *		light.name = 'Sun';
+ *
+ *	3) Create a shadow map viewer for that light and set its size and position optionally:
+ *		var shadowMapViewer = new ShadowMapViewer( light );
+ *		shadowMapViewer.size.set( 128, 128 );	//width, height  default: 256, 256
+ *		shadowMapViewer.position.set( 10, 10 );	//x, y in pixel	 default: 0, 0 (top left corner)
+ *
+ *	4) Render the shadow map viewer in your render loop:
+ *		shadowMapViewer.render( renderer );
+ *
+ *	5) Optionally: Update the shadow map viewer on window resize:
+ *		shadowMapViewer.updateForWindowResize();
+ *
+ *	6) If you set the position or size members directly, you need to call shadowMapViewer.update();
+ */
+
+import {
+	DoubleSide,
+	LinearFilter,
+	Mesh,
+	MeshBasicMaterial,
+	OrthographicCamera,
+	PlaneBufferGeometry,
+	Scene,
+	ShaderMaterial,
+	Texture,
+	UniformsUtils,
+	UnpackDepthRGBAShader
+} from "../../../build/three.module.js";
+
+var ShadowMapViewer = function ( light ) {
+
+	//- Internals
+	var scope = this;
+	var doRenderLabel = ( light.name !== undefined && light.name !== '' );
+	var userAutoClearSetting;
+
+	//Holds the initial position and dimension of the HUD
+	var frame = {
+		x: 10,
+		y: 10,
+		width: 256,
+		height: 256
+	};
+
+	var camera = new OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, 1, 10 );
+	camera.position.set( 0, 0, 2 );
+	var scene = new Scene();
+
+	//HUD for shadow map
+	var shader = UnpackDepthRGBAShader;
+
+	var uniforms = new UniformsUtils.clone( shader.uniforms );
+	var material = new ShaderMaterial( {
+		uniforms: uniforms,
+		vertexShader: shader.vertexShader,
+		fragmentShader: shader.fragmentShader
+	} );
+	var plane = new PlaneBufferGeometry( frame.width, frame.height );
+	var mesh = new Mesh( plane, material );
+
+	scene.add( mesh );
+
+
+	//Label for light's name
+	var labelCanvas, labelMesh;
+
+	if ( doRenderLabel ) {
+
+		labelCanvas = document.createElement( 'canvas' );
+
+		var context = labelCanvas.getContext( '2d' );
+		context.font = 'Bold 20px Arial';
+
+		var labelWidth = context.measureText( light.name ).width;
+		labelCanvas.width = labelWidth;
+		labelCanvas.height = 25;	//25 to account for g, p, etc.
+
+		context.font = 'Bold 20px Arial';
+		context.fillStyle = 'rgba( 255, 0, 0, 1 )';
+		context.fillText( light.name, 0, 20 );
+
+		var labelTexture = new Texture( labelCanvas );
+		labelTexture.magFilter = LinearFilter;
+		labelTexture.minFilter = LinearFilter;
+		labelTexture.needsUpdate = true;
+
+		var labelMaterial = new MeshBasicMaterial( { map: labelTexture, side: DoubleSide } );
+		labelMaterial.transparent = true;
+
+		var labelPlane = new PlaneBufferGeometry( labelCanvas.width, labelCanvas.height );
+		labelMesh = new Mesh( labelPlane, labelMaterial );
+
+		scene.add( labelMesh );
+
+	}
+
+
+	function resetPosition () {
+
+		scope.position.set( scope.position.x, scope.position.y );
+
+	}
+
+	//- API
+	// Set to false to disable displaying this shadow map
+	this.enabled = true;
+
+	// Set the size of the displayed shadow map on the HUD
+	this.size = {
+		width: frame.width,
+		height: frame.height,
+		set: function ( width, height ) {
+
+			this.width = width;
+			this.height = height;
+
+			mesh.scale.set( this.width / frame.width, this.height / frame.height, 1 );
+
+			//Reset the position as it is off when we scale stuff
+			resetPosition();
+
+		}
+	};
+
+	// Set the position of the displayed shadow map on the HUD
+	this.position = {
+		x: frame.x,
+		y: frame.y,
+		set: function ( x, y ) {
+
+			this.x = x;
+			this.y = y;
+
+			var width = scope.size.width;
+			var height = scope.size.height;
+
+			mesh.position.set( - window.innerWidth / 2 + width / 2 + this.x, window.innerHeight / 2 - height / 2 - this.y, 0 );
+
+			if ( doRenderLabel ) labelMesh.position.set( mesh.position.x, mesh.position.y - scope.size.height / 2 + labelCanvas.height / 2, 0 );
+
+		}
+	};
+
+	this.render = function ( renderer ) {
+
+		if ( this.enabled ) {
+
+			//Because a light's .shadowMap is only initialised after the first render pass
+			//we have to make sure the correct map is sent into the shader, otherwise we
+			//always end up with the scene's first added shadow casting light's shadowMap
+			//in the shader
+			//See: https://github.com/mrdoob/three.js/issues/5932
+			uniforms.tDiffuse.value = light.shadow.map.texture;
+
+			userAutoClearSetting = renderer.autoClear;
+			renderer.autoClear = false; // To allow render overlay
+			renderer.clearDepth();
+			renderer.render( scene, camera );
+			renderer.autoClear = userAutoClearSetting;	//Restore user's setting
+
+		}
+
+	};
+
+	this.updateForWindowResize = function () {
+
+		if ( this.enabled ) {
+
+			 camera.left = window.innerWidth / - 2;
+			 camera.right = window.innerWidth / 2;
+			 camera.top = window.innerHeight / 2;
+			 camera.bottom = window.innerHeight / - 2;
+			 camera.updateProjectionMatrix();
+
+			 this.update();
+		}
+
+	};
+
+	this.update = function () {
+
+		this.position.set( this.position.x, this.position.y );
+		this.size.set( this.size.width, this.size.height );
+
+	};
+
+	//Force an update to set position/size
+	this.update();
+
+};
+
+ShadowMapViewer.prototype.constructor = ShadowMapViewer;
+
+export { ShadowMapViewer };

+ 548 - 0
examples/jsm/utils/SkeletonUtils.js

@@ -0,0 +1,548 @@
+/**
+ * @author sunag / http://www.sunag.com.br
+ */
+
+import {
+	AnimationClip,
+	AnimationMixer,
+	Euler,
+	Matrix4,
+	Quaternion,
+	QuaternionKeyframeTrack,
+	SkeletonHelper,
+	Vector2,
+	Vector3,
+	VectorKeyframeTrack
+} from "../../../build/three.module.js";
+
+'use strict';
+
+var SkeletonUtils = {
+
+	retarget: function () {
+
+		var pos = new Vector3(),
+			quat = new Quaternion(),
+			scale = new Vector3(),
+			bindBoneMatrix = new Matrix4(),
+			relativeMatrix = new Matrix4(),
+			globalMatrix = new Matrix4();
+
+		return function ( target, source, options ) {
+
+			options = options || {};
+			options.preserveMatrix = options.preserveMatrix !== undefined ? options.preserveMatrix : true;
+			options.preservePosition = options.preservePosition !== undefined ? options.preservePosition : true;
+			options.preserveHipPosition = options.preserveHipPosition !== undefined ? options.preserveHipPosition : false;
+			options.useTargetMatrix = options.useTargetMatrix !== undefined ? options.useTargetMatrix : false;
+			options.hip = options.hip !== undefined ? options.hip : "hip";
+			options.names = options.names || {};
+
+			var sourceBones = source.isObject3D ? source.skeleton.bones : this.getBones( source ),
+				bones = target.isObject3D ? target.skeleton.bones : this.getBones( target ),
+				bindBones,
+				bone, name, boneTo,
+				bonesPosition, i;
+
+			// reset bones
+
+			if ( target.isObject3D ) {
+
+				target.skeleton.pose();
+
+			} else {
+
+				options.useTargetMatrix = true;
+				options.preserveMatrix = false;
+
+			}
+
+			if ( options.preservePosition ) {
+
+				bonesPosition = [];
+
+				for ( i = 0; i < bones.length; i ++ ) {
+
+					bonesPosition.push( bones[ i ].position.clone() );
+
+				}
+
+			}
+
+			if ( options.preserveMatrix ) {
+
+				// reset matrix
+
+				target.updateMatrixWorld();
+
+				target.matrixWorld.identity();
+
+				// reset children matrix
+
+				for ( i = 0; i < target.children.length; ++ i ) {
+
+					target.children[ i ].updateMatrixWorld( true );
+
+				}
+
+			}
+
+			if ( options.offsets ) {
+
+				bindBones = [];
+
+				for ( i = 0; i < bones.length; ++ i ) {
+
+					bone = bones[ i ];
+					name = options.names[ bone.name ] || bone.name;
+
+					if ( options.offsets && options.offsets[ name ] ) {
+
+						bone.matrix.multiply( options.offsets[ name ] );
+
+						bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
+
+						bone.updateMatrixWorld();
+
+					}
+
+					bindBones.push( bone.matrixWorld.clone() );
+
+				}
+
+			}
+
+			for ( i = 0; i < bones.length; ++ i ) {
+
+				bone = bones[ i ];
+				name = options.names[ bone.name ] || bone.name;
+
+				boneTo = this.getBoneByName( name, sourceBones );
+
+				globalMatrix.copy( bone.matrixWorld );
+
+				if ( boneTo ) {
+
+					boneTo.updateMatrixWorld();
+
+					if ( options.useTargetMatrix ) {
+
+						relativeMatrix.copy( boneTo.matrixWorld );
+
+					} else {
+
+						relativeMatrix.getInverse( target.matrixWorld );
+						relativeMatrix.multiply( boneTo.matrixWorld );
+
+					}
+
+					// ignore scale to extract rotation
+
+					scale.setFromMatrixScale( relativeMatrix );
+					relativeMatrix.scale( scale.set( 1 / scale.x, 1 / scale.y, 1 / scale.z ) );
+
+					// apply to global matrix
+
+					globalMatrix.makeRotationFromQuaternion( quat.setFromRotationMatrix( relativeMatrix ) );
+
+					if ( target.isObject3D ) {
+
+						var boneIndex = bones.indexOf( bone ),
+							wBindMatrix = bindBones ? bindBones[ boneIndex ] : bindBoneMatrix.getInverse( target.skeleton.boneInverses[ boneIndex ] );
+
+						globalMatrix.multiply( wBindMatrix );
+
+					}
+
+					globalMatrix.copyPosition( relativeMatrix );
+
+				}
+
+				if ( bone.parent && bone.parent.isBone ) {
+
+					bone.matrix.getInverse( bone.parent.matrixWorld );
+					bone.matrix.multiply( globalMatrix );
+
+				} else {
+
+					bone.matrix.copy( globalMatrix );
+
+				}
+
+				if ( options.preserveHipPosition && name === options.hip ) {
+
+					bone.matrix.setPosition( pos.set( 0, bone.position.y, 0 ) );
+
+				}
+
+				bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
+
+				bone.updateMatrixWorld();
+
+			}
+
+			if ( options.preservePosition ) {
+
+				for ( i = 0; i < bones.length; ++ i ) {
+
+					bone = bones[ i ];
+					name = options.names[ bone.name ] || bone.name;
+
+					if ( name !== options.hip ) {
+
+						bone.position.copy( bonesPosition[ i ] );
+
+					}
+
+				}
+
+			}
+
+			if ( options.preserveMatrix ) {
+
+				// restore matrix
+
+				target.updateMatrixWorld( true );
+
+			}
+
+		};
+
+	}(),
+
+	retargetClip: function ( target, source, clip, options ) {
+
+		options = options || {};
+		options.useFirstFramePosition = options.useFirstFramePosition !== undefined ? options.useFirstFramePosition : false;
+		options.fps = options.fps !== undefined ? options.fps : 30;
+		options.names = options.names || [];
+
+		if ( ! source.isObject3D ) {
+
+			source = this.getHelperFromSkeleton( source );
+
+		}
+
+		var numFrames = Math.round( clip.duration * ( options.fps / 1000 ) * 1000 ),
+			delta = 1 / options.fps,
+			convertedTracks = [],
+			mixer = new AnimationMixer( source ),
+			bones = this.getBones( target.skeleton ),
+			boneDatas = [],
+			positionOffset,
+			bone, boneTo, boneData,
+			name, i, j;
+
+		mixer.clipAction( clip ).play();
+		mixer.update( 0 );
+
+		source.updateMatrixWorld();
+
+		for ( i = 0; i < numFrames; ++ i ) {
+
+			var time = i * delta;
+
+			this.retarget( target, source, options );
+
+			for ( j = 0; j < bones.length; ++ j ) {
+
+				name = options.names[ bones[ j ].name ] || bones[ j ].name;
+
+				boneTo = this.getBoneByName( name, source.skeleton );
+
+				if ( boneTo ) {
+
+					bone = bones[ j ];
+					boneData = boneDatas[ j ] = boneDatas[ j ] || { bone: bone };
+
+					if ( options.hip === name ) {
+
+						if ( ! boneData.pos ) {
+
+							boneData.pos = {
+								times: new Float32Array( numFrames ),
+								values: new Float32Array( numFrames * 3 )
+							};
+
+						}
+
+						if ( options.useFirstFramePosition ) {
+
+							if ( i === 0 ) {
+
+								positionOffset = bone.position.clone();
+
+							}
+
+							bone.position.sub( positionOffset );
+
+						}
+
+						boneData.pos.times[ i ] = time;
+
+						bone.position.toArray( boneData.pos.values, i * 3 );
+
+					}
+
+					if ( ! boneData.quat ) {
+
+						boneData.quat = {
+							times: new Float32Array( numFrames ),
+							values: new Float32Array( numFrames * 4 )
+						};
+
+					}
+
+					boneData.quat.times[ i ] = time;
+
+					bone.quaternion.toArray( boneData.quat.values, i * 4 );
+
+				}
+
+			}
+
+			mixer.update( delta );
+
+			source.updateMatrixWorld();
+
+		}
+
+		for ( i = 0; i < boneDatas.length; ++ i ) {
+
+			boneData = boneDatas[ i ];
+
+			if ( boneData ) {
+
+				if ( boneData.pos ) {
+
+					convertedTracks.push( new VectorKeyframeTrack(
+						".bones[" + boneData.bone.name + "].position",
+						boneData.pos.times,
+						boneData.pos.values
+					) );
+
+				}
+
+				convertedTracks.push( new QuaternionKeyframeTrack(
+					".bones[" + boneData.bone.name + "].quaternion",
+					boneData.quat.times,
+					boneData.quat.values
+				) );
+
+			}
+
+		}
+
+		mixer.uncacheAction( clip );
+
+		return new AnimationClip( clip.name, - 1, convertedTracks );
+
+	},
+
+	getHelperFromSkeleton: function ( skeleton ) {
+
+		var source = new SkeletonHelper( skeleton.bones[ 0 ] );
+		source.skeleton = skeleton;
+
+		return source;
+
+	},
+
+	getSkeletonOffsets: function () {
+
+		var targetParentPos = new Vector3(),
+			targetPos = new Vector3(),
+			sourceParentPos = new Vector3(),
+			sourcePos = new Vector3(),
+			targetDir = new Vector2(),
+			sourceDir = new Vector2();
+
+		return function ( target, source, options ) {
+
+			options = options || {};
+			options.hip = options.hip !== undefined ? options.hip : "hip";
+			options.names = options.names || {};
+
+			if ( ! source.isObject3D ) {
+
+				source = this.getHelperFromSkeleton( source );
+
+			}
+
+			var nameKeys = Object.keys( options.names ),
+				nameValues = Object.values( options.names ),
+				sourceBones = source.isObject3D ? source.skeleton.bones : this.getBones( source ),
+				bones = target.isObject3D ? target.skeleton.bones : this.getBones( target ),
+				offsets = [],
+				bone, boneTo,
+				name, i;
+
+			target.skeleton.pose();
+
+			for ( i = 0; i < bones.length; ++ i ) {
+
+				bone = bones[ i ];
+				name = options.names[ bone.name ] || bone.name;
+
+				boneTo = this.getBoneByName( name, sourceBones );
+
+				if ( boneTo && name !== options.hip ) {
+
+					var boneParent = this.getNearestBone( bone.parent, nameKeys ),
+						boneToParent = this.getNearestBone( boneTo.parent, nameValues );
+
+					boneParent.updateMatrixWorld();
+					boneToParent.updateMatrixWorld();
+
+					targetParentPos.setFromMatrixPosition( boneParent.matrixWorld );
+					targetPos.setFromMatrixPosition( bone.matrixWorld );
+
+					sourceParentPos.setFromMatrixPosition( boneToParent.matrixWorld );
+					sourcePos.setFromMatrixPosition( boneTo.matrixWorld );
+
+					targetDir.subVectors(
+						new Vector2( targetPos.x, targetPos.y ),
+						new Vector2( targetParentPos.x, targetParentPos.y )
+					).normalize();
+
+					sourceDir.subVectors(
+						new Vector2( sourcePos.x, sourcePos.y ),
+						new Vector2( sourceParentPos.x, sourceParentPos.y )
+					).normalize();
+
+					var laterialAngle = targetDir.angle() - sourceDir.angle();
+
+					var offset = new Matrix4().makeRotationFromEuler(
+						new Euler(
+							0,
+							0,
+							laterialAngle
+						)
+					);
+
+					bone.matrix.multiply( offset );
+
+					bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
+
+					bone.updateMatrixWorld();
+
+					offsets[ name ] = offset;
+
+				}
+
+			}
+
+			return offsets;
+
+		};
+
+	}(),
+
+	renameBones: function ( skeleton, names ) {
+
+		var bones = this.getBones( skeleton );
+
+		for ( var i = 0; i < bones.length; ++ i ) {
+
+			var bone = bones[ i ];
+
+			if ( names[ bone.name ] ) {
+
+				bone.name = names[ bone.name ];
+
+			}
+
+		}
+
+		return this;
+
+	},
+
+	getBones: function ( skeleton ) {
+
+		return Array.isArray( skeleton ) ? skeleton : skeleton.bones;
+
+	},
+
+	getBoneByName: function ( name, skeleton ) {
+
+		for ( var i = 0, bones = this.getBones( skeleton ); i < bones.length; i ++ ) {
+
+			if ( name === bones[ i ].name )
+
+				return bones[ i ];
+
+		}
+
+	},
+
+	getNearestBone: function ( bone, names ) {
+
+		while ( bone.isBone ) {
+
+			if ( names.indexOf( bone.name ) !== - 1 ) {
+
+				return bone;
+
+			}
+
+			bone = bone.parent;
+
+		}
+
+	},
+
+	findBoneTrackData: function ( name, tracks ) {
+
+		var regexp = /\[(.*)\]\.(.*)/,
+			result = { name: name };
+
+		for ( var i = 0; i < tracks.length; ++ i ) {
+
+			// 1 is track name
+			// 2 is track type
+			var trackData = regexp.exec( tracks[ i ].name );
+
+			if ( trackData && name === trackData[ 1 ] ) {
+
+				result[ trackData[ 2 ] ] = i;
+
+			}
+
+		}
+
+		return result;
+
+	},
+
+	getEqualsBonesNames: function ( skeleton, targetSkeleton ) {
+
+		var sourceBones = this.getBones( skeleton ),
+			targetBones = this.getBones( targetSkeleton ),
+			bones = [];
+
+		search : for ( var i = 0; i < sourceBones.length; i ++ ) {
+
+			var boneName = sourceBones[ i ].name;
+
+			for ( var j = 0; j < targetBones.length; j ++ ) {
+
+				if ( boneName === targetBones[ j ].name ) {
+
+					bones.push( boneName );
+
+					continue search;
+
+				}
+
+			}
+
+		}
+
+		return bones;
+
+	}
+
+};
+
+export { SkeletonUtils };

+ 604 - 0
examples/jsm/utils/TypedArrayUtils.js

@@ -0,0 +1,604 @@
+
+var TypedArrayUtils = {};
+
+/**
+ * In-place quicksort for typed arrays (e.g. for Float32Array)
+ * provides fast sorting
+ * useful e.g. for a custom shader and/or BufferGeometry
+ *
+ * @author Roman Bolzern <[email protected]>, 2013
+ * @author I4DS http://www.fhnw.ch/i4ds, 2013
+ * @license MIT License <http://www.opensource.org/licenses/mit-license.php>
+ *
+ * Complexity: http://bigocheatsheet.com/ see Quicksort
+ *
+ * Example: 
+ * points: [x, y, z, x, y, z, x, y, z, ...]
+ * eleSize: 3 //because of (x, y, z)
+ * orderElement: 0 //order according to x
+ */
+
+TypedArrayUtils.quicksortIP = function ( arr, eleSize, orderElement ) {
+
+	var stack = [];
+	var sp = - 1;
+	var left = 0;
+	var right = arr.length / eleSize - 1;
+	var tmp = 0.0, x = 0, y = 0;
+
+	var swapF = function ( a, b ) {
+
+		a *= eleSize; b *= eleSize;
+
+		for ( y = 0; y < eleSize; y ++ ) {
+
+			tmp = arr[ a + y ];
+			arr[ a + y ] = arr[ b + y ];
+			arr[ b + y ] = tmp;
+
+		}
+
+	};
+	
+	var i, j, swap = new Float32Array( eleSize ), temp = new Float32Array( eleSize );
+
+	while ( true ) {
+
+		if ( right - left <= 25 ) {
+
+			for ( j = left + 1; j <= right; j ++ ) {
+
+				for ( x = 0; x < eleSize; x ++ ) {
+			
+					swap[ x ] = arr[ j * eleSize + x ];
+
+				}
+				
+				i = j - 1;
+				
+				while ( i >= left && arr[ i * eleSize + orderElement ] > swap[ orderElement ] ) {
+
+					for ( x = 0; x < eleSize; x ++ ) {
+
+						arr[ ( i + 1 ) * eleSize + x ] = arr[ i * eleSize + x ];
+
+					}
+
+					i --;
+
+				}
+
+				for ( x = 0; x < eleSize; x ++ ) {
+
+					arr[ ( i + 1 ) * eleSize + x ] = swap[ x ];
+
+				}
+
+			}
+			
+			if ( sp == - 1 ) break;
+
+			right = stack[ sp -- ]; //?
+			left = stack[ sp -- ];
+
+		} else {
+
+			var median = ( left + right ) >> 1;
+
+			i = left + 1;
+			j = right;
+	
+			swapF( median, i );
+
+			if ( arr[ left * eleSize + orderElement ] > arr[ right * eleSize + orderElement ] ) {
+		
+				swapF( left, right );
+				
+			}
+
+			if ( arr[ i * eleSize + orderElement ] > arr[ right * eleSize + orderElement ] ) {
+		
+				swapF( i, right );
+		
+			}
+
+			if ( arr[ left * eleSize + orderElement ] > arr[ i * eleSize + orderElement ] ) {
+		
+				swapF( left, i );
+			
+			}
+
+			for ( x = 0; x < eleSize; x ++ ) {
+
+				temp[ x ] = arr[ i * eleSize + x ];
+
+			}
+			
+			while ( true ) {
+				
+				do i ++; while ( arr[ i * eleSize + orderElement ] < temp[ orderElement ] );
+				do j --; while ( arr[ j * eleSize + orderElement ] > temp[ orderElement ] );
+				
+				if ( j < i ) break;
+		
+				swapF( i, j );
+			
+			}
+
+			for ( x = 0; x < eleSize; x ++ ) {
+
+				arr[ ( left + 1 ) * eleSize + x ] = arr[ j * eleSize + x ];
+				arr[ j * eleSize + x ] = temp[ x ];
+
+			}
+
+			if ( right - i + 1 >= j - left ) {
+
+				stack[ ++ sp ] = i;
+				stack[ ++ sp ] = right;
+				right = j - 1;
+
+			} else {
+
+				stack[ ++ sp ] = left;
+				stack[ ++ sp ] = j - 1;
+				left = i;
+
+			}
+
+		}
+
+	}
+
+	return arr;
+
+};
+
+
+
+/**
+ * k-d Tree for typed arrays (e.g. for Float32Array), in-place
+ * provides fast nearest neighbour search
+ * useful e.g. for a custom shader and/or BufferGeometry, saves tons of memory
+ * has no insert and remove, only buildup and neares neighbour search
+ *
+ * Based on https://github.com/ubilabs/kd-tree-javascript by Ubilabs
+ *
+ * @author Roman Bolzern <[email protected]>, 2013
+ * @author I4DS http://www.fhnw.ch/i4ds, 2013
+ * @license MIT License <http://www.opensource.org/licenses/mit-license.php>
+ *
+ * Requires typed array quicksort
+ *
+ * Example: 
+ * points: [x, y, z, x, y, z, x, y, z, ...]
+ * metric: function(a, b){	return Math.pow(a[0] - b[0], 2) +  Math.pow(a[1] - b[1], 2) +  Math.pow(a[2] - b[2], 2); }  //Manhatten distance
+ * eleSize: 3 //because of (x, y, z)
+ *
+ * Further information (including mathematical properties)
+ * http://en.wikipedia.org/wiki/Binary_tree
+ * http://en.wikipedia.org/wiki/K-d_tree
+ *
+ * If you want to further minimize memory usage, remove Node.depth and replace in search algorithm with a traversal to root node (see comments at TypedArrayUtils.Kdtree.prototype.Node)
+ */
+
+ TypedArrayUtils.Kdtree = function ( points, metric, eleSize ) {
+
+	var self = this;
+	
+	var maxDepth = 0;
+	
+	var getPointSet = function ( points, pos ) {
+
+		return points.subarray( pos * eleSize, pos * eleSize + eleSize );
+
+	};
+		
+	function buildTree( points, depth, parent, pos ) {
+
+		var dim = depth % eleSize,
+			median,
+			node,
+			plength = points.length / eleSize;
+
+		if ( depth > maxDepth ) maxDepth = depth;
+		
+		if ( plength === 0 ) return null;
+		if ( plength === 1 ) {
+
+			return new self.Node( getPointSet( points, 0 ), depth, parent, pos );
+
+		}
+
+		TypedArrayUtils.quicksortIP( points, eleSize, dim );
+		
+		median = Math.floor( plength / 2 );
+		
+		node = new self.Node( getPointSet( points, median ), depth, parent, median + pos );
+		node.left = buildTree( points.subarray( 0, median * eleSize ), depth + 1, node, pos );
+		node.right = buildTree( points.subarray( ( median + 1 ) * eleSize, points.length ), depth + 1, node, pos + median + 1 );
+
+		return node;
+	
+	}
+
+	this.root = buildTree( points, 0, null, 0 );
+		
+	this.getMaxDepth = function () {
+
+		return maxDepth;
+
+	};
+	
+	this.nearest = function ( point, maxNodes, maxDistance ) {
+	
+		 /* point: array of size eleSize 
+			maxNodes: max amount of nodes to return 
+			maxDistance: maximum distance to point result nodes should have
+			condition (not implemented): function to test node before it's added to the result list, e.g. test for view frustum
+		*/
+
+		var i,
+			result,
+			bestNodes;
+
+		bestNodes = new TypedArrayUtils.Kdtree.BinaryHeap(
+
+			function ( e ) {
+
+				return - e[ 1 ];
+
+			}
+
+					);
+
+		function nearestSearch( node ) {
+
+			var bestChild,
+				dimension = node.depth % eleSize,
+				ownDistance = metric( point, node.obj ),
+				linearDistance = 0,
+				otherChild,
+				i,
+				linearPoint = [];
+
+			function saveNode( node, distance ) {
+
+				bestNodes.push( [ node, distance ] );
+
+				if ( bestNodes.size() > maxNodes ) {
+
+					bestNodes.pop();
+
+				}
+
+			}
+
+			for ( i = 0; i < eleSize; i += 1 ) {
+
+				if ( i === node.depth % eleSize ) {
+
+					linearPoint[ i ] = point[ i ];
+
+				} else {
+
+					linearPoint[ i ] = node.obj[ i ];
+
+				}
+
+			}
+
+			linearDistance = metric( linearPoint, node.obj );
+
+			// if it's a leaf
+
+			if ( node.right === null && node.left === null ) {
+
+				if ( bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[ 1 ] ) {
+
+					saveNode( node, ownDistance );
+
+				}
+
+				return;
+
+			}
+
+			if ( node.right === null ) {
+
+				bestChild = node.left;
+
+			} else if ( node.left === null ) {
+
+				bestChild = node.right;
+
+			} else {
+
+				if ( point[ dimension ] < node.obj[ dimension ] ) {
+
+					bestChild = node.left;
+
+				} else {
+
+					bestChild = node.right;
+
+				}
+
+			}
+
+			// recursive search
+
+			nearestSearch( bestChild );
+
+			if ( bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[ 1 ] ) {
+
+				saveNode( node, ownDistance );
+
+			}
+
+			// if there's still room or the current distance is nearer than the best distance
+
+			if ( bestNodes.size() < maxNodes || Math.abs( linearDistance ) < bestNodes.peek()[ 1 ] ) {
+
+				if ( bestChild === node.left ) {
+
+					otherChild = node.right;
+
+				} else {
+
+					otherChild = node.left;
+
+				}
+
+				if ( otherChild !== null ) {
+
+					nearestSearch( otherChild );
+
+				}
+
+			}
+
+		}
+
+		if ( maxDistance ) {
+
+			for ( i = 0; i < maxNodes; i += 1 ) {
+
+				bestNodes.push( [ null, maxDistance ] );
+
+			}
+
+		}
+
+		nearestSearch( self.root );
+
+		result = [];
+
+		for ( i = 0; i < maxNodes; i += 1 ) {
+
+			if ( bestNodes.content[ i ][ 0 ] ) {
+
+				result.push( [ bestNodes.content[ i ][ 0 ], bestNodes.content[ i ][ 1 ] ] );
+
+			}
+
+		}
+		
+		return result;
+	
+	};
+	
+};
+
+/**
+ * If you need to free up additional memory and agree with an additional O( log n ) traversal time you can get rid of "depth" and "pos" in Node:
+ * Depth can be easily done by adding 1 for every parent (care: root node has depth 0, not 1)
+ * Pos is a bit tricky: Assuming the tree is balanced (which is the case when after we built it up), perform the following steps:
+ *   By traversing to the root store the path e.g. in a bit pattern (01001011, 0 is left, 1 is right)
+ *   From buildTree we know that "median = Math.floor( plength / 2 );", therefore for each bit...
+ *     0: amountOfNodesRelevantForUs = Math.floor( (pamountOfNodesRelevantForUs - 1) / 2 );
+ *     1: amountOfNodesRelevantForUs = Math.ceil( (pamountOfNodesRelevantForUs - 1) / 2 );
+ *        pos += Math.floor( (pamountOfNodesRelevantForUs - 1) / 2 );
+ *     when recursion done, we still need to add all left children of target node:
+ *        pos += Math.floor( (pamountOfNodesRelevantForUs - 1) / 2 );
+ *        and I think you need to +1 for the current position, not sure.. depends, try it out ^^
+ *
+ * I experienced that for 200'000 nodes you can get rid of 4 MB memory each, leading to 8 MB memory saved.
+ */
+TypedArrayUtils.Kdtree.prototype.Node = function ( obj, depth, parent, pos ) {
+
+	this.obj = obj;
+	this.left = null;
+	this.right = null;
+	this.parent = parent;
+	this.depth = depth;
+	this.pos = pos;
+
+}; 
+
+/**
+ * Binary heap implementation
+ * @author http://eloquentjavascript.net/appendix2.htm
+ */
+
+TypedArrayUtils.Kdtree.BinaryHeap = function ( scoreFunction ) {
+
+	this.content = [];
+	this.scoreFunction = scoreFunction;
+
+};
+
+TypedArrayUtils.Kdtree.BinaryHeap.prototype = {
+
+	push: function ( element ) {
+
+		// Add the new element to the end of the array.
+		this.content.push( element );
+
+		// Allow it to bubble up.
+		this.bubbleUp( this.content.length - 1 );
+
+	},
+
+	pop: function () {
+
+		// Store the first element so we can return it later.
+		var result = this.content[ 0 ];
+
+		// Get the element at the end of the array.
+		var end = this.content.pop();
+
+		// If there are any elements left, put the end element at the
+		// start, and let it sink down.
+		if ( this.content.length > 0 ) {
+
+			this.content[ 0 ] = end;
+			this.sinkDown( 0 );
+
+		}
+
+		return result;
+
+	},
+
+	peek: function () {
+
+		return this.content[ 0 ];
+
+	},
+
+	remove: function ( node ) {
+
+		var len = this.content.length;
+
+		// To remove a value, we must search through the array to find it.
+		for ( var i = 0; i < len; i ++ ) {
+
+			if ( this.content[ i ] == node ) {
+
+				// When it is found, the process seen in 'pop' is repeated
+				// to fill up the hole.
+				var end = this.content.pop();
+
+				if ( i != len - 1 ) {
+
+					this.content[ i ] = end;
+
+					if ( this.scoreFunction( end ) < this.scoreFunction( node ) ) {
+
+						this.bubbleUp( i );
+
+					} else {
+
+						this.sinkDown( i );
+
+					}
+
+				}
+
+				return;
+
+			}
+
+		}
+
+		throw new Error( "Node not found." );
+
+	},
+
+	size: function () {
+
+		return this.content.length;
+
+	},
+
+	bubbleUp: function ( n ) {
+
+		// Fetch the element that has to be moved.
+		var element = this.content[ n ];
+
+		// When at 0, an element can not go up any further.
+		while ( n > 0 ) {
+
+			// Compute the parent element's index, and fetch it.
+			var parentN = Math.floor( ( n + 1 ) / 2 ) - 1,
+				parent = this.content[ parentN ];
+
+			// Swap the elements if the parent is greater.
+			if ( this.scoreFunction( element ) < this.scoreFunction( parent ) ) {
+
+				this.content[ parentN ] = element;
+				this.content[ n ] = parent;
+
+				// Update 'n' to continue at the new position.
+				n = parentN;
+
+			} else {
+
+				// Found a parent that is less, no need to move it further.
+				break;
+
+			}
+
+		}
+
+	},
+
+	sinkDown: function ( n ) {
+
+		// Look up the target element and its score.
+		var length = this.content.length,
+			element = this.content[ n ],
+			elemScore = this.scoreFunction( element );
+
+		while ( true ) {
+
+			// Compute the indices of the child elements.
+			var child2N = ( n + 1 ) * 2, child1N = child2N - 1;
+
+			// This is used to store the new position of the element, if any.
+			var swap = null;
+
+			// If the first child exists (is inside the array)...
+			if ( child1N < length ) {
+
+				// Look it up and compute its score.
+				var child1 = this.content[ child1N ],
+					child1Score = this.scoreFunction( child1 );
+
+				// If the score is less than our element's, we need to swap.
+				if ( child1Score < elemScore ) swap = child1N;
+
+			}
+
+			// Do the same checks for the other child.
+			if ( child2N < length ) {
+
+				var child2 = this.content[ child2N ],
+					child2Score = this.scoreFunction( child2 );
+
+				if ( child2Score < ( swap === null ? elemScore : child1Score ) ) swap = child2N;
+
+			}
+
+			// If the element needs to be moved, swap it, and continue.
+			if ( swap !== null ) {
+
+				this.content[ n ] = this.content[ swap ];
+				this.content[ swap ] = element;
+				n = swap;
+
+			} else {
+
+				// Otherwise, we are done.
+				break;
+
+			}
+
+		}
+
+	}
+
+};
+
+export { TypedArrayUtils };

+ 195 - 0
examples/jsm/utils/UVsDebug.js

@@ -0,0 +1,195 @@
+/*
+ * @author zz85 / http://github.com/zz85
+ * @author WestLangley / http://github.com/WestLangley
+ * @author Mugen87 / https://github.com/Mugen87
+ *
+ * tool for "unwrapping" and debugging three.js geometries UV mapping
+ *
+ * Sample usage:
+ *	document.body.appendChild( UVsDebug( new THREE.SphereBufferGeometry( 10, 10, 10, 10 ) );
+ *
+ */
+
+import {
+	Vector2
+} from "../../../build/three.module.js";
+
+var UVsDebug = function ( geometry, size ) {
+
+	// handles wrapping of uv.x > 1 only
+
+	var abc = 'abc';
+	var a = new Vector2();
+	var b = new Vector2();
+
+	var uvs = [
+		new Vector2(),
+		new Vector2(),
+		new Vector2()
+	];
+
+	var face = [];
+
+	var canvas = document.createElement( 'canvas' );
+	var width = size || 1024; // power of 2 required for wrapping
+	var height = size || 1024;
+	canvas.width = width;
+	canvas.height = height;
+
+	var ctx = canvas.getContext( '2d' );
+	ctx.lineWidth = 2;
+	ctx.strokeStyle = 'rgba( 0, 0, 0, 1.0 )';
+	ctx.textAlign = 'center';
+
+	// paint background white
+
+	ctx.fillStyle = 'rgba( 255, 255, 255, 1.0 )';
+	ctx.fillRect( 0, 0, width, height );
+
+	if ( geometry.isGeometry ) {
+
+		var faces = geometry.faces;
+		var uvSet = geometry.faceVertexUvs[ 0 ];
+
+		for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
+
+			var face = faces[ i ];
+			var uv = uvSet[ i ];
+
+			face[ 0 ] = face.a;
+			face[ 1 ] = face.b;
+			face[ 2 ] = face.c;
+
+			uvs[ 0 ].copy( uv[ 0 ] );
+			uvs[ 1 ].copy( uv[ 1 ] );
+			uvs[ 2 ].copy( uv[ 2 ] );
+
+			processFace( face, uvs, i );
+
+		}
+
+	} else {
+
+		var index = geometry.index;
+		var uvAttribute = geometry.attributes.uv;
+
+		if ( index ) {
+
+			// indexed geometry
+
+			for ( var i = 0, il = index.count; i < il; i += 3 ) {
+
+				face[ 0 ] = index.getX( i );
+				face[ 1 ] = index.getX( i + 1 );
+				face[ 2 ] = index.getX( i + 2 );
+
+				uvs[ 0 ].fromBufferAttribute( uvAttribute, face[ 0 ] );
+				uvs[ 1 ].fromBufferAttribute( uvAttribute, face[ 1 ] );
+				uvs[ 2 ].fromBufferAttribute( uvAttribute, face[ 2 ] );
+
+				processFace( face, uvs, i );
+
+			}
+
+		} else {
+
+			// non-indexed geometry
+
+			for ( var i = 0, il = uvAttribute.count; i < il; i += 3 ) {
+
+				face[ 0 ] = i;
+				face[ 1 ] = i + 1;
+				face[ 2 ] = i + 2;
+
+				uvs[ 0 ].fromBufferAttribute( uvAttribute, face[ 0 ] );
+				uvs[ 1 ].fromBufferAttribute( uvAttribute, face[ 1 ] );
+				uvs[ 2 ].fromBufferAttribute( uvAttribute, face[ 2 ] );
+
+				processFace( face, uvs, i );
+
+			}
+
+		}
+
+	}
+
+	return canvas;
+
+	function processFace( face, uvs, index ) {
+
+		// draw contour of face
+
+		ctx.beginPath();
+
+		a.set( 0, 0 );
+
+		for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
+
+			var uv = uvs[ j ];
+
+			a.x += uv.x;
+			a.y += uv.y;
+
+			if ( j === 0 ) {
+
+				ctx.moveTo( uv.x * width, ( 1 - uv.y ) * height );
+
+			} else {
+
+				ctx.lineTo( uv.x * width, ( 1 - uv.y ) * height );
+
+			}
+
+		}
+
+		ctx.closePath();
+		ctx.stroke();
+
+		// calculate center of face
+
+		a.divideScalar( uvs.length );
+
+		// label the face number
+
+		ctx.font = '12pt Arial bold';
+		ctx.fillStyle = 'rgba( 0, 0, 0, 1.0 )';
+		ctx.fillText( index, a.x * width, ( 1 - a.y ) * height );
+
+		if ( a.x > 0.95 ) {
+
+			// wrap x // 0.95 is arbitrary
+
+			ctx.fillText( index, ( a.x % 1 ) * width, ( 1 - a.y ) * height );
+
+		}
+
+		//
+
+		ctx.font = '8pt Arial bold';
+		ctx.fillStyle = 'rgba( 0, 0, 0, 1.0 )';
+
+		// label uv edge orders
+
+		for ( j = 0, jl = uvs.length; j < jl; j ++ ) {
+
+			var uv = uvs[ j ];
+			b.addVectors( a, uv ).divideScalar( 2 );
+
+			var vnum = face[ j ];
+			ctx.fillText( abc[ j ] + vnum, b.x * width, ( 1 - b.y ) * height );
+
+			if ( b.x > 0.95 ) {
+
+				// wrap x
+
+				ctx.fillText( abc[ j ] + vnum, ( b.x % 1 ) * width, ( 1 - b.y ) * height );
+
+			}
+
+		}
+
+	}
+
+};
+
+export { UVsDebug };

+ 28 - 4
examples/webgl_morphtargets.html

@@ -51,9 +51,9 @@
 
 			var container;
 
-			var camera, scene, renderer;
+			var camera, scene, renderer, raycaster;
 
-			var mesh;
+			var mesh, mouse = new THREE.Vector2();
 
 			init();
 			animate();
@@ -69,7 +69,8 @@
 				scene.background = new THREE.Color( 0x222222 );
 				scene.fog = new THREE.Fog( 0x000000, 1, 15000 );
 
-				var light = new THREE.PointLight( 0xff2200 );
+				var light = new THREE.PointLight( 0xffffff );
+				light.position.z = 500;
 				camera.add( light );
 				scene.add( camera );
 
@@ -77,7 +78,7 @@
 				scene.add( light );
 
 				var geometry = new THREE.BoxGeometry( 100, 100, 100 );
-				var material = new THREE.MeshLambertMaterial( { color: 0xffffff, morphTargets: true } );
+				var material = new THREE.MeshLambertMaterial( { color: 0xff0000, morphTargets: true } );
 
 				// construct 8 blend shapes
 
@@ -169,6 +170,8 @@
 
 				//
 
+				raycaster = new THREE.Raycaster();
+
 				renderer = new THREE.WebGLRenderer();
 				renderer.setPixelRatio( window.devicePixelRatio );
 				renderer.setSize( window.innerWidth, window.innerHeight );
@@ -184,6 +187,27 @@
 
 				window.addEventListener( 'resize', onWindowResize, false );
 
+				document.addEventListener( 'click', onClick, false );
+
+			}
+
+			function onClick( event ) {
+
+				event.preventDefault();
+
+				mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
+				mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
+
+				raycaster.setFromCamera( mouse, camera );
+
+				var intersects = raycaster.intersectObject( mesh );
+
+				if ( intersects.length > 0 ) {
+
+					mesh.material.color.set( Math.random() * 0xffffff );
+
+				}
+
 			}
 
 			function onWindowResize() {

+ 1 - 1
examples/webgl_nearestneighbour.html

@@ -31,7 +31,7 @@
 		<div id="info"><a href="http://threejs.org" target="_blank" rel="noopener">three.js</a> webgl - typed arrays - nearest neighbour for 500,000 sprites</div>
 
 		<script src="../build/three.js"></script>
-		<script src="js/TypedArrayUtils.js"></script>
+		<script src="js/utils/TypedArrayUtils.js"></script>
 		<script src="js/controls/FirstPersonControls.js"></script>
 		<script type="x-shader/x-vertex" id="vertexshader">
 

+ 1 - 1
src/loaders/ObjectLoader.d.ts

@@ -13,7 +13,7 @@ export class ObjectLoader {
 
   load(
     url: string,
-    onLoad?: (object: Object3D) => void,
+    onLoad?: <ObjectType extends Object3D>(object: ObjectType) => void,
     onProgress?: (event: ProgressEvent) => void,
     onError?: (event: Error | ErrorEvent) => void
   ): void;

+ 41 - 38
src/objects/Mesh.js

@@ -126,6 +126,10 @@ Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
 		var tempB = new Vector3();
 		var tempC = new Vector3();
 
+		var morphA = new Vector3();
+		var morphB = new Vector3();
+		var morphC = new Vector3();
+
 		var uvA = new Vector2();
 		var uvB = new Vector2();
 		var uvC = new Vector2();
@@ -164,12 +168,43 @@ Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
 
 		}
 
-		function checkBufferGeometryIntersection( object, material, raycaster, ray, position, uv, a, b, c ) {
+		function checkBufferGeometryIntersection( object, material, raycaster, ray, position, morphPosition, uv, a, b, c ) {
 
 			vA.fromBufferAttribute( position, a );
 			vB.fromBufferAttribute( position, b );
 			vC.fromBufferAttribute( position, c );
 
+			var morphInfluences = object.morphTargetInfluences;
+
+			if ( material.morphTargets && morphPosition && morphInfluences ) {
+
+				morphA.set( 0, 0, 0 );
+				morphB.set( 0, 0, 0 );
+				morphC.set( 0, 0, 0 );
+
+				for ( var i = 0, il = morphPosition.length; i < il; i ++ ) {
+
+					var influence = morphInfluences[ i ];
+					var morphAttribute = morphPosition[ i ];
+
+					if ( influence === 0 ) continue;
+
+					tempA.fromBufferAttribute( morphAttribute, a );
+					tempB.fromBufferAttribute( morphAttribute, b );
+					tempC.fromBufferAttribute( morphAttribute, c );
+
+					morphA.addScaledVector( tempA.sub( vA ), influence );
+					morphB.addScaledVector( tempB.sub( vB ), influence );
+					morphC.addScaledVector( tempC.sub( vC ), influence );
+
+				}
+
+				vA.add( morphA );
+				vB.add( morphB );
+				vC.add( morphC );
+
+			}
+
 			var intersection = checkIntersection( object, material, raycaster, ray, vA, vB, vC, intersectionPoint );
 
 			if ( intersection ) {
@@ -232,6 +267,7 @@ Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
 				var a, b, c;
 				var index = geometry.index;
 				var position = geometry.attributes.position;
+				var morphPosition = geometry.morphAttributes.position;
 				var uv = geometry.attributes.uv;
 				var groups = geometry.groups;
 				var drawRange = geometry.drawRange;
@@ -259,7 +295,7 @@ Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
 								b = index.getX( j + 1 );
 								c = index.getX( j + 2 );
 
-								intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, ray, position, uv, a, b, c );
+								intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, ray, position, morphPosition, uv, a, b, c );
 
 								if ( intersection ) {
 
@@ -284,7 +320,7 @@ Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
 							b = index.getX( i + 1 );
 							c = index.getX( i + 2 );
 
-							intersection = checkBufferGeometryIntersection( this, material, raycaster, ray, position, uv, a, b, c );
+							intersection = checkBufferGeometryIntersection( this, material, raycaster, ray, position, morphPosition, uv, a, b, c );
 
 							if ( intersection ) {
 
@@ -317,7 +353,7 @@ Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
 								b = j + 1;
 								c = j + 2;
 
-								intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, ray, position, uv, a, b, c );
+								intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, ray, position, morphPosition, uv, a, b, c );
 
 								if ( intersection ) {
 
@@ -342,7 +378,7 @@ Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
 							b = i + 1;
 							c = i + 2;
 
-							intersection = checkBufferGeometryIntersection( this, material, raycaster, ray, position, uv, a, b, c );
+							intersection = checkBufferGeometryIntersection( this, material, raycaster, ray, position, morphPosition, uv, a, b, c );
 
 							if ( intersection ) {
 
@@ -380,39 +416,6 @@ Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
 					fvB = vertices[ face.b ];
 					fvC = vertices[ face.c ];
 
-					if ( faceMaterial.morphTargets === true ) {
-
-						var morphTargets = geometry.morphTargets;
-						var morphInfluences = this.morphTargetInfluences;
-
-						vA.set( 0, 0, 0 );
-						vB.set( 0, 0, 0 );
-						vC.set( 0, 0, 0 );
-
-						for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
-
-							var influence = morphInfluences[ t ];
-
-							if ( influence === 0 ) continue;
-
-							var targets = morphTargets[ t ].vertices;
-
-							vA.addScaledVector( tempA.subVectors( targets[ face.a ], fvA ), influence );
-							vB.addScaledVector( tempB.subVectors( targets[ face.b ], fvB ), influence );
-							vC.addScaledVector( tempC.subVectors( targets[ face.c ], fvC ), influence );
-
-						}
-
-						vA.add( fvA );
-						vB.add( fvB );
-						vC.add( fvC );
-
-						fvA = vA;
-						fvB = vB;
-						fvC = vC;
-
-					}
-
 					intersection = checkIntersection( this, faceMaterial, raycaster, ray, fvA, fvB, fvC, intersectionPoint );
 
 					if ( intersection ) {

+ 2 - 0
src/renderers/webvr/WebVRManager.js

@@ -379,6 +379,8 @@ function WebVRManager( renderer ) {
 
 		animation.setAnimationLoop( callback );
 
+		if ( isPresenting() ) animation.start();
+
 	};
 
 	this.submitFrame = function () {

+ 59 - 13
utils/modularize.js

@@ -4,18 +4,34 @@
 
 var fs = require( 'fs' );
 
-var srcFolder = '../examples/js/';
-var dstFolder = '../examples/jsm/';
+var srcFolder = __dirname + '/../examples/js/';
+var dstFolder = __dirname + '/../examples/jsm/';
 
 var files = [
 	{ path: 'controls/OrbitControls.js', ignoreList: [] },
 	{ path: 'controls/MapControls.js', ignoreList: [] },
 	{ path: 'controls/TrackballControls.js', ignoreList: [] },
 	// { path: 'controls/TransformControls.js', ignoreList: [] },
-	{ path: 'exporters/GLTFExporter.js', ignoreList: [] },
+
+	{ path: 'exporters/GLTFExporter.js', ignoreList: [ 'AnimationClip', 'Camera', 'Geometry', 'Material', 'Mesh', 'Object3D', 'RGBFormat', 'Scenes', 'ShaderMaterial', 'VertexColors' ] },
+	{ path: 'exporters/MMDExporter.js', ignoreList: [] },
+	{ path: 'exporters/OBJExporter.js', ignoreList: [] },
+	{ path: 'exporters/PLYExporter.js', ignoreList: [] },
+	{ path: 'exporters/STLExporter.js', ignoreList: [] },
+	{ path: 'exporters/TypedGeometryExporter.js', ignoreList: [] },
+
 	{ path: 'loaders/GLTFLoader.js', ignoreList: [ 'NoSide', 'Matrix2', 'DDSLoader' ] },
 	{ path: 'loaders/OBJLoader.js', ignoreList: [] },
-	{ path: 'loaders/MTLLoader.js', ignoreList: [] }
+	{ path: 'loaders/MTLLoader.js', ignoreList: [] },
+
+	{ path: 'utils/BufferGeometryUtils.js', ignoreList: [] },
+	{ path: 'utils/GeometryUtils.js', ignoreList: [] },
+	{ path: 'utils/MathUtils.js', ignoreList: [] },
+	{ path: 'utils/SceneUtils.js', ignoreList: [] },
+	{ path: 'utils/ShadowMapViewer.js', ignoreList: [ 'DirectionalLight', 'SpotLight' ] },
+	{ path: 'utils/SkeletonUtils.js', ignoreList: [] },
+	{ path: 'utils/TypedArrayUtils.js', ignoreList: [] },
+	{ path: 'utils/UVsDebug.js', ignoreList: [ 'SphereBufferGeometry' ] },
 ];
 
 for ( var i = 0; i < files.length; i ++ ) {
@@ -34,6 +50,14 @@ function convert( path, ignoreList ) {
 	var className = '';
 	var dependencies = {};
 
+	// imports
+
+	contents = contents.replace( /^\/\*+[^*]*\*+(?:[^/*][^*]*\*+)*\//, function ( match ) {
+
+		return `${match}\n\n_IMPORTS_`;
+
+	} );
+
 	// class name
 
 	contents = contents.replace( /THREE\.([a-zA-Z0-9]+) = /g, function ( match, p1 ) {
@@ -42,7 +66,7 @@ function convert( path, ignoreList ) {
 
 		console.log( className );
 
-		return `_IMPORTS_\n\nvar ${p1} = `;
+		return `var ${p1} = `;
 
 	} );
 
@@ -51,6 +75,14 @@ function convert( path, ignoreList ) {
 		if ( p1 === '\'' ) return match; // Inside a string
 		if ( p2 === className ) return `${p2}${p3}`;
 
+		if ( p1 === 'Math' ) {
+
+			dependencies[ '_Math' ] = true;
+
+			return '_Math.';
+
+		}
+
 		return match;
 
 	} );
@@ -69,26 +101,40 @@ function convert( path, ignoreList ) {
 
 	// constants
 
-	contents = contents.replace( /THREE\.([a-zA-Z0-9]+)/g, function ( match, p1 ) {
+	contents = contents.replace( /(\'?)THREE\.([a-zA-Z0-9]+)/g, function ( match, p1, p2 ) {
 
-		if ( ignoreList.includes( p1 ) ) return match;
-		if ( p1 === className ) return match;
+		if ( ignoreList.includes( p2 ) ) return match;
+		if ( p1 === '\'' ) return match; // Inside a string
+		if ( p2 === className ) return p2;
 
-		dependencies[ p1 ] = true;
+		if ( p2 === 'Math' || p2 === '_Math' ) {
+
+			dependencies[ '_Math' ] = true;
+
+			return '_Math';
+
+		}
+
+		dependencies[ p2 ] = true;
 
-		// console.log( match, p1 );
+		// console.log( match, p2 );
 
-		return `${p1}`;
+		return `${p2}`;
 
 	} );
 
 	//
 
-	var keys = Object.keys( dependencies ).sort().map( value => '\n\t' + value ).toString();
+	var keys = Object.keys( dependencies )
+		.filter( value => value !== className )
+		.map( value => value === '_Math' ? 'Math as _Math' : value )
+		.map( value => '\n\t' + value )
+		.sort()
+		.toString();
 	var imports = `import {${keys}\n} from "../../../build/three.module.js";`;
 	var exports = `export { ${className} };\n`;
 
-	var output = contents.replace( '_IMPORTS_', imports ) + '\n' + exports;
+	var output = contents.replace( '_IMPORTS_', keys ? imports : '' ) + '\n' + exports;
 
 	// console.log( output );
 

+ 0 - 0
examples/js/utils/ldraw/packLDrawModel.js → utils/packLDrawModel.js