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

5 6 7 8 9
 //------------------------------------------------------------------------------
 // Constants
 //------------------------------------------------------------------------------
var WEBGL_CONSTANTS = {
	POINTS: 0x0000,
F
Fernando Serrano 已提交
10 11 12 13 14 15
	LINES: 0x0001,
	LINE_LOOP: 0x0002,
	LINE_STRIP: 0x0003,
	TRIANGLES: 0x0004,
	TRIANGLE_STRIP: 0x0005,
	TRIANGLE_FAN: 0x0006,
16 17 18 19 20 21 22 23 24

	UNSIGNED_BYTE: 0x1401,
	UNSIGNED_SHORT: 0x1403,
	FLOAT: 0x1406,
	UNSIGNED_INT: 0x1405,
	ARRAY_BUFFER: 0x8892,
	ELEMENT_ARRAY_BUFFER: 0x8893,

	NEAREST: 0x2600,
F
Fernando Serrano 已提交
25 26 27 28 29
	LINEAR: 0x2601,
	NEAREST_MIPMAP_NEAREST: 0x2700,
	LINEAR_MIPMAP_NEAREST: 0x2701,
	NEAREST_MIPMAP_LINEAR: 0x2702,
	LINEAR_MIPMAP_LINEAR: 0x2703
30 31 32 33
};

var THREE_TO_WEBGL = {
	// @TODO Replace with computed property name [THREE.*] when available on es6
F
Fernando Serrano 已提交
34
	1003: WEBGL_CONSTANTS.NEAREST,
35 36 37 38
	1004: WEBGL_CONSTANTS.NEAREST_MIPMAP_NEAREST,
	1005: WEBGL_CONSTANTS.NEAREST_MIPMAP_LINEAR,
	1006: WEBGL_CONSTANTS.LINEAR,
	1007: WEBGL_CONSTANTS.LINEAR_MIPMAP_NEAREST,
F
Fernando Serrano 已提交
39
	1008: WEBGL_CONSTANTS.LINEAR_MIPMAP_LINEAR
40 41
 };

F
Fernando Serrano 已提交
42 43 44
//------------------------------------------------------------------------------
// GLTF Exporter
//------------------------------------------------------------------------------
45
THREE.GLTFExporter = function () {};
F
Fernando Serrano 已提交
46 47 48 49

