GLTFExporter.js 19.8 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 = [];
F
Fernando Serrano 已提交
81

F
Fernando Serrano 已提交
82 83 84
		/**
		 * Compare two arrays
		 */
F
Fernando Serrano 已提交
85 86 87 88 89 90
		/**
		 * 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
		 */
91
		function equalArray ( array1, array2 ) {
F
Fernando Serrano 已提交
92

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

F
Fernando Serrano 已提交
95
    		return element === array2[ index ];
F
Fernando Serrano 已提交
96

F
Fernando Serrano 已提交
97
			});
F
Fernando Serrano 已提交
98

F
Fernando Serrano 已提交
99 100
		}

F
Fernando Serrano 已提交
101 102 103 104 105 106
		/**
		 * 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 已提交
107

F
Fernando Serrano 已提交
108
			var output = {
F
Fernando Serrano 已提交
109

F
Fernando Serrano 已提交
110 111
				min: new Array( attribute.itemSize ).fill( Number.POSITIVE_INFINITY ),
				max: new Array( attribute.itemSize ).fill( Number.NEGATIVE_INFINITY )
F
Fernando Serrano 已提交
112

F
Fernando Serrano 已提交
113 114 115
			};

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

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

F
Fernando Serrano 已提交
119
					var value = attribute.array[ i * attribute.itemSize + a ];
F
Fernando Serrano 已提交
120 121 122
					output.min[ a ] = Math.min( output.min[ a ], value );
					output.max[ a ] = Math.max( output.max[ a ], value );

F
Fernando Serrano 已提交
123
				}
F
Fernando Serrano 已提交
124

F
Fernando Serrano 已提交
125 126
			}

F
Fernando Serrano 已提交
127
			return output;
F
Fernando Serrano 已提交
128 129
		}

F
Fernando Serrano 已提交
130
		/**
F
Fernando Serrano 已提交
131 132 133 134
		 * 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 已提交
135
		 */
136
		function processBuffer ( attribute, componentType, start, count ) {
F
Fernando Serrano 已提交
137

F
Fernando Serrano 已提交
138
			if ( !outputJSON.buffers ) {
F
Fernando Serrano 已提交
139

F
Fernando Serrano 已提交
140
				outputJSON.buffers = [
F
Fernando Serrano 已提交
141

F
Fernando Serrano 已提交
142
					{
F
Fernando Serrano 已提交
143

F
Fernando Serrano 已提交
144 145
						byteLength: 0,
						uri: ''
F
Fernando Serrano 已提交
146

F
Fernando Serrano 已提交
147
					}
F
Fernando Serrano 已提交
148

F
Fernando Serrano 已提交
149
				];
F
Fernando Serrano 已提交
150

F
Fernando Serrano 已提交
151 152
			}

153 154 155
			var offset = 0;
			var componentSize = componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ? 2 : 4;

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

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

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

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

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

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

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

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

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

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

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

F
Fernando Serrano 已提交
179
					}
F
Fernando Serrano 已提交
180

181
					offset += componentSize;
F
Fernando Serrano 已提交
182

F
Fernando Serrano 已提交
183
				}
F
Fernando Serrano 已提交
184

F
Fernando Serrano 已提交
185 186
			}

F
Fernando Serrano 已提交
187
			// We just use one buffer
F
Fernando Serrano 已提交
188
			dataViews.push( dataView );
F
Fernando Serrano 已提交
189

F
Fernando Serrano 已提交
190
			// Always using just one buffer
F
Fernando Serrano 已提交
191 192 193 194
			return 0;
		}

		/**
F
Fernando Serrano 已提交
195
		 * Process and generate a BufferView
F
Fernando Serrano 已提交
196 197 198
		 * @param  {[type]} data [description]
		 * @return {[type]}      [description]
		 */
