GLTFExporter.js 42.9 KB
Newer Older
F
Fernando Serrano 已提交
1 2
/**
 * @author fernandojsg / http://fernandojsg.com
3 4
 * @author Don McCurdy / https://www.donmccurdy.com
 * @author Takahiro / https://github.com/takahirox
F
Fernando Serrano 已提交
5 6
 */

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

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

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

33 34 35
	CLAMP_TO_EDGE: 33071,
	MIRRORED_REPEAT: 33648,
	REPEAT: 10497
M
Mugen87 已提交
36
};
37

38 39 40 41 42 43 44 45 46 47 48 49 50
var THREE_TO_WEBGL = {};

THREE_TO_WEBGL[ THREE.NearestFilter ] = WEBGL_CONSTANTS.NEAREST;
THREE_TO_WEBGL[ THREE.NearestMipMapNearestFilter ] = WEBGL_CONSTANTS.NEAREST_MIPMAP_NEAREST;
THREE_TO_WEBGL[ THREE.NearestMipMapLinearFilter ] = WEBGL_CONSTANTS.NEAREST_MIPMAP_LINEAR;
THREE_TO_WEBGL[ THREE.LinearFilter ] = WEBGL_CONSTANTS.LINEAR;
THREE_TO_WEBGL[ THREE.LinearMipMapNearestFilter ] = WEBGL_CONSTANTS.LINEAR_MIPMAP_NEAREST;
THREE_TO_WEBGL[ THREE.LinearMipMapLinearFilter ] = WEBGL_CONSTANTS.LINEAR_MIPMAP_LINEAR;

THREE_TO_WEBGL[ THREE.ClampToEdgeWrapping ] = WEBGL_CONSTANTS.CLAMP_TO_EDGE;
THREE_TO_WEBGL[ THREE.RepeatWrapping ] = WEBGL_CONSTANTS.REPEAT;
THREE_TO_WEBGL[ THREE.MirroredRepeatWrapping ] = WEBGL_CONSTANTS.MIRRORED_REPEAT;

51 52 53 54 55 56 57
var PATH_PROPERTIES = {
	scale: 'scale',
	position: 'translation',
	quaternion: 'rotation',
	morphTargetInfluences: 'weights'
};

F
Fernando Serrano 已提交
58 59 60
//------------------------------------------------------------------------------
// GLTF Exporter
//------------------------------------------------------------------------------
61
THREE.GLTFExporter = function () {};
F
Fernando Serrano 已提交
62 63 64 65