THREE.GLTFExporter.prototype = {

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

F
Fernando Serrano 已提交
51 52 53
	/**
	 * Parse scenes and generate GLTF output
	 * @param  {THREE.Scene or [THREE.Scenes]} input   THREE.Scene or Array of THREE.Scenes
F
Fernando Serrano 已提交
54 55
	 * @param  {Function} onDone  Callback on completed
	 * @param  {Object} options options
F
Fernando Serrano 已提交
56 57
	 *                          trs: Exports position, rotation and scale instead of matrix
	 */
F
Fernando Serrano 已提交
58 59
	parse: function ( input, onDone, options ) {

60 61
		var DEFAULT_OPTIONS = {
			trs: false,
62 63
			onlyVisible: true,
			truncateDrawRange: true
64 65 66 67
		};

		options = Object.assign( {}, DEFAULT_OPTIONS, options );

F
Fernando Serrano 已提交
68
		var outputJSON = {
F
Fernando Serrano 已提交
69

F
Fernando Serrano 已提交
70
			asset: {
F
Fernando Serrano 已提交
71

F
Fernando Serrano 已提交
72 73
				version: "2.0",
				generator: "THREE.JS GLTFExporter" // @QUESTION Does it support spaces?
F
Fernando Serrano 已提交
74

F
Fernando Serrano 已提交
75
		 	}
F
Fernando Serrano 已提交
76

F
Fernando Serrano 已提交
77 78 79 80
    };

		var byteOffset = 0;
		var dataViews = [];
81 82 83 84 85 86
		var cachedData = {

			images: {},
			materials: {}

		};
F
Fernando Serrano 已提交
87

F
Fernando Serrano 已提交
88 89 90
		/**
		 * Compare two arrays
		 */
F
Fernando Serrano 已提交
91 92 93 94 95 96
		/**
		 * Compare two arrays
		 * @param  {Array} array1 Array 1 to compare
		 * @param  {Array} array2 Array 2 to compare
		 * @return {Boolean}        Returns true if both arrays are equal
		 */
97
		function equalArray ( array1, array2 ) {
F
Fernando Serrano 已提交
98

F
Fernando Serrano 已提交
99
			return ( array1.length === array2.length ) && array1.every( function( element, index ) {
F
Fernando Serrano 已提交
100

F
Fernando Serrano 已提交
101
    		return element === array2[ index ];
F
Fernando Serrano 已提交
102

F
Fernando Serrano 已提交
103
			});
F
Fernando Serrano 已提交
104

F
Fernando Serrano 已提交
105 106
		}

F
Fernando Serrano 已提交
107 108 109 110 111 112
		/**
		 * 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 ) {
F
Fernando Serrano 已提交
113

F
Fernando Serrano 已提交
114
			var output = {
F
Fernando Serrano 已提交
115

F
Fernando Serrano 已提交
116 117
				min: new Array( attribute.itemSize ).fill( Number.POSITIVE_INFINITY ),
				max: new Array( attribute.itemSize ).fill( Number.NEGATIVE_INFINITY )
F
Fernando Serrano 已提交
118

F
Fernando Serrano 已提交
119 120 121
			};

			for ( var i = 0; i < attribute.count; i++ ) {
F
Fernando Serrano 已提交
122

F
Fernando Serrano 已提交
123
				for ( var a = 0; a < attribute.itemSize; a++ ) {
F
Fernando Serrano 已提交
124

F
Fernando Serrano 已提交
125
					var value = attribute.array[ i * attribute.itemSize + a ];
F
Fernando Serrano 已提交
126 127 128
					output.min[ a ] = Math.min( output.min[ a ], value );
					output.max[ a ] = Math.max( output.max[ a ], value );

F
Fernando Serrano 已提交
129
				}
F
Fernando Serrano 已提交
130

F
Fernando Serrano 已提交
131 132
			}

F
Fernando Serrano 已提交
133
			return output;
F
Fernando Serrano 已提交
134 135
		}

F
Fernando Serrano 已提交
136
		/**
F
Fernando Serrano 已提交
137 138 139 140
		 * 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 已提交
141
		 */
142
		function processBuffer ( attribute, componentType, start, count ) {
F
Fernando Serrano 已提交
143

F
Fernando Serrano 已提交
144
			if ( !outputJSON.buffers ) {
F
Fernando Serrano 已提交
145

F
Fernando Serrano 已提交
146
				outputJSON.buffers = [
F
Fernando Serrano 已提交
147

F
Fernando Serrano 已提交
148
					{
F
Fernando Serrano 已提交
149

F
Fernando Serrano 已提交
150 151
						byteLength: 0,
						uri: ''
F
Fernando Serrano 已提交
152

F
Fernando Serrano 已提交
153
					}
F
Fernando Serrano 已提交
154

F
Fernando Serrano 已提交
155
				];
F
Fernando Serrano 已提交
156

F
Fernando Serrano 已提交
157 158
			}

159 160 161
			var offset = 0;
			var componentSize = componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ? 2 : 4;

F
Fernando Serrano 已提交
162
			// Create a new dataview and dump the attribute's array into it
163
			var byteLength = count * attribute.itemSize * componentSize;
F
Fernando Serrano 已提交
164

165
			var dataView = new DataView( new ArrayBuffer( byteLength ) );
F
Fernando Serrano 已提交
166

167
			for ( var i = start; i < start + count; i++ ) {
F
Fernando Serrano 已提交
168

F
Fernando Serrano 已提交
169
				for (var a = 0; a < attribute.itemSize; a++ ) {
F
Fernando Serrano 已提交
170

F
Fernando Serrano 已提交
171
					var value = attribute.array[ i * attribute.itemSize + a ];
F
Fernando Serrano 已提交
172

173
					if ( componentType === WEBGL_CONSTANTS.FLOAT ) {
F
Fernando Serrano 已提交
174

F
Fernando Serrano 已提交
175
						dataView.setFloat32( offset, value, true );
F
Fernando Serrano 已提交
176

177
					} else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_INT ) {
F
Fernando Serrano 已提交
178

F
Fernando Serrano 已提交
179
						dataView.setUint8( offset, value, true );
F
Fernando Serrano 已提交
180

181
					} else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ) {
F
Fernando Serrano 已提交
182

F
Fernando Serrano 已提交
183
						dataView.setUint16( offset, value, true );
F
Fernando Serrano 已提交
184

F
Fernando Serrano 已提交
185
					}
F
Fernando Serrano 已提交
186

187
					offset += componentSize;
F
Fernando Serrano 已提交
188

F
Fernando Serrano 已提交
189
				}
F
Fernando Serrano 已提交
190

F
Fernando Serrano 已提交
191 192
			}

F
Fernando Serrano 已提交
193
			// We just use one buffer
F
Fernando Serrano 已提交
194
			dataViews.push( dataView );
F
Fernando Serrano 已提交
195

F
Fernando Serrano 已提交
196
			// Always using just one buffer
F
Fernando Serrano 已提交
197 198 199 200
			return 0;
		}

		/**
F
Fernando Serrano 已提交
201
		 * Process and generate a BufferView
F
Fernando Serrano 已提交
202 203 204
		 * @param  {[type]} data [description]
		 * @return {[type]}      [description]
		 */
