GLTF2Loader.js 65.8 KB
Newer Older
D
Don McCurdy 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/**
 * @author Rich Tibbett / https://github.com/richtr
 * @author mrdoob / http://mrdoob.com/
 * @author Tony Parisi / http://www.tonyparisi.com/
 * @author Takahiro / https://github.com/takahirox
 * @author Don McCurdy / https://www.donmccurdy.com
 */

THREE.GLTF2Loader = ( function () {

	function GLTF2Loader( manager ) {

		this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;

	}

	GLTF2Loader.prototype = {

		constructor: GLTF2Loader,

		load: function ( url, onLoad, onProgress, onError ) {

			var scope = this;

M
Mugen87 已提交
25
			var path = this.path && ( typeof this.path === 'string' ) ? this.path : THREE.Loader.prototype.extractUrlBase( url );
D
Don McCurdy 已提交
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57

			var loader = new THREE.FileLoader( scope.manager );

			loader.setResponseType( 'arraybuffer' );

			loader.load( url, function ( data ) {

				scope.parse( data, onLoad, path );

			}, onProgress, onError );

		},

		setCrossOrigin: function ( value ) {

			this.crossOrigin = value;

		},

		setPath: function ( value ) {

			this.path = value;

		},

		parse: function ( data, callback, path ) {

			var content;
			var extensions = {};

			var magic = convertUint8ArrayToString( new Uint8Array( data, 0, 4 ) );

58
			if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) {
D
Don McCurdy 已提交
59 60 61 62 63 64 65 66 67 68 69 70

				extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
				content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content;

			} else {

				content = convertUint8ArrayToString( new Uint8Array( data ) );

			}

			var json = JSON.parse( content );

71
			if ( json.extensionsUsed ) {
D
Don McCurdy 已提交
72

73 74 75 76 77 78
				if( json.extensionsUsed.indexOf( EXTENSIONS.KHR_LIGHTS ) >= 0 ) {

					extensions[ EXTENSIONS.KHR_LIGHTS ] = new GLTFLightsExtension( json );

				}

79 80 81 82 83 84 85 86 87 88 89
				if( json.extensionsUsed.indexOf( EXTENSIONS.KHR_MATERIALS_COMMON ) >= 0 ) {

					extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ] = new GLTFMaterialsCommonExtension( json );

				}

				if( json.extensionsUsed.indexOf( EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ) >= 0 ) {

					extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] = new GLTFMaterialsPbrSpecularGlossinessExtension();

				}
D
Don McCurdy 已提交
90

91 92 93 94 95 96
				if ( json.extensionsUsed.indexOf( EXTENSIONS.KHR_TECHNIQUE_WEBGL ) >= 0 ) {

					extensions[ EXTENSIONS.KHR_TECHNIQUE_WEBGL ] = new GLTFTechniqueWebglExtension( json );

				}

D
Don McCurdy 已提交
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
			}

			console.time( 'GLTF2Loader' );

			var parser = new GLTFParser( json, extensions, {

				path: path || this.path,
				crossOrigin: this.crossOrigin

			} );

			parser.parse( function ( scene, scenes, cameras, animations ) {

				console.timeEnd( 'GLTF2Loader' );

				var glTF = {
M
Mugen87 已提交
113 114 115 116
					scene: scene,
					scenes: scenes,
					cameras: cameras,
					animations: animations
D
Don McCurdy 已提交
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
				};

				callback( glTF );

			} );

		}

	};

	/* GLTFREGISTRY */

	function GLTFRegistry() {

		var objects = {};

		return	{

			get: function ( key ) {

				return objects[ key ];

			},

			add: function ( key, object ) {

				objects[ key ] = object;

			},

			remove: function ( key ) {

				delete objects[ key ];

			},

			removeAll: function () {

				objects = {};

			},

			update: function ( scene, camera ) {

				for ( var name in objects ) {

					var object = objects[ name ];

					if ( object.update ) {

						object.update( scene, camera );

					}

				}

			}

		};

	}

	/* GLTFSHADER */

	function GLTFShader( targetNode, allNodes ) {

		var boundUniforms = {};

		// bind each uniform to its source node

		var uniforms = targetNode.material.uniforms;

		for ( var uniformId in uniforms ) {

			var uniform = uniforms[ uniformId ];

			if ( uniform.semantic ) {

				var sourceNodeRef = uniform.node;

				var sourceNode = targetNode;

				if ( sourceNodeRef ) {

					sourceNode = allNodes[ sourceNodeRef ];

				}

				boundUniforms[ uniformId ] = {
					semantic: uniform.semantic,
					sourceNode: sourceNode,
					targetNode: targetNode,
					uniform: uniform
				};

			}

		}

		this.boundUniforms = boundUniforms;
		this._m4 = new THREE.Matrix4();

	}

	// Update - update all the uniform values
	GLTFShader.prototype.update = function ( scene, camera ) {

		var boundUniforms = this.boundUniforms;

		for ( var name in boundUniforms ) {

			var boundUniform = boundUniforms[ name ];

			switch ( boundUniform.semantic ) {

M
Mugen87 已提交
232
				case 'MODELVIEW':
D
Don McCurdy 已提交
233 234 235 236 237

					var m4 = boundUniform.uniform.value;
					m4.multiplyMatrices( camera.matrixWorldInverse, boundUniform.sourceNode.matrixWorld );
					break;

M
Mugen87 已提交
238
				case 'MODELVIEWINVERSETRANSPOSE':
D
Don McCurdy 已提交
239 240 241 242 243 244

					var m3 = boundUniform.uniform.value;
					this._m4.multiplyMatrices( camera.matrixWorldInverse, boundUniform.sourceNode.matrixWorld );
					m3.getNormalMatrix( this._m4 );
					break;

M
Mugen87 已提交
245
				case 'PROJECTION':
D
Don McCurdy 已提交
246 247 248 249 250

					var m4 = boundUniform.uniform.value;
					m4.copy( camera.projectionMatrix );
					break;

M
Mugen87 已提交
251
				case 'JOINTMATRIX':
D
Don McCurdy 已提交
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272

					var m4v = boundUniform.uniform.value;

					for ( var mi = 0; mi < m4v.length; mi ++ ) {

						// So it goes like this:
						// SkinnedMesh world matrix is already baked into MODELVIEW;
						// transform joints to local space,
						// then transform using joint's inverse
						m4v[ mi ]
							.getInverse( boundUniform.sourceNode.matrixWorld )
							.multiply( boundUniform.targetNode.skeleton.bones[ mi ].matrixWorld )
							.multiply( boundUniform.targetNode.skeleton.boneInverses[ mi ] )
							.multiply( boundUniform.targetNode.bindMatrix );

					}

					break;

				default :

M
Mugen87 已提交
273
					console.warn( 'THREE.GLTF2Loader: Unhandled shader semantic: ' + boundUniform.semantic );
D
Don McCurdy 已提交
274 275 276 277 278 279 280 281 282 283 284 285 286 287
					break;

			}

		}

	};

	/*********************************/
	/********** EXTENSIONS ***********/
	/*********************************/

	var EXTENSIONS = {
		KHR_BINARY_GLTF: 'KHR_binary_glTF',
288
		KHR_LIGHTS: 'KHR_lights',
289
		KHR_MATERIALS_COMMON: 'KHR_materials_common',
290 291
		KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
		KHR_TECHNIQUE_WEBGL: 'KHR_technique_webgl',
D
Don McCurdy 已提交
292 293
	};

294 295 296 297 298 299
	/**
	 * Lights Extension
	 *
	 * Specification: PENDING
	 */
	function GLTFLightsExtension( json ) {
D
Don McCurdy 已提交
300

301
		this.name = EXTENSIONS.KHR_LIGHTS;
D
Don McCurdy 已提交
302 303 304

		this.lights = {};

305
		var extension = ( json.extensions && json.extensions[ EXTENSIONS.KHR_LIGHTS ] ) || {};
D
Don McCurdy 已提交
306 307 308 309 310 311 312
		var lights = extension.lights || {};

		for ( var lightId in lights ) {

			var light = lights[ lightId ];
			var lightNode;

313
			var color = new THREE.Color().fromArray( light.color );
D
Don McCurdy 已提交
314 315 316

			switch ( light.type ) {

317
				case 'directional':
D
Don McCurdy 已提交
318 319 320 321
					lightNode = new THREE.DirectionalLight( color );
					lightNode.position.set( 0, 0, 1 );
					break;

322
				case 'point':
D
Don McCurdy 已提交
323 324 325
					lightNode = new THREE.PointLight( color );
					break;

326
				case 'spot':
D
Don McCurdy 已提交
327 328 329 330
					lightNode = new THREE.SpotLight( color );
					lightNode.position.set( 0, 0, 1 );
					break;

331
				case 'ambient':
D
Don McCurdy 已提交
332 333 334 335 336 337 338
					lightNode = new THREE.AmbientLight( color );
					break;

			}

			if ( lightNode ) {

339 340 341 342 343 344 345 346 347 348 349 350 351 352
				if ( light.constantAttenuation !== undefined ) {

					lightNode.intensity = light.constantAttenuation;

				}

				if ( light.linearAttenuation !== undefined ) {

					lightNode.distance = 1 / light.linearAttenuation;

				}

				if ( light.quadraticAttenuation !== undefined ) {

353
					lightNode.decay = light.quadraticAttenuation;
354 355 356 357 358 359 360 361 362 363 364

				}

				if ( light.fallOffAngle !== undefined ) {

					lightNode.angle = light.fallOffAngle;

				}

				if ( light.fallOffExponent !== undefined ) {

M
Mugen87 已提交
365
					console.warn( 'THREE.GLTF2Loader:: light.fallOffExponent not currently supported.' );
366 367 368

				}

369
				lightNode.name = light.name || ( 'light_' + lightId );
D
Don McCurdy 已提交
370 371 372 373 374 375 376 377
				this.lights[ lightId ] = lightNode;

			}

		}

	}

