GLTFExporter.js 18.7 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 35 36 37 38 39
	1003: WEBGL_CONSTANTS.NEAREST,
	1004: WEBGL_CONSTANTS.LINEAR,
	1005: WEBGL_CONSTANTS.NEAREST_MIPMAP_NEAREST,
	1006: WEBGL_CONSTANTS.LINEAR_MIPMAP_NEAREST,
	1007: WEBGL_CONSTANTS.NEAREST_MIPMAP_LINEAR,
	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 ) {

F
Fernando Serrano 已提交
60
		options = options || {};
F
Fernando Serrano 已提交
61 62

		var outputJSON = {
F
Fernando Serrano 已提交
63

F
Fernando Serrano 已提交
64
			asset: {
F
Fernando Serrano 已提交
65

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

F
Fernando Serrano 已提交
69
		 	}
F
Fernando Serrano 已提交
70

F
Fernando Serrano 已提交
71 72 73 74
    };

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

F
Fernando Serrano 已提交
76 77 78
		/**
		 * Compare two arrays
		 */
F
Fernando Serrano 已提交
79 80 81 82 83 84
		/**
		 * 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
		 */
85
		function equalArray ( array1, array2 ) {
F
Fernando Serrano 已提交
86

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

F
Fernando Serrano 已提交
89
    		return element === array2[ index ];
F
Fernando Serrano 已提交
90

F
Fernando Serrano 已提交
91
			});
F
Fernando Serrano 已提交
92

F
Fernando Serrano 已提交
93 94
		}

F
Fernando Serrano 已提交
95 96 97 98 99 100
		/**
		 * 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 已提交
101

F
Fernando Serrano 已提交
102
			var output = {
F
Fernando Serrano 已提交
103

F
Fernando Serrano 已提交
104 105
				min: new Array( attribute.itemSize ).fill( Number.POSITIVE_INFINITY ),
				max: new Array( attribute.itemSize ).fill( Number.NEGATIVE_INFINITY )
F
Fernando Serrano 已提交
106

F
Fernando Serrano 已提交
107 108 109
			};

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

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

F
Fernando Serrano 已提交
113
					var value = attribute.array[ i * attribute.itemSize + a ];
F
Fernando Serrano 已提交
114 115 116
					output.min[ a ] = Math.min( output.min[ a ], value );
					output.max[ a ] = Math.max( output.max[ a ], value );

F
Fernando Serrano 已提交
117
				}
F
Fernando Serrano 已提交
118

F
Fernando Serrano 已提交
119 120
			}

F
Fernando Serrano 已提交
121
			return output;
F
Fernando Serrano 已提交
122 123
		}

F
Fernando Serrano 已提交
124
		/**
F
Fernando Serrano 已提交
125 126 127 128
		 * 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 已提交
129 130
		 */
		function processBuffer ( attribute, componentType ) {
F
Fernando Serrano 已提交
131

F
Fernando Serrano 已提交
132
			if ( !outputJSON.buffers ) {
F
Fernando Serrano 已提交
133

F
Fernando Serrano 已提交
134
				outputJSON.buffers = [
F
Fernando Serrano 已提交
135

F
Fernando Serrano 已提交
136
					{
F
Fernando Serrano 已提交
137

F
Fernando Serrano 已提交
138 139
						byteLength: 0,
						uri: ''
F
Fernando Serrano 已提交
140

F
Fernando Serrano 已提交
141
					}
F
Fernando Serrano 已提交
142

F
Fernando Serrano 已提交
143
				];
F
Fernando Serrano 已提交
144

F
Fernando Serrano 已提交
145 146
			}

F
Fernando Serrano 已提交
147
			// Create a new dataview and dump the attribute's array into it
F
Fernando Serrano 已提交
148 149 150
			var dataView = new DataView( new ArrayBuffer( attribute.array.byteLength ) );

			var offset = 0;
151
			var offsetInc = componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ? 2 : 4;
F
Fernando Serrano 已提交
152 153

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

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

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

159
					if ( componentType === WEBGL_CONSTANTS.FLOAT ) {
F
Fernando Serrano 已提交
160

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

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

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

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

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

F
Fernando Serrano 已提交
171
					}
F
Fernando Serrano 已提交
172

F
Fernando Serrano 已提交
173
					offset += offsetInc;
F
Fernando Serrano 已提交
174

F
Fernando Serrano 已提交
175
				}