205
		function processBufferView ( data, componentType, start, count ) {
F
Fernando Serrano 已提交
206

207
			var isVertexAttributes = componentType === WEBGL_CONSTANTS.FLOAT;
F
Fernando Serrano 已提交
208

F
Fernando Serrano 已提交
209
			if ( !outputJSON.bufferViews ) {
F
Fernando Serrano 已提交
210

F
Fernando Serrano 已提交
211
				outputJSON.bufferViews = [];
F
Fernando Serrano 已提交
212

F
Fernando Serrano 已提交
213 214
			}

215 216 217 218 219
			var componentSize = componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ? 2 : 4;

			// Create a new dataview and dump the attribute's array into it
			var byteLength = count * data.itemSize * componentSize;

F
Fernando Serrano 已提交
220
			var gltfBufferView = {
F
Fernando Serrano 已提交
221

222
				buffer: processBuffer( data, componentType, start, count ),
F
Fernando Serrano 已提交
223
				byteOffset: byteOffset,
224 225
				byteLength: byteLength,
				byteStride: data.itemSize * componentSize,
226
				target: isVertexAttributes ? WEBGL_CONSTANTS.ARRAY_BUFFER : WEBGL_CONSTANTS.ELEMENT_ARRAY_BUFFER
F
Fernando Serrano 已提交
227

F
Fernando Serrano 已提交
228 229
			};

230
			byteOffset += byteLength;
F
Fernando Serrano 已提交
231

F
Fernando Serrano 已提交
232
			outputJSON.bufferViews.push( gltfBufferView );
F
Fernando Serrano 已提交
233 234

			// @TODO Ideally we'll have just two bufferviews: 0 is for vertex attributes, 1 for indices
F
Fernando Serrano 已提交
235
			var output = {
F
Fernando Serrano 已提交
236

F
Fernando Serrano 已提交
237 238
				id: outputJSON.bufferViews.length - 1,
				byteLength: 0
F
Fernando Serrano 已提交
239

F
Fernando Serrano 已提交
240
			};
F
Fernando Serrano 已提交
241

F
Fernando Serrano 已提交
242
			return output;
F
Fernando Serrano 已提交
243

F
Fernando Serrano 已提交
244 245 246
		}

		/**
F
Fernando Serrano 已提交
247 248 249
		 * 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 已提交
250
		 */