THREE.GLTFExporter.prototype = {

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

F
Fernando Serrano 已提交
67 68 69
	/**
	 * Parse scenes and generate GLTF output
	 * @param  {THREE.Scene or [THREE.Scenes]} input   THREE.Scene or Array of THREE.Scenes
F
Fernando Serrano 已提交
70 71
	 * @param  {Function} onDone  Callback on completed
	 * @param  {Object} options options
F
Fernando Serrano 已提交
72
	 */
F
Fernando Serrano 已提交
73 74
	parse: function ( input, onDone, options ) {

75
		var DEFAULT_OPTIONS = {
76
			binary: false,
77
			trs: false,
78
			onlyVisible: true,
79
			truncateDrawRange: true,
80
			embedImages: true,
81
			animations: [],
82
			forceIndices: false,
83
			forcePowerOfTwoTextures: false
84 85 86 87
		};

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

D
Don McCurdy 已提交
88 89 90 91 92 93 94
		if ( options.animations.length > 0 ) {

			// Only TRS properties, and not matrices, may be targeted by animation.
			options.trs = true;

		}

F
Fernando Serrano 已提交
95
		var outputJSON = {
F
Fernando Serrano 已提交
96

F
Fernando Serrano 已提交
97
			asset: {
F
Fernando Serrano 已提交
98

F
Fernando Serrano 已提交
99
				version: "2.0",
M
Mr.doob 已提交
100
				generator: "THREE.GLTFExporter"
F
Fernando Serrano 已提交
101

M
Mr.doob 已提交
102
			}
F
Fernando Serrano 已提交
103

M
Mr.doob 已提交
104
		};
F
Fernando Serrano 已提交
105 106

		var byteOffset = 0;
107 108
		var buffers = [];
		var pending = [];
T
Takahiro 已提交
109
		var nodeMap = new Map();
D
Don McCurdy 已提交
110
		var skins = [];
111
		var extensionsUsed = {};
112 113
		var cachedData = {

114
			meshes: new Map(),
115
			attributes: new Map(),
116
			attributesNormalized: new Map(),
117
			materials: new Map(),
118 119
			textures: new Map(),
			images: new Map()
120 121

		};
F
Fernando Serrano 已提交
122

123 124
		var cachedCanvas;

F
Fernando Serrano 已提交
125 126 127
		/**
		 * Compare two arrays
		 */
F
Fernando Serrano 已提交
128 129 130 131 132 133
		/**
		 * 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
		 */
M
Mr.doob 已提交
134
		function equalArray( array1, array2 ) {
F
Fernando Serrano 已提交
135

M
Mugen87 已提交
136
			return ( array1.length === array2.length ) && array1.every( function ( element, index ) {
F
Fernando Serrano 已提交
137

M
Mr.doob 已提交
138
				return element === array2[ index ];
F
Fernando Serrano 已提交
139

M
Mugen87 已提交
140
			} );
F
Fernando Serrano 已提交
141

F
Fernando Serrano 已提交
142 143
		}

144 145 146 147 148
		/**
		 * Converts a string to an ArrayBuffer.
		 * @param  {string} text
		 * @return {ArrayBuffer}
		 */
149
		function stringToArrayBuffer( text ) {
150 151 152 153 154 155 156

			if ( window.TextEncoder !== undefined ) {

				return new TextEncoder().encode( text ).buffer;

			}

157
			var array = new Uint8Array( new ArrayBuffer( text.length ) );
158

159
			for ( var i = 0, il = text.length; i < il; i ++ ) {
160

161
				var value = text.charCodeAt( i );
162

163
				// Replacing multi-byte character with space(0x20).
F
Fernando Serrano 已提交
164
				array[ i ] = value > 0xFF ? 0x20 : value;
165 166 167

			}

168
			return array.buffer;
169 170 171

		}

F
Fernando Serrano 已提交
172
		/**
173
		 * Get the min and max vectors from the given attribute
T
Takahiro 已提交
174 175 176
		 * @param  {THREE.BufferAttribute} attribute Attribute to find the min/max in range from start to start + count
		 * @param  {Integer} start
		 * @param  {Integer} count
F
Fernando Serrano 已提交
177 178
		 * @return {Object} Object containing the `min` and `max` values (As an array of attribute.itemSize components)
		 */
T
Takahiro 已提交
179
		function getMinMax( attribute, start, count ) {
F
Fernando Serrano 已提交
180

F
Fernando Serrano 已提交
181
			var output = {
F
Fernando Serrano 已提交
182

F
Fernando Serrano 已提交
183 184
				min: new Array( attribute.itemSize ).fill( Number.POSITIVE_INFINITY ),
				max: new Array( attribute.itemSize ).fill( Number.NEGATIVE_INFINITY )
F
Fernando Serrano 已提交
185

F
Fernando Serrano 已提交
186 187
			};

T
Takahiro 已提交
188
			for ( var i = start; i < start + count; i ++ ) {
F
Fernando Serrano 已提交
189

M
Mugen87 已提交
190
				for ( var a = 0; a < attribute.itemSize; a ++ ) {
F
Fernando Serrano 已提交
191

F
Fernando Serrano 已提交
192
					var value = attribute.array[ i * attribute.itemSize + a ];
F
Fernando Serrano 已提交
193 194 195
					output.min[ a ] = Math.min( output.min[ a ], value );
					output.max[ a ] = Math.max( output.max[ a ], value );

F
Fernando Serrano 已提交
196
				}
F
Fernando Serrano 已提交
197

F
Fernando Serrano 已提交
198 199
			}

F
Fernando Serrano 已提交
200
			return output;
M
Mugen87 已提交
201

F
Fernando Serrano 已提交
202 203
		}

204 205 206 207 208 209 210 211 212 213 214 215 216
		/**
		 * Checks if image size is POT.
		 *
		 * @param {Image} image The image to be checked.
		 * @returns {Boolean} Returns true if image size is POT.
		 *
		 */
		function isPowerOfTwo( image ) {

			return THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height );

		}

217 218 219 220 221 222 223 224 225
		/**
		 * Checks if normal attribute values are normalized.
		 *
		 * @param {THREE.BufferAttribute} normal
		 * @returns {Boolean}
		 *
		 */
		function isNormalizedNormalAttribute( normal ) {

226
			if ( cachedData.attributesNormalized.has( normal ) ) {
227 228 229 230 231

				return false;

			}

T
Takahiro 已提交
232
			var v = new THREE.Vector3();
233

T
Takahiro 已提交
234
			for ( var i = 0, il = normal.count; i < il; i ++ ) {
235 236

				// 0.0005 is from glTF-validator
T
Takahiro 已提交
237
				if ( Math.abs( v.fromArray( normal.array, i * 3 ).length() - 1.0 ) > 0.0005 ) return false;
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253

			}

			return true;

		}

		/**
		 * Creates normalized normal buffer attribute.
		 *
		 * @param {THREE.BufferAttribute} normal
		 * @returns {THREE.BufferAttribute}
		 *
		 */
		function createNormalizedNormalAttribute( normal ) {

254
			if ( cachedData.attributesNormalized.has( normal ) ) {
255

256
				return cachedData.attributesNormalized.get( normal );
257 258 259 260 261 262 263

			}

			var attribute = normal.clone();

			var v = new THREE.Vector3();

T
Takahiro 已提交
264
			for ( var i = 0, il = attribute.count; i < il; i ++ ) {
265

T
Takahiro 已提交
266
				v.fromArray( attribute.array, i * 3 );
267 268 269 270 271 272 273 274 275 276 277 278

				if ( v.x === 0 && v.y === 0 && v.z === 0 ) {

					// if values can't be normalized set (1, 0, 0)
					v.setX( 1.0 );

				} else {

					v.normalize();

				}

T
Takahiro 已提交
279
				v.toArray( attribute.array, i * 3 );
280 281 282

			}

283
			cachedData.attributesNormalized.set( normal, attribute );
284 285 286 287 288

			return attribute;

		}

289 290 291 292 293 294 295 296 297 298
		/**
		 * Get the required size + padding for a buffer, rounded to the next 4-byte boundary.
		 * https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#data-alignment
		 *
		 * @param {Integer} bufferSize The size the original buffer.
		 * @returns {Integer} new buffer size with required padding.
		 *
		 */
		function getPaddedBufferSize( bufferSize ) {

299
			return Math.ceil( bufferSize / 4 ) * 4;
300 301

		}
M
Mugen87 已提交
302

F
Fernando Serrano 已提交
303
		/**
304 305
		 * Returns a buffer aligned to 4-byte boundary.
		 *
F
Fernando Serrano 已提交
306
		 * @param {ArrayBuffer} arrayBuffer Buffer to pad
307
		 * @param {Integer} paddingByte (Optional)
F
Fernando Serrano 已提交
308 309
		 * @returns {ArrayBuffer} The same buffer if it's already aligned to 4-byte boundary or a new buffer
		 */
310
		function getPaddedArrayBuffer( arrayBuffer, paddingByte ) {
311

312
			paddingByte = paddingByte || 0;
313

F
Fernando Serrano 已提交
314
			var paddedLength = getPaddedBufferSize( arrayBuffer.byteLength );
315

316
			if ( paddedLength !== arrayBuffer.byteLength ) {
317

318 319
				var array = new Uint8Array( paddedLength );
				array.set( new Uint8Array( arrayBuffer ) );
320

321
				if ( paddingByte !== 0 ) {
322

T
Takahiro 已提交
323
					for ( var i = arrayBuffer.byteLength; i < paddedLength; i ++ ) {
324

325
						array[ i ] = paddingByte;
326 327 328 329

					}

				}
330

331
				return array.buffer;
F
Fernando Serrano 已提交
332 333 334 335 336 337 338

			}

			return arrayBuffer;

		}

339 340 341
		/**
		 * Serializes a userData.
		 *
342
		 * @param {THREE.Object3D|THREE.Material} object
343 344
		 * @returns {Object}
		 */
345
		function serializeUserData( object ) {
346 347 348

			try {

349
				return JSON.parse( JSON.stringify( object.userData ) );
350

351
			} catch ( error ) {
352

353 354
				console.warn( 'THREE.GLTFExporter: userData of \'' + object.name + '\' ' +
					'won\'t be serialized because of JSON.stringify error - ' + error.message );
355

356 357
				return {};

358 359 360 361
			}

		}

362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
		/**
		 * Applies a texture transform, if present, to the map definition. Requires
		 * the KHR_texture_transform extension.
		 */
		function applyTextureTransform( mapDef, texture ) {

			var didTransform = false
			var transformDef = {};

			if ( texture.offset.x !== 0 || texture.offset.y !== 0 ) {

				transformDef.offset = texture.offset.toArray();
				didTransform = true;

			}

			if ( texture.rotation !== 0 ) {

				transformDef.rotation = texture.rotation;
				didTransform = true;

			}

			if ( texture.repeat.x !== 1 || texture.repeat.y !== 1 ) {

				transformDef.scale = texture.repeat.toArray();
				didTransform = true;				

			}

			if ( didTransform ) {

				mapDef.extensions = mapDef.extensions || {};
				mapDef.extensions[ 'KHR_texture_transform' ] = transformDef;
				extensionsUsed[ 'KHR_texture_transform' ] = true;

			}

		}

F
Fernando Serrano 已提交
402
		/**
F
Fernando Serrano 已提交
403
		 * Process a buffer to append to the default one.
404 405
		 * @param  {ArrayBuffer} buffer
		 * @return {Integer}
F
Fernando Serrano 已提交
406
		 */
407
		function processBuffer( buffer ) {
F
Fernando Serrano 已提交
408

M
Mugen87 已提交
409
			if ( ! outputJSON.buffers ) {
F
Fernando Serrano 已提交
410

411
				outputJSON.buffers = [ { byteLength: 0 } ];
F
Fernando Serrano 已提交
412

413
			}
F
Fernando Serrano 已提交
414

415 416
			// All buffers are merged before export.
			buffers.push( buffer );
F
Fernando Serrano 已提交
417

418
			return 0;
F
Fernando Serrano 已提交
419

420
		}
F
Fernando Serrano 已提交
421

422 423 424 425 426 427 428 429 430 431
		/**
		 * Process and generate a BufferView
		 * @param  {THREE.BufferAttribute} attribute
		 * @param  {number} componentType
		 * @param  {number} start
		 * @param  {number} count
		 * @param  {number} target (Optional) Target usage of the BufferView
		 * @return {Object}
		 */
		function processBufferView( attribute, componentType, start, count, target ) {
F
Fernando Serrano 已提交
432

433
			if ( ! outputJSON.bufferViews ) {
434

435
				outputJSON.bufferViews = [];
M
Mugen87 已提交
436

437
			}
F
Fernando Serrano 已提交
438

439
			// Create a new dataview and dump the attribute's array into it
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456

			var componentSize;

			if ( componentType === WEBGL_CONSTANTS.UNSIGNED_BYTE ) {

				componentSize = 1;

			} else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ) {

				componentSize = 2;

			} else {

				componentSize = 4;

			}

457
			var byteLength = getPaddedBufferSize( count * attribute.itemSize * componentSize );
458
			var dataView = new DataView( new ArrayBuffer( byteLength ) );
459
			var offset = 0;
F
Fernando Serrano 已提交
460

M
Mugen87 已提交
461
			for ( var i = start; i < start + count; i ++ ) {
F
Fernando Serrano 已提交
462

M
Mugen87 已提交
463
				for ( var a = 0; a < attribute.itemSize; a ++ ) {
F
Fernando Serrano 已提交
464

465 466
					// @TODO Fails on InterleavedBufferAttribute, and could probably be
					// optimized for normal BufferAttribute.
F
Fernando Serrano 已提交
467
					var value = attribute.array[ i * attribute.itemSize + a ];
F
Fernando Serrano 已提交
468

469
					if ( componentType === WEBGL_CONSTANTS.FLOAT ) {
F
Fernando Serrano 已提交
470

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

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

S
selimbek 已提交
475
						dataView.setUint32( offset, value, true );
F
Fernando Serrano 已提交
476

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

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

481 482 483 484
					} else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_BYTE ) {

						dataView.setUint8( offset, value );

F
Fernando Serrano 已提交
485
					}
F
Fernando Serrano 已提交
486

487
					offset += componentSize;
F
Fernando Serrano 已提交
488

F
Fernando Serrano 已提交
489
				}
F
Fernando Serrano 已提交
490

F
Fernando Serrano 已提交
491 492 493
			}

			var gltfBufferView = {
F
Fernando Serrano 已提交
494

495
				buffer: processBuffer( dataView.buffer ),
F
Fernando Serrano 已提交
496
				byteOffset: byteOffset,
497
				byteLength: byteLength
F
Fernando Serrano 已提交
498

F
Fernando Serrano 已提交
499 500
			};

501 502
			if ( target !== undefined ) gltfBufferView.target = target;