F
Fernando Serrano 已提交
176

F
Fernando Serrano 已提交
177 178
			}

F
Fernando Serrano 已提交
179
			// We just use one buffer
F
Fernando Serrano 已提交
180
			dataViews.push( dataView );
F
Fernando Serrano 已提交
181

F
Fernando Serrano 已提交
182
			// Always using just one buffer
F
Fernando Serrano 已提交
183 184 185 186
			return 0;
		}

		/**
F
Fernando Serrano 已提交
187
		 * Process and generate a BufferView
F
Fernando Serrano 已提交
188 189 190 191
		 * @param  {[type]} data [description]
		 * @return {[type]}      [description]
		 */
		function processBufferView ( data, componentType ) {
F
Fernando Serrano 已提交
192

193
			var isVertexAttributes = componentType === WEBGL_CONSTANTS.FLOAT;
F
Fernando Serrano 已提交
194

F
Fernando Serrano 已提交
195
			if ( !outputJSON.bufferViews ) {
F
Fernando Serrano 已提交
196

F
Fernando Serrano 已提交
197
				outputJSON.bufferViews = [];
F
Fernando Serrano 已提交
198

F
Fernando Serrano 已提交
199 200 201
			}

			var gltfBufferView = {
F
Fernando Serrano 已提交
202

F
Fernando Serrano 已提交
203 204 205
				buffer: processBuffer( data, componentType ),
				byteOffset: byteOffset,
				byteLength: data.array.byteLength,
206 207
				byteStride: data.itemSize * ( componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ? 2 : 4 ),
				target: isVertexAttributes ? WEBGL_CONSTANTS.ARRAY_BUFFER : WEBGL_CONSTANTS.ELEMENT_ARRAY_BUFFER
F
Fernando Serrano 已提交
208

F
Fernando Serrano 已提交
209 210 211 212
			};

			byteOffset += data.array.byteLength;

F
Fernando Serrano 已提交
213
			outputJSON.bufferViews.push( gltfBufferView );
F
Fernando Serrano 已提交
214 215

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

F
Fernando Serrano 已提交
218 219
				id: outputJSON.bufferViews.length - 1,
				byteLength: 0
F
Fernando Serrano 已提交
220

F
Fernando Serrano 已提交
221
			};
F
Fernando Serrano 已提交
222

F
Fernando Serrano 已提交
223
			return output;
F
Fernando Serrano 已提交
224

F
Fernando Serrano 已提交
225 226 227
		}

		/**
F
Fernando Serrano 已提交
228 229 230
		 * 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 已提交
231 232
		 */
		function processAccessor ( attribute ) {
F
Fernando Serrano 已提交
233

F
Fernando Serrano 已提交
234
			if ( !outputJSON.accessors ) {
F
Fernando Serrano 已提交
235

F
Fernando Serrano 已提交
236
				outputJSON.accessors = [];
F
Fernando Serrano 已提交
237

F
Fernando Serrano 已提交
238 239 240
			}

			var types = [
F
Fernando Serrano 已提交
241

F
Fernando Serrano 已提交
242 243 244 245
				'SCALAR',
				'VEC2',
				'VEC3',
				'VEC4'
F
Fernando Serrano 已提交
246

F
Fernando Serrano 已提交
247 248
			];

249 250
			var componentType;

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

254
				componentType = WEBGL_CONSTANTS.FLOAT;
F
Fernando Serrano 已提交
255

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

258
				componentType = WEBGL_CONSTANTS.UNSIGNED_INT;
F
Fernando Serrano 已提交
259

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

262
				componentType = WEBGL_CONSTANTS.UNSIGNED_SHORT;
F
Fernando Serrano 已提交
263

264
			} else {
F
Fernando Serrano 已提交
265

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

268
			}