251
		function processAccessor ( attribute, geometry ) {
F
Fernando Serrano 已提交
252

F
Fernando Serrano 已提交
253
			if ( !outputJSON.accessors ) {
F
Fernando Serrano 已提交
254

F
Fernando Serrano 已提交
255
				outputJSON.accessors = [];
F
Fernando Serrano 已提交
256

F
Fernando Serrano 已提交
257 258 259
			}

			var types = [
F
Fernando Serrano 已提交
260

F
Fernando Serrano 已提交
261 262 263 264
				'SCALAR',
				'VEC2',
				'VEC3',
				'VEC4'
F
Fernando Serrano 已提交
265

F
Fernando Serrano 已提交
266 267
			];

268 269
			var componentType;

F
Fernando Serrano 已提交
270
			// Detect the component type of the attribute array (float, uint or ushort)
271
			if ( attribute.array.constructor === Float32Array ) {
F
Fernando Serrano 已提交
272

273
				componentType = WEBGL_CONSTANTS.FLOAT;
F
Fernando Serrano 已提交
274

275
			} else if ( attribute.array.constructor === Uint32Array ) {
F
Fernando Serrano 已提交
276

277
				componentType = WEBGL_CONSTANTS.UNSIGNED_INT;
F
Fernando Serrano 已提交
278

279
			} else if ( attribute.array.constructor === Uint16Array ) {
F
Fernando Serrano 已提交
280

281
				componentType = WEBGL_CONSTANTS.UNSIGNED_SHORT;
F
Fernando Serrano 已提交
282

283
			} else {
F
Fernando Serrano 已提交
284

285
				throw new Error( 'THREE.GLTFExporter: Unsupported bufferAttribute component type.' );
F
Fernando Serrano 已提交
286

287
			}
F
Fernando Serrano 已提交
288 289

			var minMax = getMinMax( attribute );
290 291 292 293 294 295 296 297 298 299 300

			var start = 0;
			var count = attribute.count;

			// @TODO Indexed buffer geometry with drawRange not supported yet
			if ( options.truncateDrawRange && geometry.index === null ) {
				start = geometry.drawRange.start;
				count = geometry.drawRange.count !== Infinity ? geometry.drawRange.count : attribute.count;
			}

			var bufferView = processBufferView( attribute, componentType, start, count );
F
Fernando Serrano 已提交
301

F
Fernando Serrano 已提交
302
			var gltfAccessor = {
F
Fernando Serrano 已提交
303

F
Fernando Serrano 已提交
304 305 306
				bufferView: bufferView.id,
				byteOffset: bufferView.byteOffset,
				componentType: componentType,
307
				count: count,
F
Fernando Serrano 已提交
308 309
				max: minMax.max,
				min: minMax.min,
F
Fernando Serrano 已提交
310
				type: types[ attribute.itemSize - 1 ]
F
Fernando Serrano 已提交
311

F
Fernando Serrano 已提交
312 313 314 315 316
			};

			outputJSON.accessors.push( gltfAccessor );

			return outputJSON.accessors.length - 1;
F
Fernando Serrano 已提交
317

F
Fernando Serrano 已提交
318 319 320
		}

		/**
F
Fernando Serrano 已提交
321 322 323 324 325
		 * 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 已提交
326

327 328 329 330 331 332
			if ( cachedData.images[ map.uuid ] ) {

				return cachedData.images[ map.uuid ];

			}

F
Fernando Serrano 已提交
333
			if ( !outputJSON.images ) {
F
Fernando Serrano 已提交
334

F
Fernando Serrano 已提交
335
				outputJSON.images = [];
F
Fernando Serrano 已提交
336

F
Fernando Serrano 已提交
337 338 339 340
			}

			var gltfImage = {};

F
Fernando Serrano 已提交
341
			if ( options.embedImages ) {
F
Fernando Serrano 已提交
342

F
Fernando Serrano 已提交
343
				// @TODO { bufferView, mimeType }
F
Fernando Serrano 已提交
344

F
Fernando Serrano 已提交
345
			} else {
F
Fernando Serrano 已提交
346

F
Fernando Serrano 已提交
347 348
				// @TODO base64 based on options
				gltfImage.uri = map.image.src;
F
Fernando Serrano 已提交
349

F
Fernando Serrano 已提交
350 351 352 353
			}

			outputJSON.images.push( gltfImage );

354 355 356 357
			var index = outputJSON.images.length - 1;
			cachedData.images[ map.uuid ] = index;

			return index;
F
Fernando Serrano 已提交
358

F
Fernando Serrano 已提交
359 360 361 362 363 364 365 366
		}

		/**
		 * 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 已提交
367

F
Fernando Serrano 已提交
368
			if ( !outputJSON.samplers ) {
F
Fernando Serrano 已提交
369

F
Fernando Serrano 已提交
370
				outputJSON.samplers = [];
F
Fernando Serrano 已提交
371

F
Fernando Serrano 已提交
372 373 374
			}

			var gltfSampler = {
F
Fernando Serrano 已提交
375

376 377 378 379
				magFilter: THREE_TO_WEBGL[ map.magFilter ],
				minFilter: THREE_TO_WEBGL[ map.minFilter ],
				wrapS: THREE_TO_WEBGL[ map.wrapS ],
				wrapT: THREE_TO_WEBGL[ map.wrapT ]
F
Fernando Serrano 已提交
380

F
Fernando Serrano 已提交
381 382 383 384 385
			};

			outputJSON.samplers.push( gltfSampler );

			return outputJSON.samplers.length - 1;
F
Fernando Serrano 已提交
386

F
Fernando Serrano 已提交
387 388 389 390 391 392 393 394
		}

		/**
		 * Process texture
		 * @param  {Texture} map Map to process
		 * @return {Integer}     Index of the processed texture in the "textures" array
		 */
		function processTexture ( map ) {
F
Fernando Serrano 已提交
395

F
Fernando Serrano 已提交
396
			if (!outputJSON.textures) {
F
Fernando Serrano 已提交
397

F
Fernando Serrano 已提交
398
				outputJSON.textures = [];
F
Fernando Serrano 已提交
399

F
Fernando Serrano 已提交
400 401 402
			}

			var gltfTexture = {
F
Fernando Serrano 已提交
403

F
Fernando Serrano 已提交
404 405
				sampler: processSampler( map ),
				source: processImage( map )
F
Fernando Serrano 已提交
406

F
Fernando Serrano 已提交
407 408 409 410 411
			};

			outputJSON.textures.push( gltfTexture );

			return outputJSON.textures.length - 1;
F
Fernando Serrano 已提交
412

F
Fernando Serrano 已提交
413 414 415 416 417 418
		}

		/**
		 * Process material
		 * @param  {THREE.Material} material Material to process
		 * @return {Integer}      Index of the processed material in the "materials" array
F
Fernando Serrano 已提交
419 420
		 */
		function processMaterial ( material ) {
F
Fernando Serrano 已提交
421

422 423 424 425 426 427
			if ( cachedData.materials[ material.uuid ] ) {

				return cachedData.materials[ material.uuid ];

			}

F
Fernando Serrano 已提交
428
			if ( !outputJSON.materials ) {
F
Fernando Serrano 已提交
429

F
Fernando Serrano 已提交
430
				outputJSON.materials = [];
F
Fernando Serrano 已提交
431

F
Fernando Serrano 已提交
432
			}
F
Fernando Serrano 已提交
433

434 435 436 437 438 439 440 441
			if ( material instanceof THREE.ShaderMaterial ) {

				console.warn( 'GLTFExporter: THREE.ShaderMaterial not supported.' );
				return null;

			}


442 443
			if ( !( material instanceof THREE.MeshStandardMaterial ) ) {

444
				console.warn( 'GLTFExporter: Currently just THREE.StandardMaterial is supported. Material conversion may lose information.' );
445

F
Fernando Serrano 已提交
446 447 448
			}

			// @QUESTION Should we avoid including any attribute that has the default value?
449
			var gltfMaterial = {
F
Fernando Serrano 已提交
450

451
				pbrMetallicRoughness: {}
F
Fernando Serrano 已提交
452

453
			};
454

455 456
			// pbrMetallicRoughness.baseColorFactor
			var color = material.color.toArray().concat( [ material.opacity ] );
F
Fernando Serrano 已提交
457

458
			if ( !equalArray( color, [ 1, 1, 1, 1 ] ) ) {
459

460
				gltfMaterial.pbrMetallicRoughness.baseColorFactor = color;
461 462 463

			}

464
			if ( material instanceof THREE.MeshStandardMaterial ) {
465

466 467
				gltfMaterial.pbrMetallicRoughness.metallicFactor = material.metalness;
				gltfMaterial.pbrMetallicRoughness.roughnessFactor = material.roughness;
468

469
 			} else {
470

471 472
					gltfMaterial.pbrMetallicRoughness.metallicFactor = 0.5;
					gltfMaterial.pbrMetallicRoughness.roughnessFactor = 0.5;
F
Fernando Serrano 已提交
473

474
			}
475

476 477
			// pbrMetallicRoughness.baseColorTexture
			if ( material.map ) {
478

479
				gltfMaterial.pbrMetallicRoughness.baseColorTexture = {
F
Fernando Serrano 已提交
480

481
					index: processTexture( material.map )
F
Fernando Serrano 已提交
482

483
				};
484

485
			}
486

F
Fernando Serrano 已提交
487 488 489
			if ( material instanceof THREE.MeshBasicMaterial ||
				material instanceof THREE.LineBasicMaterial ||
				material instanceof THREE.PointsMaterial ) {
490 491 492 493

			} else {

				// emissiveFactor
494
				var emissive = material.emissive.clone().multiplyScalar( material.emissiveIntensity ).toArray();
F
Fernando Serrano 已提交
495

496 497 498 499
				if ( !equalArray( emissive, [ 0, 0, 0 ] ) ) {

					gltfMaterial.emissiveFactor = emissive;

F
Fernando Serrano 已提交
500
				}
501 502 503 504 505 506

				// emissiveTexture
				if ( material.emissiveMap ) {

					gltfMaterial.emissiveTexture = {

507
						index: processTexture( material.emissiveMap )
508 509 510 511 512 513 514 515 516 517 518

					};

				}

			}

			// normalTexture
			if ( material.normalMap ) {

				gltfMaterial.normalTexture = {
F
Fernando Serrano 已提交
519

520
					index: processTexture( material.normalMap )
F
Fernando Serrano 已提交
521

522 523
				};

524 525 526 527 528 529 530 531 532 533 534 535
				if ( material.normalScale.x !== -1 ) {

					if ( material.normalScale.x !== material.normalScale.y ) {

						console.warn('GLTFExporter: Normal scale components are different, ignoring Y and exporting X');

					}

					gltfMaterial.normalTexture.scale = material.normalScale.x;

				}

F
Fernando Serrano 已提交
536 537
			}

538 539 540 541
			// occlusionTexture
			if ( material.aoMap ) {

				gltfMaterial.occlusionTexture = {
F
Fernando Serrano 已提交
542

543
					index: processTexture( material.aoMap )
F
Fernando Serrano 已提交
544

545 546
				};

547 548 549 550 551 552
				if ( material.aoMapIntensity !== 1.0 ) {

					gltfMaterial.occlusionTexture.strength = material.aoMapIntensity;

				}

553 554 555 556 557
			}

			// alphaMode
			if ( material.transparent ) {

558 559 560 561 562 563 564
				gltfMaterial.alphaMode = 'MASK'; // @FIXME We should detect MASK or BLEND

				if ( material.alphaTest !== 0.5 ) {

					gltfMaterial.alphaCutoff = material.alphaTest;

				}
565 566 567 568

			}

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

F
Fernando Serrano 已提交
571
				gltfMaterial.doubleSided = true;
572

F
Fernando Serrano 已提交
573 574
			}

