GLTFExporter.js 15.0 KB
Newer Older
F
Fernando Serrano 已提交
1 2 3 4
/**
 * @author fernandojsg / http://fernandojsg.com
 */

F
Fernando Serrano 已提交
5 6 7
//------------------------------------------------------------------------------
// GLTF Exporter
//------------------------------------------------------------------------------
F
Fernando Serrano 已提交
8 9 10
THREE.GLTFExporter = function ( renderer ) {
	this.renderer = renderer;
};
F
Fernando Serrano 已提交
11 12 13 14

THREE.GLTFExporter.prototype = {

	constructor: THREE.GLTFExporter,
F
Fernando Serrano 已提交
15

F
Fernando Serrano 已提交
16 17 18 19 20 21 22
	/**
	 * Parse scenes and generate GLTF output
	 * @param  {THREE.Scene or [THREE.Scenes]} input   THREE.Scene or Array of THREE.Scenes
	 * @param  {[type]} onDone  Callback on completed
	 * @param  {[type]} options options
	 *                          trs: Exports position, rotation and scale instead of matrix
	 */
F
Fernando Serrano 已提交
23 24
	parse: function ( input, onDone, options ) {

F
Fernando Serrano 已提交
25
		options = options || {};
F
Fernando Serrano 已提交
26

27 28
		var glUtils = new THREE.WebGLUtils( this.renderer.context, this.renderer.extensions );
		var gl = this.renderer.context;
F
Fernando Serrano 已提交
29

F
Fernando Serrano 已提交
30
		var outputJSON = {
F
Fernando Serrano 已提交
31 32 33 34
			asset: {
				version: "2.0",
				generator: "THREE.JS GLTFExporter" // @QUESTION Does it support spaces?
		 	}
F
Fernando Serrano 已提交
35 36 37 38
    };

		var byteOffset = 0;
		var dataViews = [];
F
Fernando Serrano 已提交
39

F
Fernando Serrano 已提交
40 41 42
		/**
		 * Compare two arrays
		 */
43
		function equalArray ( array1, array2 ) {
F
Fernando Serrano 已提交
44 45 46 47 48
			return ( array1.length === array2.length ) && array1.every( function( element, index ) {
    		return element === array2[ index ];
			});
		}

F
Fernando Serrano 已提交
49 50 51 52 53 54 55 56 57 58 59 60
		/**
		 * Get the min and he max vectors from the given attribute
		 * @param  {THREE.WebGLAttribute} attribute Attribute to find the min/max
		 * @return {Object} Object containing the `min` and `max` values (As an array of attribute.itemSize components)
		 */
		function getMinMax ( attribute ) {
			var output = {
				min: new Array( attribute.itemSize ).fill( Number.POSITIVE_INFINITY ),
				max: new Array( attribute.itemSize ).fill( Number.NEGATIVE_INFINITY )
			};

			for ( var i = 0; i < attribute.count; i++ ) {
F
Fernando Serrano 已提交
61 62
				for ( var a = 0; a < attribute.itemSize; a++ ) {
					var value = attribute.array[ i * attribute.itemSize + a ];
F
Fernando Serrano 已提交
63 64 65 66 67 68 69
					output.min[ a ] = Math.min( output.min[ a ], value );
					output.max[ a ] = Math.max( output.max[ a ], value );
				}
			}

			return output;
		}
F
Fernando Serrano 已提交
70

F
Fernando Serrano 已提交
71 72 73 74 75 76 77 78 79 80 81 82 83 84
		/**
		 * Add extension to the extensions array
		 * @param {String} extensionName Extension name
		 */
		function addExtension ( extensionName ) {
			if ( !outputJSON.extensionsUsed ) {
				outputJSON.extensionsUsed = [];
			}

			if ( outputJSON.extensionsUsed.indexOf( extensionName ) !== -1 ) {
				outputJSON.extensionsUsed.push( extensionName );
			}
		}

F
Fernando Serrano 已提交
85
		/**
F
Fernando Serrano 已提交
86 87 88 89
		 * Process a buffer to append to the default one.
		 * @param  {THREE.BufferAttribute} attribute     Attribute to store
		 * @param  {Integer} componentType Component type (Unsigned short, unsigned int or float)
		 * @return {Integer}               Index of the buffer created (Currently always 0)
F
Fernando Serrano 已提交
90 91
		 */
		function processBuffer ( attribute, componentType ) {
F
Fernando Serrano 已提交
92
			if ( !outputJSON.buffers ) {
F
Fernando Serrano 已提交
93 94 95 96 97 98 99 100
				outputJSON.buffers = [
					{
						byteLength: 0,
						uri: ''
					}
				];
			}

F
Fernando Serrano 已提交
101
			// Create a new dataview and dump the attribute's array into it
F
Fernando Serrano 已提交
102 103 104
			var dataView = new DataView( new ArrayBuffer( attribute.array.byteLength ) );

			var offset = 0;
105
			var offsetInc = componentType === gl.UNSIGNED_SHORT ? 2 : 4;
F
Fernando Serrano 已提交
106 107 108

			for ( var i = 0; i < attribute.count; i++ ) {
				for (var a = 0; a < attribute.itemSize; a++ ) {
F
Fernando Serrano 已提交
109
					var value = attribute.array[ i * attribute.itemSize + a ];
110
					if ( componentType === gl.FLOAT ) {
F
Fernando Serrano 已提交
111
						dataView.setFloat32( offset, value, true );
112
					} else if ( componentType === gl.UNSIGNED_INT ) {
F
Fernando Serrano 已提交
113
						dataView.setUint8( offset, value, true );
114
					} else if ( componentType === gl.UNSIGNED_SHORT ) {
F
Fernando Serrano 已提交
115
						dataView.setUint16( offset, value, true );
F
Fernando Serrano 已提交
116 117 118 119 120
					}
					offset += offsetInc;
				}
			}

F
Fernando Serrano 已提交
121
			// We just use one buffer
F
Fernando Serrano 已提交
122
			dataViews.push( dataView );
F
Fernando Serrano 已提交
123 124 125 126 127

			return 0;
		}

		/**
F
Fernando Serrano 已提交
128
		 * Process and generate a BufferView
F
Fernando Serrano 已提交
129 130 131 132
		 * @param  {[type]} data [description]
		 * @return {[type]}      [description]
		 */
		function processBufferView ( data, componentType ) {
133
			var isVertexAttributes = componentType === gl.FLOAT;
F
Fernando Serrano 已提交
134
			if ( !outputJSON.bufferViews ) {
F
Fernando Serrano 已提交
135 136 137 138 139 140 141
				outputJSON.bufferViews = [];
			}

			var gltfBufferView = {
				buffer: processBuffer( data, componentType ),
				byteOffset: byteOffset,
				byteLength: data.array.byteLength,
142 143
				byteStride: data.itemSize * ( componentType === gl.UNSIGNED_SHORT ? 2 : 4 ),
				target: isVertexAttributes ? gl.ARRAY_BUFFER : gl.ELEMENT_ARRAY_BUFFER
F
Fernando Serrano 已提交
144 145 146 147
			};

			byteOffset += data.array.byteLength;

F
Fernando Serrano 已提交
148
			outputJSON.bufferViews.push( gltfBufferView );
F
Fernando Serrano 已提交
149 150

			// @TODO Ideally we'll have just two bufferviews: 0 is for vertex attributes, 1 for indices
F
Fernando Serrano 已提交
151 152 153 154 155 156 157 158
			var output = {
				id: outputJSON.bufferViews.length - 1,
				byteLength: 0
			};
			return output;
		}

		/**
F
Fernando Serrano 已提交
159 160 161
		 * Process attribute to generate an accessor
		 * @param  {THREE.WebGLAttribute} attribute Attribute to process
		 * @return {Integer}           Index of the processed accessor on the "accessors" array
F
Fernando Serrano 已提交
162 163
		 */
		function processAccessor ( attribute ) {
F
Fernando Serrano 已提交
164
			if ( !outputJSON.accessors ) {
F
Fernando Serrano 已提交
165 166 167 168
				outputJSON.accessors = [];
			}

			var types = [
F
Fernando Serrano 已提交
169 170 171 172
				'SCALAR',
				'VEC2',
				'VEC3',
				'VEC4'
F
Fernando Serrano 已提交
173 174
			];

F
Fernando Serrano 已提交
175
			// Detect the component type of the attribute array (float, uint or ushort)
176 177
			var componentType = attribute instanceof THREE.Float32BufferAttribute ? gl.FLOAT :
				( attribute instanceof THREE.Uint32BufferAttribute ? gl.UNSIGNED_INT : gl.UNSIGNED_SHORT );
F
Fernando Serrano 已提交
178 179 180

			var minMax = getMinMax( attribute );
			var bufferView = processBufferView( attribute, componentType );
F
Fernando Serrano 已提交
181

F
Fernando Serrano 已提交
182 183 184 185 186 187 188
			var gltfAccessor = {
				bufferView: bufferView.id,
				byteOffset: bufferView.byteOffset,
				componentType: componentType,
				count: attribute.count,
				max: minMax.max,
				min: minMax.min,
F
Fernando Serrano 已提交
189
				type: types[ attribute.itemSize - 1 ]
F
Fernando Serrano 已提交
190 191 192 193 194 195 196 197
			};

			outputJSON.accessors.push( gltfAccessor );

			return outputJSON.accessors.length - 1;
		}

		/**
F
Fernando Serrano 已提交
198 199 200 201 202
		 * Process image
		 * @param  {Texture} map Texture to process
		 * @return {Integer}     Index of the processed texture in the "images" array
		 */
		function processImage ( map ) {
F
Fernando Serrano 已提交
203
			if ( !outputJSON.images ) {
F
Fernando Serrano 已提交
204 205 206 207 208
				outputJSON.images = [];
			}

			var gltfImage = {};

F
Fernando Serrano 已提交
209
			if ( options.embedImages ) {
F
Fernando Serrano 已提交
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
				// @TODO { bufferView, mimeType }
			} else {
				// @TODO base64 based on options
				gltfImage.uri = map.image.src;
			}

			outputJSON.images.push( gltfImage );

			return outputJSON.images.length - 1;
		}

		/**
		 * Process sampler
		 * @param  {Texture} map Texture to process
		 * @return {Integer}     Index of the processed texture in the "samplers" array
		 */
		function processSampler ( map ) {
F
Fernando Serrano 已提交
227
			if ( !outputJSON.samplers ) {
F
Fernando Serrano 已提交
228 229 230 231
				outputJSON.samplers = [];
			}

			var gltfSampler = {
F
Fernando Serrano 已提交
232 233 234 235
				magFilter: glUtils.convert( map.magFilter ),
				minFilter: glUtils.convert( map.minFilter ),
				wrapS: glUtils.convert( map.wrapS ),
				wrapT: glUtils.convert( map.wrapT )
F
Fernando Serrano 已提交
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
			};

			outputJSON.samplers.push( gltfSampler );

			return outputJSON.samplers.length - 1;
		}

		/**
		 * Process texture
		 * @param  {Texture} map Map to process
		 * @return {Integer}     Index of the processed texture in the "textures" array
		 */
		function processTexture ( map ) {
			if (!outputJSON.textures) {
				outputJSON.textures = [];
			}

			var gltfTexture = {
F
Fernando Serrano 已提交
254 255
				sampler: processSampler( map ),
				source: processImage( map )
F
Fernando Serrano 已提交
256 257 258 259 260 261 262 263 264 265 266
			};

			outputJSON.textures.push( gltfTexture );

			return outputJSON.textures.length - 1;
		}

		/**
		 * Process material
		 * @param  {THREE.Material} material Material to process
		 * @return {Integer}      Index of the processed material in the "materials" array
F
Fernando Serrano 已提交
267 268
		 */
		function processMaterial ( material ) {
F
Fernando Serrano 已提交
269
			if ( !outputJSON.materials ) {
F
Fernando Serrano 已提交
270 271
				outputJSON.materials = [];
			}
F
Fernando Serrano 已提交
272 273 274 275 276 277

			if ( !material instanceof THREE.MeshStandardMaterial ) {
				throw 'Currently just support THREE.StandardMaterial is supported';
			}

			// @QUESTION Should we avoid including any attribute that has the default value?
278 279 280 281 282
			var gltfMaterial = {};

			if ( material instanceof THREE.MeshStandardMaterial ) {

				gltfMaterial.pbrMetallicRoughness = {
F
Fernando Serrano 已提交
283
					baseColorFactor: material.color.toArray().concat( [ material.opacity ] ),
F
Fernando Serrano 已提交
284 285
					metallicFactor: material.metalness,
					roughnessFactor: material.roughness
286 287 288 289 290 291 292 293 294 295 296 297
				};

			}

			if ( material instanceof THREE.MeshBasicMaterial ) {

				// emissiveFactor
				var color = material.color.toArray();
				if ( !equalArray( color, [ 0, 0, 0 ] ) ) {

					gltfMaterial.emissiveFactor = color;

F
Fernando Serrano 已提交
298 299
				}

300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
				// emissiveTexture
				if ( material.map ) {

					gltfMaterial.emissiveTexture = {

						index: processTexture( material.map ),
						texCoord: 0 // @FIXME

					};

				}

			} else {

				// emissiveFactor
				var emissive = material.emissive.toArray();
				if ( !equalArray( emissive, [ 0, 0, 0 ] ) ) {

					gltfMaterial.emissiveFactor = emissive;

F
Fernando Serrano 已提交
320
				}
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353

				// pbrMetallicRoughness.baseColorTexture
				if ( material.map ) {

					gltfMaterial.pbrMetallicRoughness.baseColorTexture = {
						index: processTexture( material.map ),
						texCoord: 0 // @FIXME
					};

				}

				// emissiveTexture
				if ( material.emissiveMap ) {

					gltfMaterial.emissiveTexture = {

						index: processTexture( material.emissiveMap ),
						texCoord: 0 // @FIXME

					};

				}

			}

			// normalTexture
			if ( material.normalMap ) {

				gltfMaterial.normalTexture = {
					index: processTexture( material.normalMap ),
					texCoord: 0 // @FIXME
				};

F
Fernando Serrano 已提交
354 355
			}

356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
			// occlusionTexture
			if ( material.aoMap ) {

				gltfMaterial.occlusionTexture = {
					index: processTexture( material.aoMap ),
					texCoord: 0 // @FIXME
				};

			}

			// alphaMode
			if ( material.transparent ) {

				gltfMaterial.alphaMode = 'BLEND'; // @FIXME We should detect MASK or BLEND

			}

			// doubleSided
F
Fernando Serrano 已提交
374
			if ( material.side === THREE.DoubleSide ) {
375

F
Fernando Serrano 已提交
376
				gltfMaterial.doubleSided = true;
377

F
Fernando Serrano 已提交
378 379
			}

380 381
			if ( material.name !== undefined ) {

F
Fernando Serrano 已提交
382
				gltfMaterial.name = material.name;
383

F
Fernando Serrano 已提交
384 385
			}

F
Fernando Serrano 已提交
386
			outputJSON.materials.push( gltfMaterial );
F
Fernando Serrano 已提交
387 388

			return outputJSON.materials.length - 1;
389

F
Fernando Serrano 已提交
390 391 392
		}

		/**
F
Fernando Serrano 已提交
393 394 395
		 * Process mesh
		 * @param  {THREE.Mesh} mesh Mesh to process
		 * @return {Integer}      Index of the processed mesh in the "meshes" array
F
Fernando Serrano 已提交
396 397 398 399 400 401 402
		 */
		function processMesh( mesh ) {
			if ( !outputJSON.meshes ) {
				outputJSON.meshes = [];
			}

			var geometry = mesh.geometry;
F
Fernando Serrano 已提交
403 404

			// @FIXME Select the correct mode based on the mesh
405
			var mode = gl.TRIANGLES;
F
Fernando Serrano 已提交
406 407 408 409 410 411 412 413 414 415 416 417

			var gltfMesh = {
				primitives: [
					{
						mode: mode,
						attributes: {},
						material: processMaterial( mesh.material ),
					 	indices: processAccessor( geometry.index )
					}
				]
			};

F
Fernando Serrano 已提交
418 419
			// We've just one primitive per mesh
			var gltfAttributes = gltfMesh.primitives[ 0 ].attributes;
F
Fernando Serrano 已提交
420 421
			var attributes = geometry.attributes;

F
Fernando Serrano 已提交
422 423
			// Conversion between attributes names in threejs and gltf spec
			var nameConversion = {
F
Fernando Serrano 已提交
424 425 426
				uv: 'TEXCOORD_0',
				uv2: 'TEXCOORD_1',
				color: 'COLOR_0'
F
Fernando Serrano 已提交
427 428 429
			};

			// For every attribute create an accessor
F
Fernando Serrano 已提交
430
			for ( attributeName in geometry.attributes ) {
F
Fernando Serrano 已提交
431
				var attribute = geometry.attributes[ attributeName ];
F
Fernando Serrano 已提交
432 433
				attributeName = nameConversion[ attributeName ] || attributeName.toUpperCase()
				gltfAttributes[ attributeName ] = processAccessor( attribute );
F
Fernando Serrano 已提交
434 435 436 437 438 439 440 441 442 443 444 445
			}

			// @todo Not really necessary, isn't it?
			if ( geometry.type ) {
				gltfMesh.name = geometry.type;
			}

			outputJSON.meshes.push( gltfMesh );

			return outputJSON.meshes.length - 1;
		}

F
Fernando Serrano 已提交
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
		/**
		 * Process camera
		 * @param  {THREE.Camera} camera Camera to process
		 * @return {Integer}      Index of the processed mesh in the "camera" array
		 */
		function processCamera( camera ) {
			if ( !outputJSON.cameras ) {
				outputJSON.cameras = [];
			}

			var isOrtho = camera instanceof THREE.OrthographicCamera;

			var gltfCamera = {
				type: isOrtho ? 'orthographic' : 'perspective'
			};

			if ( isOrtho ) {

				gltfCamera.orthographic = {

					xmag: camera.right * 2,
					ymag: camera.top * 2,
					zfar: camera.far,
					znear: camera.near

				}

			} else {

				gltfCamera.perspective = {

					aspectRatio: camera.aspect,
					yfov: THREE.Math.degToRad( camera.fov ) / camera.aspect,
					zfar: camera.far,
					znear: camera.near

				};

			}

486
			if ( camera.name !== undefined ) {
F
Fernando Serrano 已提交
487 488 489 490 491 492 493 494
				gltfCamera.name = camera.type;
			}

			outputJSON.cameras.push( gltfCamera );

			return outputJSON.cameras.length - 1;
		}

F
Fernando Serrano 已提交
495 496 497 498 499 500 501
		/**
		 * Process Object3D node
		 * @param  {THREE.Object3D} node Object3D to processNode
		 * @return {Integer}      Index of the node in the nodes list
		 */
		function processNode ( object ) {

F
Fernando Serrano 已提交
502
			if ( !outputJSON.nodes ) {
F
Fernando Serrano 已提交
503 504 505
				outputJSON.nodes = [];
			}

F
Fernando Serrano 已提交
506 507 508 509 510 511 512
			var gltfNode = {};

			if ( options.trs ) {
				var rotation = object.quaternion.toArray();
				var position = object.position.toArray();
				var scale = object.scale.toArray();

513
				if ( !equalArray( rotation, [ 0, 0, 0, 1 ] ) ) {
F
Fernando Serrano 已提交
514 515 516
					gltfNode.rotation = rotation;
				}

517
				if ( !equalArray( position, [ 0, 0, 0 ] ) ) {
F
Fernando Serrano 已提交
518 519 520
					gltfNode.position = position;
				}

521
				if ( !equalArray( scale, [ 1, 1, 1 ] ) ) {
F
Fernando Serrano 已提交
522 523 524 525 526
					gltfNode.scale = scale;
				}

			} else {
				object.updateMatrix();
527
				if (! equalArray( object.matrix.elements, [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ] ) ) {
F
Fernando Serrano 已提交
528 529
					gltfNode.matrix = object.matrix.elements;
				}
F
Fernando Serrano 已提交
530 531
			};

532
			if ( object.name !== undefined ) {
F
Fernando Serrano 已提交
533 534 535 536 537
				gltfNode.name = object.name;
			}

			if ( object instanceof THREE.Mesh ) {
				gltfNode.mesh = processMesh( object );
F
Fernando Serrano 已提交
538 539
			} else if ( object instanceof THREE.Camera ) {
				gltfNode.camera = processCamera( object );
F
Fernando Serrano 已提交
540 541 542
			}

			if ( object.children.length > 0 ) {
F
Fernando Serrano 已提交
543
				gltfNode.children = [];
F
Fernando Serrano 已提交
544 545 546 547

				for ( var i = 0, l = object.children.length; i < l; i ++ ) {
					var child = object.children[ i ];
					if ( child instanceof THREE.Mesh ) {
F
Fernando Serrano 已提交
548
						gltfNode.children.push( processNode( child ) );
F
Fernando Serrano 已提交
549 550 551 552 553 554 555 556 557 558
					}
				}
			}

			outputJSON.nodes.push( gltfNode );

			return outputJSON.nodes.length - 1;
		}

		/**
F
Fernando Serrano 已提交
559
		 * Process Scene
F
Fernando Serrano 已提交
560 561 562
		 * @param  {THREE.Scene} node Scene to process
		 */
		function processScene( scene ) {
F
Fernando Serrano 已提交
563

564
			if ( !outputJSON.scenes ) {
F
Fernando Serrano 已提交
565 566 567 568 569 570 571 572
				outputJSON.scenes = [];
				outputJSON.scene = 0;
			}

			var gltfScene = {
				nodes: []
			};

573
			if ( scene.name !== undefined ) {
F
Fernando Serrano 已提交
574 575 576
				gltfScene.name = scene.name;
			}

F
Fernando Serrano 已提交
577
			outputJSON.scenes.push( gltfScene );
F
Fernando Serrano 已提交
578 579

			for ( var i = 0, l = scene.children.length; i < l; i ++ ) {
F
Fernando Serrano 已提交
580 581
				var child = scene.children[ i ];

F
Fernando Serrano 已提交
582 583
				// @TODO Right now we just process meshes and lights
				if ( child instanceof THREE.Mesh || child instanceof THREE.Camera ) {
F
Fernando Serrano 已提交
584 585
					gltfScene.nodes.push( processNode( child ) );
				}
F
Fernando Serrano 已提交
586 587 588
			}
		}

F
Fernando Serrano 已提交
589 590 591 592 593 594 595 596
		// Process the scene/s
		if ( input instanceof Array ) {
			for ( i = 0; i < input.length; i++ ) {
				processScene( input[ i ] );
			}
		} else {
			processScene( input );
		}
F
Fernando Serrano 已提交
597

F
Fernando Serrano 已提交
598
		// Generate buffer
F
Fernando Serrano 已提交
599 600 601 602
		// Create a new blob with all the dataviews from the buffers
		var blob = new Blob( dataViews, { type: 'application/octet-binary' } );

		// Update the bytlength of the only main buffer and update the uri with the base64 representation of it
603 604 605 606 607 608 609 610 611 612 613 614 615 616
		if ( outputJSON.buffers && outputJSON.buffers.length > 0 ) {
			outputJSON.buffers[ 0 ].byteLength = blob.size;
			objectURL = URL.createObjectURL( blob );

			var reader = new window.FileReader();
			 reader.readAsDataURL( blob );
			 reader.onloadend = function() {
				 base64data = reader.result;
				 outputJSON.buffers[ 0 ].uri = base64data;
				 onDone( outputJSON );
			 }
		} else {
			onDone ( outputJSON );
		}
F
Fernando Serrano 已提交
617 618
	}
};