GLTFExporter.js 20.0 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 461
					index: processTexture( material.map ),
					texCoord: 0 // @FIXME
F
Fernando Serrano 已提交
462

463
				};
464

465
			}
466

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

			} else {

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

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

					gltfMaterial.emissiveFactor = emissive;

F
Fernando Serrano 已提交
480
				}
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499

				// emissiveTexture
				if ( material.emissiveMap ) {

					gltfMaterial.emissiveTexture = {

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

					};

				}

			}

			// normalTexture
			if ( material.normalMap ) {

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

501 502
					index: processTexture( material.normalMap ),
					texCoord: 0 // @FIXME
F
Fernando Serrano 已提交
503

504 505
				};

F
Fernando Serrano 已提交
506 507
			}

508 509 510 511
			// occlusionTexture
			if ( material.aoMap ) {

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

513 514
					index: processTexture( material.aoMap ),
					texCoord: 0 // @FIXME
F
Fernando Serrano 已提交
515

516 517 518 519 520 521 522 523 524 525 526 527
				};

			}

			// alphaMode
			if ( material.transparent ) {

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

			}

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

F
Fernando Serrano 已提交
530
				gltfMaterial.doubleSided = true;
531

F
Fernando Serrano 已提交
532 533
			}

F
Fernando Serrano 已提交
534
			if ( material.name ) {
535

F
Fernando Serrano 已提交
536
				gltfMaterial.name = material.name;
537

F
Fernando Serrano 已提交
538 539
			}

F
Fernando Serrano 已提交
540
			outputJSON.materials.push( gltfMaterial );
F
Fernando Serrano 已提交
541 542

			return outputJSON.materials.length - 1;
543

F
Fernando Serrano 已提交
544 545 546
		}

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

F
Fernando Serrano 已提交
553
			if ( !outputJSON.meshes ) {
F
Fernando Serrano 已提交
554 555 556

				outputJSON.meshes = [];

F
Fernando Serrano 已提交
557 558 559
			}

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

561 562 563
			// Use the correct mode
			if ( mesh instanceof THREE.LineSegments ) {

564
				mode = WEBGL_CONSTANTS.LINES;
565 566 567

			} else if ( mesh instanceof THREE.LineLoop ) {

568
				mode = WEBGL_CONSTANTS.LINE_LOOP;
569 570 571

			} else if ( mesh instanceof THREE.Line ) {

572
				mode = WEBGL_CONSTANTS.LINE_STRIP;
573 574 575

			} else if ( mesh instanceof THREE.Points ) {

576
				mode = WEBGL_CONSTANTS.POINTS;
577 578 579

			} else {

580
				if ( !geometry.isBufferGeometry ) {
581 582 583 584 585 586 587

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

				}

588 589
				if ( mesh.drawMode === THREE.TriangleFanDrawMode ) {

F
Fernando Serrano 已提交
590
					console.warn( 'GLTFExporter: TriangleFanDrawMode and wireframe incompatible.' );
591
					mode = WEBGL_CONSTANTS.TRIANGLE_FAN;
592 593 594

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

595
					mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINE_STRIP : WEBGL_CONSTANTS.TRIANGLE_STRIP;
596 597 598

				} else {

599
					mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINES : WEBGL_CONSTANTS.TRIANGLES;
600 601 602 603

				}

			}
F
Fernando Serrano 已提交
604 605 606 607 608 609 610 611 612 613

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

614
			var material = processMaterial( mesh.material );
615
			if ( material !== null ) {
616 617 618 619 620 621

				gltfMesh.primitives[ 0 ].material = material;

			}


622 623
			if ( geometry.index ) {

624
				gltfMesh.primitives[ 0 ].indices = processAccessor( geometry.index, geometry );
625 626 627

			}

F
Fernando Serrano 已提交
628 629
			// We've just one primitive per mesh
			var gltfAttributes = gltfMesh.primitives[ 0 ].attributes;
F
Fernando Serrano 已提交
630 631
			var attributes = geometry.attributes;

F
Fernando Serrano 已提交
632 633
			// Conversion between attributes names in threejs and gltf spec
			var nameConversion = {
F
Fernando Serrano 已提交
634

F
Fernando Serrano 已提交
635 636
				uv: 'TEXCOORD_0',
				uv2: 'TEXCOORD_1',
637 638 639
				color: 'COLOR_0',
				skinWeight: 'WEIGHTS_0',
				skinIndex: 'JOINTS_0'
F
Fernando Serrano 已提交
640

F
Fernando Serrano 已提交
641 642
			};

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