F
Fernando Serrano 已提交
575
			if ( material.name ) {
576

F
Fernando Serrano 已提交
577
				gltfMaterial.name = material.name;
578

F
Fernando Serrano 已提交
579 580
			}

F
Fernando Serrano 已提交
581
			outputJSON.materials.push( gltfMaterial );
F
Fernando Serrano 已提交
582

583 584 585 586
			var index = outputJSON.materials.length - 1;
			cachedData.materials[ material.uuid ] = index;

			return index;
587

F
Fernando Serrano 已提交
588 589 590
		}

		/**
F
Fernando Serrano 已提交
591 592 593
		 * Process mesh
		 * @param  {THREE.Mesh} mesh Mesh to process
		 * @return {Integer}      Index of the processed mesh in the "meshes" array
F
Fernando Serrano 已提交
594 595
		 */
		function processMesh( mesh ) {
F
Fernando Serrano 已提交
596

F
Fernando Serrano 已提交
597
			if ( !outputJSON.meshes ) {
F
Fernando Serrano 已提交
598 599 600

				outputJSON.meshes = [];

F
Fernando Serrano 已提交
601 602 603
			}

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

605 606 607
			// Use the correct mode
			if ( mesh instanceof THREE.LineSegments ) {

608
				mode = WEBGL_CONSTANTS.LINES;
609 610 611

			} else if ( mesh instanceof THREE.LineLoop ) {

612
				mode = WEBGL_CONSTANTS.LINE_LOOP;
613 614 615

			} else if ( mesh instanceof THREE.Line ) {

616
				mode = WEBGL_CONSTANTS.LINE_STRIP;
617 618 619

			} else if ( mesh instanceof THREE.Points ) {

620
				mode = WEBGL_CONSTANTS.POINTS;
621 622 623

			} else {

624
				if ( !geometry.isBufferGeometry ) {
625 626 627 628 629 630 631

					var geometryTemp = new THREE.BufferGeometry();
					geometryTemp.fromGeometry( geometry );
					geometry = geometryTemp;

				}

632 633
				if ( mesh.drawMode === THREE.TriangleFanDrawMode ) {

F
Fernando Serrano 已提交
634
					console.warn( 'GLTFExporter: TriangleFanDrawMode and wireframe incompatible.' );
635
					mode = WEBGL_CONSTANTS.TRIANGLE_FAN;
636 637 638

				} else if ( mesh.drawMode === THREE.TriangleStripDrawMode ) {

639
					mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINE_STRIP : WEBGL_CONSTANTS.TRIANGLE_STRIP;
640 641 642

				} else {

643
					mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINES : WEBGL_CONSTANTS.TRIANGLES;
644 645 646 647

				}

			}
F
Fernando Serrano 已提交
648 649 650 651 652 653 654 655 656 657

			var gltfMesh = {
				primitives: [
					{
						mode: mode,
						attributes: {},
					}
				]
			};

658
			var material = processMaterial( mesh.material );
659
			if ( material !== null ) {
660 661 662 663 664 665

				gltfMesh.primitives[ 0 ].material = material;

			}


666 667
			if ( geometry.index ) {

668
				gltfMesh.primitives[ 0 ].indices = processAccessor( geometry.index, geometry );
669 670 671

			}

F
Fernando Serrano 已提交
672 673
			// We've just one primitive per mesh
			var gltfAttributes = gltfMesh.primitives[ 0 ].attributes;
F
Fernando Serrano 已提交
674 675
			var attributes = geometry.attributes;

F
Fernando Serrano 已提交
676 677
			// Conversion between attributes names in threejs and gltf spec
			var nameConversion = {
F
Fernando Serrano 已提交
678

F
Fernando Serrano 已提交
679 680
				uv: 'TEXCOORD_0',
				uv2: 'TEXCOORD_1',
681 682 683
				color: 'COLOR_0',
				skinWeight: 'WEIGHTS_0',
				skinIndex: 'JOINTS_0'
F
Fernando Serrano 已提交
684

F
Fernando Serrano 已提交
685 686
			};

687
			// @QUESTION Detect if .vertexColors = THREE.VertexColors?
F
Fernando Serrano 已提交
688
			// For every attribute create an accessor
F
Fernando Serrano 已提交
689 690
			for ( var attributeName in geometry.attributes ) {

F
Fernando Serrano 已提交
691
				var attribute = geometry.attributes[ attributeName ];
F
Fernando Serrano 已提交
692
				attributeName = nameConversion[ attributeName ] || attributeName.toUpperCase();
693
				gltfAttributes[ attributeName ] = processAccessor( attribute, geometry );
F
Fernando Serrano 已提交
694

F
Fernando Serrano 已提交
695 696 697 698 699 700 701
			}

			outputJSON.meshes.push( gltfMesh );

			return outputJSON.meshes.length - 1;
		}