378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
	/**
	 * Common Materials Extension
	 *
	 * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/Khronos/KHR_materials_common
	 */
	function GLTFMaterialsCommonExtension( json ) {

		this.name = EXTENSIONS.KHR_MATERIALS_COMMON;

	}

	GLTFMaterialsCommonExtension.prototype.getMaterialType = function ( material ) {

		var khrMaterial = material.extensions[ this.name ];

		switch ( khrMaterial.type ) {

			case 'commonBlinn' :
			case 'commonPhong' :
				return THREE.MeshPhongMaterial;

			case 'commonLambert' :
				return THREE.MeshLambertMaterial;

			case 'commonConstant' :
			default :
				return THREE.MeshBasicMaterial;

		}

	};

	GLTFMaterialsCommonExtension.prototype.extendParams = function ( materialParams, material, dependencies ) {

		var khrMaterial = material.extensions[ this.name ];

		var keys = [];

		// TODO: Currently ignored: 'ambientFactor', 'ambientTexture'
		switch ( khrMaterial.type ) {

			case 'commonBlinn' :
			case 'commonPhong' :
				keys.push( 'diffuseFactor', 'diffuseTexture', 'specularFactor', 'specularTexture', 'shininessFactor' );
				break;

			case 'commonLambert' :
				keys.push( 'diffuseFactor', 'diffuseTexture' );
				break;

			case 'commonConstant' :
			default :
				break;

		}

		var materialValues = {};

		keys.forEach( function( v ) {

			if ( khrMaterial[ v ] !== undefined ) materialValues[ v ] = khrMaterial[ v ];

		} );

		if ( materialValues.diffuseFactor !== undefined ) {

			materialParams.color = new THREE.Color().fromArray( materialValues.diffuseFactor );
445
			materialParams.opacity = materialValues.diffuseFactor[ 3 ];
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474

		}

		if ( materialValues.diffuseTexture !== undefined ) {

			materialParams.map = dependencies.textures[ materialValues.diffuseTexture.index ];

		}

		if ( materialValues.specularFactor !== undefined ) {

			materialParams.specular = new THREE.Color().fromArray( materialValues.specularFactor );

		}

		if ( materialValues.specularTexture !== undefined ) {

			materialParams.specularMap = dependencies.textures[ materialValues.specularTexture.index ];

		}

		if ( materialValues.shininessFactor !== undefined ) {

			materialParams.shininess = materialValues.shininessFactor;

		}

	};

D
Don McCurdy 已提交
475 476 477
	/* BINARY EXTENSION */

	var BINARY_EXTENSION_BUFFER_NAME = 'binary_glTF';
478 479 480
	var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
	var BINARY_EXTENSION_HEADER_LENGTH = 12;
	var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 };
D
Don McCurdy 已提交
481 482 483 484

	function GLTFBinaryExtension( data ) {

		this.name = EXTENSIONS.KHR_BINARY_GLTF;
485 486
		this.content = null;
		this.body = null;
D
Don McCurdy 已提交
487 488 489

		var headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );

490
		this.header = {
D
Don McCurdy 已提交
491 492
			magic: convertUint8ArrayToString( new Uint8Array( data.slice( 0, 4 ) ) ),
			version: headerView.getUint32( 4, true ),
493
			length: headerView.getUint32( 8, true )
D
Don McCurdy 已提交
494 495
		};

496
		if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) {
D
Don McCurdy 已提交
497

M
Mugen87 已提交
498
			throw new Error( 'THREE.GLTF2Loader: Unsupported glTF-Binary header.' );
D
Don McCurdy 已提交
499

500
		} else if ( this.header.version < 2.0 ) {
D
Don McCurdy 已提交
501

M
Mugen87 已提交
502
			throw new Error( 'THREE.GLTF2Loader: Legacy binary file detected. Use GLTFLoader instead.' );
D
Don McCurdy 已提交
503 504 505

		}

506 507
		var chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH );
		var chunkIndex = 0;
D
Don McCurdy 已提交
508

509
		while ( chunkIndex < chunkView.byteLength ) {
D
Don McCurdy 已提交
510

511 512
			var chunkLength = chunkView.getUint32( chunkIndex, true );
			chunkIndex += 4;
D
Don McCurdy 已提交
513

514 515
			var chunkType = chunkView.getUint32( chunkIndex, true );
			chunkIndex += 4;
D
Don McCurdy 已提交
516

517
			if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) {
D
Don McCurdy 已提交
518

519 520
				var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength );
				this.content = convertUint8ArrayToString( contentArray );
D
Don McCurdy 已提交
521

522
			} else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) {
D
Don McCurdy 已提交
523

524 525
				var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
				this.body = data.slice( byteOffset, byteOffset + chunkLength );
D
Don McCurdy 已提交
526

527
			}
D
Don McCurdy 已提交
528

529
			// Clients must ignore chunks with unknown types.
D
Don McCurdy 已提交
530

531 532 533 534 535 536
			chunkIndex += chunkLength;

		}

		if ( this.content === null ) {

M
Mugen87 已提交
537
			throw new Error( 'THREE.GLTF2Loader: JSON content not found.' );
538 539 540 541

		}

	}
D
Don McCurdy 已提交
542

543 544 545 546 547
	/**
	 * WebGL Technique Extension
	 *
	 * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/Khronos/KHR_technique_webgl
	 */
548 549 550 551 552 553 554 555 556 557 558 559
	function GLTFTechniqueWebglExtension( json ) {

		this.name = EXTENSIONS.KHR_TECHNIQUE_WEBGL;

		var extension = ( json.extensions && json.extensions[ EXTENSIONS.KHR_TECHNIQUE_WEBGL ] ) || {};

		this.techniques = extension.techniques || {};
		this.programs = extension.programs || {};
		this.shaders = extension.shaders || {};

	}

560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
	GLTFTechniqueWebglExtension.prototype.getMaterialType = function () {

		return DeferredShaderMaterial;

	};

	GLTFTechniqueWebglExtension.prototype.extendParams = function ( materialParams, material, dependencies ) {

		var extension = material[ EXTENSIONS.KHR_TECHNIQUE_WEBGL ];
		var technique = dependencies.techniques[ extension.technique ];

		materialParams.uniforms = {};

		var program = dependencies.programs[ technique.program ];

		if ( program === undefined ) {

			return;

		}

		materialParams.fragmentShader = dependencies.shaders[ program.fragmentShader ];

		if ( ! materialParams.fragmentShader ) {

M
Mugen87 已提交
585
			throw new Error( 'THREE.GLTF2Loader: Missing fragment shader definition: ', program.fragmentShader );
586 587 588 589 590 591 592

		}

		var vertexShader = dependencies.shaders[ program.vertexShader ];

		if ( ! vertexShader ) {

M
Mugen87 已提交
593
			throw new Error( 'THREE.GLTF2Loader: Missing vertex shader definition: ', program.vertexShader );
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657

		}

		// IMPORTANT: FIX VERTEX SHADER ATTRIBUTE DEFINITIONS
		materialParams.vertexShader = replaceTHREEShaderAttributes( vertexShader, technique );

		var uniforms = technique.uniforms;

		for ( var uniformId in uniforms ) {

			var pname = uniforms[ uniformId ];
			var shaderParam = technique.parameters[ pname ];

			var ptype = shaderParam.type;

			if ( WEBGL_TYPE[ ptype ] ) {

				var pcount = shaderParam.count;
				var value;

				if ( material.values !== undefined ) value = material.values[ pname ];

				var uvalue = new WEBGL_TYPE[ ptype ]();
				var usemantic = shaderParam.semantic;
				var unode = shaderParam.node;

				switch ( ptype ) {

					case WEBGL_CONSTANTS.FLOAT:

						uvalue = shaderParam.value;

						if ( pname === 'transparency' ) {

							materialParams.transparent = true;

						}

						if ( value !== undefined ) {

							uvalue = value;

						}

						break;

					case WEBGL_CONSTANTS.FLOAT_VEC2:
					case WEBGL_CONSTANTS.FLOAT_VEC3:
					case WEBGL_CONSTANTS.FLOAT_VEC4:
					case WEBGL_CONSTANTS.FLOAT_MAT3:

						if ( shaderParam && shaderParam.value ) {

							uvalue.fromArray( shaderParam.value );

						}

						if ( value ) {

							uvalue.fromArray( value );

						}

						break;
658

659 660 661
					case WEBGL_CONSTANTS.FLOAT_MAT2:

						// what to do?
M
Mugen87 已提交
662
						console.warn( 'THREE.GLTF2Loader: FLOAT_MAT2 is not a supported uniform type.' );
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736
						break;

					case WEBGL_CONSTANTS.FLOAT_MAT4:

						if ( pcount ) {

							uvalue = new Array( pcount );

							for ( var mi = 0; mi < pcount; mi ++ ) {

								uvalue[ mi ] = new WEBGL_TYPE[ ptype ]();

							}

							if ( shaderParam && shaderParam.value ) {

								var m4v = shaderParam.value;
								uvalue.fromArray( m4v );

							}

							if ( value ) {

								uvalue.fromArray( value );

							}

						} else {

							if ( shaderParam && shaderParam.value ) {

								var m4 = shaderParam.value;
								uvalue.fromArray( m4 );

							}

							if ( value ) {

								uvalue.fromArray( value );

							}

						}

						break;

					case WEBGL_CONSTANTS.SAMPLER_2D:

						if ( value !== undefined ) {

							uvalue = dependencies.textures[ value ];

						} else if ( shaderParam.value !== undefined ) {

							uvalue = dependencies.textures[ shaderParam.value ];

						} else {

							uvalue = null;

						}

						break;

				}

				materialParams.uniforms[ uniformId ] = {
					value: uvalue,
					semantic: usemantic,
					node: unode
				};

			} else {

M
Mugen87 已提交
737
				throw new Error( 'THREE.GLTF2Loader: Unknown shader uniform param type: ' + ptype );
738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783

			}

		}

		var states = technique.states || {};
		var enables = states.enable || [];
		var functions = states.functions || {};

		var enableCullFace = false;
		var enableDepthTest = false;
		var enableBlend = false;

		for ( var i = 0, il = enables.length; i < il; i ++ ) {

			var enable = enables[ i ];

			switch ( STATES_ENABLES[ enable ] ) {

				case 'CULL_FACE':

					enableCullFace = true;

					break;

				case 'DEPTH_TEST':

					enableDepthTest = true;

					break;

				case 'BLEND':

					enableBlend = true;

					break;

				// TODO: implement
				case 'SCISSOR_TEST':
				case 'POLYGON_OFFSET_FILL':
				case 'SAMPLE_ALPHA_TO_COVERAGE':

					break;

				default:

M
Mugen87 已提交
784
					throw new Error( 'THREE.GLTF2Loader: Unknown technique.states.enable: ' + enable );
785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845

			}

		}

		if ( enableCullFace ) {

			materialParams.side = functions.cullFace !== undefined ? WEBGL_SIDES[ functions.cullFace ] : THREE.FrontSide;

		} else {

			materialParams.side = THREE.DoubleSide;

		}

		materialParams.depthTest = enableDepthTest;
		materialParams.depthFunc = functions.depthFunc !== undefined ? WEBGL_DEPTH_FUNCS[ functions.depthFunc ] : THREE.LessDepth;
		materialParams.depthWrite = functions.depthMask !== undefined ? functions.depthMask[ 0 ] : true;

		materialParams.blending = enableBlend ? THREE.CustomBlending : THREE.NoBlending;
		materialParams.transparent = enableBlend;

		var blendEquationSeparate = functions.blendEquationSeparate;

		if ( blendEquationSeparate !== undefined ) {

			materialParams.blendEquation = WEBGL_BLEND_EQUATIONS[ blendEquationSeparate[ 0 ] ];
			materialParams.blendEquationAlpha = WEBGL_BLEND_EQUATIONS[ blendEquationSeparate[ 1 ] ];

		} else {

			materialParams.blendEquation = THREE.AddEquation;
			materialParams.blendEquationAlpha = THREE.AddEquation;

		}

		var blendFuncSeparate = functions.blendFuncSeparate;

		if ( blendFuncSeparate !== undefined ) {

			materialParams.blendSrc = WEBGL_BLEND_FUNCS[ blendFuncSeparate[ 0 ] ];
			materialParams.blendDst = WEBGL_BLEND_FUNCS[ blendFuncSeparate[ 1 ] ];
			materialParams.blendSrcAlpha = WEBGL_BLEND_FUNCS[ blendFuncSeparate[ 2 ] ];
			materialParams.blendDstAlpha = WEBGL_BLEND_FUNCS[ blendFuncSeparate[ 3 ] ];

		} else {

			materialParams.blendSrc = THREE.OneFactor;
			materialParams.blendDst = THREE.ZeroFactor;
			materialParams.blendSrcAlpha = THREE.OneFactor;
			materialParams.blendDstAlpha = THREE.ZeroFactor;

		}

	};

	/**
	 * Specular-Glossiness Extension
	 *
	 * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
	 */