F
Fernando Serrano 已提交
269 270 271

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

F
Fernando Serrano 已提交
273
			var gltfAccessor = {
F
Fernando Serrano 已提交
274

F
Fernando Serrano 已提交
275 276 277 278 279 280
				bufferView: bufferView.id,
				byteOffset: bufferView.byteOffset,
				componentType: componentType,
				count: attribute.count,
				max: minMax.max,
				min: minMax.min,
F
Fernando Serrano 已提交
281
				type: types[ attribute.itemSize - 1 ]
F
Fernando Serrano 已提交
282

F
Fernando Serrano 已提交
283 284 285 286 287
			};

			outputJSON.accessors.push( gltfAccessor );

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

F
Fernando Serrano 已提交
289 290 291
		}

		/**
F
Fernando Serrano 已提交
292 293 294 295 296
		 * 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 已提交
297

F
Fernando Serrano 已提交
298
			if ( !outputJSON.images ) {
F
Fernando Serrano 已提交
299

F
Fernando Serrano 已提交
300
				outputJSON.images = [];
F
Fernando Serrano 已提交
301

F
Fernando Serrano 已提交
302 303 304 305
			}

			var gltfImage = {};

F
Fernando Serrano 已提交
306
			if ( options.embedImages ) {
F
Fernando Serrano 已提交
307

F
Fernando Serrano 已提交
308
				// @TODO { bufferView, mimeType }
F
Fernando Serrano 已提交
309

F
Fernando Serrano 已提交
310
			} else {
F
Fernando Serrano 已提交
311

F
Fernando Serrano 已提交
312 313
				// @TODO base64 based on options
				gltfImage.uri = map.image.src;
F
Fernando Serrano 已提交
314

F
Fernando Serrano 已提交
315 316 317 318 319
			}

			outputJSON.images.push( gltfImage );

			return outputJSON.images.length - 1;
F
Fernando Serrano 已提交
320

F
Fernando Serrano 已提交
321 322 323 324 325 326 327 328
		}

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

F
Fernando Serrano 已提交
330
			if ( !outputJSON.samplers ) {
F
Fernando Serrano 已提交
331

F
Fernando Serrano 已提交
332
				outputJSON.samplers = [];
F
Fernando Serrano 已提交
333

F
Fernando Serrano 已提交
334 335 336
			}

			var gltfSampler = {
F
Fernando Serrano 已提交
337

338 339 340 341
				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 已提交
342

F
Fernando Serrano 已提交
343 344 345 346 347
			};

			outputJSON.samplers.push( gltfSampler );

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

F
Fernando Serrano 已提交
349 350 351 352 353 354 355 356
		}

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

F
Fernando Serrano 已提交
358
			if (!outputJSON.textures) {
F
Fernando Serrano 已提交
359

F
Fernando Serrano 已提交
360
				outputJSON.textures = [];
F
Fernando Serrano 已提交
361

F
Fernando Serrano 已提交
362 363 364
			}

			var gltfTexture = {
F
Fernando Serrano 已提交
365

F
Fernando Serrano 已提交
366 367
				sampler: processSampler( map ),
				source: processImage( map )
F
Fernando Serrano 已提交
368

F
Fernando Serrano 已提交
369 370 371 372 373
			};

			outputJSON.textures.push( gltfTexture );

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

F
Fernando Serrano 已提交
375 376 377 378 379 380
		}

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

F
Fernando Serrano 已提交
384
			if ( !outputJSON.materials ) {
F
Fernando Serrano 已提交
385

F
Fernando Serrano 已提交
386
				outputJSON.materials = [];
F
Fernando Serrano 已提交
387

F
Fernando Serrano 已提交
388
			}
F
Fernando Serrano 已提交
389

390 391 392 393
			if ( !( material instanceof THREE.MeshStandardMaterial ) ) {

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

F
Fernando Serrano 已提交
394 395 396
			}

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

399
				pbrMetallicRoughness: {}
F
Fernando Serrano 已提交
400

401
			};
402

403 404
			// pbrMetallicRoughness.baseColorFactor
			var color = material.color.toArray().concat( [ material.opacity ] );
F
Fernando Serrano 已提交
405

406
			if ( !equalArray( color, [ 1, 1, 1, 1 ] ) ) {
407

408
				gltfMaterial.pbrMetallicRoughness.baseColorFactor = color;
409 410 411

			}

412
			if ( material instanceof THREE.MeshStandardMaterial ) {
413

414 415
				gltfMaterial.pbrMetallicRoughness.metallicFactor = material.metalness;
				gltfMaterial.pbrMetallicRoughness.roughnessFactor = material.roughness;
416

417
 			} else {
418

419 420
					gltfMaterial.pbrMetallicRoughness.metallicFactor = 0.5;
					gltfMaterial.pbrMetallicRoughness.roughnessFactor = 0.5;
F
Fernando Serrano 已提交
421

422
			}
423

424 425
			// pbrMetallicRoughness.baseColorTexture
			if ( material.map ) {
426

427
				gltfMaterial.pbrMetallicRoughness.baseColorTexture = {
F
Fernando Serrano 已提交
428

429 430
					index: processTexture( material.map ),
					texCoord: 0 // @FIXME
F
Fernando Serrano 已提交
431

432
				};
433

434
			}
435

F
Fernando Serrano 已提交
436 437 438
			if ( material instanceof THREE.MeshBasicMaterial ||
				material instanceof THREE.LineBasicMaterial ||
				material instanceof THREE.PointsMaterial ) {
439 440 441 442

			} else {

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

445 446 447 448
				if ( !equalArray( emissive, [ 0, 0, 0 ] ) ) {

					gltfMaterial.emissiveFactor = emissive;

F
Fernando Serrano 已提交
449
				}
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468

				// emissiveTexture
				if ( material.emissiveMap ) {

					gltfMaterial.emissiveTexture = {

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

					};

				}

			}

			// normalTexture
			if ( material.normalMap ) {

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

470 471
					index: processTexture( material.normalMap ),
					texCoord: 0 // @FIXME
F
Fernando Serrano 已提交
472

473 474
				};

F
Fernando Serrano 已提交
475 476
			}

477 478 479 480
			// occlusionTexture
			if ( material.aoMap ) {

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

482 483
					index: processTexture( material.aoMap ),
					texCoord: 0 // @FIXME
F
Fernando Serrano 已提交
484

485 486 487 488 489 490 491 492 493 494 495 496
				};

			}

			// alphaMode
			if ( material.transparent ) {

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

			}

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

F
Fernando Serrano 已提交
499
				gltfMaterial.doubleSided = true;
500

F
Fernando Serrano 已提交
501 502
			}

F
Fernando Serrano 已提交
503
			if ( material.name ) {
504

F
Fernando Serrano 已提交
505
				gltfMaterial.name = material.name;
506

F
Fernando Serrano 已提交
507 508
			}

F
Fernando Serrano 已提交
509
			outputJSON.materials.push( gltfMaterial );
F
Fernando Serrano 已提交
510 511

			return outputJSON.materials.length - 1;
512

F
Fernando Serrano 已提交
513 514 515
		}

		/**
F
Fernando Serrano 已提交
516 517 518
		 * Process mesh
		 * @param  {THREE.Mesh} mesh Mesh to process
		 * @return {Integer}      Index of the processed mesh in the "meshes" array
F
Fernando Serrano 已提交
519 520
		 */
		function processMesh( mesh ) {
F
Fernando Serrano 已提交
521

F
Fernando Serrano 已提交
522
			if ( !outputJSON.meshes ) {
F
Fernando Serrano 已提交
523 524 525

				outputJSON.meshes = [];

F
Fernando Serrano 已提交
526 527 528
			}

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

530 531 532
			// Use the correct mode
			if ( mesh instanceof THREE.LineSegments ) {

533
				mode = WEBGL_CONSTANTS.LINES;
534 535 536

			} else if ( mesh instanceof THREE.LineLoop ) {

537
				mode = WEBGL_CONSTANTS.LINE_LOOP;
538 539 540

			} else if ( mesh instanceof THREE.Line ) {

541
				mode = WEBGL_CONSTANTS.LINE_STRIP;
542 543 544

			} else if ( mesh instanceof THREE.Points ) {

545
				mode = WEBGL_CONSTANTS.POINTS;
546 547 548

			} else {

549 550 551 552 553 554 555 556
				if ( !( geometry instanceof THREE.BufferGeometry) ) {

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

				}

557 558
				if ( mesh.drawMode === THREE.TriangleFanDrawMode ) {

F
Fernando Serrano 已提交
559
					console.warn( 'GLTFExporter: TriangleFanDrawMode and wireframe incompatible.' );
560
					mode = WEBGL_CONSTANTS.TRIANGLE_FAN;
561 562 563

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

564
					mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINE_STRIP : WEBGL_CONSTANTS.TRIANGLE_STRIP;
565 566 567

				} else {

568
					mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINES : WEBGL_CONSTANTS.TRIANGLES;
569 570 571 572

				}

			}
F
Fernando Serrano 已提交
573 574 575 576 577 578

			var gltfMesh = {
				primitives: [
					{
						mode: mode,
						attributes: {},
579
						material: processMaterial( mesh.material )
F
Fernando Serrano 已提交
580 581 582 583
					}
				]
			};

584 585 586 587 588 589
			if ( geometry.index ) {

				gltfMesh.primitives[ 0 ].indices = processAccessor( geometry.index );

			}

F
Fernando Serrano 已提交
590 591
			// We've just one primitive per mesh
			var gltfAttributes = gltfMesh.primitives[ 0 ].attributes;
F
Fernando Serrano 已提交
592 593
			var attributes = geometry.attributes;

F
Fernando Serrano 已提交
594 595
			// Conversion between attributes names in threejs and gltf spec
			var nameConversion = {
F
Fernando Serrano 已提交
596

F
Fernando Serrano 已提交
597 598
				uv: 'TEXCOORD_0',
				uv2: 'TEXCOORD_1',
599 600 601
				color: 'COLOR_0',
				skinWeight: 'WEIGHTS_0',
				skinIndex: 'JOINTS_0'
F
Fernando Serrano 已提交
602

F
Fernando Serrano 已提交
603 604
			};

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

F
Fernando Serrano 已提交
609
				var attribute = geometry.attributes[ attributeName ];
F
Fernando Serrano 已提交
610
				attributeName = nameConversion[ attributeName ] || attributeName.toUpperCase();
F
Fernando Serrano 已提交
611
				gltfAttributes[ attributeName ] = processAccessor( attribute );
F
Fernando Serrano 已提交
612

F
Fernando Serrano 已提交
613 614 615 616 617 618 619
			}

			outputJSON.meshes.push( gltfMesh );

			return outputJSON.meshes.length - 1;
		}