503 504 505
			if ( target === WEBGL_CONSTANTS.ARRAY_BUFFER ) {

				// Only define byteStride for vertex attributes.
506
				gltfBufferView.byteStride = attribute.itemSize * componentSize;
507 508 509

			}

510
			byteOffset += byteLength;
F
Fernando Serrano 已提交
511

F
Fernando Serrano 已提交
512
			outputJSON.bufferViews.push( gltfBufferView );
F
Fernando Serrano 已提交
513

514
			// @TODO Merge bufferViews where possible.
F
Fernando Serrano 已提交
515
			var output = {
F
Fernando Serrano 已提交
516

F
Fernando Serrano 已提交
517 518
				id: outputJSON.bufferViews.length - 1,
				byteLength: 0
F
Fernando Serrano 已提交
519

F
Fernando Serrano 已提交
520
			};
F
Fernando Serrano 已提交
521

F
Fernando Serrano 已提交
522
			return output;
F
Fernando Serrano 已提交
523

F
Fernando Serrano 已提交
524 525
		}

526 527 528 529 530
		/**
		 * Process and generate a BufferView from an image Blob.
		 * @param {Blob} blob
		 * @return {Promise<Integer>}
		 */
D
Don McCurdy 已提交
531
		function processBufferViewImage( blob ) {
532 533 534 535 536 537 538

			if ( ! outputJSON.bufferViews ) {

				outputJSON.bufferViews = [];

			}

D
Don McCurdy 已提交
539
			return new Promise( function ( resolve ) {
540 541 542

				var reader = new window.FileReader();
				reader.readAsArrayBuffer( blob );
D
Don McCurdy 已提交
543
				reader.onloadend = function () {
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558

					var buffer = getPaddedArrayBuffer( reader.result );

					var bufferView = {
						buffer: processBuffer( buffer ),
						byteOffset: byteOffset,
						byteLength: buffer.byteLength
					};

					byteOffset += buffer.byteLength;

					outputJSON.bufferViews.push( bufferView );

					resolve( outputJSON.bufferViews.length - 1 );

D
Don McCurdy 已提交
559
				};
560 561 562 563 564

			} );

		}

F
Fernando Serrano 已提交
565
		/**
F
Fernando Serrano 已提交
566
		 * Process attribute to generate an accessor
567 568
		 * @param  {THREE.BufferAttribute} attribute Attribute to process
		 * @param  {THREE.BufferGeometry} geometry (Optional) Geometry used for truncated draw range
T
Takahiro 已提交
569 570
		 * @param  {Integer} start (Optional)
		 * @param  {Integer} count (Optional)
F
Fernando Serrano 已提交
571
		 * @return {Integer}           Index of the processed accessor on the "accessors" array
F
Fernando Serrano 已提交
572
		 */
T
Takahiro 已提交
573
		function processAccessor( attribute, geometry, start, count ) {
F
Fernando Serrano 已提交
574

D
Don McCurdy 已提交
575
			var types = {
F
Fernando Serrano 已提交
576

D
Don McCurdy 已提交
577 578 579 580 581
				1: 'SCALAR',
				2: 'VEC2',
				3: 'VEC3',
				4: 'VEC4',
				16: 'MAT4'
F
Fernando Serrano 已提交
582

D
Don McCurdy 已提交
583
			};
F
Fernando Serrano 已提交
584

585 586
			var componentType;

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

590
				componentType = WEBGL_CONSTANTS.FLOAT;
F
Fernando Serrano 已提交
591

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

594
				componentType = WEBGL_CONSTANTS.UNSIGNED_INT;
F
Fernando Serrano 已提交
595

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

598
				componentType = WEBGL_CONSTANTS.UNSIGNED_SHORT;
F
Fernando Serrano 已提交
599

600 601 602 603
			} else if ( attribute.array.constructor === Uint8Array ) {

				componentType = WEBGL_CONSTANTS.UNSIGNED_BYTE;

604
			} else {
F
Fernando Serrano 已提交
605

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

608
			}
F
Fernando Serrano 已提交
609

T
Takahiro 已提交
610 611
			if ( start === undefined ) start = 0;
			if ( count === undefined ) count = attribute.count;
612 613

			// @TODO Indexed buffer geometry with drawRange not supported yet
614
			if ( options.truncateDrawRange && geometry !== undefined && geometry.index === null ) {
M
Mugen87 已提交
615

T
Takahiro 已提交
616 617
				var end = start + count;
				var end2 = geometry.drawRange.count === Infinity
M
Mugen87 已提交
618 619
					? attribute.count
					: geometry.drawRange.start + geometry.drawRange.count;
T
Takahiro 已提交
620 621 622 623 624

				start = Math.max( start, geometry.drawRange.start );
				count = Math.min( end, end2 ) - start;

				if ( count < 0 ) count = 0;
M
Mugen87 已提交
625

626 627
			}

628
			// Skip creating an accessor if the attribute doesn't have data to export
F
Fernando Serrano 已提交
629
			if ( count === 0 ) {
630

631
				return null;
632 633 634

			}

T
Takahiro 已提交
635 636
			var minMax = getMinMax( attribute, start, count );

637 638 639 640 641 642
			var bufferViewTarget;

			// If geometry isn't provided, don't infer the target usage of the bufferView. For
			// animation samplers, target must not be set.
			if ( geometry !== undefined ) {

T
Takahiro 已提交
643
				bufferViewTarget = attribute === geometry.index ? WEBGL_CONSTANTS.ELEMENT_ARRAY_BUFFER : WEBGL_CONSTANTS.ARRAY_BUFFER;
644 645 646 647

			}

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

F
Fernando Serrano 已提交
649
			var gltfAccessor = {
F
Fernando Serrano 已提交
650

F
Fernando Serrano 已提交
651 652 653
				bufferView: bufferView.id,
				byteOffset: bufferView.byteOffset,
				componentType: componentType,
654
				count: count,
F
Fernando Serrano 已提交
655 656
				max: minMax.max,
				min: minMax.min,
D
Don McCurdy 已提交
657
				type: types[ attribute.itemSize ]
F
Fernando Serrano 已提交
658

F
Fernando Serrano 已提交
659 660
			};

661 662 663 664 665 666
			if ( ! outputJSON.accessors ) {

				outputJSON.accessors = [];

			}

F
Fernando Serrano 已提交
667 668 669
			outputJSON.accessors.push( gltfAccessor );

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

F
Fernando Serrano 已提交
671 672 673
		}

		/**
F
Fernando Serrano 已提交
674
		 * Process image
675
		 * @param  {Image} image to process
676
		 * @param  {Integer} format of the image (e.g. THREE.RGBFormat, THREE.RGBAFormat etc)
677
		 * @param  {Boolean} flipY before writing out the image
F
Fernando Serrano 已提交
678 679
		 * @return {Integer}     Index of the processed texture in the "images" array
		 */
680
		function processImage( image, format, flipY ) {
F
Fernando Serrano 已提交
681

682
			if ( ! cachedData.images.has( image ) ) {
683

684 685 686 687 688
				cachedData.images.set( image, {} );

			}

			var cachedImages = cachedData.images.get( image );
689 690
			var mimeType = format === THREE.RGBAFormat ? 'image/png' : 'image/jpeg';
			var key = mimeType + ":flipY/" + flipY.toString();
F
Fernando Serrano 已提交
691

692 693 694
			if ( cachedImages[ key ] !== undefined ) {

				return cachedImages[ key ];
695 696

			}
697

M
Mugen87 已提交
698
			if ( ! outputJSON.images ) {
F
Fernando Serrano 已提交
699

F
Fernando Serrano 已提交
700
				outputJSON.images = [];
F
Fernando Serrano 已提交
701

F
Fernando Serrano 已提交
702 703
			}

M
Mugen87 已提交
704
			var gltfImage = { mimeType: mimeType };
705

706
			if ( options.embedImages ) {
F
Fernando Serrano 已提交
707

708
				var canvas = cachedCanvas = cachedCanvas || document.createElement( 'canvas' );
709

710 711
				canvas.width = image.width;
				canvas.height = image.height;
712

713
				if ( options.forcePowerOfTwoTextures && ! isPowerOfTwo( image ) ) {
714

715
					console.warn( 'GLTFExporter: Resized non-power-of-two image.', image );
716 717 718 719 720 721

					canvas.width = THREE.Math.floorPowerOfTwo( canvas.width );
					canvas.height = THREE.Math.floorPowerOfTwo( canvas.height );

				}

722
				var ctx = canvas.getContext( '2d' );
723

724
				if ( flipY === true ) {
725

726
					ctx.translate( 0, canvas.height );
M
Mugen87 已提交
727
					ctx.scale( 1, - 1 );
728 729 730

				}

731
				ctx.drawImage( image, 0, 0, canvas.width, canvas.height );
732

733 734 735 736 737 738 739 740 741 742 743
				if ( options.binary === true ) {

					pending.push( new Promise( function ( resolve ) {

						canvas.toBlob( function ( blob ) {

							processBufferViewImage( blob ).then( function ( bufferViewIndex ) {

								gltfImage.bufferView = bufferViewIndex;

								resolve();
744

745 746 747 748 749 750 751 752 753 754 755
							} );

						}, mimeType );

					} ) );

				} else {

					gltfImage.uri = canvas.toDataURL( mimeType );

				}
F
Fernando Serrano 已提交
756

F
Fernando Serrano 已提交
757
			} else {
F
Fernando Serrano 已提交
758

759
				gltfImage.uri = image.src;
F
Fernando Serrano 已提交
760

F
Fernando Serrano 已提交
761 762 763 764
			}

			outputJSON.images.push( gltfImage );

765
			var index = outputJSON.images.length - 1;
766
			cachedImages[ key ] = index;
F
Fernando Serrano 已提交
767

768
			return index;
F
Fernando Serrano 已提交
769

F
Fernando Serrano 已提交
770 771 772 773 774 775 776
		}

		/**
		 * Process sampler
		 * @param  {Texture} map Texture to process
		 * @return {Integer}     Index of the processed texture in the "samplers" array
		 */