846 847 848 849
	function GLTFMaterialsPbrSpecularGlossinessExtension() {

		return {

850 851 852 853 854 855 856 857
			name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,

			getMaterialType: function () {

				return THREE.ShaderMaterial;

			},

858 859 860 861 862
			extendParams: function ( params, material, dependencies ) {

				// specification
				// https://github.com/sbtron/glTF/tree/KHRpbrSpecGloss/extensions/Khronos/KHR_materials_pbrSpecularGlossiness

863
				var pbrSpecularGlossiness = material.extensions[ this.name ];
864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948

				var shader = THREE.ShaderLib[ 'standard' ];

				var uniforms = THREE.UniformsUtils.clone( shader.uniforms );

				var specularMapParsFragmentChunk = [
					'#ifdef USE_SPECULARMAP',
					'	uniform sampler2D specularMap;',
					'#endif'
				].join( '\n' );

				var glossinessMapParsFragmentChunk = [
					'#ifdef USE_GLOSSINESSMAP',
					'	uniform sampler2D glossinessMap;',
					'#endif'
				].join( '\n' );

				var specularMapFragmentChunk = [
					'vec3 specularFactor = specular;',
					'#ifdef USE_SPECULARMAP',
					'	vec4 texelSpecular = texture2D( specularMap, vUv );',
					'	// reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture',
					'	specularFactor *= texelSpecular.rgb;',
					'#endif'
				].join( '\n' );

				var glossinessMapFragmentChunk = [
					'float glossinessFactor = glossiness;',
					'#ifdef USE_GLOSSINESSMAP',
					'	vec4 texelGlossiness = texture2D( glossinessMap, vUv );',
					'	// reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture',
					'	glossinessFactor *= texelGlossiness.a;',
					'#endif'
				].join( '\n' );

				var lightPhysicalFragmentChunk = [
					'PhysicalMaterial material;',
					'material.diffuseColor = diffuseColor.rgb;',
					'material.specularRoughness = clamp( 1.0 - glossinessFactor, 0.04, 1.0 );',
					'material.specularColor = specularFactor.rgb;',
				].join( '\n' );

				var fragmentShader = shader.fragmentShader
							.replace( '#include <specularmap_fragment>', '' )
							.replace( 'uniform float roughness;', 'uniform vec3 specular;' )
							.replace( 'uniform float metalness;', 'uniform float glossiness;' )
							.replace( '#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk )
							.replace( '#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk )
							.replace( '#include <roughnessmap_fragment>', specularMapFragmentChunk )
							.replace( '#include <metalnessmap_fragment>', glossinessMapFragmentChunk )
							.replace( '#include <lights_physical_fragment>', lightPhysicalFragmentChunk );

				delete uniforms.roughness;
				delete uniforms.metalness;
				delete uniforms.roughnessMap;
				delete uniforms.metalnessMap;

				uniforms.specular = { value: new THREE.Color().setHex( 0x111111 ) };
				uniforms.glossiness = { value: 0.5 };
				uniforms.specularMap = { value: null };
				uniforms.glossinessMap = { value: null };

				params.vertexShader = shader.vertexShader;
				params.fragmentShader = fragmentShader;
				params.uniforms = uniforms;
				params.defines = { 'STANDARD': '' };

				params.color = new THREE.Color( 1.0, 1.0, 1.0 );
				params.opacity = 1.0;

				if ( Array.isArray( pbrSpecularGlossiness.diffuseFactor ) ) {

					var array = pbrSpecularGlossiness.diffuseFactor;

					params.color.fromArray( array );
					params.opacity = array[ 3 ];

				}

				if ( pbrSpecularGlossiness.diffuseTexture !== undefined ) {

					params.map = dependencies.textures[ pbrSpecularGlossiness.diffuseTexture.index ];

				}

949
				params.emissive = new THREE.Color( 0.0, 0.0, 0.0 );
950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982
				params.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
				params.specular = new THREE.Color( 1.0, 1.0, 1.0 );

				if ( Array.isArray( pbrSpecularGlossiness.specularFactor ) ) {

					params.specular.fromArray( pbrSpecularGlossiness.specularFactor );

				}

				if ( pbrSpecularGlossiness.specularGlossinessTexture !== undefined ) {

					params.glossinessMap = dependencies.textures[ pbrSpecularGlossiness.specularGlossinessTexture.index ];
					params.specularMap = dependencies.textures[ pbrSpecularGlossiness.specularGlossinessTexture.index ];

				}

			},

			createMaterial: function ( params ) {

				// setup material properties based on MeshStandardMaterial for Specular-Glossiness

				var material = new THREE.ShaderMaterial( {
					defines: params.defines,
					vertexShader: params.vertexShader,
					fragmentShader: params.fragmentShader,
					uniforms: params.uniforms,
					fog: true,
					lights: true,
					opacity: params.opacity,
					transparent: params.transparent
				} );

983 984
				material.isGLTFSpecularGlossinessMaterial = true;

985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
				material.color = params.color;

				material.map = params.map === undefined ? null : params.map;

				material.lightMap = null;
				material.lightMapIntensity = 1.0;

				material.aoMap = params.aoMap === undefined ? null : params.aoMap;
				material.aoMapIntensity = 1.0;

				material.emissive = params.emissive;
				material.emissiveIntensity = 1.0;
				material.emissiveMap = params.emissiveMap === undefined ? null : params.emissiveMap;

				material.bumpMap = params.bumpMap === undefined ? null : params.bumpMap;
				material.bumpScale = 1;

				material.normalMap = params.normalMap === undefined ? null : params.normalMap;
				material.normalScale = new THREE.Vector2( 1, 1 );

				material.displacementMap = null;
				material.displacementScale = 1;
				material.displacementBias = 0;

				material.specularMap = params.specularMap === undefined ? null : params.specularMap;
				material.specular = params.specular;

				material.glossinessMap = params.glossinessMap === undefined ? null : params.glossinessMap;
				material.glossiness = params.glossiness;

				material.alphaMap = null;

				material.envMap = params.envMap === undefined ? null : params.envMap;
				material.envMapIntensity = 1.0;

				material.refractionRatio = 0.98;

				material.extensions.derivatives = true;

				return material;

			},

			// Here's based on refreshUniformsCommon() and refreshUniformsStandard() in WebGLRenderer.
			refreshUniforms: function ( renderer, scene, camera, geometry, material, group ) {

				var uniforms = material.uniforms;
				var defines = material.defines;

				uniforms.opacity.value = material.opacity;

				uniforms.diffuse.value.copy( material.color );
				uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );

				uniforms.map.value = material.map;
				uniforms.specularMap.value = material.specularMap;
				uniforms.alphaMap.value = material.alphaMap;

				uniforms.lightMap.value = material.lightMap;
				uniforms.lightMapIntensity.value = material.lightMapIntensity;

				uniforms.aoMap.value = material.aoMap;
				uniforms.aoMapIntensity.value = material.aoMapIntensity;

				// uv repeat and offset setting priorities
				// 1. color map
				// 2. specular map
				// 3. normal map
				// 4. bump map
				// 5. alpha map
				// 6. emissive map

				var uvScaleMap;

				if ( material.map ) {

					uvScaleMap = material.map;

				} else if ( material.specularMap ) {

					uvScaleMap = material.specularMap;

				} else if ( material.displacementMap ) {

					uvScaleMap = material.displacementMap;

				} else if ( material.normalMap ) {

					uvScaleMap = material.normalMap;

				} else if ( material.bumpMap ) {

					uvScaleMap = material.bumpMap;

				} else if ( material.glossinessMap ) {

					uvScaleMap = material.glossinessMap;

				} else if ( material.alphaMap ) {

					uvScaleMap = material.alphaMap;

				} else if ( material.emissiveMap ) {

					uvScaleMap = material.emissiveMap;

				}

				if ( uvScaleMap !== undefined ) {

					// backwards compatibility
					if ( uvScaleMap.isWebGLRenderTarget ) {

						uvScaleMap = uvScaleMap.texture;

					}

					var offset = uvScaleMap.offset;
					var repeat = uvScaleMap.repeat;

					uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );

				}

				uniforms.envMap.value = material.envMap;
				uniforms.envMapIntensity.value = material.envMapIntensity;
				uniforms.flipEnvMap.value = ( material.envMap && material.envMap.isCubeTexture ) ? -1 : 1;

				uniforms.refractionRatio.value = material.refractionRatio;

				uniforms.specular.value.copy( material.specular );
				uniforms.glossiness.value = material.glossiness;

				uniforms.glossinessMap.value = material.glossinessMap;

				uniforms.emissiveMap.value = material.emissiveMap;
				uniforms.bumpMap.value = material.bumpMap;
				uniforms.normalMap.value = material.normalMap;

				uniforms.displacementMap.value = material.displacementMap;
				uniforms.displacementScale.value = material.displacementScale;
				uniforms.displacementBias.value = material.displacementBias;

				if ( uniforms.glossinessMap.value !== null && defines.USE_GLOSSINESSMAP === undefined ) {

					defines.USE_GLOSSINESSMAP = '';
					// set USE_ROUGHNESSMAP to enable vUv
					defines.USE_ROUGHNESSMAP = ''

				}

				if ( uniforms.glossinessMap.value === null && defines.USE_GLOSSINESSMAP !== undefined ) {

					delete defines.USE_GLOSSINESSMAP;
					delete defines.USE_ROUGHNESSMAP;

				}

			}

		};

	}