F
Fernando Serrano 已提交
620 621 622 623 624 625
		/**
		 * 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 已提交
626

F
Fernando Serrano 已提交
627
			if ( !outputJSON.cameras ) {
F
Fernando Serrano 已提交
628

F
Fernando Serrano 已提交
629
				outputJSON.cameras = [];
F
Fernando Serrano 已提交
630

F
Fernando Serrano 已提交
631 632 633 634 635
			}

			var isOrtho = camera instanceof THREE.OrthographicCamera;

			var gltfCamera = {
F
Fernando Serrano 已提交
636

F
Fernando Serrano 已提交
637
				type: isOrtho ? 'orthographic' : 'perspective'
F
Fernando Serrano 已提交
638

F
Fernando Serrano 已提交
639 640 641 642 643 644 645 646 647 648 649
			};

			if ( isOrtho ) {

				gltfCamera.orthographic = {

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

F
Fernando Serrano 已提交
650
				};
F
Fernando Serrano 已提交
651 652 653 654 655 656 657 658 659 660 661 662 663 664

			} else {

				gltfCamera.perspective = {

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

				};

			}

F
Fernando Serrano 已提交
665 666
			if ( camera.name ) {

F
Fernando Serrano 已提交
667
				gltfCamera.name = camera.type;
F
Fernando Serrano 已提交
668

F
Fernando Serrano 已提交
669 670 671 672 673 674 675
			}

			outputJSON.cameras.push( gltfCamera );

			return outputJSON.cameras.length - 1;
		}

F
Fernando Serrano 已提交
676 677 678 679 680 681 682
		/**
		 * 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 已提交
683
			if ( !outputJSON.nodes ) {
F
Fernando Serrano 已提交
684

F
Fernando Serrano 已提交
685
				outputJSON.nodes = [];
F
Fernando Serrano 已提交
686

F
Fernando Serrano 已提交
687 688
			}

F
Fernando Serrano 已提交
689 690 691
			var gltfNode = {};

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

F
Fernando Serrano 已提交
693 694 695 696
				var rotation = object.quaternion.toArray();
				var position = object.position.toArray();
				var scale = object.scale.toArray();

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

F
Fernando Serrano 已提交
699
					gltfNode.rotation = rotation;
F
Fernando Serrano 已提交
700

F
Fernando Serrano 已提交
701 702
				}

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

F
Fernando Serrano 已提交
705
					gltfNode.position = position;
F
Fernando Serrano 已提交
706

F
Fernando Serrano 已提交
707 708
				}

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

F
Fernando Serrano 已提交
711
					gltfNode.scale = scale;
F
Fernando Serrano 已提交
712

F
Fernando Serrano 已提交
713 714 715
				}

			} else {
F
Fernando Serrano 已提交
716

F
Fernando Serrano 已提交
717
				object.updateMatrix();
718
				if (! equalArray( object.matrix.elements, [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ] ) ) {
F
Fernando Serrano 已提交
719

F
Fernando Serrano 已提交
720
					gltfNode.matrix = object.matrix.elements;
F
Fernando Serrano 已提交
721

F
Fernando Serrano 已提交
722
				}
F
Fernando Serrano 已提交
723

F
Fernando Serrano 已提交
724 725 726 727
			}

			if ( object.name ) {

F
Fernando Serrano 已提交
728
				gltfNode.name = object.name;
F
Fernando Serrano 已提交
729

F
Fernando Serrano 已提交
730 731
			}

732 733 734 735 736 737 738 739 740 741 742 743 744 745
			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 已提交
746 747 748 749
			if ( object instanceof THREE.Mesh ||
				object instanceof THREE.Line ||
				object instanceof THREE.Points ) {

F
Fernando Serrano 已提交
750
				gltfNode.mesh = processMesh( object );
F
Fernando Serrano 已提交
751

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

F
Fernando Serrano 已提交
754
				gltfNode.camera = processCamera( object );
F
Fernando Serrano 已提交
755

F
Fernando Serrano 已提交
756 757 758
			}

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

F
Fernando Serrano 已提交
760
				gltfNode.children = [];
F
Fernando Serrano 已提交
761 762

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

F
Fernando Serrano 已提交
764
					var child = object.children[ i ];
F
Fernando Serrano 已提交
765 766 767 768 769 770
					if ( child instanceof THREE.Mesh ||
						child instanceof THREE.Camera ||
						child instanceof THREE.Group ||
						child instanceof THREE.Line ||
						child instanceof THREE.Points) {

F
Fernando Serrano 已提交
771
						gltfNode.children.push( processNode( child ) );
F
Fernando Serrano 已提交
772

F
Fernando Serrano 已提交
773
					}
F
Fernando Serrano 已提交
774

F
Fernando Serrano 已提交
775
				}
F
Fernando Serrano 已提交
776

F
Fernando Serrano 已提交
777 778 779 780 781
			}

			outputJSON.nodes.push( gltfNode );

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

F
Fernando Serrano 已提交
783 784 785
		}

		/**
F
Fernando Serrano 已提交
786
		 * Process Scene
F
Fernando Serrano 已提交
787 788 789
		 * @param  {THREE.Scene} node Scene to process
		 */
		function processScene( scene ) {
F
Fernando Serrano 已提交
790

791
			if ( !outputJSON.scenes ) {
F
Fernando Serrano 已提交
792

F
Fernando Serrano 已提交
793 794
				outputJSON.scenes = [];
				outputJSON.scene = 0;
F
Fernando Serrano 已提交
795

F
Fernando Serrano 已提交
796 797 798
			}

			var gltfScene = {
F
Fernando Serrano 已提交
799

F
Fernando Serrano 已提交
800
				nodes: []
F
Fernando Serrano 已提交
801

F
Fernando Serrano 已提交
802 803
			};

F
Fernando Serrano 已提交
804 805
			if ( scene.name ) {

F
Fernando Serrano 已提交
806
				gltfScene.name = scene.name;
F
Fernando Serrano 已提交
807

F
Fernando Serrano 已提交
808 809
			}

F
Fernando Serrano 已提交
810
			outputJSON.scenes.push( gltfScene );
F
Fernando Serrano 已提交
811 812

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

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

F
Fernando Serrano 已提交
816 817 818 819 820 821 822
				// @TODO We don't process lights yet
				if ( child instanceof THREE.Mesh ||
					child instanceof THREE.Camera ||
					child instanceof THREE.Group ||
					child instanceof THREE.Line ||
					child instanceof THREE.Points) {

F
Fernando Serrano 已提交
823
					gltfScene.nodes.push( processNode( child ) );
F
Fernando Serrano 已提交
824

F
Fernando Serrano 已提交
825
				}
F
Fernando Serrano 已提交
826

F
Fernando Serrano 已提交
827
			}