F
Fernando Serrano 已提交
702 703 704 705 706 707
		/**
		 * Process camera
		 * @param  {THREE.Camera} camera Camera to process
		 * @return {Integer}      Index of the processed mesh in the "camera" array
		 */
		function processCamera( camera ) {
F
Fernando Serrano 已提交
708

F
Fernando Serrano 已提交
709
			if ( !outputJSON.cameras ) {
F
Fernando Serrano 已提交
710

F
Fernando Serrano 已提交
711
				outputJSON.cameras = [];
F
Fernando Serrano 已提交
712

F
Fernando Serrano 已提交
713 714 715 716 717
			}

			var isOrtho = camera instanceof THREE.OrthographicCamera;

			var gltfCamera = {
F
Fernando Serrano 已提交
718

F
Fernando Serrano 已提交
719
				type: isOrtho ? 'orthographic' : 'perspective'
F
Fernando Serrano 已提交
720

F
Fernando Serrano 已提交
721 722 723 724 725 726 727 728 729 730 731
			};

			if ( isOrtho ) {

				gltfCamera.orthographic = {

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

F
Fernando Serrano 已提交
732
				};
F
Fernando Serrano 已提交
733 734 735 736 737 738 739 740 741 742 743 744 745 746

			} else {

				gltfCamera.perspective = {

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

				};

			}

F
Fernando Serrano 已提交
747 748
			if ( camera.name ) {

F
Fernando Serrano 已提交
749
				gltfCamera.name = camera.type;
F
Fernando Serrano 已提交
750

F
Fernando Serrano 已提交
751 752 753 754 755 756 757
			}

			outputJSON.cameras.push( gltfCamera );

			return outputJSON.cameras.length - 1;
		}