D
Don McCurdy 已提交
1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
	/*********************************/
	/********** INTERNALS ************/
	/*********************************/

	/* CONSTANTS */

	var WEBGL_CONSTANTS = {
		FLOAT: 5126,
		//FLOAT_MAT2: 35674,
		FLOAT_MAT3: 35675,
		FLOAT_MAT4: 35676,
		FLOAT_VEC2: 35664,
		FLOAT_VEC3: 35665,
		FLOAT_VEC4: 35666,
		LINEAR: 9729,
		REPEAT: 10497,
		SAMPLER_2D: 35678,
		TRIANGLES: 4,
		LINES: 1,
		UNSIGNED_BYTE: 5121,
		UNSIGNED_SHORT: 5123,

		VERTEX_SHADER: 35633,
		FRAGMENT_SHADER: 35632
	};

	var WEBGL_TYPE = {
		5126: Number,
		//35674: THREE.Matrix2,
		35675: THREE.Matrix3,
		35676: THREE.Matrix4,
		35664: THREE.Vector2,
		35665: THREE.Vector3,
		35666: THREE.Vector4,
		35678: THREE.Texture
	};

	var WEBGL_COMPONENT_TYPES = {
		5120: Int8Array,
		5121: Uint8Array,
		5122: Int16Array,
		5123: Uint16Array,
		5125: Uint32Array,
		5126: Float32Array
	};

	var WEBGL_FILTERS = {
		9728: THREE.NearestFilter,
		9729: THREE.LinearFilter,
		9984: THREE.NearestMipMapNearestFilter,
		9985: THREE.LinearMipMapNearestFilter,
		9986: THREE.NearestMipMapLinearFilter,
		9987: THREE.LinearMipMapLinearFilter
	};

	var WEBGL_WRAPPINGS = {
		33071: THREE.ClampToEdgeWrapping,
		33648: THREE.MirroredRepeatWrapping,
		10497: THREE.RepeatWrapping
	};

	var WEBGL_TEXTURE_FORMATS = {
		6406: THREE.AlphaFormat,
		6407: THREE.RGBFormat,
		6408: THREE.RGBAFormat,
		6409: THREE.LuminanceFormat,
		6410: THREE.LuminanceAlphaFormat
	};

	var WEBGL_TEXTURE_DATATYPES = {
		5121: THREE.UnsignedByteType,
		32819: THREE.UnsignedShort4444Type,
		32820: THREE.UnsignedShort5551Type,
		33635: THREE.UnsignedShort565Type
	};

	var WEBGL_SIDES = {
		1028: THREE.BackSide,  // Culling front
		1029: THREE.FrontSide  // Culling back
		//1032: THREE.NoSide   // Culling front and back, what to do?
	};

	var WEBGL_DEPTH_FUNCS = {
		512: THREE.NeverDepth,
		513: THREE.LessDepth,
		514: THREE.EqualDepth,
		515: THREE.LessEqualDepth,
		516: THREE.GreaterEqualDepth,
		517: THREE.NotEqualDepth,
		518: THREE.GreaterEqualDepth,
		519: THREE.AlwaysDepth
	};

	var WEBGL_BLEND_EQUATIONS = {
		32774: THREE.AddEquation,
		32778: THREE.SubtractEquation,
		32779: THREE.ReverseSubtractEquation
	};

	var WEBGL_BLEND_FUNCS = {
		0: THREE.ZeroFactor,
		1: THREE.OneFactor,
		768: THREE.SrcColorFactor,
		769: THREE.OneMinusSrcColorFactor,
		770: THREE.SrcAlphaFactor,
		771: THREE.OneMinusSrcAlphaFactor,
		772: THREE.DstAlphaFactor,
		773: THREE.OneMinusDstAlphaFactor,
		774: THREE.DstColorFactor,
		775: THREE.OneMinusDstColorFactor,
		776: THREE.SrcAlphaSaturateFactor
		// The followings are not supported by Three.js yet
		//32769: CONSTANT_COLOR,
		//32770: ONE_MINUS_CONSTANT_COLOR,
		//32771: CONSTANT_ALPHA,
		//32772: ONE_MINUS_CONSTANT_COLOR
	};

	var WEBGL_TYPE_SIZES = {
		'SCALAR': 1,
		'VEC2': 2,
		'VEC3': 3,
		'VEC4': 4,
		'MAT2': 4,
		'MAT3': 9,
		'MAT4': 16
	};

	var PATH_PROPERTIES = {
		scale: 'scale',
		translation: 'position',
T
Takahiro 已提交
1280 1281
		rotation: 'quaternion',
		weights: 'morphTargetInfluences'
D
Don McCurdy 已提交
1282 1283 1284
	};

	var INTERPOLATION = {
1285 1286
		CATMULLROMSPLINE: THREE.InterpolateSmooth,
		CUBICSPLINE: THREE.InterpolateSmooth,
D
Don McCurdy 已提交
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299
		LINEAR: THREE.InterpolateLinear,
		STEP: THREE.InterpolateDiscrete
	};

	var STATES_ENABLES = {
		2884: 'CULL_FACE',
		2929: 'DEPTH_TEST',
		3042: 'BLEND',
		3089: 'SCISSOR_TEST',
		32823: 'POLYGON_OFFSET_FILL',
		32926: 'SAMPLE_ALPHA_TO_COVERAGE'
	};

1300 1301 1302 1303 1304 1305
	var ALPHA_MODES = {
		OPAQUE: 'OPAQUE',
		MASK: 'MASK',
		BLEND: 'BLEND'
	};

D
Don McCurdy 已提交
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334
	/* UTILITY FUNCTIONS */

	function _each( object, callback, thisObj ) {

		if ( !object ) {
			return Promise.resolve();
		}

		var results;
		var fns = [];

		if ( Object.prototype.toString.call( object ) === '[object Array]' ) {

			results = [];

			var length = object.length;

			for ( var idx = 0; idx < length; idx ++ ) {

				var value = callback.call( thisObj || this, object[ idx ], idx );

				if ( value ) {

					fns.push( value );

					if ( value instanceof Promise ) {

						value.then( function( key, value ) {

1335
							results[ key ] = value;
D
Don McCurdy 已提交
1336

1337
						}.bind( this, idx ));
D
Don McCurdy 已提交
1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398

					} else {

						results[ idx ] = value;

					}

				}

			}

		} else {

			results = {};

			for ( var key in object ) {

				if ( object.hasOwnProperty( key ) ) {

					var value = callback.call( thisObj || this, object[ key ], key );

					if ( value ) {

						fns.push( value );

						if ( value instanceof Promise ) {

							value.then( function( key, value ) {

								results[ key ] = value;

							}.bind( this, key ));

						} else {

							results[ key ] = value;

						}

					}

				}

			}

		}

		return Promise.all( fns ).then( function() {

			return results;

		});

	}

	function resolveURL( url, path ) {

		// Invalid URL
		if ( typeof url !== 'string' || url === '' )
			return '';

0
06wj 已提交
1399 1400
		// Absolute URL http://,https://,//
		if ( /^(https?:)?\/\//i.test( url ) ) {
D
Don McCurdy 已提交
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412

			return url;

		}

		// Data URI
		if ( /^data:.*,.*$/i.test( url ) ) {

			return url;

		}

1413 1414 1415 1416 1417 1418 1419
		// Blob URL
		if ( /^blob:.*$/i.test( url ) ) {

			return url;

		}

D
Don McCurdy 已提交
1420 1421 1422 1423 1424 1425 1426
		// Relative URL
		return ( path || '' ) + url;

	}

	function convertUint8ArrayToString( array ) {

1427 1428 1429 1430 1431 1432 1433 1434 1435
		if ( window.TextDecoder !== undefined ) {

			return new TextDecoder().decode( array );

		}

		// Avoid the String.fromCharCode.apply(null, array) shortcut, which
		// throws a "maximum call stack size exceeded" error for large arrays.

D
Don McCurdy 已提交
1436 1437
		var s = '';

1438
		for ( var i = 0, il = array.length; i < il; i ++ ) {
D
Don McCurdy 已提交
1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493

			s += String.fromCharCode( array[ i ] );

		}

		return s;

	}

	// Three.js seems too dependent on attribute names so globally
	// replace those in the shader code
	function replaceTHREEShaderAttributes( shaderText, technique ) {

		// Expected technique attributes
		var attributes = {};

		for ( var attributeId in technique.attributes ) {

			var pname = technique.attributes[ attributeId ];

			var param = technique.parameters[ pname ];
			var atype = param.type;
			var semantic = param.semantic;

			attributes[ attributeId ] = {
				type: atype,
				semantic: semantic
			};

		}

		// Figure out which attributes to change in technique

		var shaderParams = technique.parameters;
		var shaderAttributes = technique.attributes;
		var params = {};

		for ( var attributeId in attributes ) {

			var pname = shaderAttributes[ attributeId ];
			var shaderParam = shaderParams[ pname ];
			var semantic = shaderParam.semantic;
			if ( semantic ) {

				params[ attributeId ] = shaderParam;

			}

		}

		for ( var pname in params ) {

			var param = params[ pname ];
			var semantic = param.semantic;

M
Mugen87 已提交
1494
			var regEx = new RegExp( '\\b' + pname + '\\b', 'g' );
D
Don McCurdy 已提交
1495 1496 1497

			switch ( semantic ) {

1498
				case 'POSITION':
D
Don McCurdy 已提交
1499 1500 1501 1502

					shaderText = shaderText.replace( regEx, 'position' );
					break;

1503
				case 'NORMAL':
D
Don McCurdy 已提交
1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514

					shaderText = shaderText.replace( regEx, 'normal' );
					break;

				case 'TEXCOORD_0':
				case 'TEXCOORD0':
				case 'TEXCOORD':

					shaderText = shaderText.replace( regEx, 'uv' );
					break;

1515 1516 1517 1518 1519
				case 'TEXCOORD_1':

					shaderText = shaderText.replace( regEx, 'uv2' );
					break;

D
Don McCurdy 已提交
1520 1521 1522 1523 1524 1525 1526
				case 'COLOR_0':
				case 'COLOR0':
				case 'COLOR':

					shaderText = shaderText.replace( regEx, 'color' );
					break;

1527 1528
				case 'WEIGHTS_0':
				case 'WEIGHT': // WEIGHT semantic deprecated.
D
Don McCurdy 已提交
1529 1530 1531 1532

					shaderText = shaderText.replace( regEx, 'skinWeight' );
					break;

1533 1534
				case 'JOINTS_0':
				case 'JOINT': // JOINT semantic deprecated.
D
Don McCurdy 已提交
1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546

					shaderText = shaderText.replace( regEx, 'skinIndex' );
					break;

			}

		}

		return shaderText;

	}

1547 1548 1549
	/**
	 * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
	 */