F
Fernando Serrano 已提交
828

F
Fernando Serrano 已提交
829 830
		}

831 832 833 834 835 836 837
		/**
		 * 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();
838
			scene.name = 'AuxScene';
839 840 841

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

842 843 844
				// 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 ] );
845 846 847 848 849 850 851

			}

			processScene( scene );

		}

852
		function processInput( input ) {
853

854
			input = input instanceof Array ? input : [ input ];
F
Fernando Serrano 已提交
855

856
			var objectsWithoutScene = [];
F
Fernando Serrano 已提交
857
			for ( i = 0; i < input.length; i++ ) {
F
Fernando Serrano 已提交
858

859
				if ( input[ i ] instanceof THREE.Scene ) {
860 861 862

					processScene( input[ i ] );

863
				} else {
864

865
					objectsWithoutScene.push( input[ i ] );
866

867
				}
F
Fernando Serrano 已提交
868

F
Fernando Serrano 已提交
869
			}
F
Fernando Serrano 已提交
870

871
			if ( objectsWithoutScene.length > 0 ) {
872

873
				processObjects( objectsWithoutScene );
874 875

			}
F
Fernando Serrano 已提交
876

F
Fernando Serrano 已提交
877
		}
F
Fernando Serrano 已提交
878

879 880
		processInput( input );

F
Fernando Serrano 已提交
881
		// Generate buffer
F
Fernando Serrano 已提交
882 883 884 885
		// 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
886
		if ( outputJSON.buffers && outputJSON.buffers.length > 0 ) {
F
Fernando Serrano 已提交
887

888 889 890 891 892 893
			outputJSON.buffers[ 0 ].byteLength = blob.size;
			objectURL = URL.createObjectURL( blob );

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

895 896 897
				 base64data = reader.result;
				 outputJSON.buffers[ 0 ].uri = base64data;
				 onDone( outputJSON );
F
Fernando Serrano 已提交
898 899 900

			 };

901
		} else {
F
Fernando Serrano 已提交
902

903
			onDone ( outputJSON );
F
Fernando Serrano 已提交
904

905
		}
F
Fernando Serrano 已提交
906 907
	}
};