F
Fernando Serrano 已提交
758 759 760 761 762 763 764
		/**
		 * Process Object3D node
		 * @param  {THREE.Object3D} node Object3D to processNode
		 * @return {Integer}      Index of the node in the nodes list
		 */
		function processNode ( object ) {

765 766 767
			if ( object instanceof THREE.Light ) {

				console.warn( 'GLTFExporter: Unsupported node type:', object.constructor.name );
768
				return null;
769 770 771

			}

F
Fernando Serrano 已提交
772
			if ( !outputJSON.nodes ) {
F
Fernando Serrano 已提交
773

F
Fernando Serrano 已提交
774
				outputJSON.nodes = [];
F
Fernando Serrano 已提交
775

F
Fernando Serrano 已提交
776 777
			}

F
Fernando Serrano 已提交
778 779 780
			var gltfNode = {};

			if ( options.trs ) {
F
Fernando Serrano 已提交
781

F
Fernando Serrano 已提交
782 783 784 785
				var rotation = object.quaternion.toArray();
				var position = object.position.toArray();
				var scale = object.scale.toArray();

786
				if ( !equalArray( rotation, [ 0, 0, 0, 1 ] ) ) {
F
Fernando Serrano 已提交
787

F
Fernando Serrano 已提交
788
					gltfNode.rotation = rotation;
F
Fernando Serrano 已提交
789

F
Fernando Serrano 已提交
790 791
				}

792
				if ( !equalArray( position, [ 0, 0, 0 ] ) ) {
F
Fernando Serrano 已提交
793

F
Fernando Serrano 已提交
794
					gltfNode.position = position;
F
Fernando Serrano 已提交
795

F
Fernando Serrano 已提交
796 797
				}

798
				if ( !equalArray( scale, [ 1, 1, 1 ] ) ) {
F
Fernando Serrano 已提交
799

F
Fernando Serrano 已提交
800
					gltfNode.scale = scale;
F
Fernando Serrano 已提交
801

F
Fernando Serrano 已提交
802 803 804
				}

			} else {
F
Fernando Serrano 已提交
805

F
Fernando Serrano 已提交
806
				object.updateMatrix();
807
				if (! equalArray( object.matrix.elements, [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ] ) ) {
F
Fernando Serrano 已提交
808

F
Fernando Serrano 已提交
809
					gltfNode.matrix = object.matrix.elements;
F
Fernando Serrano 已提交
810

F
Fernando Serrano 已提交
811
				}
F
Fernando Serrano 已提交
812

F
Fernando Serrano 已提交
813 814 815 816
			}

			if ( object.name ) {

F
Fernando Serrano 已提交
817
				gltfNode.name = object.name;
F
Fernando Serrano 已提交
818

F
Fernando Serrano 已提交
819 820
			}

821 822 823 824 825 826 827 828 829 830 831 832 833 834
			if ( object.userData && Object.keys( object.userData ).length > 0 ) {

				try {

					gltfNode.extras = JSON.parse( JSON.stringify( object.userData ) );

				} catch (e) {

					throw new Error( 'GLTFExporter: userData can\'t be serialized' );

				}

			}

F
Fernando Serrano 已提交
835 836 837 838
			if ( object instanceof THREE.Mesh ||
				object instanceof THREE.Line ||
				object instanceof THREE.Points ) {

F
Fernando Serrano 已提交
839
				gltfNode.mesh = processMesh( object );
F
Fernando Serrano 已提交
840

F
Fernando Serrano 已提交
841
			} else if ( object instanceof THREE.Camera ) {
F
Fernando Serrano 已提交
842

F
Fernando Serrano 已提交
843
				gltfNode.camera = processCamera( object );
F
Fernando Serrano 已提交
844

F
Fernando Serrano 已提交
845 846 847
			}

			if ( object.children.length > 0 ) {
F
Fernando Serrano 已提交
848

849
				var children = [];
F
Fernando Serrano 已提交
850 851

				for ( var i = 0, l = object.children.length; i < l; i ++ ) {
F
Fernando Serrano 已提交
852

F
Fernando Serrano 已提交
853
					var child = object.children[ i ];
F
Fernando Serrano 已提交
854

855 856
					if ( child.visible || options.onlyVisible === false ) {

857 858
						var node = processNode( child );

859
						if ( node !== null ) {
860

861
							children.push( node );
862 863

						}
F
Fernando Serrano 已提交
864

F
Fernando Serrano 已提交
865
					}
F
Fernando Serrano 已提交
866

F
Fernando Serrano 已提交
867
				}
F
Fernando Serrano 已提交
868

869 870 871 872 873 874 875
				if ( children.length > 0 ) {

					gltfNode.children = children;

				}


F
Fernando Serrano 已提交
876 877 878 879 880
			}

			outputJSON.nodes.push( gltfNode );

			return outputJSON.nodes.length - 1;
F
Fernando Serrano 已提交
881

F
Fernando Serrano 已提交
882 883 884
		}

		/**
F
Fernando Serrano 已提交
885
		 * Process Scene
F
Fernando Serrano 已提交
886 887 888
		 * @param  {THREE.Scene} node Scene to process
		 */
		function processScene( scene ) {
F
Fernando Serrano 已提交
889

890
			if ( !outputJSON.scenes ) {
F
Fernando Serrano 已提交
891

F
Fernando Serrano 已提交
892 893
				outputJSON.scenes = [];
				outputJSON.scene = 0;
F
Fernando Serrano 已提交
894

F
Fernando Serrano 已提交
895 896 897
			}

			var gltfScene = {
F
Fernando Serrano 已提交
898

F
Fernando Serrano 已提交
899
				nodes: []
F
Fernando Serrano 已提交
900

F
Fernando Serrano 已提交
901 902
			};

F
Fernando Serrano 已提交
903 904
			if ( scene.name ) {

F
Fernando Serrano 已提交
905
				gltfScene.name = scene.name;
F
Fernando Serrano 已提交
906

F
Fernando Serrano 已提交
907 908
			}

F
Fernando Serrano 已提交
909
			outputJSON.scenes.push( gltfScene );
F
Fernando Serrano 已提交
910

911 912
			var nodes = [];

F
Fernando Serrano 已提交
913
			for ( var i = 0, l = scene.children.length; i < l; i ++ ) {
F
Fernando Serrano 已提交
914

F
Fernando Serrano 已提交
915 916
				var child = scene.children[ i ];

917
				if ( child.visible || options.onlyVisible === false ) {
F
Fernando Serrano 已提交
918

919 920
					var node = processNode( child );

921
					if ( node !== null ) {
922

923
						nodes.push( node );
924 925

					}
926 927 928

				}

929
			}
930

931
			if ( nodes.length > 0 ) {
F
Fernando Serrano 已提交
932

933
				gltfScene.nodes = nodes;
F
Fernando Serrano 已提交
934

F
Fernando Serrano 已提交
935
			}
F
Fernando Serrano 已提交
936

F
Fernando Serrano 已提交
937 938
		}