D
Don McCurdy 已提交
1550 1551
	function createDefaultMaterial() {

1552 1553 1554 1555 1556
		return new THREE.MeshStandardMaterial( {
			color: 0xFFFFFF,
			emissive: 0x000000,
			metalness: 1,
			roughness: 1,
D
Don McCurdy 已提交
1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618
			transparent: false,
			depthTest: true,
			side: THREE.FrontSide
		} );

	}

	// Deferred constructor for RawShaderMaterial types
	function DeferredShaderMaterial( params ) {

		this.isDeferredShaderMaterial = true;

		this.params = params;

	}

	DeferredShaderMaterial.prototype.create = function () {

		var uniforms = THREE.UniformsUtils.clone( this.params.uniforms );

		for ( var uniformId in this.params.uniforms ) {

			var originalUniform = this.params.uniforms[ uniformId ];

			if ( originalUniform.value instanceof THREE.Texture ) {

				uniforms[ uniformId ].value = originalUniform.value;
				uniforms[ uniformId ].value.needsUpdate = true;

			}

			uniforms[ uniformId ].semantic = originalUniform.semantic;
			uniforms[ uniformId ].node = originalUniform.node;

		}

		this.params.uniforms = uniforms;

		return new THREE.RawShaderMaterial( this.params );

	};

	/* GLTF PARSER */

	function GLTFParser( json, extensions, options ) {

		this.json = json || {};
		this.extensions = extensions || {};
		this.options = options || {};

		// loader object cache
		this.cache = new GLTFRegistry();

	}

	GLTFParser.prototype._withDependencies = function ( dependencies ) {

		var _dependencies = {};

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

			var dependency = dependencies[ i ];
M
Mugen87 已提交
1619
			var fnName = 'load' + dependency.charAt( 0 ).toUpperCase() + dependency.slice( 1 );
D
Don McCurdy 已提交
1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655

			var cached = this.cache.get( dependency );

			if ( cached !== undefined ) {

				_dependencies[ dependency ] = cached;

			} else if ( this[ fnName ] ) {

				var fn = this[ fnName ]();
				this.cache.add( dependency, fn );

				_dependencies[ dependency ] = fn;

			}

		}

		return _each( _dependencies, function ( dependency ) {

			return dependency;

		} );

	};

	GLTFParser.prototype.parse = function ( callback ) {

		var json = this.json;

		// Clear the loader cache
		this.cache.removeAll();

		// Fire the callback on complete
		this._withDependencies( [

M
Mugen87 已提交
1656 1657 1658
			'scenes',
			'cameras',
			'animations'
D
Don McCurdy 已提交
1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669

		] ).then( function ( dependencies ) {

			var scenes = [];

			for ( var name in dependencies.scenes ) {

				scenes.push( dependencies.scenes[ name ] );

			}

1670 1671
			var scene = json.scene !== undefined ? dependencies.scenes[ json.scene ] : scenes[ 0 ];

D
Don McCurdy 已提交
1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698
			var cameras = [];

			for ( var name in dependencies.cameras ) {

				var camera = dependencies.cameras[ name ];
				cameras.push( camera );

			}

			var animations = [];

			for ( var name in dependencies.animations ) {

				animations.push( dependencies.animations[ name ] );

			}

			callback( scene, scenes, cameras, animations );

		} );

	};

	GLTFParser.prototype.loadShaders = function () {

		var json = this.json;
		var options = this.options;
1699
		var extensions = this.extensions;
D
Don McCurdy 已提交
1700 1701 1702

		return this._withDependencies( [

M
Mugen87 已提交
1703
			'bufferViews'
D
Don McCurdy 已提交
1704 1705 1706

		] ).then( function ( dependencies ) {

1707 1708 1709 1710 1711
			var shaders = extensions[ EXTENSIONS.KHR_TECHNIQUE_WEBGL ] !== undefined ? extensions[ EXTENSIONS.KHR_TECHNIQUE_WEBGL ].shaders : json.shaders;

			if ( shaders === undefined ) shaders = {};

			return _each( shaders, function ( shader ) {
D
Don McCurdy 已提交
1712

1713
				if ( shader.bufferView !== undefined ) {
D
Don McCurdy 已提交
1714

1715 1716 1717
					var bufferView = dependencies.bufferViews[ shader.bufferView ];
					var array = new Uint8Array( bufferView );
					return convertUint8ArrayToString( array );
D
Don McCurdy 已提交
1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746

				}

				return new Promise( function ( resolve ) {

					var loader = new THREE.FileLoader();
					loader.setResponseType( 'text' );
					loader.load( resolveURL( shader.uri, options.path ), function ( shaderText ) {

						resolve( shaderText );

					} );

				} );

			} );

		} );

	};

	GLTFParser.prototype.loadBuffers = function () {

		var json = this.json;
		var extensions = this.extensions;
		var options = this.options;

		return _each( json.buffers, function ( buffer, name ) {

1747
			if ( buffer.type === 'arraybuffer' || buffer.type === undefined ) {
D
Don McCurdy 已提交
1748

1749 1750
				// If present, GLB container is required to be the first buffer.
				if ( buffer.uri === undefined && name === 0 ) {
D
Don McCurdy 已提交
1751

1752
					return extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body;
D
Don McCurdy 已提交
1753

1754
				}
D
Don McCurdy 已提交
1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769

				return new Promise( function ( resolve ) {

					var loader = new THREE.FileLoader();
					loader.setResponseType( 'arraybuffer' );
					loader.load( resolveURL( buffer.uri, options.path ), function ( buffer ) {

						resolve( buffer );

					} );

				} );

			} else {

M
Mugen87 已提交
1770
				console.warn( 'THREE.GLTF2Loader: %s buffer type is not supported.', buffer.type );
D
Don McCurdy 已提交
1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783

			}

		} );

	};

	GLTFParser.prototype.loadBufferViews = function () {

		var json = this.json;

		return this._withDependencies( [

M
Mugen87 已提交
1784
			'buffers'
D
Don McCurdy 已提交
1785 1786 1787 1788 1789 1790 1791

		] ).then( function ( dependencies ) {

			return _each( json.bufferViews, function ( bufferView ) {

				var arraybuffer = dependencies.buffers[ bufferView.buffer ];

1792 1793
				var byteLength = bufferView.byteLength || 0;
				var byteOffset = bufferView.byteOffset || 0;
D
Don McCurdy 已提交
1794

1795
				return arraybuffer.slice( byteOffset, byteOffset + byteLength );
D
Don McCurdy 已提交
1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808

			} );

		} );

	};

	GLTFParser.prototype.loadAccessors = function () {

		var json = this.json;

		return this._withDependencies( [

M
Mugen87 已提交
1809
			'bufferViews'
D
Don McCurdy 已提交
1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821

		] ).then( function ( dependencies ) {

			return _each( json.accessors, function ( accessor ) {

				var arraybuffer = dependencies.bufferViews[ accessor.bufferView ];
				var itemSize = WEBGL_TYPE_SIZES[ accessor.type ];
				var TypedArray = WEBGL_COMPONENT_TYPES[ accessor.componentType ];

				// For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
				var elementBytes = TypedArray.BYTES_PER_ELEMENT;
				var itemBytes = elementBytes * itemSize;
D
Don McCurdy 已提交
1822
				var byteStride = json.bufferViews[ accessor.bufferView ].byteStride;
1823 1824
				var array;

D
Don McCurdy 已提交
1825
				// The buffer is not interleaved if the stride is the item size in bytes.
1826
				if ( byteStride && byteStride !== itemBytes ) {
D
Don McCurdy 已提交
1827 1828

					// Use the full buffer if it's interleaved.
1829
					array = new TypedArray( arraybuffer );
D
Don McCurdy 已提交
1830 1831

					// Integer parameters to IB/IBA are in array elements, not bytes.
1832
					var ib = new THREE.InterleavedBuffer( array, byteStride / elementBytes );
D
Don McCurdy 已提交
1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856

					return new THREE.InterleavedBufferAttribute( ib, itemSize, accessor.byteOffset / elementBytes );

				} else {

					array = new TypedArray( arraybuffer, accessor.byteOffset, accessor.count * itemSize );

					return new THREE.BufferAttribute( array, itemSize );

				}

			} );

		} );

	};

	GLTFParser.prototype.loadTextures = function () {

		var json = this.json;
		var options = this.options;

		return this._withDependencies( [

M
Mugen87 已提交
1857
			'bufferViews'
D
Don McCurdy 已提交
1858 1859 1860 1861 1862

		] ).then( function ( dependencies ) {

			return _each( json.textures, function ( texture ) {

1863
				if ( texture.source !== undefined ) {
D
Don McCurdy 已提交
1864 1865 1866 1867 1868 1869

					return new Promise( function ( resolve ) {

						var source = json.images[ texture.source ];
						var sourceUri = source.uri;

D
Don McCurdy 已提交
1870 1871
						var urlCreator;

1872
						if ( source.bufferView !== undefined ) {
D
Don McCurdy 已提交
1873

1874
							var bufferView = dependencies.bufferViews[ source.bufferView ];
1875
							var blob = new Blob( [ bufferView ], { type: source.mimeType } );
D
Don McCurdy 已提交
1876
							urlCreator = window.URL || window.webkitURL;
1877
							sourceUri = urlCreator.createObjectURL( blob );
D
Don McCurdy 已提交
1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892

						}

						var textureLoader = THREE.Loader.Handlers.get( sourceUri );

						if ( textureLoader === null ) {

							textureLoader = new THREE.TextureLoader();

						}

						textureLoader.setCrossOrigin( options.crossOrigin );

						textureLoader.load( resolveURL( sourceUri, options.path ), function ( _texture ) {

D
Don McCurdy 已提交
1893 1894 1895 1896 1897 1898
							if ( urlCreator !== undefined ) {

								urlCreator.revokeObjectURL( sourceUri );

							}

D
Don McCurdy 已提交
1899 1900 1901 1902 1903 1904 1905 1906
							_texture.flipY = false;

							if ( texture.name !== undefined ) _texture.name = texture.name;

							_texture.format = texture.format !== undefined ? WEBGL_TEXTURE_FORMATS[ texture.format ] : THREE.RGBAFormat;

							if ( texture.internalFormat !== undefined && _texture.format !== WEBGL_TEXTURE_FORMATS[ texture.internalFormat ] ) {

M
Mugen87 已提交
1907
								console.warn( 'THREE.GLTF2Loader: Three.js does not support texture internalFormat which is different from texture format. ' +
1908
															'internalFormat will be forced to be the same value as format.' );
D
Don McCurdy 已提交
1909 1910 1911 1912 1913

							}

							_texture.type = texture.type !== undefined ? WEBGL_TEXTURE_DATATYPES[ texture.type ] : THREE.UnsignedByteType;

T
Takahiro 已提交
1914 1915
							var samplers = json.samplers || {};
							var sampler = samplers[ texture.sampler ] || {};
D
Don McCurdy 已提交
1916

1917
							_texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || THREE.LinearFilter;
1918
							_texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || THREE.LinearMipMapLinearFilter;
1919 1920
							_texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || THREE.RepeatWrapping;
							_texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || THREE.RepeatWrapping;
D
Don McCurdy 已提交
1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942

							resolve( _texture );

						}, undefined, function () {

							resolve();

						} );

					} );

				}

			} );

		} );

	};

	GLTFParser.prototype.loadMaterials = function () {

		var json = this.json;
1943
		var extensions = this.extensions;
D
Don McCurdy 已提交
1944 1945 1946

		return this._withDependencies( [

1947 1948
			'shaders',
			'textures'
D
Don McCurdy 已提交
1949 1950 1951 1952 1953 1954 1955

		] ).then( function ( dependencies ) {

			return _each( json.materials, function ( material ) {

				var materialType;
				var materialParams = {};
1956
				var materialExtensions = material.extensions || {};
D
Don McCurdy 已提交
1957

1958
				if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_COMMON ] ) {
1959

1960 1961
					materialType = extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ].getMaterialType( material );
					extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ].extendParams( materialParams, material, dependencies );
1962

1963
				} else if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] ) {
1964

1965
					materialType = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].getMaterialType( material );