199
		function processBufferView ( data, componentType, start, count ) {
F
Fernando Serrano 已提交
200

201
			var isVertexAttributes = componentType === WEBGL_CONSTANTS.FLOAT;
F
Fernando Serrano 已提交
202

F
Fernando Serrano 已提交
203
			if ( !outputJSON.bufferViews ) {
F
Fernando Serrano 已提交
204

F
Fernando Serrano 已提交
205
				outputJSON.bufferViews = [];
F
Fernando Serrano 已提交
206

F
Fernando Serrano 已提交
207 208
			}

209 210 211 212 213
			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 已提交
214
			var gltfBufferView = {
F
Fernando Serrano 已提交
215

216
				buffer: processBuffer( data, componentType, start, count ),
F
Fernando Serrano 已提交
217
				byteOffset: byteOffset,
218 219
				byteLength: byteLength,
				byteStride: data.itemSize * componentSize,
220
				target: isVertexAttributes ? WEBGL_CONSTANTS.ARRAY_BUFFER : WEBGL_CONSTANTS.ELEMENT_ARRAY_BUFFER
F
Fernando Serrano 已提交
221

F
Fernando Serrano 已提交
222 223
			};

224
			byteOffset += byteLength;
F
Fernando Serrano 已提交
225

F
Fernando Serrano 已提交
226
			outputJSON.bufferViews.push( gltfBufferView );
F
Fernando Serrano 已提交
227 228

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

F
Fernando Serrano 已提交
231 232
				id: outputJSON.bufferViews.length - 1,
				byteLength: 0
F
Fernando Serrano 已提交
233

F
Fernando Serrano 已提交
234
			};
F
Fernando Serrano 已提交
235

F
Fernando Serrano 已提交
236
			return output;
F
Fernando Serrano 已提交
237

F
Fernando Serrano 已提交
238 239 240
		}

		/**
F
Fernando Serrano 已提交
241 242 243
		 * 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 已提交
244
		 */
245
		function processAccessor ( attribute, geometry ) {
F
Fernando Serrano 已提交
246

F
Fernando Serrano 已提交
247
			if ( !outputJSON.accessors ) {
F
Fernando Serrano 已提交
248

F
Fernando Serrano 已提交
249
				outputJSON.accessors = [];
F
Fernando Serrano 已提交
250

F
Fernando Serrano 已提交
251 252 253
			}

			var types = [
F
Fernando Serrano 已提交
254

F
Fernando Serrano 已提交
255 256 257 258
				'SCALAR',
				'VEC2',
				'VEC3',
				'VEC4'
F
Fernando Serrano 已提交
259

F
Fernando Serrano 已提交
260 261
			];

262 263
			var componentType;

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

267
				componentType = WEBGL_CONSTANTS.FLOAT;
F
Fernando Serrano 已提交
268

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

271
				componentType = WEBGL_CONSTANTS.UNSIGNED_INT;
F
Fernando Serrano 已提交
272

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

275
				componentType = WEBGL_CONSTANTS.UNSIGNED_SHORT;
F
Fernando Serrano 已提交
276

277
			} else {
F
Fernando Serrano 已提交
278

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

281
			}
F
Fernando Serrano 已提交
282 283

			var minMax = getMinMax( attribute );
284 285 286 287 288 289 290 291 292 293 294

			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 已提交
295

F
Fernando Serrano 已提交
296
			var gltfAccessor = {
F
Fernando Serrano 已提交
297

F
Fernando Serrano 已提交
298 299 300
				bufferView: bufferView.id,
				byteOffset: bufferView.byteOffset,
				componentType: componentType,
301
				count: count,
F
Fernando Serrano 已提交
302 303
				max: minMax.max,
				min: minMax.min,
F
Fernando Serrano 已提交
304
				type: types[ attribute.itemSize - 1 ]
F
Fernando Serrano 已提交
305

F
Fernando Serrano 已提交
306 307 308 309 310
			};

			outputJSON.accessors.push( gltfAccessor );

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