F
Fernando Serrano 已提交
647
				var attribute = geometry.attributes[ attributeName ];
F
Fernando Serrano 已提交
648
				attributeName = nameConversion[ attributeName ] || attributeName.toUpperCase();
649
				gltfAttributes[ attributeName ] = processAccessor( attribute, geometry );
F
Fernando Serrano 已提交
650

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

			outputJSON.meshes.push( gltfMesh );

			return outputJSON.meshes.length - 1;
		}

F
Fernando Serrano 已提交
658 659 660 661 662 663
		/**
		 * 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 已提交
664

F
Fernando Serrano 已提交
665
			if ( !outputJSON.cameras ) {
F
Fernando Serrano 已提交
666

F
Fernando Serrano 已提交
667
				outputJSON.cameras = [];
F
Fernando Serrano 已提交
668

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

			var isOrtho = camera instanceof THREE.OrthographicCamera;

			var gltfCamera = {
F
Fernando Serrano 已提交
674

F
Fernando Serrano 已提交
675
				type: isOrtho ? 'orthographic' : 'perspective'
F
Fernando Serrano 已提交
676

F
Fernando Serrano 已提交
677 678 679 680 681 682 683 684 685 686 687
			};

			if ( isOrtho ) {

				gltfCamera.orthographic = {

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

F
Fernando Serrano 已提交
688
				};
F
Fernando Serrano 已提交
689 690 691 692 693 694 695 696 697 698 699 700 701 702

			} else {

				gltfCamera.perspective = {

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

				};

			}

F
Fernando Serrano 已提交
703 704
			if ( camera.name ) {

F
Fernando Serrano 已提交
705
				gltfCamera.name = camera.type;
F
Fernando Serrano 已提交
706

F
Fernando Serrano 已提交
707 708 709 710 711 712 713
			}

			outputJSON.cameras.push( gltfCamera );

			return outputJSON.cameras.length - 1;
		}

F
Fernando Serrano 已提交
714 715 716 717 718 719 720
		/**
		 * 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 已提交
721
			if ( !outputJSON.nodes ) {
F
Fernando Serrano 已提交
722

F
Fernando Serrano 已提交
723
				outputJSON.nodes = [];
F
Fernando Serrano 已提交
724

F
Fernando Serrano 已提交
725 726
			}

F
Fernando Serrano 已提交
727 728 729
			var gltfNode = {};

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

F
Fernando Serrano 已提交
731 732 733 734
				var rotation = object.quaternion.toArray();
				var position = object.position.toArray();
				var scale = object.scale.toArray();

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

F
Fernando Serrano 已提交
737
					gltfNode.rotation = rotation;
F
Fernando Serrano 已提交
738

F
Fernando Serrano 已提交
739 740
				}

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

F
Fernando Serrano 已提交
743
					gltfNode.position = position;
F
Fernando Serrano 已提交
744

F
Fernando Serrano 已提交
745 746
				}

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

F
Fernando Serrano 已提交
749
					gltfNode.scale = scale;
F
Fernando Serrano 已提交
750

F
Fernando Serrano 已提交
751 752 753
				}

			} else {
F
Fernando Serrano 已提交
754

F
Fernando Serrano 已提交
755
				object.updateMatrix();
756
				if (! equalArray( object.matrix.elements, [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ] ) ) {
F
Fernando Serrano 已提交
757

F
Fernando Serrano 已提交
758
					gltfNode.matrix = object.matrix.elements;
F
Fernando Serrano 已提交
759

F
Fernando Serrano 已提交
760
				}
F
Fernando Serrano 已提交
761

F
Fernando Serrano 已提交
762 763 764 765
			}

			if ( object.name ) {

F
Fernando Serrano 已提交
766
				gltfNode.name = object.name;
F
Fernando Serrano 已提交
767

F
Fernando Serrano 已提交
768 769
			}

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

F
Fernando Serrano 已提交
788
				gltfNode.mesh = processMesh( object );
F
Fernando Serrano 已提交
789

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

F
Fernando Serrano 已提交
792
				gltfNode.camera = processCamera( object );
F
Fernando Serrano 已提交
793

F
Fernando Serrano 已提交
794 795 796
			}

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

798
				var children = [];
F
Fernando Serrano 已提交
799 800

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

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

804 805 806 807 808 809 810 811 812 813 814
					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 已提交
815

F
Fernando Serrano 已提交
816
					}
F
Fernando Serrano 已提交
817

F
Fernando Serrano 已提交
818
				}
F
Fernando Serrano 已提交
819

820 821 822 823 824 825 826
				if ( children.length > 0 ) {

					gltfNode.children = children;

				}


F
Fernando Serrano 已提交
827 828 829 830 831
			}

			outputJSON.nodes.push( gltfNode );

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

F
Fernando Serrano 已提交
833 834 835
		}

		/**
F
Fernando Serrano 已提交
836
		 * Process Scene
F
Fernando Serrano 已提交
837 838 839
		 * @param  {THREE.Scene} node Scene to process
		 */
		function processScene( scene ) {
F
Fernando Serrano 已提交
840

841
			if ( !outputJSON.scenes ) {
F
Fernando Serrano 已提交
842

F
Fernando Serrano 已提交
843 844
				outputJSON.scenes = [];
				outputJSON.scene = 0;
F
Fernando Serrano 已提交
845

F
Fernando Serrano 已提交
846 847 848
			}

			var gltfScene = {
F
Fernando Serrano 已提交
849

F
Fernando Serrano 已提交
850
				nodes: []
F
Fernando Serrano 已提交
851

F
Fernando Serrano 已提交
852 853
			};

F
Fernando Serrano 已提交
854 855
			if ( scene.name ) {

F
Fernando Serrano 已提交
856
				gltfScene.name = scene.name;
F
Fernando Serrano 已提交
857

F
Fernando Serrano 已提交
858 859
			}

F
Fernando Serrano 已提交
860
			outputJSON.scenes.push( gltfScene );
F
Fernando Serrano 已提交
861

862 863
			var nodes = [];

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

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

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

870 871 872 873 874 875 876 877 878 879
					// @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 ) );

					}