1966
					extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].extendParams( materialParams, material, dependencies );
1967

1968
				} else if ( materialExtensions[ EXTENSIONS.KHR_TECHNIQUE_WEBGL ] ) {
1969

1970
					materialType = extensions[ EXTENSIONS.KHR_TECHNIQUE_WEBGL ].getMaterialType( material );
1971
					extensions[ EXTENSIONS.KHR_TECHNIQUE_WEBGL ].extendParams( materialParams, material, dependencies );
1972

1973
				} else if ( material.pbrMetallicRoughness !== undefined ) {
1974

1975 1976
					// Specification:
					// https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
1977

1978
					materialType = THREE.MeshStandardMaterial;
1979

1980
					var metallicRoughness = material.pbrMetallicRoughness;
1981

1982 1983
					materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
					materialParams.opacity = 1.0;
1984

1985
					if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
1986

1987
						var array = metallicRoughness.baseColorFactor;
1988

1989 1990
						materialParams.color.fromArray( array );
						materialParams.opacity = array[ 3 ];
1991 1992 1993

					}

1994
					if ( metallicRoughness.baseColorTexture !== undefined ) {
1995

1996
						materialParams.map = dependencies.textures[ metallicRoughness.baseColorTexture.index ];
1997 1998 1999

					}

2000 2001
					materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
					materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
2002

2003
					if ( metallicRoughness.metallicRoughnessTexture !== undefined ) {
2004

2005 2006 2007
						var textureIndex = metallicRoughness.metallicRoughnessTexture.index;
						materialParams.metalnessMap = dependencies.textures[ textureIndex ];
						materialParams.roughnessMap = dependencies.textures[ textureIndex ];
2008 2009 2010

					}

D
Don McCurdy 已提交
2011 2012
				} else {

2013
					materialType = THREE.MeshPhongMaterial;
D
Don McCurdy 已提交
2014

2015
				}
D
Don McCurdy 已提交
2016

2017
				if ( material.doubleSided === true ) {
D
Don McCurdy 已提交
2018

2019
					materialParams.side = THREE.DoubleSide;
D
Don McCurdy 已提交
2020 2021 2022

				}

2023 2024 2025
				var alphaMode = material.alphaMode || ALPHA_MODES.OPAQUE;

				if ( alphaMode !== ALPHA_MODES.OPAQUE ) {
D
Don McCurdy 已提交
2026

2027
					materialParams.transparent = true;
D
Don McCurdy 已提交
2028

2029
				} else {
D
Don McCurdy 已提交
2030

2031
					materialParams.transparent = false;
D
Don McCurdy 已提交
2032 2033 2034

				}

2035
				if ( material.normalTexture !== undefined ) {
D
Don McCurdy 已提交
2036

2037
					materialParams.normalMap = dependencies.textures[ material.normalTexture.index ];
D
Don McCurdy 已提交
2038 2039 2040

				}

2041
				if ( material.occlusionTexture !== undefined ) {
D
Don McCurdy 已提交
2042

2043
					materialParams.aoMap = dependencies.textures[ material.occlusionTexture.index ];
D
Don McCurdy 已提交
2044 2045 2046

				}

2047
				if ( material.emissiveFactor !== undefined ) {
D
Don McCurdy 已提交
2048 2049 2050

					if ( materialType === THREE.MeshBasicMaterial ) {

2051
						materialParams.color = new THREE.Color().fromArray( material.emissiveFactor );
D
Don McCurdy 已提交
2052 2053 2054

					} else {

2055
						materialParams.emissive = new THREE.Color().fromArray( material.emissiveFactor );
D
Don McCurdy 已提交
2056 2057 2058

					}

2059 2060 2061
				}

				if ( material.emissiveTexture !== undefined ) {
D
Don McCurdy 已提交
2062 2063 2064

					if ( materialType === THREE.MeshBasicMaterial ) {

2065
						materialParams.map = dependencies.textures[ material.emissiveTexture.index ];
D
Don McCurdy 已提交
2066 2067 2068

					} else {

2069
						materialParams.emissiveMap = dependencies.textures[ material.emissiveTexture.index ];
D
Don McCurdy 已提交
2070 2071 2072 2073 2074

					}

				}

2075 2076 2077 2078
				var _material;

				if ( materialType === THREE.ShaderMaterial ) {

2079
					_material = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].createMaterial( materialParams );
2080 2081 2082 2083 2084 2085 2086

				} else {

					_material = new materialType( materialParams );

				}

D
Don McCurdy 已提交
2087 2088
				if ( material.name !== undefined ) _material.name = material.name;

2089 2090 2091 2092
				// Normal map textures use OpenGL conventions:
				// https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#materialnormaltexture
				_material.normalScale.x = -1;