939 940 941 942 943 944 945
		/**
		 * Creates a THREE.Scene to hold a list of objects and parse it
		 * @param  {Array} objects List of objects to process
		 */
		function processObjects ( objects ) {

			var scene = new THREE.Scene();
946
			scene.name = 'AuxScene';
947 948 949

			for ( var i = 0; i < objects.length; i++ ) {

950 951 952
				// We push directly to children instead of calling `add` to prevent
				// modify the .parent and break its original scene and hierarchy
				scene.children.push( objects[ i ] );
953 954 955 956 957 958 959

			}

			processScene( scene );

		}

960
		function processInput( input ) {
961

962
			input = input instanceof Array ? input : [ input ];
F
Fernando Serrano 已提交
963

964
			var objectsWithoutScene = [];
F
Fernando Serrano 已提交
965
			for ( i = 0; i < input.length; i++ ) {
F
Fernando Serrano 已提交
966

967
				if ( input[ i ] instanceof THREE.Scene ) {
968 969 970

					processScene( input[ i ] );

971
				} else {
972

973
					objectsWithoutScene.push( input[ i ] );
974

975
				}
F
Fernando Serrano 已提交
976

F
Fernando Serrano 已提交
977
			}
F
Fernando Serrano 已提交
978

979
			if ( objectsWithoutScene.length > 0 ) {
980

981
				processObjects( objectsWithoutScene );
982 983

			}
F
Fernando Serrano 已提交
984

F
Fernando Serrano 已提交
985
		}
F
Fernando Serrano 已提交
986

987 988
		processInput( input );

F
Fernando Serrano 已提交
989
		// Generate buffer
F
Fernando Serrano 已提交
990
		// Create a new blob with all the dataviews from the buffers
991
		var blob = new Blob( dataViews, { type: 'application/octet-stream' } );
F
Fernando Serrano 已提交
992 993

		// Update the bytlength of the only main buffer and update the uri with the base64 representation of it
994
		if ( outputJSON.buffers && outputJSON.buffers.length > 0 ) {
F
Fernando Serrano 已提交
995

996 997 998 999 1000 1001
			outputJSON.buffers[ 0 ].byteLength = blob.size;
			objectURL = URL.createObjectURL( blob );

			var reader = new window.FileReader();
			 reader.readAsDataURL( blob );
			 reader.onloadend = function() {
F
Fernando Serrano 已提交
1002

1003 1004 1005
				 base64data = reader.result;
				 outputJSON.buffers[ 0 ].uri = base64data;
				 onDone( outputJSON );
F
Fernando Serrano 已提交
1006 1007 1008

			 };

1009
		} else {
F
Fernando Serrano 已提交
1010

1011
			onDone ( outputJSON );
F
Fernando Serrano 已提交
1012

1013
		}
F
Fernando Serrano 已提交
1014 1015
	}
};