M
Mr.doob 已提交
777
		function processSampler( map ) {
F
Fernando Serrano 已提交
778

M
Mugen87 已提交
779
			if ( ! outputJSON.samplers ) {
F
Fernando Serrano 已提交
780

F
Fernando Serrano 已提交
781
				outputJSON.samplers = [];
F
Fernando Serrano 已提交
782

F
Fernando Serrano 已提交
783 784 785
			}

			var gltfSampler = {
F
Fernando Serrano 已提交
786

787 788 789 790
				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 已提交
791

F
Fernando Serrano 已提交
792 793 794 795 796
			};

			outputJSON.samplers.push( gltfSampler );

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

F
Fernando Serrano 已提交
798 799 800 801 802 803 804
		}

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

T
Takahiro 已提交
807
			if ( cachedData.textures.has( map ) ) {
T
Takahiro 已提交
808

T
Takahiro 已提交
809
				return cachedData.textures.get( map );
T
Takahiro 已提交
810 811 812

			}

M
Mugen87 已提交
813
			if ( ! outputJSON.textures ) {
F
Fernando Serrano 已提交
814

F
Fernando Serrano 已提交
815
				outputJSON.textures = [];
F
Fernando Serrano 已提交
816

F
Fernando Serrano 已提交
817 818 819
			}

			var gltfTexture = {
F
Fernando Serrano 已提交
820

F
Fernando Serrano 已提交
821
				sampler: processSampler( map ),
M
Mugen87 已提交
822
				source: processImage( map.image, map.format, map.flipY )
F
Fernando Serrano 已提交
823

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

			outputJSON.textures.push( gltfTexture );

T
Takahiro 已提交
828
			var index = outputJSON.textures.length - 1;
T
Takahiro 已提交
829
			cachedData.textures.set( map, index );
T
Takahiro 已提交
830 831

			return index;
F
Fernando Serrano 已提交
832

F
Fernando Serrano 已提交
833 834 835 836 837 838
		}

		/**
		 * Process material
		 * @param  {THREE.Material} material Material to process
		 * @return {Integer}      Index of the processed material in the "materials" array
F
Fernando Serrano 已提交
839
		 */
M
Mr.doob 已提交
840
		function processMaterial( material ) {
F
Fernando Serrano 已提交
841

T
Takahiro 已提交
842
			if ( cachedData.materials.has( material ) ) {
843

T
Takahiro 已提交
844
				return cachedData.materials.get( material );
845 846 847

			}

M
Mugen87 已提交
848
			if ( ! outputJSON.materials ) {
F
Fernando Serrano 已提交
849

F
Fernando Serrano 已提交
850
				outputJSON.materials = [];
F
Fernando Serrano 已提交
851

F
Fernando Serrano 已提交
852
			}
F
Fernando Serrano 已提交
853

854
			if ( material.isShaderMaterial ) {
855 856 857 858 859 860

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

			}

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

864
				pbrMetallicRoughness: {}
F
Fernando Serrano 已提交
865

866
			};
867

868
			if ( material.isMeshBasicMaterial ) {
869 870 871 872 873

				gltfMaterial.extensions = { KHR_materials_unlit: {} };

				extensionsUsed[ 'KHR_materials_unlit' ] = true;

874
			} else if ( ! material.isMeshStandardMaterial ) {
875 876 877 878 879

				console.warn( 'GLTFExporter: Use MeshStandardMaterial or MeshBasicMaterial for best results.' );

			}

880 881
			// pbrMetallicRoughness.baseColorFactor
			var color = material.color.toArray().concat( [ material.opacity ] );
F
Fernando Serrano 已提交
882

M
Mugen87 已提交
883
			if ( ! equalArray( color, [ 1, 1, 1, 1 ] ) ) {
884

885
				gltfMaterial.pbrMetallicRoughness.baseColorFactor = color;
886 887 888

			}

889
			if ( material.isMeshStandardMaterial ) {
890

891 892
				gltfMaterial.pbrMetallicRoughness.metallicFactor = material.metalness;
				gltfMaterial.pbrMetallicRoughness.roughnessFactor = material.roughness;
893

894
			} else if ( material.isMeshBasicMaterial ) {
895 896 897 898

				gltfMaterial.pbrMetallicRoughness.metallicFactor = 0.0;
				gltfMaterial.pbrMetallicRoughness.roughnessFactor = 0.9;

M
Mr.doob 已提交
899
			} else {
900

M
Mugen87 已提交
901 902
				gltfMaterial.pbrMetallicRoughness.metallicFactor = 0.5;
				gltfMaterial.pbrMetallicRoughness.roughnessFactor = 0.5;
F
Fernando Serrano 已提交
903

904
			}
905

906 907 908 909 910
			// pbrMetallicRoughness.metallicRoughnessTexture
			if ( material.metalnessMap || material.roughnessMap ) {

				if ( material.metalnessMap === material.roughnessMap ) {

911 912 913
					var metalRoughMapDef = { index: processTexture( material.metalnessMap ) };
					applyTextureTransform( metalRoughMapDef, material.metalnessMap );
					gltfMaterial.pbrMetallicRoughness.metallicRoughnessTexture = metalRoughMapDef;
914 915 916 917 918 919 920 921 922

				} else {

					console.warn( 'THREE.GLTFExporter: Ignoring metalnessMap and roughnessMap because they are not the same Texture.' );

				}

			}

923 924
			// pbrMetallicRoughness.baseColorTexture
			if ( material.map ) {
925

926 927 928
				var baseColorMapDef = { index: processTexture( material.map ) };
				applyTextureTransform( baseColorMapDef, material.map );
				gltfMaterial.pbrMetallicRoughness.baseColorTexture = baseColorMapDef;
929

930
			}
931

932 933 934
			if ( material.isMeshBasicMaterial ||
				material.isLineBasicMaterial ||
				material.isPointsMaterial ) {
935 936 937 938

			} else {

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

M
Mugen87 已提交
941
				if ( ! equalArray( emissive, [ 0, 0, 0 ] ) ) {
942 943 944

					gltfMaterial.emissiveFactor = emissive;

F
Fernando Serrano 已提交
945
				}
946 947 948 949

				// emissiveTexture
				if ( material.emissiveMap ) {

950 951 952
					var emissiveMapDef = { index: processTexture( material.emissiveMap ) };
					applyTextureTransform( emissiveMapDef, material.emissiveMap );
					gltfMaterial.emissiveTexture = emissiveMapDef;
953 954 955 956 957 958 959 960

				}

			}

			// normalTexture
			if ( material.normalMap ) {

961
				var normalMapDef = { index: processTexture( material.normalMap ) };
962

M
Mugen87 已提交
963
				if ( material.normalScale.x !== - 1 ) {
964 965 966

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

M
Mugen87 已提交
967
						console.warn( 'THREE.GLTFExporter: Normal scale components are different, ignoring Y and exporting X.' );
968 969 970

					}

971
					normalMapDef.scale = material.normalScale.x;
972 973 974

				}

975 976 977 978
				applyTextureTransform( normalMapDef, material.normalMap );

				gltfMaterial.normalTexture = normalMapDef;

F
Fernando Serrano 已提交
979 980
			}

981 982 983
			// occlusionTexture
			if ( material.aoMap ) {

984
				var occlusionMapDef = { index: processTexture( material.aoMap ) };
985

986 987
				if ( material.aoMapIntensity !== 1.0 ) {

988
					occlusionMapDef.strength = material.aoMapIntensity;
989 990 991

				}

992 993 994 995
				applyTextureTransform( occlusionMapDef, material.aoMap );

				gltfMaterial.occlusionTexture = occlusionMapDef;

996 997 998
			}

			// alphaMode