D
Don McCurdy 已提交
2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106
				return _material;

			} );

		} );

	};

	GLTFParser.prototype.loadMeshes = function () {

		var json = this.json;

		return this._withDependencies( [

M
Mugen87 已提交
2107 2108
			'accessors',
			'materials'
D
Don McCurdy 已提交
2109 2110 2111 2112 2113

		] ).then( function ( dependencies ) {

			return _each( json.meshes, function ( mesh ) {

2114
				var group = new THREE.Group();
D
Don McCurdy 已提交
2115 2116 2117 2118 2119 2120 2121 2122 2123 2124
				if ( mesh.name !== undefined ) group.name = mesh.name;

				if ( mesh.extras ) group.userData = mesh.extras;

				var primitives = mesh.primitives || [];

				for ( var name in primitives ) {

					var primitive = primitives[ name ];

D
Don McCurdy 已提交
2125 2126
					var material = primitive.material !== undefined ? dependencies.materials[ primitive.material ] : createDefaultMaterial();

2127 2128
					var geometry;

D
Don McCurdy 已提交
2129 2130
					var meshNode;

D
Don McCurdy 已提交
2131 2132
					if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES || primitive.mode === undefined ) {

2133
						geometry = new THREE.BufferGeometry();
D
Don McCurdy 已提交
2134 2135 2136 2137 2138 2139 2140

						var attributes = primitive.attributes;

						for ( var attributeId in attributes ) {

							var attributeEntry = attributes[ attributeId ];

2141
							if ( attributeEntry === undefined ) return;
D
Don McCurdy 已提交
2142 2143 2144 2145 2146 2147

							var bufferAttribute = dependencies.accessors[ attributeEntry ];

							switch ( attributeId ) {

								case 'POSITION':
2148

D
Don McCurdy 已提交
2149 2150 2151 2152
									geometry.addAttribute( 'position', bufferAttribute );
									break;

								case 'NORMAL':
2153

D
Don McCurdy 已提交
2154 2155 2156 2157 2158 2159
									geometry.addAttribute( 'normal', bufferAttribute );
									break;

								case 'TEXCOORD_0':
								case 'TEXCOORD0':
								case 'TEXCOORD':
2160

D
Don McCurdy 已提交
2161 2162 2163
									geometry.addAttribute( 'uv', bufferAttribute );
									break;

S
Steven Vergenz 已提交
2164
								case 'TEXCOORD_1':
2165

S
Steven Vergenz 已提交
2166 2167 2168
									geometry.addAttribute( 'uv2', bufferAttribute );
									break;

D
Don McCurdy 已提交
2169 2170 2171
								case 'COLOR_0':
								case 'COLOR0':
								case 'COLOR':
2172

D
Don McCurdy 已提交
2173 2174 2175
									geometry.addAttribute( 'color', bufferAttribute );
									break;

2176 2177 2178
								case 'WEIGHTS_0':
								case 'WEIGHT': // WEIGHT semantic deprecated.

D
Don McCurdy 已提交
2179 2180 2181
									geometry.addAttribute( 'skinWeight', bufferAttribute );
									break;

2182 2183 2184
								case 'JOINTS_0':
								case 'JOINT': // JOINT semantic deprecated.

D
Don McCurdy 已提交
2185 2186 2187 2188 2189 2190 2191
									geometry.addAttribute( 'skinIndex', bufferAttribute );
									break;

							}

						}

2192
						if ( primitive.indices !== undefined ) {
D
Don McCurdy 已提交
2193 2194 2195 2196 2197

							geometry.setIndex( dependencies.accessors[ primitive.indices ] );

						}

2198
						if ( material.aoMap
2199 2200 2201
								&& geometry.attributes.uv2 === undefined
								&& geometry.attributes.uv !== undefined ) {

M
Mugen87 已提交
2202
							console.log( 'THREE.GLTF2Loader: Duplicating UVs to support aoMap.' );
2203 2204 2205 2206
							geometry.addAttribute( 'uv2', new THREE.BufferAttribute( geometry.attributes.uv.array, 2 ) );

						}

D
Don McCurdy 已提交
2207
						meshNode = new THREE.Mesh( geometry, material );
D
Don McCurdy 已提交
2208 2209
						meshNode.castShadow = true;

T
Takahiro 已提交
2210 2211 2212 2213 2214
						if ( primitive.targets !== undefined ) {

							var targets = primitive.targets;
							var morphAttributes = geometry.morphAttributes;

T
Takahiro 已提交
2215 2216 2217 2218 2219
							morphAttributes.position = [];
							morphAttributes.normal = [];

							material.morphTargets = true;

T
Takahiro 已提交
2220 2221 2222
							for ( var i = 0, il = targets.length; i < il; i ++ ) {

								var target = targets[ i ];
2223
								var attributeName = 'morphTarget' + i;
T
Takahiro 已提交
2224

T
Takahiro 已提交
2225
								var positionAttribute, normalAttribute;
T
Takahiro 已提交
2226

T
Takahiro 已提交
2227
								if ( target.POSITION !== undefined ) {
T
Takahiro 已提交
2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239

									// Three.js morph formula is
									//   position
									//     + weight0 * ( morphTarget0 - position )
									//     + weight1 * ( morphTarget1 - position )
									//     ...
									// while the glTF one is
									//   position
									//     + weight0 * morphTarget0
									//     + weight1 * morphTarget1
									//     ...
									// then adding position to morphTarget.
T
Takahiro 已提交
2240 2241
									// So morphTarget value will depend on mesh's position, then cloning attribute
									// for the case if attribute is shared among two or more meshes.
T
Takahiro 已提交
2242

T
Takahiro 已提交
2243
									positionAttribute = dependencies.accessors[ target.POSITION ].clone();
T
Takahiro 已提交
2244 2245
									var position = geometry.attributes.position;

2246 2247 2248 2249 2250 2251 2252 2253
									for ( var j = 0, jl = positionAttribute.count; j < jl; j ++ ) {

										positionAttribute.setXYZ(
											j,
											positionAttribute.getX( j ) + position.getX( j ),
											positionAttribute.getY( j ) + position.getY( j ),
											positionAttribute.getZ( j ) + position.getZ( j )
										);
T
Takahiro 已提交
2254 2255 2256

									}

2257
								} else if ( geometry.attributes.position ) {
T
Takahiro 已提交
2258 2259 2260 2261

									// Copying the original position not to affect the final position.
									// See the formula above.
									positionAttribute = geometry.attributes.position.clone();
T
Takahiro 已提交
2262 2263 2264 2265 2266 2267 2268 2269 2270

								}

								if ( target.NORMAL !== undefined ) {

									material.morphNormals = true;

									// see target.POSITION's comment

T
Takahiro 已提交
2271
									normalAttribute = dependencies.accessors[ target.NORMAL ].clone();
T
Takahiro 已提交
2272 2273
									var normal = geometry.attributes.normal;

2274 2275 2276 2277 2278 2279 2280 2281
									for ( var j = 0, jl = normalAttribute.count; j < jl; j ++ ) {

										normalAttribute.setXYZ(
											j,
											normalAttribute.getX( j ) + normal.getX( j ),
											normalAttribute.getY( j ) + normal.getY( j ),
											normalAttribute.getZ( j ) + normal.getZ( j )
										);
T
Takahiro 已提交
2282 2283 2284

									}

2285
								} else if ( geometry.attributes.normal ) {
T
Takahiro 已提交
2286 2287

									normalAttribute = geometry.attributes.normal.clone();
T
Takahiro 已提交
2288 2289 2290 2291 2292 2293 2294 2295

								}

								// TODO: implement
								if ( target.TANGENT !== undefined ) {

								}

2296 2297 2298 2299 2300 2301 2302 2303
								if ( positionAttribute ) {

									positionAttribute.name = attributeName;
									morphAttributes.position.push( positionAttribute );

								}

								if ( normalAttribute ) {
T
Takahiro 已提交
2304

2305 2306 2307 2308
									normalAttribute.name = attributeName;
									morphAttributes.normal.push( normalAttribute );

								}
T
Takahiro 已提交
2309

T
Takahiro 已提交
2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325
							}

							meshNode.updateMorphTargets();

							if ( mesh.weights !== undefined ) {

								for ( var i = 0, il = mesh.weights.length; i < il; i ++ ) {

									meshNode.morphTargetInfluences[ i ] = mesh.weights[ i ];

								}

							}

						}

D
Don McCurdy 已提交
2326 2327
					} else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {

2328
						geometry = new THREE.BufferGeometry();
D
Don McCurdy 已提交
2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355

						var attributes = primitive.attributes;

						for ( var attributeId in attributes ) {

							var attributeEntry = attributes[ attributeId ];

							if ( ! attributeEntry ) return;

							var bufferAttribute = dependencies.accessors[ attributeEntry ];

							switch ( attributeId ) {

								case 'POSITION':
									geometry.addAttribute( 'position', bufferAttribute );
									break;

								case 'COLOR_0':
								case 'COLOR0':
								case 'COLOR':
									geometry.addAttribute( 'color', bufferAttribute );
									break;

							}

						}

2356
						if ( primitive.indices !== undefined ) {
D
Don McCurdy 已提交
2357 2358 2359 2360 2361

							geometry.setIndex( dependencies.accessors[ primitive.indices ] );

						}

D
Don McCurdy 已提交
2362 2363
						meshNode = new THREE.LineSegments( geometry, material );

D
Don McCurdy 已提交
2364 2365
					} else {

M
Mugen87 已提交
2366
						throw new Error( 'THREE.GLTF2Loader: Only triangular and line primitives are supported.' );
D
Don McCurdy 已提交
2367 2368 2369

					}

2370
					if ( geometry.attributes.color !== undefined ) {
D
Don McCurdy 已提交
2371

2372 2373
						material.vertexColors = THREE.VertexColors;
						material.needsUpdate = true;
D
Don McCurdy 已提交
2374 2375 2376

					}

2377
					meshNode.name = group.name + '_' + name;
D
Don McCurdy 已提交
2378 2379 2380 2381 2382

					if ( primitive.extras ) meshNode.userData = primitive.extras;

					group.add( meshNode );

D
Don McCurdy 已提交
2383 2384 2385 2386 2387 2388 2389 2390 2391 2392
				}

				return group;

			} );

		} );

	};

2393 2394 2395
	/**
	 * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
	 */