880 881 882

				}

883
			}
884

885
			if ( nodes.length > 0 ) {
F
Fernando Serrano 已提交
886

887
				gltfScene.nodes = nodes;
F
Fernando Serrano 已提交
888

F
Fernando Serrano 已提交
889
			}
F
Fernando Serrano 已提交
890

F
Fernando Serrano 已提交
891 892
		}

893 894 895 896 897 898 899
		/**
		 * 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();
900
			scene.name = 'AuxScene';
901 902 903

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

904 905 906
				// 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 ] );
907 908 909 910 911 912 913

			}

			processScene( scene );

		}

914
		function processInput( input ) {
915

916
			input = input instanceof Array ? input : [ input ];
F
Fernando Serrano 已提交
917

918
			var objectsWithoutScene = [];
F
Fernando Serrano 已提交
919
			for ( i = 0; i < input.length; i++ ) {
F
Fernando Serrano 已提交
920

921
				if ( input[ i ] instanceof THREE.Scene ) {
922 923 924

					processScene( input[ i ] );

925
				} else {
926

927
					objectsWithoutScene.push( input[ i ] );
928

929
				}
F
Fernando Serrano 已提交
930

F
Fernando Serrano 已提交
931
			}
F
Fernando Serrano 已提交
932

933
			if ( objectsWithoutScene.length > 0 ) {
934

935
				processObjects( objectsWithoutScene );
936 937

			}
F
Fernando Serrano 已提交
938

F
Fernando Serrano 已提交
939
		}
F
Fernando Serrano 已提交
940

941 942
		processInput( input );

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

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

950 951 952 953 954 955
			outputJSON.buffers[ 0 ].byteLength = blob.size;
			objectURL = URL.createObjectURL( blob );

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

957 958 959
				 base64data = reader.result;
				 outputJSON.buffers[ 0 ].uri = base64data;
				 onDone( outputJSON );
F
Fernando Serrano 已提交
960 961 962

			 };

963
		} else {
F
Fernando Serrano 已提交
964

965
			onDone ( outputJSON );
F
Fernando Serrano 已提交
966

967
		}
F
Fernando Serrano 已提交
968 969
	}
};