F
Fernando Serrano 已提交
312 313 314
		}

		/**
F
Fernando Serrano 已提交
315 316 317 318 319
		 * 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 已提交
320

F
Fernando Serrano 已提交
321
			if ( !outputJSON.images ) {
F
Fernando Serrano 已提交
322

F
Fernando Serrano 已提交
323
				outputJSON.images = [];
F
Fernando Serrano 已提交
324

F
Fernando Serrano 已提交
325 326 327 328
			}

			var gltfImage = {};

F
Fernando Serrano 已提交
329
			if ( options.embedImages ) {
F
Fernando Serrano 已提交
330

F
Fernando Serrano 已提交
331
				// @TODO { bufferView, mimeType }
F
Fernando Serrano 已提交
332

F
Fernando Serrano 已提交
333
			} else {
F
Fernando Serrano 已提交
334

F
Fernando Serrano 已提交
335 336
				// @TODO base64 based on options
				gltfImage.uri = map.image.src;
F
Fernando Serrano 已提交
337

F
Fernando Serrano 已提交
338 339 340 341 342
			}

			outputJSON.images.push( gltfImage );

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

F
Fernando Serrano 已提交
344 345 346 347 348 349 350 351
		}

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

F
Fernando Serrano 已提交
353
			if ( !outputJSON.samplers ) {
F
Fernando Serrano 已提交
354

F
Fernando Serrano 已提交
355
				outputJSON.samplers = [];
F
Fernando Serrano 已提交
356

F
Fernando Serrano 已提交
357 358 359
			}

			var gltfSampler = {
F
Fernando Serrano 已提交
360

361 362 363 364
				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 已提交
365

F
Fernando Serrano 已提交
366 367 368 369 370
			};

			outputJSON.samplers.push( gltfSampler );

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

F
Fernando Serrano 已提交
372 373 374 375 376 377 378 379
		}

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

F
Fernando Serrano 已提交
381
			if (!outputJSON.textures) {
F
Fernando Serrano 已提交
382

F
Fernando Serrano 已提交
383
				outputJSON.textures = [];
F
Fernando Serrano 已提交
384

F
Fernando Serrano 已提交
385 386 387
			}

			var gltfTexture = {
F
Fernando Serrano 已提交
388

F
Fernando Serrano 已提交
389 390
				sampler: processSampler( map ),
				source: processImage( map )
F
Fernando Serrano 已提交
391

F
Fernando Serrano 已提交
392 393 394 395 396
			};

			outputJSON.textures.push( gltfTexture );

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

F
Fernando Serrano 已提交
398 399 400 401 402 403
		}

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

F
Fernando Serrano 已提交
407
			if ( !outputJSON.materials ) {
F
Fernando Serrano 已提交
408

F
Fernando Serrano 已提交
409
				outputJSON.materials = [];
F
Fernando Serrano 已提交
410

F
Fernando Serrano 已提交
411
			}
F
Fernando Serrano 已提交
412

413 414 415 416 417 418 419 420
			if ( material instanceof THREE.ShaderMaterial ) {

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

			}


421 422
			if ( !( material instanceof THREE.MeshStandardMaterial ) ) {

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

F
Fernando Serrano 已提交
425 426 427
			}

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

430
				pbrMetallicRoughness: {}
F
Fernando Serrano 已提交
431

432
			};
433

434 435
			// pbrMetallicRoughness.baseColorFactor
			var color = material.color.toArray().concat( [ material.opacity ] );
F
Fernando Serrano 已提交
436

437
			if ( !equalArray( color, [ 1, 1, 1, 1 ] ) ) {
438

439
				gltfMaterial.pbrMetallicRoughness.baseColorFactor = color;
440 441 442

			}

443
			if ( material instanceof THREE.MeshStandardMaterial ) {
444

445 446
				gltfMaterial.pbrMetallicRoughness.metallicFactor = material.metalness;
				gltfMaterial.pbrMetallicRoughness.roughnessFactor = material.roughness;
447

448
 			} else {
449

450 451
					gltfMaterial.pbrMetallicRoughness.metallicFactor = 0.5;
					gltfMaterial.pbrMetallicRoughness.roughnessFactor = 0.5;
F
Fernando Serrano 已提交
452

453
			}
454

455 456
			// pbrMetallicRoughness.baseColorTexture
			if ( material.map ) {
457

458
				gltfMaterial.pbrMetallicRoughness.baseColorTexture = {
F
Fernando Serrano 已提交
459

460
					index: processTexture( material.map )
F
Fernando Serrano 已提交
461

462
				};
463

464
			}
465

F
Fernando Serrano 已提交
466 467 468
			if ( material instanceof THREE.MeshBasicMaterial ||
				material instanceof THREE.LineBasicMaterial ||
				material instanceof THREE.PointsMaterial ) {
469 470 471 472

			} else {

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

475 476 477 478
				if ( !equalArray( emissive, [ 0, 0, 0 ] ) ) {

					gltfMaterial.emissiveFactor = emissive;

F
Fernando Serrano 已提交
479
				}
480 481 482 483 484 485

				// emissiveTexture
				if ( material.emissiveMap ) {

					gltfMaterial.emissiveTexture = {

486
						index: processTexture( material.emissiveMap )
487 488 489 490 491 492 493 494 495 496 497

					};

				}

			}

			// normalTexture
			if ( material.normalMap ) {

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

499
					index: processTexture( material.normalMap )
F
Fernando Serrano 已提交
500

501 502
				};

F
Fernando Serrano 已提交
503 504
			}

505 506 507 508
			// occlusionTexture
			if ( material.aoMap ) {

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

510
					index: processTexture( material.aoMap )
F
Fernando Serrano 已提交
511

512 513 514 515 516 517 518 519 520 521 522 523
				};

			}

			// alphaMode
			if ( material.transparent ) {

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

			}

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

F
Fernando Serrano 已提交
526
				gltfMaterial.doubleSided = true;
527

F
Fernando Serrano 已提交
528 529
			}

F
Fernando Serrano 已提交
530
			if ( material.name ) {
531

F
Fernando Serrano 已提交
532
				gltfMaterial.name = material.name;
533

F
Fernando Serrano 已提交
534 535
			}

F
Fernando Serrano 已提交
536
			outputJSON.materials.push( gltfMaterial );
F
Fernando Serrano 已提交
537 538

			return outputJSON.materials.length - 1;
539

F
Fernando Serrano 已提交
540 541 542
		}

		/**
F
Fernando Serrano 已提交
543 544 545
		 * Process mesh
		 * @param  {THREE.Mesh} mesh Mesh to process
		 * @return {Integer}      Index of the processed mesh in the "meshes" array
F
Fernando Serrano 已提交
546 547
		 */
		function processMesh( mesh ) {
F
Fernando Serrano 已提交
548

F
Fernando Serrano 已提交
549
			if ( !outputJSON.meshes ) {
F
Fernando Serrano 已提交
550 551 552

				outputJSON.meshes = [];

F
Fernando Serrano 已提交
553 554 555
			}

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

557 558 559
			// Use the correct mode
			if ( mesh instanceof THREE.LineSegments ) {

560
				mode = WEBGL_CONSTANTS.LINES;
561 562 563

			} else if ( mesh instanceof THREE.LineLoop ) {

564
				mode = WEBGL_CONSTANTS.LINE_LOOP;
565 566 567

			} else if ( mesh instanceof THREE.Line ) {

568
				mode = WEBGL_CONSTANTS.LINE_STRIP;
569 570 571

			} else if ( mesh instanceof THREE.Points ) {

572
				mode = WEBGL_CONSTANTS.POINTS;
573 574 575

			} else {

576
				if ( !geometry.isBufferGeometry ) {
577 578 579 580 581 582 583

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

				}

584 585
				if ( mesh.drawMode === THREE.TriangleFanDrawMode ) {

F
Fernando Serrano 已提交
586
					console.warn( 'GLTFExporter: TriangleFanDrawMode and wireframe incompatible.' );
587
					mode = WEBGL_CONSTANTS.TRIANGLE_FAN;
588 589 590

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

591
					mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINE_STRIP : WEBGL_CONSTANTS.TRIANGLE_STRIP;
592 593 594

				} else {

595
					mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINES : WEBGL_CONSTANTS.TRIANGLES;
596 597 598 599

				}

			}
F
Fernando Serrano 已提交
600 601 602 603 604 605 606 607 608 609

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

610 611 612 613 614 615 616 617
			var material = processMaterial( mesh.material );
			if ( material ) {

				gltfMesh.primitives[ 0 ].material = material;

			}


618 619
			if ( geometry.index ) {

620
				gltfMesh.primitives[ 0 ].indices = processAccessor( geometry.index, geometry );
621 622 623

			}

F
Fernando Serrano 已提交
624 625
			// We've just one primitive per mesh
			var gltfAttributes = gltfMesh.primitives[ 0 ].attributes;
F
Fernando Serrano 已提交
626 627
			var attributes = geometry.attributes;

F
Fernando Serrano 已提交
628 629
			// Conversion between attributes names in threejs and gltf spec
			var nameConversion = {
F
Fernando Serrano 已提交
630

F
Fernando Serrano 已提交
631 632
				uv: 'TEXCOORD_0',
				uv2: 'TEXCOORD_1',
633 634 635
				color: 'COLOR_0',
				skinWeight: 'WEIGHTS_0',
				skinIndex: 'JOINTS_0'
F
Fernando Serrano 已提交
636

F
Fernando Serrano 已提交
637 638
			};

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

F
Fernando Serrano 已提交
643
				var attribute = geometry.attributes[ attributeName ];
F
Fernando Serrano 已提交
644
				attributeName = nameConversion[ attributeName ] || attributeName.toUpperCase();
645
				gltfAttributes[ attributeName ] = processAccessor( attribute, geometry );
F
Fernando Serrano 已提交
646

F
Fernando Serrano 已提交
647 648 649 650 651 652 653
			}

			outputJSON.meshes.push( gltfMesh );

			return outputJSON.meshes.length - 1;
		}