999
			if ( material.transparent || material.alphaTest > 0.0 ) {
1000

1001
				gltfMaterial.alphaMode = material.opacity < 1.0 ? 'BLEND' : 'MASK';
1002

1003 1004
				// Write alphaCutoff if it's non-zero and different from the default (0.5).
				if ( material.alphaTest > 0.0 && material.alphaTest !== 0.5 ) {
1005 1006 1007 1008

					gltfMaterial.alphaCutoff = material.alphaTest;

				}
1009 1010 1011 1012

			}

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

F
Fernando Serrano 已提交
1015
				gltfMaterial.doubleSided = true;
1016

F
Fernando Serrano 已提交
1017 1018
			}

1019
			if ( material.name !== '' ) {
1020

F
Fernando Serrano 已提交
1021
				gltfMaterial.name = material.name;
1022

F
Fernando Serrano 已提交
1023 1024
			}

1025 1026
			if ( Object.keys( material.userData ).length > 0 ) {

1027
				gltfMaterial.extras = serializeUserData( material );
1028 1029 1030

			}

F
Fernando Serrano 已提交
1031
			outputJSON.materials.push( gltfMaterial );
F
Fernando Serrano 已提交
1032

1033
			var index = outputJSON.materials.length - 1;
T
Takahiro 已提交
1034
			cachedData.materials.set( material, index );
1035 1036

			return index;
1037

F
Fernando Serrano 已提交
1038 1039 1040
		}

		/**
F
Fernando Serrano 已提交
1041 1042 1043
		 * Process mesh
		 * @param  {THREE.Mesh} mesh Mesh to process
		 * @return {Integer}      Index of the processed mesh in the "meshes" array
F
Fernando Serrano 已提交
1044 1045
		 */
		function processMesh( mesh ) {
F
Fernando Serrano 已提交
1046

1047 1048 1049 1050 1051 1052 1053
			var cacheKey = mesh.geometry.uuid + ':' + mesh.material.uuid;
			if ( cachedData.meshes.has( cacheKey ) ) {

				return cachedData.meshes.get( cacheKey );

			}

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

M
Mr.doob 已提交
1056 1057
			var mode;

1058
			// Use the correct mode
1059
			if ( mesh.isLineSegments ) {
1060

1061
				mode = WEBGL_CONSTANTS.LINES;
1062

1063
			} else if ( mesh.isLineLoop ) {
1064

1065
				mode = WEBGL_CONSTANTS.LINE_LOOP;
1066

1067
			} else if ( mesh.isLine ) {
1068

1069
				mode = WEBGL_CONSTANTS.LINE_STRIP;
1070

1071
			} else if ( mesh.isPoints ) {
1072

1073
				mode = WEBGL_CONSTANTS.POINTS;
1074 1075 1076

			} else {

M
Mugen87 已提交
1077
				if ( ! geometry.isBufferGeometry ) {
1078 1079 1080 1081 1082 1083 1084

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

				}

1085 1086
				if ( mesh.drawMode === THREE.TriangleFanDrawMode ) {

F
Fernando Serrano 已提交
1087
					console.warn( 'GLTFExporter: TriangleFanDrawMode and wireframe incompatible.' );
1088
					mode = WEBGL_CONSTANTS.TRIANGLE_FAN;
1089 1090 1091

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

1092
					mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINE_STRIP : WEBGL_CONSTANTS.TRIANGLE_STRIP;
1093 1094 1095

				} else {

1096
					mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINES : WEBGL_CONSTANTS.TRIANGLES;
1097 1098 1099 1100

				}

			}
F
Fernando Serrano 已提交
1101

T
Takahiro 已提交
1102
			var gltfMesh = {};
1103

T
Takahiro 已提交
1104 1105 1106
			var attributes = {};
			var primitives = [];
			var targets = [];
F
Fernando Serrano 已提交
1107

F
Fernando Serrano 已提交
1108 1109
			// Conversion between attributes names in threejs and gltf spec
			var nameConversion = {
F
Fernando Serrano 已提交
1110

F
Fernando Serrano 已提交
1111 1112
				uv: 'TEXCOORD_0',
				uv2: 'TEXCOORD_1',
1113 1114 1115
				color: 'COLOR_0',
				skinWeight: 'WEIGHTS_0',
				skinIndex: 'JOINTS_0'
F
Fernando Serrano 已提交
1116

F
Fernando Serrano 已提交
1117 1118
			};

1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
			var originalNormal = geometry.getAttribute( 'normal' );

			if ( originalNormal !== undefined && ! isNormalizedNormalAttribute( originalNormal ) ) {

				console.warn( 'THREE.GLTFExporter: Creating normalized normal attribute from the non-normalized one.' );

				geometry.addAttribute( 'normal', createNormalizedNormalAttribute( originalNormal ) );

			}

1129
			// @QUESTION Detect if .vertexColors = THREE.VertexColors?
F
Fernando Serrano 已提交
1130
			// For every attribute create an accessor
1131
			var modifiedAttribute;
F
Fernando Serrano 已提交
1132 1133
			for ( var attributeName in geometry.attributes ) {

F
Fernando Serrano 已提交
1134
				var attribute = geometry.attributes[ attributeName ];
F
Fernando Serrano 已提交
1135
				attributeName = nameConversion[ attributeName ] || attributeName.toUpperCase();
D
Don McCurdy 已提交
1136

1137 1138 1139 1140 1141 1142 1143
				if ( cachedData.attributes.has( attribute ) ) {

					attributes[ attributeName ] = cachedData.attributes.get( attribute );
					continue;

				}

1144
				// JOINTS_0 must be UNSIGNED_BYTE or UNSIGNED_SHORT.
1145
				modifiedAttribute = null;
1146
				var array = attribute.array;
1147
				if ( attributeName === 'JOINTS_0' &&
1148 1149
					! ( array instanceof Uint16Array ) &&
					! ( array instanceof Uint8Array ) ) {
1150 1151

					console.warn( 'GLTFExporter: Attribute "skinIndex" converted to type UNSIGNED_SHORT.' );
1152
					modifiedAttribute = new THREE.BufferAttribute( new Uint16Array( array ), attribute.itemSize, attribute.normalized );
1153 1154 1155

				}

D
Don McCurdy 已提交
1156
				if ( attributeName.substr( 0, 5 ) !== 'MORPH' ) {
F
Fernando Serrano 已提交
1157

1158
					var accessor = processAccessor( modifiedAttribute || attribute, geometry );
1159
					if ( accessor !== null ) {
D
Don McCurdy 已提交
1160

1161
						attributes[ attributeName ] = accessor;
1162
						cachedData.attributes.set( attribute, accessor );
1163 1164

					}
D
Don McCurdy 已提交
1165 1166 1167 1168 1169

				}

			}

1170 1171
			if ( originalNormal !== undefined ) geometry.addAttribute( 'normal', originalNormal );

1172 1173 1174 1175 1176 1177 1178
			// Skip if no exportable attributes found
			if ( Object.keys( attributes ).length === 0 ) {

				return null;

			}

D
Don McCurdy 已提交
1179 1180 1181
			// Morph targets
			if ( mesh.morphTargetInfluences !== undefined && mesh.morphTargetInfluences.length > 0 ) {

1182
				var weights = [];
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
				var targetNames = [];
				var reverseDictionary = {};

				if ( mesh.morphTargetDictionary !== undefined ) {

					for ( var key in mesh.morphTargetDictionary ) {

						reverseDictionary[ mesh.morphTargetDictionary[ key ] ] = key;

					}

				}

D
Don McCurdy 已提交
1196 1197 1198 1199
				for ( var i = 0; i < mesh.morphTargetInfluences.length; ++ i ) {

					var target = {};

1200 1201
					var warned = false;

D
Don McCurdy 已提交
1202 1203
					for ( var attributeName in geometry.morphAttributes ) {

T
Takahiro 已提交
1204
						// glTF 2.0 morph supports only POSITION/NORMAL/TANGENT.
1205
						// Three.js doesn't support TANGENT yet.
T
Takahiro 已提交
1206 1207 1208

						if ( attributeName !== 'position' && attributeName !== 'normal' ) {

1209 1210 1211 1212 1213 1214 1215
							if ( ! warned ) {

								console.warn( 'GLTFExporter: Only POSITION and NORMAL morph are supported.' );
								warned = true;

							}

T
Takahiro 已提交
1216 1217 1218 1219
							continue;

						}

D
Don McCurdy 已提交
1220
						var attribute = geometry.morphAttributes[ attributeName ][ i ];
1221
						var gltfAttributeName = attributeName.toUpperCase();
T
Takahiro 已提交
1222

1223
						// Three.js morph attribute has absolute values while the one of glTF has relative values.
T
Takahiro 已提交
1224 1225 1226 1227 1228
						//
						// glTF 2.0 Specification:
						// https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#morph-targets

						var baseAttribute = geometry.attributes[ attributeName ];
1229 1230 1231 1232 1233 1234 1235 1236

						if ( cachedData.attributes.has( baseAttribute ) ) {

							target[ gltfAttributeName ] = cachedData.attributes.get( baseAttribute );
							continue;

						}

T
Takahiro 已提交
1237
						// Clones attribute not to override
1238
						var relativeAttribute = attribute.clone();
T
Takahiro 已提交
1239 1240 1241

						for ( var j = 0, jl = attribute.count; j < jl; j ++ ) {

1242
							relativeAttribute.setXYZ(
T
Takahiro 已提交
1243 1244 1245 1246 1247 1248 1249 1250
								j,
								attribute.getX( j ) - baseAttribute.getX( j ),
								attribute.getY( j ) - baseAttribute.getY( j ),
								attribute.getZ( j ) - baseAttribute.getZ( j )
							);

						}

1251 1252
						target[ gltfAttributeName ] = processAccessor( relativeAttribute, geometry );
						cachedData.attributes.set( baseAttribute, target[ gltfAttributeName ] );
D
Don McCurdy 已提交
1253 1254 1255

					}

T
Takahiro 已提交
1256
					targets.push( target );
D
Don McCurdy 已提交
1257

1258
					weights.push( mesh.morphTargetInfluences[ i ] );
1259
					if ( mesh.morphTargetDictionary !== undefined ) targetNames.push( reverseDictionary[ i ] );
1260

D
Don McCurdy 已提交
1261
				}
F
Fernando Serrano 已提交
1262

1263 1264
				gltfMesh.weights = weights;

1265 1266 1267 1268 1269 1270 1271
				if ( targetNames.length > 0 ) {

					gltfMesh.extras = {};
					gltfMesh.extras.targetNames = targetNames;

				}

F
Fernando Serrano 已提交
1272 1273
			}

1274 1275
			var extras = ( Object.keys( geometry.userData ).length > 0 ) ? serializeUserData( geometry ) : undefined;

1276
			var forceIndices = options.forceIndices;
T
Takahiro 已提交
1277
			var isMultiMaterial = Array.isArray( mesh.material );
1278

1279
			if ( isMultiMaterial && geometry.groups.length === 0 ) return null;
1280

1281
			if ( ! forceIndices && geometry.index === null && isMultiMaterial ) {
1282 1283

				// temporal workaround.
1284
				console.warn( 'THREE.GLTFExporter: Creating index for non-indexed multi-material mesh.' );
1285 1286 1287 1288
				forceIndices = true;

			}

1289
			var didForceIndices = false;
T
Takahiro 已提交
1290

1291
			if ( geometry.index === null && forceIndices ) {
T
Takahiro 已提交
1292

1293
				var indices = [];
T
Takahiro 已提交
1294

1295
				for ( var i = 0, il = geometry.attributes.position.count; i < il; i ++ ) {
T
Takahiro 已提交
1296 1297 1298 1299 1300

					indices[ i ] = i;

				}

1301
				geometry.setIndex( indices );
T
Takahiro 已提交
1302

1303
				didForceIndices = true;
T
Takahiro 已提交
1304 1305 1306

			}

F
Fernando Serrano 已提交
1307
			var materials = isMultiMaterial ? mesh.material : [ mesh.material ];
1308
			var groups = isMultiMaterial ? geometry.groups : [ { materialIndex: 0, start: undefined, count: undefined } ];
T
Takahiro 已提交
1309

1310
			for ( var i = 0, il = groups.length; i < il; i ++ ) {
T
Takahiro 已提交
1311 1312 1313 1314 1315 1316

				var primitive = {
					mode: mode,
					attributes: attributes,
				};

1317 1318
				if ( extras ) primitive.extras = extras;

T
Takahiro 已提交
1319 1320 1321 1322
				if ( targets.length > 0 ) primitive.targets = targets;

				if ( geometry.index !== null ) {

1323 1324 1325 1326 1327 1328 1329 1330 1331 1332
					if ( cachedData.attributes.has( geometry.index ) ) {

						primitive.indices = cachedData.attributes.get( geometry.index );

					} else {

						primitive.indices = processAccessor( geometry.index, geometry, groups[ i ].start, groups[ i ].count );
						cachedData.attributes.set( geometry.index, primitive.indices );

					}
T
Takahiro 已提交
1333 1334 1335

				}

1336
				var material = processMaterial( materials[ groups[ i ].materialIndex ] );
1337

1338
				if ( material !== null ) {
1339

1340
					primitive.material = material;
1341 1342

				}
T
Takahiro 已提交
1343

1344 1345
				primitives.push( primitive );

T
Takahiro 已提交
1346 1347
			}

1348
			if ( didForceIndices ) {
T
Takahiro 已提交
1349

1350
				geometry.setIndex( null );
T
Takahiro 已提交
1351 1352 1353 1354 1355

			}

			gltfMesh.primitives = primitives;

1356 1357 1358 1359 1360
			if ( ! outputJSON.meshes ) {

				outputJSON.meshes = [];

			}
F
Fernando Serrano 已提交
1361

F
Fernando Serrano 已提交
1362 1363
			outputJSON.meshes.push( gltfMesh );

1364 1365 1366 1367
			var index = outputJSON.meshes.length - 1;
			cachedData.meshes.set( cacheKey, index );

			return index;
M
Mugen87 已提交
1368

F
Fernando Serrano 已提交
1369 1370
		}