D
Don McCurdy 已提交
2396 2397 2398 2399 2400 2401
	GLTFParser.prototype.loadCameras = function () {

		var json = this.json;

		return _each( json.cameras, function ( camera ) {

2402
			var _camera;
D
Don McCurdy 已提交
2403

2404
			var params = camera[ camera.type ];
D
Don McCurdy 已提交
2405

2406
			if ( !params ) {
D
Don McCurdy 已提交
2407

M
Mugen87 已提交
2408
				console.warn( 'THREE.GLTF2Loader: Missing camera parameters.' );
2409
				return;
D
Don McCurdy 已提交
2410

2411
			}
D
Don McCurdy 已提交
2412

2413
			if ( camera.type === 'perspective' ) {
D
Don McCurdy 已提交
2414

2415 2416
				var aspectRatio = params.aspectRatio || 1;
				var xfov = params.yfov * aspectRatio;
D
Don McCurdy 已提交
2417

2418
				_camera = new THREE.PerspectiveCamera( THREE.Math.radToDeg( xfov ), aspectRatio, params.znear || 1, params.zfar || 2e6 );
D
Don McCurdy 已提交
2419

2420
			} else if ( camera.type === 'orthographic' ) {
D
Don McCurdy 已提交
2421

2422
				_camera = new THREE.OrthographicCamera( params.xmag / -2, params.xmag / 2, params.ymag / 2, params.ymag / -2, params.znear, params.zfar );
D
Don McCurdy 已提交
2423 2424 2425

			}

2426 2427 2428 2429 2430
			if ( camera.name !== undefined ) _camera.name = camera.name;
			if ( camera.extras ) _camera.userData = camera.extras;

			return _camera;

D
Don McCurdy 已提交
2431 2432 2433 2434 2435 2436 2437 2438 2439 2440
		} );

	};

	GLTFParser.prototype.loadSkins = function () {

		var json = this.json;

		return this._withDependencies( [

M
Mugen87 已提交
2441
			'accessors'
D
Don McCurdy 已提交
2442 2443 2444 2445 2446 2447

		] ).then( function ( dependencies ) {

			return _each( json.skins, function ( skin ) {

				var _skin = {
D
Don McCurdy 已提交
2448
					joints: skin.joints,
D
Don McCurdy 已提交
2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465
					inverseBindMatrices: dependencies.accessors[ skin.inverseBindMatrices ]
				};

				return _skin;

			} );

		} );

	};

	GLTFParser.prototype.loadAnimations = function () {

		var json = this.json;

		return this._withDependencies( [

M
Mugen87 已提交
2466 2467
			'accessors',
			'nodes'
D
Don McCurdy 已提交
2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482

		] ).then( function ( dependencies ) {

			return _each( json.animations, function ( animation, animationId ) {

				var tracks = [];

				for ( var channelId in animation.channels ) {

					var channel = animation.channels[ channelId ];
					var sampler = animation.samplers[ channel.sampler ];

					if ( sampler ) {

						var target = channel.target;
2483
						var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
D
Don McCurdy 已提交
2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496
						var input = animation.parameters !== undefined ? animation.parameters[ sampler.input ] : sampler.input;
						var output = animation.parameters !== undefined ? animation.parameters[ sampler.output ] : sampler.output;

						var inputAccessor = dependencies.accessors[ input ];
						var outputAccessor = dependencies.accessors[ output ];

						var node = dependencies.nodes[ name ];

						if ( node ) {

							node.updateMatrix();
							node.matrixAutoUpdate = true;

T
Takahiro 已提交
2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518
							var TypedKeyframeTrack;

							switch ( PATH_PROPERTIES[ target.path ] ) {

								case PATH_PROPERTIES.weights:

									TypedKeyframeTrack = THREE.NumberKeyframeTrack;
									break;

								case PATH_PROPERTIES.rotation:

									TypedKeyframeTrack = THREE.QuaternionKeyframeTrack;
									break;

								case PATH_PROPERTIES.position:
								case PATH_PROPERTIES.scale:
								default:

									TypedKeyframeTrack = THREE.VectorKeyframeTrack;
									break;

							}
D
Don McCurdy 已提交
2519 2520

							var targetName = node.name ? node.name : node.uuid;
2521 2522 2523 2524 2525 2526 2527

							if ( sampler.interpolation === 'CATMULLROMSPLINE' ) {

								console.warn( 'THREE.GLTF2Loader: CATMULLROMSPLINE interpolation is not supported. Using CUBICSPLINE instead.' );

							}

D
Don McCurdy 已提交
2528 2529
							var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : THREE.InterpolateLinear;

T
Takahiro 已提交
2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554
							var targetNames = [];

							if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {

								// node should be THREE.Group here but
								// PATH_PROPERTIES.weights(morphTargetInfluences) should be
								// the property of a mesh object under node.
								// So finding targets here.

								node.traverse( function ( object ) {

									if ( object.isMesh === true && object.material.morphTargets === true ) {

										targetNames.push( object.name ? object.name : object.uuid );

									}

								} );

							} else {

								targetNames.push( targetName );

							}

D
Don McCurdy 已提交
2555 2556 2557
							// KeyframeTrack.optimize() will modify given 'times' and 'values'
							// buffers before creating a truncated copy to keep. Because buffers may
							// be reused by other tracks, make copies here.
T
Takahiro 已提交
2558 2559 2560 2561 2562 2563 2564 2565 2566 2567
							for ( var i = 0, il = targetNames.length; i < il; i ++ ) {

								tracks.push( new TypedKeyframeTrack(
									targetNames[ i ] + '.' + PATH_PROPERTIES[ target.path ],
									THREE.AnimationUtils.arraySlice( inputAccessor.array, 0 ),
									THREE.AnimationUtils.arraySlice( outputAccessor.array, 0 ),
									interpolation
								) );

							}
D
Don McCurdy 已提交
2568 2569 2570 2571 2572 2573 2574

						}

					}

				}

M
Mugen87 已提交
2575
				var name = animation.name !== undefined ? animation.name : 'animation_' + animationId;
D
Don McCurdy 已提交
2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590

				return new THREE.AnimationClip( name, undefined, tracks );

			} );

		} );

	};

	GLTFParser.prototype.loadNodes = function () {

		var json = this.json;
		var extensions = this.extensions;
		var scope = this;

D
Don McCurdy 已提交
2591
		var nodes = json.nodes || [];
2592
		var skins = json.skins || [];
D
Don McCurdy 已提交
2593

D
Don McCurdy 已提交
2594
		// Nothing in the node definition indicates whether it is a Bone or an
2595 2596
		// Object3D. Use the skins' joint references to mark bones.
		skins.forEach( function ( skin ) {
D
Don McCurdy 已提交
2597

2598
			skin.joints.forEach( function ( id ) {
D
Don McCurdy 已提交
2599

2600
				nodes[ id ].isBone = true;
D
Don McCurdy 已提交
2601

2602
			} );
D
Don McCurdy 已提交
2603

D
Don McCurdy 已提交
2604 2605 2606 2607 2608 2609 2610 2611 2612
		} );

		return _each( json.nodes, function ( node ) {

			var matrix = new THREE.Matrix4();

			var _node = node.isBone === true ? new THREE.Bone() : new THREE.Object3D();

			if ( node.name !== undefined ) {
D
Don McCurdy 已提交
2613

D
Don McCurdy 已提交
2614
				_node.name = THREE.PropertyBinding.sanitizeNodeName( node.name );
D
Don McCurdy 已提交
2615 2616 2617

			}

D
Don McCurdy 已提交
2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652
			if ( node.extras ) _node.userData = node.extras;

			if ( node.matrix !== undefined ) {

				matrix.fromArray( node.matrix );
				_node.applyMatrix( matrix );

			} else {

				if ( node.translation !== undefined ) {

					_node.position.fromArray( node.translation );

				}

				if ( node.rotation !== undefined ) {

					_node.quaternion.fromArray( node.rotation );

				}

				if ( node.scale !== undefined ) {

					_node.scale.fromArray( node.scale );

				}

			}

			return _node;

		} ).then( function ( __nodes ) {

			return scope._withDependencies( [

M
Mugen87 已提交
2653 2654 2655
				'meshes',
				'skins',
				'cameras'
D
Don McCurdy 已提交
2656 2657 2658 2659 2660 2661 2662

			] ).then( function ( dependencies ) {

				return _each( __nodes, function ( _node, nodeId ) {

					var node = json.nodes[ nodeId ];

2663 2664 2665 2666 2667 2668 2669 2670
					var meshes;

					if ( node.mesh !== undefined) {

						meshes = [ node.mesh ];

					} else if ( node.meshes !== undefined ) {

M
Mugen87 已提交
2671
						console.warn( 'THREE.GLTF2Loader: Legacy glTF file detected. Nodes may have no more than one mesh.' );
2672 2673 2674 2675 2676 2677

						meshes = node.meshes;

					}

					if ( meshes !== undefined ) {
D
Don McCurdy 已提交
2678

2679
						for ( var meshId in meshes ) {
D
Don McCurdy 已提交
2680

2681
							var mesh = meshes[ meshId ];
D
Don McCurdy 已提交
2682 2683 2684 2685
							var group = dependencies.meshes[ mesh ];

							if ( group === undefined ) {

M
Mugen87 已提交
2686
								console.warn( 'THREE.GLTF2Loader: Could not find node "' + mesh + '".' );
D
Don McCurdy 已提交
2687 2688 2689 2690
								continue;

							}

2691
							//do not clone children as they will be replaced anyway
2692
							var clonedgroup = group.clone( false );
D
Don McCurdy 已提交
2693 2694 2695 2696 2697 2698 2699 2700
							for ( var childrenId in group.children ) {

								var child = group.children[ childrenId ];

								// clone Mesh to add to _node

								var originalMaterial = child.material;
								var originalGeometry = child.geometry;
2701
								var originalInfluences = child.morphTargetInfluences;
D
Don McCurdy 已提交
2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731
								var originalUserData = child.userData;
								var originalName = child.name;

								var material;

								if ( originalMaterial.isDeferredShaderMaterial ) {

									originalMaterial = material = originalMaterial.create();

								} else {

									material = originalMaterial;

								}

								switch ( child.type ) {

									case 'LineSegments':
										child = new THREE.LineSegments( originalGeometry, material );
										break;

									case 'LineLoop':
										child = new THREE.LineLoop( originalGeometry, material );
										break;

									case 'Line':
										child = new THREE.Line( originalGeometry, material );
										break;

									default:
2732
										child = new THREE.Mesh( originalGeometry, material );
D
Don McCurdy 已提交
2733 2734 2735 2736

								}

								child.castShadow = true;
2737
								child.morphTargetInfluences = originalInfluences;
D
Don McCurdy 已提交
2738 2739 2740 2741 2742
								child.userData = originalUserData;
								child.name = originalName;

								var skinEntry;

T
Takahiro 已提交
2743
								if ( node.skin !== undefined ) {
D
Don McCurdy 已提交
2744 2745 2746 2747 2748 2749 2750 2751 2752

									skinEntry = dependencies.skins[ node.skin ];

								}

								// Replace Mesh with SkinnedMesh in library
								if ( skinEntry ) {

									var geometry = originalGeometry;
D
Don McCurdy 已提交
2753
									material = originalMaterial;
2754
									material.skinning = true;
D
Don McCurdy 已提交
2755

2756
									child = new THREE.SkinnedMesh( geometry, material );
D
Don McCurdy 已提交
2757 2758 2759 2760 2761 2762 2763
									child.castShadow = true;
									child.userData = originalUserData;
									child.name = originalName;

									var bones = [];
									var boneInverses = [];

D
Don McCurdy 已提交
2764
									for ( var i = 0, l = skinEntry.joints.length; i < l; i ++ ) {
D
Don McCurdy 已提交
2765

D
Don McCurdy 已提交
2766 2767
										var jointId = skinEntry.joints[ i ];
										var jointNode = __nodes[ jointId ];
D
Don McCurdy 已提交
2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778

										if ( jointNode ) {

											bones.push( jointNode );

											var m = skinEntry.inverseBindMatrices.array;
											var mat = new THREE.Matrix4().fromArray( m, i * 16 );
											boneInverses.push( mat );

										} else {

M
Mugen87 已提交
2779
											console.warn( 'THREE.GLTF2Loader: Joint "%s" could not be found.', jointId );
D
Don McCurdy 已提交
2780 2781 2782 2783 2784

										}

									}

2785
									child.bind( new THREE.Skeleton( bones, boneInverses ), child.matrixWorld );
D
Don McCurdy 已提交
2786 2787 2788 2789

								}


2790
								clonedgroup.add(child);
D
Don McCurdy 已提交
2791
							}
2792
							_node.add( clonedgroup );
D
Don McCurdy 已提交
2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805
						}

					}

					if ( node.camera !== undefined ) {

						var camera = dependencies.cameras[ node.camera ];

						_node.add( camera );

					}

					if ( node.extensions
2806 2807
							 && node.extensions[ EXTENSIONS.KHR_LIGHTS ]
							 && node.extensions[ EXTENSIONS.KHR_LIGHTS ].light !== undefined ) {
D
Don McCurdy 已提交
2808

2809 2810
						var lights = extensions[ EXTENSIONS.KHR_LIGHTS ].lights;
						_node.add( lights[ node.extensions[ EXTENSIONS.KHR_LIGHTS ].light ] );
D
Don McCurdy 已提交
2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826

					}

					return _node;

				} );

			} );

		} );

	};

	GLTFParser.prototype.loadScenes = function () {

		var json = this.json;
2827
		var extensions = this.extensions;
D
Don McCurdy 已提交
2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854

		// scene node hierachy builder

		function buildNodeHierachy( nodeId, parentObject, allNodes ) {

			var _node = allNodes[ nodeId ];
			parentObject.add( _node );

			var node = json.nodes[ nodeId ];

			if ( node.children ) {

				var children = node.children;

				for ( var i = 0, l = children.length; i < l; i ++ ) {

					var child = children[ i ];
					buildNodeHierachy( child, _node, allNodes );

				}

			}

		}

		return this._withDependencies( [

M
Mugen87 已提交
2855
			'nodes'
D
Don McCurdy 已提交
2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879

		] ).then( function ( dependencies ) {

			return _each( json.scenes, function ( scene ) {

				var _scene = new THREE.Scene();
				if ( scene.name !== undefined ) _scene.name = scene.name;

				if ( scene.extras ) _scene.userData = scene.extras;

				var nodes = scene.nodes || [];

				for ( var i = 0, l = nodes.length; i < l; i ++ ) {

					var nodeId = nodes[ i ];
					buildNodeHierachy( nodeId, _scene, dependencies.nodes );

				}

				_scene.traverse( function ( child ) {

					// Register raw material meshes with GLTF2Loader.Shaders
					if ( child.material && child.material.isRawShaderMaterial ) {

2880 2881 2882 2883
						child.gltfShader = new GLTFShader( child, dependencies.nodes );
						child.onBeforeRender = function(renderer, scene, camera){
							this.gltfShader.update(scene, camera);
						};
D
Don McCurdy 已提交
2884 2885 2886

					}

2887
					// for Specular-Glossiness.
2888
					if ( child.material && child.material.isGLTFSpecularGlossinessMaterial ) {
2889

2890
						child.onBeforeRender = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].refreshUniforms;
2891 2892 2893

					}

D
Don McCurdy 已提交
2894 2895
				} );

2896 2897 2898 2899 2900 2901 2902 2903 2904 2905
				// Ambient lighting, if present, is always attached to the scene root.
				if ( scene.extensions
							 && scene.extensions[ EXTENSIONS.KHR_LIGHTS ]
							 && scene.extensions[ EXTENSIONS.KHR_LIGHTS ].light !== undefined ) {

					var lights = extensions[ EXTENSIONS.KHR_LIGHTS ].lights;
					_scene.add( lights[ scene.extensions[ EXTENSIONS.KHR_LIGHTS ].light ] );

				}

D
Don McCurdy 已提交
2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916
				return _scene;

			} );

		} );

	};

	return GLTF2Loader;

} )();