F
Fernando Serrano 已提交
654 655 656 657 658 659
		/**
		 * 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 已提交
660

F
Fernando Serrano 已提交
661
			if ( !outputJSON.cameras ) {
F
Fernando Serrano 已提交
662

F
Fernando Serrano 已提交
663
				outputJSON.cameras = [];
F
Fernando Serrano 已提交
664

F
Fernando Serrano 已提交
665 666 667 668 669
			}

			var isOrtho = camera instanceof THREE.OrthographicCamera;

			var gltfCamera = {
F
Fernando Serrano 已提交
670

F
Fernando Serrano 已提交
671
				type: isOrtho ? 'orthographic' : 'perspective'
F
Fernando Serrano 已提交
672

F
Fernando Serrano 已提交
673 674 675 676 677 678 679 680 681 682 683
			};

			if ( isOrtho ) {

				gltfCamera.orthographic = {

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

F
Fernando Serrano 已提交
684
				};
F
Fernando Serrano 已提交
685 686 687 688 689 690 691 692 693 694 695 696 697 698

			} else {

				gltfCamera.perspective = {

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

				};

			}

F
Fernando Serrano 已提交
699 700
			if ( camera.name ) {

F
Fernando Serrano 已提交
701
				gltfCamera.name = camera.type;
F
Fernando Serrano 已提交
702

F
Fernando Serrano 已提交
703 704 705 706 707 708 709
			}

			outputJSON.cameras.push( gltfCamera );

			return outputJSON.cameras.length - 1;
		}

F
Fernando Serrano 已提交
710 711 712 713 714 715 716
		/**
		 * 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 已提交
717
			if ( !outputJSON.nodes ) {
F
Fernando Serrano 已提交
718

F
Fernando Serrano 已提交
719
				outputJSON.nodes = [];
F
Fernando Serrano 已提交
720

F
Fernando Serrano 已提交
721 722
			}

F
Fernando Serrano 已提交
723 724 725
			var gltfNode = {};

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

F
Fernando Serrano 已提交
727 728 729 730
				var rotation = object.quaternion.toArray();
				var position = object.position.toArray();
				var scale = object.scale.toArray();

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

F
Fernando Serrano 已提交
733
					gltfNode.rotation = rotation;
F
Fernando Serrano 已提交
734

F
Fernando Serrano 已提交
735 736
				}

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

F
Fernando Serrano 已提交
739
					gltfNode.position = position;
F
Fernando Serrano 已提交
740

F
Fernando Serrano 已提交
741 742
				}

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

F
Fernando Serrano 已提交
745
					gltfNode.scale = scale;
F
Fernando Serrano 已提交
746

F
Fernando Serrano 已提交
747 748 749
				}

			} else {
F
Fernando Serrano 已提交
750

F
Fernando Serrano 已提交
751
				object.updateMatrix();
752
				if (! equalArray( object.matrix.elements, [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ] ) ) {
F
Fernando Serrano 已提交
753

F
Fernando Serrano 已提交
754
					gltfNode.matrix = object.matrix.elements;
F
Fernando Serrano 已提交
755

F
Fernando Serrano 已提交
756
				}
F
Fernando Serrano 已提交
757

F
Fernando Serrano 已提交
758 759 760 761
			}

			if ( object.name ) {

F
Fernando Serrano 已提交
762
				gltfNode.name = object.name;
F
Fernando Serrano 已提交
763

F
Fernando Serrano 已提交
764 765
			}

766 767 768 769 770 771 772 773 774 775 776 777 778 779
			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 已提交
780 781 782 783
			if ( object instanceof THREE.Mesh ||
				object instanceof THREE.Line ||
				object instanceof THREE.Points ) {

F
Fernando Serrano 已提交
784
				gltfNode.mesh = processMesh( object );
F
Fernando Serrano 已提交
785

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

F
Fernando Serrano 已提交
788
				gltfNode.camera = processCamera( object );
F
Fernando Serrano 已提交
789

F
Fernando Serrano 已提交
790 791 792
			}

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

794
				var children = [];
F
Fernando Serrano 已提交
795 796

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

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

800 801 802 803 804 805 806 807 808 809 810
					if ( child.visible || options.onlyVisible === false ) {

						if ( child instanceof THREE.Mesh ||
							child instanceof THREE.Camera ||
							child instanceof THREE.Group ||
							child instanceof THREE.Line ||
							child instanceof THREE.Points) {

							children.push( processNode( child ) );

						}
F
Fernando Serrano 已提交
811

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

F
Fernando Serrano 已提交
814
				}
F
Fernando Serrano 已提交
815

816 817 818 819 820 821 822
				if ( children.length > 0 ) {

					gltfNode.children = children;

				}


F
Fernando Serrano 已提交
823 824 825 826 827
			}

			outputJSON.nodes.push( gltfNode );

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

F
Fernando Serrano 已提交
829 830 831
		}

		/**
F
Fernando Serrano 已提交
832
		 * Process Scene
F
Fernando Serrano 已提交
833 834 835
		 * @param  {THREE.Scene} node Scene to process
		 */
		function processScene( scene ) {
F
Fernando Serrano 已提交
836

837
			if ( !outputJSON.scenes ) {
F
Fernando Serrano 已提交
838

F
Fernando Serrano 已提交
839 840
				outputJSON.scenes = [];
				outputJSON.scene = 0;
F
Fernando Serrano 已提交
841

F
Fernando Serrano 已提交
842 843 844
			}

			var gltfScene = {
F
Fernando Serrano 已提交
845

F
Fernando Serrano 已提交
846
				nodes: []
F
Fernando Serrano 已提交
847

F
Fernando Serrano 已提交
848 849
			};

F
Fernando Serrano 已提交
850 851
			if ( scene.name ) {

F
Fernando Serrano 已提交
852
				gltfScene.name = scene.name;
F
Fernando Serrano 已提交
853

F
Fernando Serrano 已提交
854 855
			}

F
Fernando Serrano 已提交
856
			outputJSON.scenes.push( gltfScene );
F
Fernando Serrano 已提交
857

858 859
			var nodes = [];

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

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

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

866 867 868 869 870 871 872 873 874 875
					// @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) {

						nodes.push( processNode( child ) );

					}