F
Fernando Serrano 已提交
1371 1372 1373 1374 1375 1376
		/**
		 * 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 已提交
1377

M
Mugen87 已提交
1378
			if ( ! outputJSON.cameras ) {
F
Fernando Serrano 已提交
1379

F
Fernando Serrano 已提交
1380
				outputJSON.cameras = [];
F
Fernando Serrano 已提交
1381

F
Fernando Serrano 已提交
1382 1383
			}

1384
			var isOrtho = camera.isOrthographicCamera;
F
Fernando Serrano 已提交
1385 1386

			var gltfCamera = {
F
Fernando Serrano 已提交
1387

F
Fernando Serrano 已提交
1388
				type: isOrtho ? 'orthographic' : 'perspective'
F
Fernando Serrano 已提交
1389

F
Fernando Serrano 已提交
1390 1391 1392 1393 1394 1395 1396 1397
			};

			if ( isOrtho ) {

				gltfCamera.orthographic = {

					xmag: camera.right * 2,
					ymag: camera.top * 2,
1398 1399
					zfar: camera.far <= 0 ? 0.001 : camera.far,
					znear: camera.near < 0 ? 0 : camera.near
F
Fernando Serrano 已提交
1400

F
Fernando Serrano 已提交
1401
				};
F
Fernando Serrano 已提交
1402 1403 1404 1405 1406 1407 1408

			} else {

				gltfCamera.perspective = {

					aspectRatio: camera.aspect,
					yfov: THREE.Math.degToRad( camera.fov ) / camera.aspect,
1409 1410
					zfar: camera.far <= 0 ? 0.001 : camera.far,
					znear: camera.near < 0 ? 0 : camera.near
F
Fernando Serrano 已提交
1411 1412 1413 1414 1415

				};

			}

1416
			if ( camera.name !== '' ) {
F
Fernando Serrano 已提交
1417

F
Fernando Serrano 已提交
1418
				gltfCamera.name = camera.type;
F
Fernando Serrano 已提交
1419

F
Fernando Serrano 已提交
1420 1421 1422 1423 1424
			}

			outputJSON.cameras.push( gltfCamera );

			return outputJSON.cameras.length - 1;
M
Mugen87 已提交
1425

F
Fernando Serrano 已提交
1426 1427
		}

1428 1429 1430 1431 1432 1433 1434 1435 1436 1437
		/**
		 * Creates glTF animation entry from AnimationClip object.
		 *
		 * Status:
		 * - Only properties listed in PATH_PROPERTIES may be animated.
		 *
		 * @param {THREE.AnimationClip} clip
		 * @param {THREE.Object3D} root
		 * @return {number}
		 */