876 877 878

				}

879
			}
880

881
			if ( nodes.length > 0 ) {
F
Fernando Serrano 已提交
882

883
				gltfScene.nodes = nodes;
F
Fernando Serrano 已提交
884

F
Fernando Serrano 已提交
885
			}
F
Fernando Serrano 已提交
886

F
Fernando Serrano 已提交
887 888
		}

889 890 891 892 893 894 895
		/**
		 * 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();
896
			scene.name = 'AuxScene';
897 898 899

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

900 901 902
				// 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 ] );
903 904 905 906 907 908 909

			}

			processScene( scene );

		}

910
		function processInput( input ) {
911

912
			input = input instanceof Array ? input : [ input ];
F
Fernando Serrano 已提交
913

914
			var objectsWithoutScene = [];
F
Fernando Serrano 已提交
915
			for ( i = 0; i < input.length; i++ ) {
F
Fernando Serrano 已提交
916

917
				if ( input[ i ] instanceof THREE.Scene ) {
918 919 920

					processScene( input[ i ] );

921
				} else {
922

923
					objectsWithoutScene.push( input[ i ] );
924

925
				}
F
Fernando Serrano 已提交
926

F
Fernando Serrano 已提交
927
			}
F
Fernando Serrano 已提交
928

929
			if ( objectsWithoutScene.length > 0 ) {
930

931
				processObjects( objectsWithoutScene );
932 933

			}
F
Fernando Serrano 已提交
934

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

937 938
		processInput( input );

F
Fernando Serrano 已提交
939
		// Generate buffer
F
Fernando Serrano 已提交
940
		// Create a new blob with all the dataviews from the buffers
941
		var blob = new Blob( dataViews, { type: 'application/octet-stream' } );
F
Fernando Serrano 已提交
942 943

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

946 947 948 949 950 951
			outputJSON.buffers[ 0 ].byteLength = blob.size;
			objectURL = URL.createObjectURL( blob );

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

953 954 955
				 base64data = reader.result;
				 outputJSON.buffers[ 0 ].uri = base64data;
				 onDone( outputJSON );
F
Fernando Serrano 已提交
956 957 958

			 };

959
		} else {
F
Fernando Serrano 已提交
960

961
			onDone ( outputJSON );
F
Fernando Serrano 已提交
962

963
		}
F
Fernando Serrano 已提交
964 965
	}
};