M
Mugen87 已提交
1438
		function processAnimation( clip, root ) {
1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455

			if ( ! outputJSON.animations ) {

				outputJSON.animations = [];

			}

			var channels = [];
			var samplers = [];

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

				var track = clip.tracks[ i ];
				var trackBinding = THREE.PropertyBinding.parseTrackName( track.name );
				var trackNode = THREE.PropertyBinding.findNode( root, trackBinding.nodeName );
				var trackProperty = PATH_PROPERTIES[ trackBinding.propertyName ];

1456
				if ( trackBinding.objectName === 'bones' ) {
1457

1458 1459 1460 1461 1462 1463 1464 1465 1466
					if ( trackNode.isSkinnedMesh === true ) {

						trackNode = trackNode.skeleton.getBoneByName( trackBinding.objectIndex );

					} else {

						trackNode = undefined;

					}
1467 1468 1469

				}

1470 1471 1472
				if ( ! trackNode || ! trackProperty ) {

					console.warn( 'THREE.GLTFExporter: Could not export animation track "%s".', track.name );
1473
					return null;
1474 1475 1476

				}

D
Don McCurdy 已提交
1477 1478 1479 1480 1481
				var inputItemSize = 1;
				var outputItemSize = track.values.length / track.times.length;

				if ( trackProperty === PATH_PROPERTIES.morphTargetInfluences ) {

1482 1483 1484
					if ( trackNode.morphTargetInfluences.length !== 1 &&
						trackBinding.propertyIndex !== undefined ) {

1485 1486 1487
						console.warn( 'THREE.GLTFExporter: Skipping animation track "%s". ' +
							'Morph target keyframe tracks must target all available morph targets ' +
							'for the given mesh.', track.name );
1488 1489 1490 1491
						continue;

					}

D
Don McCurdy 已提交
1492 1493 1494 1495
					outputItemSize /= trackNode.morphTargetInfluences.length;

				}

T
Takahiro 已提交
1496 1497
				var interpolation;

1498 1499
				// @TODO export CubicInterpolant(InterpolateSmooth) as CUBICSPLINE

1500
				// Detecting glTF cubic spline interpolant by checking factory method's special property
1501 1502
				// GLTFCubicSplineInterpolant is a custom interpolant and track doesn't return
				// valid value from .getInterpolation().
1503
				if ( track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline === true ) {
T
Takahiro 已提交
1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521

					interpolation = 'CUBICSPLINE';

					// itemSize of CUBICSPLINE keyframe is 9
					// (VEC3 * 3: inTangent, splineVertex, and outTangent)
					// but needs to be stored as VEC3 so dividing by 3 here.
					outputItemSize /= 3;

				} else if ( track.getInterpolation() === THREE.InterpolateDiscrete ) {

					interpolation = 'STEP';

				} else {

					interpolation = 'LINEAR';

				}

1522 1523
				samplers.push( {

D
Don McCurdy 已提交
1524 1525
					input: processAccessor( new THREE.BufferAttribute( track.times, inputItemSize ) ),
					output: processAccessor( new THREE.BufferAttribute( track.values, outputItemSize ) ),
T
Takahiro 已提交
1526
					interpolation: interpolation
1527 1528 1529 1530 1531 1532 1533

				} );

				channels.push( {

					sampler: samplers.length - 1,
					target: {
T
Takahiro 已提交
1534
						node: nodeMap.get( trackNode ),
1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553
						path: trackProperty
					}

				} );

			}

			outputJSON.animations.push( {

				name: clip.name || 'clip_' + outputJSON.animations.length,
				samplers: samplers,
				channels: channels

			} );

			return outputJSON.animations.length - 1;

		}

D
Don McCurdy 已提交
1554 1555
		function processSkin( object ) {

T
Takahiro 已提交
1556
			var node = outputJSON.nodes[ nodeMap.get( object ) ];
D
Don McCurdy 已提交
1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567

			var skeleton = object.skeleton;
			var rootJoint = object.skeleton.bones[ 0 ];

			if ( rootJoint === undefined ) return null;

			var joints = [];
			var inverseBindMatrices = new Float32Array( skeleton.bones.length * 16 );

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

T
Takahiro 已提交
1568
				joints.push( nodeMap.get( skeleton.bones[ i ] ) );
D
Don McCurdy 已提交
1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583

				skeleton.boneInverses[ i ].toArray( inverseBindMatrices, i * 16 );

			}

			if ( outputJSON.skins === undefined ) {

				outputJSON.skins = [];

			}

			outputJSON.skins.push( {

				inverseBindMatrices: processAccessor( new THREE.BufferAttribute( inverseBindMatrices, 16 ) ),
				joints: joints,
T
Takahiro 已提交
1584
				skeleton: nodeMap.get( rootJoint )
D
Don McCurdy 已提交
1585 1586 1587 1588 1589 1590 1591 1592 1593

			} );

			var skinIndex = node.skin = outputJSON.skins.length - 1;

			return skinIndex;

		}

F
Fernando Serrano 已提交
1594 1595 1596 1597 1598
		/**
		 * Process Object3D node
		 * @param  {THREE.Object3D} node Object3D to processNode
		 * @return {Integer}      Index of the node in the nodes list
		 */
M
Mr.doob 已提交
1599
		function processNode( object ) {
F
Fernando Serrano 已提交
1600

1601
			if ( object.isLight ) {
1602 1603

				console.warn( 'GLTFExporter: Unsupported node type:', object.constructor.name );
1604
				return null;
1605 1606 1607

			}

M
Mugen87 已提交
1608
			if ( ! outputJSON.nodes ) {
F
Fernando Serrano 已提交
1609

F
Fernando Serrano 已提交
1610
				outputJSON.nodes = [];
F
Fernando Serrano 已提交
1611

F
Fernando Serrano 已提交
1612 1613
			}

F
Fernando Serrano 已提交
1614 1615 1616
			var gltfNode = {};

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

F
Fernando Serrano 已提交
1618 1619 1620 1621
				var rotation = object.quaternion.toArray();
				var position = object.position.toArray();
				var scale = object.scale.toArray();

M
Mugen87 已提交
1622
				if ( ! equalArray( rotation, [ 0, 0, 0, 1 ] ) ) {
F
Fernando Serrano 已提交
1623

F
Fernando Serrano 已提交
1624
					gltfNode.rotation = rotation;
F
Fernando Serrano 已提交
1625

F
Fernando Serrano 已提交
1626 1627
				}

M
Mugen87 已提交
1628
				if ( ! equalArray( position, [ 0, 0, 0 ] ) ) {
F
Fernando Serrano 已提交
1629

D
Don McCurdy 已提交
1630
					gltfNode.translation = position;
F
Fernando Serrano 已提交
1631

F
Fernando Serrano 已提交
1632 1633
				}

M
Mugen87 已提交
1634
				if ( ! equalArray( scale, [ 1, 1, 1 ] ) ) {
F
Fernando Serrano 已提交
1635

F
Fernando Serrano 已提交
1636
					gltfNode.scale = scale;
F
Fernando Serrano 已提交
1637

F
Fernando Serrano 已提交
1638 1639 1640
				}

			} else {
F
Fernando Serrano 已提交
1641

F
Fernando Serrano 已提交
1642
				object.updateMatrix();
M
Mugen87 已提交
1643
				if ( ! equalArray( object.matrix.elements, [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ] ) ) {
F
Fernando Serrano 已提交
1644

F
Fernando Serrano 已提交
1645
					gltfNode.matrix = object.matrix.elements;
F
Fernando Serrano 已提交
1646

F
Fernando Serrano 已提交
1647
				}
F
Fernando Serrano 已提交
1648

F
Fernando Serrano 已提交
1649 1650
			}

1651
			// We don't export empty strings name because it represents no-name in Three.js.
1652
			if ( object.name !== '' ) {
F
Fernando Serrano 已提交
1653

C
Christopher Cook 已提交
1654
				gltfNode.name = String( object.name );
F
Fernando Serrano 已提交
1655

F
Fernando Serrano 已提交
1656 1657
			}

1658 1659
			if ( object.userData && Object.keys( object.userData ).length > 0 ) {

1660
				gltfNode.extras = serializeUserData( object );
1661 1662 1663

			}

1664
			if ( object.isMesh || object.isLine || object.isPoints ) {
F
Fernando Serrano 已提交
1665

1666 1667
				var mesh = processMesh( object );

1668
				if ( mesh !== null ) {
1669 1670 1671 1672

					gltfNode.mesh = mesh;

				}
F
Fernando Serrano 已提交
1673

1674
			} else if ( object.isCamera ) {
F
Fernando Serrano 已提交
1675

F
Fernando Serrano 已提交
1676
				gltfNode.camera = processCamera( object );
F
Fernando Serrano 已提交
1677

F
Fernando Serrano 已提交
1678 1679
			}

1680
			if ( object.isSkinnedMesh ) {
D
Don McCurdy 已提交
1681 1682 1683 1684 1685

				skins.push( object );

			}

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

1688
				var children = [];
F
Fernando Serrano 已提交
1689 1690

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

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

1694 1695
					if ( child.visible || options.onlyVisible === false ) {

1696 1697
						var node = processNode( child );

1698
						if ( node !== null ) {
1699

1700
							children.push( node );
1701 1702

						}
F
Fernando Serrano 已提交
1703

F
Fernando Serrano 已提交
1704
					}
F
Fernando Serrano 已提交
1705

F
Fernando Serrano 已提交
1706
				}
F
Fernando Serrano 已提交
1707

1708 1709 1710 1711 1712 1713 1714
				if ( children.length > 0 ) {

					gltfNode.children = children;

				}


F
Fernando Serrano 已提交
1715 1716 1717 1718
			}

			outputJSON.nodes.push( gltfNode );

T
Takahiro 已提交
1719 1720
			var nodeIndex = outputJSON.nodes.length - 1;
			nodeMap.set( object, nodeIndex );
1721 1722

			return nodeIndex;
F
Fernando Serrano 已提交
1723

F
Fernando Serrano 已提交
1724 1725 1726
		}

		/**
F
Fernando Serrano 已提交
1727
		 * Process Scene
F
Fernando Serrano 已提交
1728 1729 1730
		 * @param  {THREE.Scene} node Scene to process
		 */
		function processScene( scene ) {
F
Fernando Serrano 已提交
1731

M
Mugen87 已提交
1732
			if ( ! outputJSON.scenes ) {
F
Fernando Serrano 已提交
1733

F
Fernando Serrano 已提交
1734 1735
				outputJSON.scenes = [];
				outputJSON.scene = 0;
F
Fernando Serrano 已提交
1736

F
Fernando Serrano 已提交
1737 1738 1739
			}

			var gltfScene = {
F
Fernando Serrano 已提交
1740

F
Fernando Serrano 已提交
1741
				nodes: []
F
Fernando Serrano 已提交
1742

F
Fernando Serrano 已提交
1743 1744
			};

1745
			if ( scene.name !== '' ) {
F
Fernando Serrano 已提交
1746

F
Fernando Serrano 已提交
1747
				gltfScene.name = scene.name;
F
Fernando Serrano 已提交
1748

F
Fernando Serrano 已提交
1749 1750
			}

M
makc 已提交
1751 1752 1753 1754 1755 1756
			if ( scene.userData && Object.keys( scene.userData ).length > 0 ) {

				gltfScene.extras = serializeUserData( scene );

			}

F
Fernando Serrano 已提交
1757
			outputJSON.scenes.push( gltfScene );
F
Fernando Serrano 已提交
1758

1759 1760
			var nodes = [];

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

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

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

1767 1768
					var node = processNode( child );

1769
					if ( node !== null ) {
1770

1771
						nodes.push( node );
1772 1773

					}
1774 1775 1776

				}

1777
			}
1778

1779
			if ( nodes.length > 0 ) {
F
Fernando Serrano 已提交
1780

1781
				gltfScene.nodes = nodes;
F
Fernando Serrano 已提交
1782

F
Fernando Serrano 已提交
1783
			}
F
Fernando Serrano 已提交
1784

F
Fernando Serrano 已提交
1785 1786
		}

1787 1788 1789 1790
		/**
		 * Creates a THREE.Scene to hold a list of objects and parse it
		 * @param  {Array} objects List of objects to process
		 */
M
Mr.doob 已提交
1791
		function processObjects( objects ) {
1792 1793

			var scene = new THREE.Scene();
1794
			scene.name = 'AuxScene';
1795

M
Mugen87 已提交
1796
			for ( var i = 0; i < objects.length; i ++ ) {
1797

1798 1799 1800
				// 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 ] );
1801 1802 1803 1804 1805 1806 1807

			}

			processScene( scene );

		}

1808
		function processInput( input ) {
1809

1810
			input = input instanceof Array ? input : [ input ];
F
Fernando Serrano 已提交
1811

1812
			var objectsWithoutScene = [];
M
Mr.doob 已提交
1813

M
Mugen87 已提交
1814
			for ( var i = 0; i < input.length; i ++ ) {
F
Fernando Serrano 已提交
1815

1816
				if ( input[ i ] instanceof THREE.Scene ) {
1817 1818 1819

					processScene( input[ i ] );

1820
				} else {
1821

1822
					objectsWithoutScene.push( input[ i ] );
1823

1824
				}
F
Fernando Serrano 已提交
1825

F
Fernando Serrano 已提交
1826
			}
F
Fernando Serrano 已提交
1827

1828
			if ( objectsWithoutScene.length > 0 ) {
1829

1830
				processObjects( objectsWithoutScene );
1831 1832

			}
F
Fernando Serrano 已提交
1833

D
Don McCurdy 已提交
1834 1835 1836 1837 1838 1839
			for ( var i = 0; i < skins.length; ++ i ) {

				processSkin( skins[ i ] );

			}

1840 1841 1842 1843 1844 1845
			for ( var i = 0; i < options.animations.length; ++ i ) {

				processAnimation( options.animations[ i ], input[ 0 ] );

			}

F
Fernando Serrano 已提交
1846
		}
F
Fernando Serrano 已提交
1847

D
Don McCurdy 已提交
1848
		processInput( input );
F
Fernando Serrano 已提交
1849

1850
		Promise.all( pending ).then( function () {
F
Fernando Serrano 已提交
1851

1852 1853
			// Merge buffers.
			var blob = new Blob( buffers, { type: 'application/octet-stream' } );
1854

1855 1856 1857 1858
			// Declare extensions.
			var extensionsUsedList = Object.keys( extensionsUsed );
			if ( extensionsUsedList.length > 0 ) outputJSON.extensionsUsed = extensionsUsedList;

1859
			if ( outputJSON.buffers && outputJSON.buffers.length > 0 ) {
1860

1861 1862
				// Update bytelength of the single buffer.
				outputJSON.buffers[ 0 ].byteLength = blob.size;
F
Fernando Serrano 已提交
1863

1864
				var reader = new window.FileReader();
1865

1866
				if ( options.binary === true ) {
1867

1868
					// https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#glb-file-format-specification
1869

1870 1871 1872
					var GLB_HEADER_BYTES = 12;
					var GLB_HEADER_MAGIC = 0x46546C67;
					var GLB_VERSION = 2;
1873

1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887
					var GLB_CHUNK_PREFIX_BYTES = 8;
					var GLB_CHUNK_TYPE_JSON = 0x4E4F534A;
					var GLB_CHUNK_TYPE_BIN = 0x004E4942;

					reader.readAsArrayBuffer( blob );
					reader.onloadend = function () {

						// Binary chunk.
						var binaryChunk = getPaddedArrayBuffer( reader.result );
						var binaryChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) );
						binaryChunkPrefix.setUint32( 0, binaryChunk.byteLength, true );
						binaryChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_BIN, true );

						// JSON chunk.
1888
						var jsonChunk = getPaddedArrayBuffer( stringToArrayBuffer( JSON.stringify( outputJSON ) ), 0x20 );
1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917
						var jsonChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) );
						jsonChunkPrefix.setUint32( 0, jsonChunk.byteLength, true );
						jsonChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_JSON, true );

						// GLB header.
						var header = new ArrayBuffer( GLB_HEADER_BYTES );
						var headerView = new DataView( header );
						headerView.setUint32( 0, GLB_HEADER_MAGIC, true );
						headerView.setUint32( 4, GLB_VERSION, true );
						var totalByteLength = GLB_HEADER_BYTES
							+ jsonChunkPrefix.byteLength + jsonChunk.byteLength
							+ binaryChunkPrefix.byteLength + binaryChunk.byteLength;
						headerView.setUint32( 8, totalByteLength, true );

						var glbBlob = new Blob( [
							header,
							jsonChunkPrefix,
							jsonChunk,
							binaryChunkPrefix,
							binaryChunk
						], { type: 'application/octet-stream' } );

						var glbReader = new window.FileReader();
						glbReader.readAsArrayBuffer( glbBlob );
						glbReader.onloadend = function () {

							onDone( glbReader.result );

						};
F
Fernando Serrano 已提交
1918

1919 1920
					};

1921
				} else {
1922

1923 1924
					reader.readAsDataURL( blob );
					reader.onloadend = function () {
1925

1926 1927 1928
						var base64data = reader.result;
						outputJSON.buffers[ 0 ].uri = base64data;
						onDone( outputJSON );
1929

1930
					};
F
Fernando Serrano 已提交
1931

1932
				}
F
Fernando Serrano 已提交
1933

1934
			} else {
F
Fernando Serrano 已提交
1935

1936
				onDone( outputJSON );
1937

1938
			}
1939

1940
		} );
1941

F
Fernando Serrano 已提交
1942
	}
M
Mr.doob 已提交
1943

D
Don McCurdy 已提交
1944
};