ColladaLoader.js 79.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
import {
	AmbientLight,
	AnimationClip,
	Bone,
	BufferGeometry,
	ClampToEdgeWrapping,
	Color,
	DirectionalLight,
	DoubleSide,
	Euler,
	FileLoader,
	Float32BufferAttribute,
	Group,
	Line,
	LineBasicMaterial,
	LineSegments,
17
	Loader,
18
	LoaderUtils,
M
Mugen87 已提交
19
	MathUtils,
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
	Matrix4,
	Mesh,
	MeshBasicMaterial,
	MeshLambertMaterial,
	MeshPhongMaterial,
	OrthographicCamera,
	PerspectiveCamera,
	PointLight,
	Quaternion,
	QuaternionKeyframeTrack,
	RepeatWrapping,
	Scene,
	Skeleton,
	SkinnedMesh,
	SpotLight,
	TextureLoader,
	Vector3,
	VectorKeyframeTrack
38 39
} from '../../../build/three.module.js';
import { TGALoader } from '../loaders/TGALoader.js';
40

41
class ColladaLoader extends Loader {
42

43
	constructor( manager ) {
44

45
		super( manager );
46

47
	}
48

49
	load( url, onLoad, onProgress, onError ) {
50

51
		const scope = this;
52

53
		const path = ( scope.path === '' ) ? LoaderUtils.extractUrlBase( url ) : scope.path;
54

55
		const loader = new FileLoader( scope.manager );
56
		loader.setPath( scope.path );
57
		loader.setRequestHeader( scope.requestHeader );
58
		loader.setWithCredentials( scope.withCredentials );
59 60
		loader.load( url, function ( text ) {

M
Mugen87 已提交
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
			try {

				onLoad( scope.parse( text, path ) );

			} catch ( e ) {

				if ( onError ) {

					onError( e );

				} else {

					console.error( e );

				}

				scope.manager.itemError( url );

			}
80 81 82

		}, onProgress, onError );

83
	}
84

85
	parse( text, path ) {
86 87 88 89 90

		function getElementsByTagName( xml, name ) {

			// Non recursive xml.getElementsByTagName() ...

91 92
			const array = [];
			const childNodes = xml.childNodes;
93

94
			for ( let i = 0, l = childNodes.length; i < l; i ++ ) {
95

96
				const child = childNodes[ i ];
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113

				if ( child.nodeName === name ) {

					array.push( child );

				}

			}

			return array;

		}

		function parseStrings( text ) {

			if ( text.length === 0 ) return [];

114 115
			const parts = text.trim().split( /\s+/ );
			const array = new Array( parts.length );
116

117
			for ( let i = 0, l = parts.length; i < l; i ++ ) {
118 119 120 121 122 123 124 125 126 127 128 129 130

				array[ i ] = parts[ i ];

			}

			return array;

		}

		function parseFloats( text ) {

			if ( text.length === 0 ) return [];

131 132
			const parts = text.trim().split( /\s+/ );
			const array = new Array( parts.length );
133

134
			for ( let i = 0, l = parts.length; i < l; i ++ ) {
135 136 137 138 139 140 141 142 143 144 145 146 147

				array[ i ] = parseFloat( parts[ i ] );

			}

			return array;

		}

		function parseInts( text ) {

			if ( text.length === 0 ) return [];

148 149
			const parts = text.trim().split( /\s+/ );
			const array = new Array( parts.length );
150

151
			for ( let i = 0, l = parts.length; i < l; i ++ ) {
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

				array[ i ] = parseInt( parts[ i ] );

			}

			return array;

		}

		function parseId( text ) {

			return text.substring( 1 );

		}

		function generateId() {

			return 'three_default_' + ( count ++ );

		}

		function isEmpty( object ) {

			return Object.keys( object ).length === 0;

		}

		// asset

		function parseAsset( xml ) {

			return {
				unit: parseAssetUnit( getElementsByTagName( xml, 'unit' )[ 0 ] ),
				upAxis: parseAssetUpAxis( getElementsByTagName( xml, 'up_axis' )[ 0 ] )
			};

		}

		function parseAssetUnit( xml ) {

			if ( ( xml !== undefined ) && ( xml.hasAttribute( 'meter' ) === true ) ) {

				return parseFloat( xml.getAttribute( 'meter' ) );

			} else {

				return 1; // default 1 meter

			}

		}

		function parseAssetUpAxis( xml ) {

			return xml !== undefined ? xml.textContent : 'Y_UP';

		}

		// library

		function parseLibrary( xml, libraryName, nodeName, parser ) {

214
			const library = getElementsByTagName( xml, libraryName )[ 0 ];
215 216 217

			if ( library !== undefined ) {

218
				const elements = getElementsByTagName( library, nodeName );
219

220
				for ( let i = 0; i < elements.length; i ++ ) {
221 222 223 224 225 226 227 228 229 230 231

					parser( elements[ i ] );

				}

			}

		}

		function buildLibrary( data, builder ) {

232
			for ( const name in data ) {
233

234
				const object = data[ name ];
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
				object.build = builder( data[ name ] );

			}

		}

		// get

		function getBuild( data, builder ) {

			if ( data.build !== undefined ) return data.build;

			data.build = builder( data );

			return data.build;

		}

		// animation

		function parseAnimation( xml ) {

257
			const data = {
258 259 260 261 262
				sources: {},
				samplers: {},
				channels: {}
			};

263
			let hasChildren = false;
264

265
			for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
266

267
				const child = xml.childNodes[ i ];
268 269 270

				if ( child.nodeType !== 1 ) continue;

271
				let id;
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289

				switch ( child.nodeName ) {

					case 'source':
						id = child.getAttribute( 'id' );
						data.sources[ id ] = parseSource( child );
						break;

					case 'sampler':
						id = child.getAttribute( 'id' );
						data.samplers[ id ] = parseAnimationSampler( child );
						break;

					case 'channel':
						id = child.getAttribute( 'target' );
						data.channels[ id ] = parseAnimationChannel( child );
						break;

290 291 292 293 294 295
					case 'animation':
						// hierarchy of related animations
						parseAnimation( child );
						hasChildren = true;
						break;

296 297 298 299 300 301 302
					default:
						console.log( child );

				}

			}

303 304 305 306 307 308 309
			if ( hasChildren === false ) {

				// since 'id' attributes can be optional, it's necessary to generate a UUID for unqiue assignment

				library.animations[ xml.getAttribute( 'id' ) || MathUtils.generateUUID() ] = data;

			}
310 311 312 313 314

		}

		function parseAnimationSampler( xml ) {

315
			const data = {
316 317 318
				inputs: {},
			};

319
			for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
320

321
				const child = xml.childNodes[ i ];
322 323 324 325 326 327

				if ( child.nodeType !== 1 ) continue;

				switch ( child.nodeName ) {

					case 'input':
328 329
						const id = parseId( child.getAttribute( 'source' ) );
						const semantic = child.getAttribute( 'semantic' );
330 331 332 333 334 335 336 337 338 339 340 341 342
						data.inputs[ semantic ] = id;
						break;

				}

			}

			return data;

		}

		function parseAnimationChannel( xml ) {

343
			const data = {};
344

345
			const target = xml.getAttribute( 'target' );
346 347 348

			// parsing SID Addressing Syntax

349
			let parts = target.split( '/' );
350

351 352
			const id = parts.shift();
			let sid = parts.shift();
353 354 355

			// check selection syntax

356 357
			const arraySyntax = ( sid.indexOf( '(' ) !== - 1 );
			const memberSyntax = ( sid.indexOf( '.' ) !== - 1 );
358 359 360 361 362 363 364 365 366 367 368 369 370

			if ( memberSyntax ) {

				//  member selection access

				parts = sid.split( '.' );
				sid = parts.shift();
				data.member = parts.shift();

			} else if ( arraySyntax ) {

				// array-access syntax. can be used to express fields in one-dimensional vectors or two-dimensional matrices.

371
				const indices = sid.split( '(' );
372 373
				sid = indices.shift();

374
				for ( let i = 0; i < indices.length; i ++ ) {
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397

					indices[ i ] = parseInt( indices[ i ].replace( /\)/, '' ) );

				}

				data.indices = indices;

			}

			data.id = id;
			data.sid = sid;

			data.arraySyntax = arraySyntax;
			data.memberSyntax = memberSyntax;

			data.sampler = parseId( xml.getAttribute( 'source' ) );

			return data;

		}

		function buildAnimation( data ) {

398
			const tracks = [];
399

400 401 402
			const channels = data.channels;
			const samplers = data.samplers;
			const sources = data.sources;
403

404
			for ( const target in channels ) {
405 406 407

				if ( channels.hasOwnProperty( target ) ) {

408 409
					const channel = channels[ target ];
					const sampler = samplers[ channel.sampler ];
410

411 412
					const inputId = sampler.inputs.INPUT;
					const outputId = sampler.inputs.OUTPUT;
413

414 415
					const inputSource = sources[ inputId ];
					const outputSource = sources[ outputId ];
416

417
					const animation = buildAnimationChannel( channel, inputSource, outputSource );
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436

					createKeyframeTracks( animation, tracks );

				}

			}

			return tracks;

		}

		function getAnimation( id ) {

			return getBuild( library.animations[ id ], buildAnimation );

		}

		function buildAnimationChannel( channel, inputSource, outputSource ) {

437 438
			const node = library.nodes[ channel.id ];
			const object3D = getNode( node.id );
439

440 441
			const transform = node.transforms[ channel.sid ];
			const defaultMatrix = node.matrix.clone().transpose();
442

443 444
			let time, stride;
			let i, il, j, jl;
445

446
			const data = {};
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463

			// the collada spec allows the animation of data in various ways.
			// depending on the transform type (matrix, translate, rotate, scale), we execute different logic

			switch ( transform ) {

				case 'matrix':

					for ( i = 0, il = inputSource.array.length; i < il; i ++ ) {

						time = inputSource.array[ i ];
						stride = i * outputSource.stride;

						if ( data[ time ] === undefined ) data[ time ] = {};

						if ( channel.arraySyntax === true ) {

464 465
							const value = outputSource.array[ stride ];
							const index = channel.indices[ 0 ] + 4 * channel.indices[ 1 ];
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496

							data[ time ][ index ] = value;

						} else {

							for ( j = 0, jl = outputSource.stride; j < jl; j ++ ) {

								data[ time ][ j ] = outputSource.array[ stride + j ];

							}

						}

					}

					break;

				case 'translate':
					console.warn( 'THREE.ColladaLoader: Animation transform type "%s" not yet implemented.', transform );
					break;

				case 'rotate':
					console.warn( 'THREE.ColladaLoader: Animation transform type "%s" not yet implemented.', transform );
					break;

				case 'scale':
					console.warn( 'THREE.ColladaLoader: Animation transform type "%s" not yet implemented.', transform );
					break;

			}

497
			const keyframes = prepareAnimationData( data, defaultMatrix );
498

499
			const animation = {
500 501 502 503 504 505 506 507 508 509
				name: object3D.uuid,
				keyframes: keyframes
			};

			return animation;

		}

		function prepareAnimationData( data, defaultMatrix ) {

510
			const keyframes = [];
511 512 513

			// transfer data into a sortable array

514
			for ( const time in data ) {
515 516 517 518 519 520 521 522 523 524 525

				keyframes.push( { time: parseFloat( time ), value: data[ time ] } );

			}

			// ensure keyframes are sorted by time

			keyframes.sort( ascending );

			// now we clean up all animation data, so we can use them for keyframe tracks

526
			for ( let i = 0; i < 16; i ++ ) {
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543

				transformAnimationData( keyframes, i, defaultMatrix.elements[ i ] );

			}

			return keyframes;

			// array sort function

			function ascending( a, b ) {

				return a.time - b.time;

			}

		}

544 545 546
		const position = new Vector3();
		const scale = new Vector3();
		const quaternion = new Quaternion();
547 548 549

		function createKeyframeTracks( animation, tracks ) {

550 551
			const keyframes = animation.keyframes;
			const name = animation.name;
552

553 554 555 556
			const times = [];
			const positionData = [];
			const quaternionData = [];
			const scaleData = [];
557

558
			for ( let i = 0, l = keyframes.length; i < l; i ++ ) {
559

560
				const keyframe = keyframes[ i ];
561

562 563
				const time = keyframe.time;
				const value = keyframe.value;
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584

				matrix.fromArray( value ).transpose();
				matrix.decompose( position, quaternion, scale );

				times.push( time );
				positionData.push( position.x, position.y, position.z );
				quaternionData.push( quaternion.x, quaternion.y, quaternion.z, quaternion.w );
				scaleData.push( scale.x, scale.y, scale.z );

			}

			if ( positionData.length > 0 ) tracks.push( new VectorKeyframeTrack( name + '.position', times, positionData ) );
			if ( quaternionData.length > 0 ) tracks.push( new QuaternionKeyframeTrack( name + '.quaternion', times, quaternionData ) );
			if ( scaleData.length > 0 ) tracks.push( new VectorKeyframeTrack( name + '.scale', times, scaleData ) );

			return tracks;

		}

		function transformAnimationData( keyframes, property, defaultValue ) {

585
			let keyframe;
586

587 588
			let empty = true;
			let i, l;
589 590 591 592 593 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

			// check, if values of a property are missing in our keyframes

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

				keyframe = keyframes[ i ];

				if ( keyframe.value[ property ] === undefined ) {

					keyframe.value[ property ] = null; // mark as missing

				} else {

					empty = false;

				}

			}

			if ( empty === true ) {

				// no values at all, so we set a default value

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

					keyframe = keyframes[ i ];

					keyframe.value[ property ] = defaultValue;

				}

			} else {

				// filling gaps

				createMissingKeyframes( keyframes, property );

			}

		}

		function createMissingKeyframes( keyframes, property ) {

632
			let prev, next;
633

634
			for ( let i = 0, l = keyframes.length; i < l; i ++ ) {
635

636
				const keyframe = keyframes[ i ];
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668

				if ( keyframe.value[ property ] === null ) {

					prev = getPrev( keyframes, i, property );
					next = getNext( keyframes, i, property );

					if ( prev === null ) {

						keyframe.value[ property ] = next.value[ property ];
						continue;

					}

					if ( next === null ) {

						keyframe.value[ property ] = prev.value[ property ];
						continue;

					}

					interpolate( keyframe, prev, next, property );

				}

			}

		}

		function getPrev( keyframes, i, property ) {

			while ( i >= 0 ) {

669
				const keyframe = keyframes[ i ];
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684

				if ( keyframe.value[ property ] !== null ) return keyframe;

				i --;

			}

			return null;

		}

		function getNext( keyframes, i, property ) {

			while ( i < keyframes.length ) {

685
				const keyframe = keyframes[ i ];
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

				if ( keyframe.value[ property ] !== null ) return keyframe;

				i ++;

			}

			return null;

		}

		function interpolate( key, prev, next, property ) {

			if ( ( next.time - prev.time ) === 0 ) {

				key.value[ property ] = prev.value[ property ];
				return;

			}

			key.value[ property ] = ( ( key.time - prev.time ) * ( next.value[ property ] - prev.value[ property ] ) / ( next.time - prev.time ) ) + prev.value[ property ];

		}

		// animation clips

		function parseAnimationClip( xml ) {

714
			const data = {
715 716 717 718 719 720
				name: xml.getAttribute( 'id' ) || 'default',
				start: parseFloat( xml.getAttribute( 'start' ) || 0 ),
				end: parseFloat( xml.getAttribute( 'end' ) || 0 ),
				animations: []
			};

721
			for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
722

723
				const child = xml.childNodes[ i ];
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742

				if ( child.nodeType !== 1 ) continue;

				switch ( child.nodeName ) {

					case 'instance_animation':
						data.animations.push( parseId( child.getAttribute( 'url' ) ) );
						break;

				}

			}

			library.clips[ xml.getAttribute( 'id' ) ] = data;

		}

		function buildAnimationClip( data ) {

743
			const tracks = [];
744

745 746 747
			const name = data.name;
			const duration = ( data.end - data.start ) || - 1;
			const animations = data.animations;
748

749
			for ( let i = 0, il = animations.length; i < il; i ++ ) {
750

751
				const animationTracks = getAnimation( animations[ i ] );
752

753
				for ( let j = 0, jl = animationTracks.length; j < jl; j ++ ) {
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774

					tracks.push( animationTracks[ j ] );

				}

			}

			return new AnimationClip( name, duration, tracks );

		}

		function getAnimationClip( id ) {

			return getBuild( library.clips[ id ], buildAnimationClip );

		}

		// controller

		function parseController( xml ) {

775
			const data = {};
776

777
			for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
778

779
				const child = xml.childNodes[ i ];
780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805

				if ( child.nodeType !== 1 ) continue;

				switch ( child.nodeName ) {

					case 'skin':
						// there is exactly one skin per controller
						data.id = parseId( child.getAttribute( 'source' ) );
						data.skin = parseSkin( child );
						break;

					case 'morph':
						data.id = parseId( child.getAttribute( 'source' ) );
						console.warn( 'THREE.ColladaLoader: Morph target animation not supported yet.' );
						break;

				}

			}

			library.controllers[ xml.getAttribute( 'id' ) ] = data;

		}

		function parseSkin( xml ) {

806
			const data = {
807 808 809
				sources: {}
			};

810
			for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
811

812
				const child = xml.childNodes[ i ];
813 814 815 816 817 818 819 820 821 822

				if ( child.nodeType !== 1 ) continue;

				switch ( child.nodeName ) {

					case 'bind_shape_matrix':
						data.bindShapeMatrix = parseFloats( child.textContent );
						break;

					case 'source':
823
						const id = child.getAttribute( 'id' );
824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844
						data.sources[ id ] = parseSource( child );
						break;

					case 'joints':
						data.joints = parseJoints( child );
						break;

					case 'vertex_weights':
						data.vertexWeights = parseVertexWeights( child );
						break;

				}

			}

			return data;

		}

		function parseJoints( xml ) {

845
			const data = {
846 847 848
				inputs: {}
			};

849
			for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
850

851
				const child = xml.childNodes[ i ];
852 853 854 855 856 857

				if ( child.nodeType !== 1 ) continue;

				switch ( child.nodeName ) {

					case 'input':
858 859
						const semantic = child.getAttribute( 'semantic' );
						const id = parseId( child.getAttribute( 'source' ) );
860 861 862 863 864 865 866 867 868 869 870 871 872
						data.inputs[ semantic ] = id;
						break;

				}

			}

			return data;

		}

		function parseVertexWeights( xml ) {

873
			const data = {
874 875 876
				inputs: {}
			};

877
			for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
878

879
				const child = xml.childNodes[ i ];
880 881 882 883 884 885

				if ( child.nodeType !== 1 ) continue;

				switch ( child.nodeName ) {

					case 'input':
886 887 888
						const semantic = child.getAttribute( 'semantic' );
						const id = parseId( child.getAttribute( 'source' ) );
						const offset = parseInt( child.getAttribute( 'offset' ) );
889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909
						data.inputs[ semantic ] = { id: id, offset: offset };
						break;

					case 'vcount':
						data.vcount = parseInts( child.textContent );
						break;

					case 'v':
						data.v = parseInts( child.textContent );
						break;

				}

			}

			return data;

		}

		function buildController( data ) {

910
			const build = {
911 912 913
				id: data.id
			};

914
			const geometry = library.geometries[ build.id ];
915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932

			if ( data.skin !== undefined ) {

				build.skin = buildSkin( data.skin );

				// we enhance the 'sources' property of the corresponding geometry with our skin data

				geometry.sources.skinIndices = build.skin.indices;
				geometry.sources.skinWeights = build.skin.weights;

			}

			return build;

		}

		function buildSkin( data ) {

933
			const BONE_LIMIT = 4;
934

935
			const build = {
936 937 938 939 940 941 942 943 944 945 946
				joints: [], // this must be an array to preserve the joint order
				indices: {
					array: [],
					stride: BONE_LIMIT
				},
				weights: {
					array: [],
					stride: BONE_LIMIT
				}
			};

947 948
			const sources = data.sources;
			const vertexWeights = data.vertexWeights;
949

950 951 952 953
			const vcount = vertexWeights.vcount;
			const v = vertexWeights.v;
			const jointOffset = vertexWeights.inputs.JOINT.offset;
			const weightOffset = vertexWeights.inputs.WEIGHT.offset;
954

955 956
			const jointSource = data.sources[ data.joints.inputs.JOINT ];
			const inverseSource = data.sources[ data.joints.inputs.INV_BIND_MATRIX ];
957

958 959
			const weights = sources[ vertexWeights.inputs.WEIGHT.id ].array;
			let stride = 0;
960

961
			let i, j, l;
962 963 964 965 966

			// procces skin data for each vertex

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

967 968
				const jointCount = vcount[ i ]; // this is the amount of joints that affect a single vertex
				const vertexSkinData = [];
969 970 971

				for ( j = 0; j < jointCount; j ++ ) {

972 973 974
					const skinIndex = v[ stride + jointOffset ];
					const weightId = v[ stride + weightOffset ];
					const skinWeight = weights[ weightId ];
975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991

					vertexSkinData.push( { index: skinIndex, weight: skinWeight } );

					stride += 2;

				}

				// we sort the joints in descending order based on the weights.
				// this ensures, we only procced the most important joints of the vertex

				vertexSkinData.sort( descending );

				// now we provide for each vertex a set of four index and weight values.
				// the order of the skin data matches the order of vertices

				for ( j = 0; j < BONE_LIMIT; j ++ ) {

992
					const d = vertexSkinData[ j ];
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

					if ( d !== undefined ) {

						build.indices.array.push( d.index );
						build.weights.array.push( d.weight );

					} else {

						build.indices.array.push( 0 );
						build.weights.array.push( 0 );

					}

				}

			}

			// setup bind matrix

			if ( data.bindShapeMatrix ) {

				build.bindMatrix = new Matrix4().fromArray( data.bindShapeMatrix ).transpose();

			} else {

				build.bindMatrix = new Matrix4().identity();

			}

			// process bones and inverse bind matrix data

			for ( i = 0, l = jointSource.array.length; i < l; i ++ ) {

1026 1027
				const name = jointSource.array[ i ];
				const boneInverse = new Matrix4().fromArray( inverseSource.array, i * inverseSource.stride ).transpose();
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

				build.joints.push( { name: name, boneInverse: boneInverse } );

			}

			return build;

			// array sort function

			function descending( a, b ) {

				return b.weight - a.weight;

			}

		}

		function getController( id ) {

			return getBuild( library.controllers[ id ], buildController );

		}

		// image

		function parseImage( xml ) {

1055
			const data = {
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
				init_from: getElementsByTagName( xml, 'init_from' )[ 0 ].textContent
			};

			library.images[ xml.getAttribute( 'id' ) ] = data;

		}

		function buildImage( data ) {

			if ( data.build !== undefined ) return data.build;

			return data.init_from;

		}

		function getImage( id ) {

1073
			const data = library.images[ id ];
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090

			if ( data !== undefined ) {

				return getBuild( data, buildImage );

			}

			console.warn( 'THREE.ColladaLoader: Couldn\'t find image with ID:', id );

			return null;

		}

		// effect

		function parseEffect( xml ) {

1091
			const data = {};
1092

1093
			for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
1094

1095
				const child = xml.childNodes[ i ];
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114

				if ( child.nodeType !== 1 ) continue;

				switch ( child.nodeName ) {

					case 'profile_COMMON':
						data.profile = parseEffectProfileCOMMON( child );
						break;

				}

			}

			library.effects[ xml.getAttribute( 'id' ) ] = data;

		}

		function parseEffectProfileCOMMON( xml ) {

1115
			const data = {
1116 1117 1118 1119
				surfaces: {},
				samplers: {}
			};

1120
			for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
1121

1122
				const child = xml.childNodes[ i ];
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 1149

				if ( child.nodeType !== 1 ) continue;

				switch ( child.nodeName ) {

					case 'newparam':
						parseEffectNewparam( child, data );
						break;

					case 'technique':
						data.technique = parseEffectTechnique( child );
						break;

					case 'extra':
						data.extra = parseEffectExtra( child );
						break;

				}

			}

			return data;

		}

		function parseEffectNewparam( xml, data ) {

1150
			const sid = xml.getAttribute( 'sid' );
1151

1152
			for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
1153

1154
				const child = xml.childNodes[ i ];
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175

				if ( child.nodeType !== 1 ) continue;

				switch ( child.nodeName ) {

					case 'surface':
						data.surfaces[ sid ] = parseEffectSurface( child );
						break;

					case 'sampler2D':
						data.samplers[ sid ] = parseEffectSampler( child );
						break;

				}

			}

		}

		function parseEffectSurface( xml ) {

1176
			const data = {};
1177

1178
			for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
1179

1180
				const child = xml.childNodes[ i ];
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199

				if ( child.nodeType !== 1 ) continue;

				switch ( child.nodeName ) {

					case 'init_from':
						data.init_from = child.textContent;
						break;

				}

			}

			return data;

		}

		function parseEffectSampler( xml ) {

1200
			const data = {};
1201

1202
			for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
1203

1204
				const child = xml.childNodes[ i ];
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223

				if ( child.nodeType !== 1 ) continue;

				switch ( child.nodeName ) {

					case 'source':
						data.source = child.textContent;
						break;

				}

			}

			return data;

		}

		function parseEffectTechnique( xml ) {

1224
			const data = {};
1225

1226
			for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
1227

1228
				const child = xml.childNodes[ i ];
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251

				if ( child.nodeType !== 1 ) continue;

				switch ( child.nodeName ) {

					case 'constant':
					case 'lambert':
					case 'blinn':
					case 'phong':
						data.type = child.nodeName;
						data.parameters = parseEffectParameters( child );
						break;

				}

			}

			return data;

		}

		function parseEffectParameters( xml ) {

1252
			const data = {};
1253

1254
			for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
1255

1256
				const child = xml.childNodes[ i ];
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287

				if ( child.nodeType !== 1 ) continue;

				switch ( child.nodeName ) {

					case 'emission':
					case 'diffuse':
					case 'specular':
					case 'bump':
					case 'ambient':
					case 'shininess':
					case 'transparency':
						data[ child.nodeName ] = parseEffectParameter( child );
						break;
					case 'transparent':
						data[ child.nodeName ] = {
							opaque: child.getAttribute( 'opaque' ),
							data: parseEffectParameter( child )
						};
						break;

				}

			}

			return data;

		}

		function parseEffectParameter( xml ) {

1288
			const data = {};
1289

1290
			for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
1291

1292
				const child = xml.childNodes[ i ];
1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319

				if ( child.nodeType !== 1 ) continue;

				switch ( child.nodeName ) {

					case 'color':
						data[ child.nodeName ] = parseFloats( child.textContent );
						break;

					case 'float':
						data[ child.nodeName ] = parseFloat( child.textContent );
						break;

					case 'texture':
						data[ child.nodeName ] = { id: child.getAttribute( 'texture' ), extra: parseEffectParameterTexture( child ) };
						break;

				}

			}

			return data;

		}

		function parseEffectParameterTexture( xml ) {

1320
			const data = {
1321 1322 1323
				technique: {}
			};

1324
			for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
1325

1326
				const child = xml.childNodes[ i ];
1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345

				if ( child.nodeType !== 1 ) continue;

				switch ( child.nodeName ) {

					case 'extra':
						parseEffectParameterTextureExtra( child, data );
						break;

				}

			}

			return data;

		}

		function parseEffectParameterTextureExtra( xml, data ) {

1346
			for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
1347

1348
				const child = xml.childNodes[ i ];
1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365

				if ( child.nodeType !== 1 ) continue;

				switch ( child.nodeName ) {

					case 'technique':
						parseEffectParameterTextureExtraTechnique( child, data );
						break;

				}

			}

		}

		function parseEffectParameterTextureExtraTechnique( xml, data ) {

1366
			for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
1367

1368
				const child = xml.childNodes[ i ];
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 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409

				if ( child.nodeType !== 1 ) continue;

				switch ( child.nodeName ) {

					case 'repeatU':
					case 'repeatV':
					case 'offsetU':
					case 'offsetV':
						data.technique[ child.nodeName ] = parseFloat( child.textContent );
						break;

					case 'wrapU':
					case 'wrapV':

						// some files have values for wrapU/wrapV which become NaN via parseInt

						if ( child.textContent.toUpperCase() === 'TRUE' ) {

							data.technique[ child.nodeName ] = 1;

						} else if ( child.textContent.toUpperCase() === 'FALSE' ) {

							data.technique[ child.nodeName ] = 0;

						} else {

							data.technique[ child.nodeName ] = parseInt( child.textContent );

						}

						break;

				}

			}

		}

		function parseEffectExtra( xml ) {

1410
			const data = {};
1411

1412
			for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
1413

1414
				const child = xml.childNodes[ i ];
1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433

				if ( child.nodeType !== 1 ) continue;

				switch ( child.nodeName ) {

					case 'technique':
						data.technique = parseEffectExtraTechnique( child );
						break;

				}

			}

			return data;

		}

		function parseEffectExtraTechnique( xml ) {

1434
			const data = {};
1435

1436
			for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
1437

1438
				const child = xml.childNodes[ i ];
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

				if ( child.nodeType !== 1 ) continue;

				switch ( child.nodeName ) {

					case 'double_sided':
						data[ child.nodeName ] = parseInt( child.textContent );
						break;

				}

			}

			return data;

		}

		function buildEffect( data ) {

			return data;

		}

		function getEffect( id ) {

			return getBuild( library.effects[ id ], buildEffect );

		}

		// material

		function parseMaterial( xml ) {

1472
			const data = {
1473 1474 1475
				name: xml.getAttribute( 'name' )
			};

1476
			for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
1477

1478
				const child = xml.childNodes[ i ];
1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497

				if ( child.nodeType !== 1 ) continue;

				switch ( child.nodeName ) {

					case 'instance_effect':
						data.url = parseId( child.getAttribute( 'url' ) );
						break;

				}

			}

			library.materials[ xml.getAttribute( 'id' ) ] = data;

		}

		function getTextureLoader( image ) {

1498
			let loader;
1499

1500
			let extension = image.slice( ( image.lastIndexOf( '.' ) - 1 >>> 0 ) + 2 ); // http://www.jstips.co/en/javascript/get-file-extension/
1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519
			extension = extension.toLowerCase();

			switch ( extension ) {

				case 'tga':
					loader = tgaLoader;
					break;

				default:
					loader = textureLoader;

			}

			return loader;

		}

		function buildMaterial( data ) {

1520 1521 1522
			const effect = getEffect( data.url );
			const technique = effect.profile.technique;
			const extra = effect.profile.extra;
1523

1524
			let material;
1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546

			switch ( technique.type ) {

				case 'phong':
				case 'blinn':
					material = new MeshPhongMaterial();
					break;

				case 'lambert':
					material = new MeshLambertMaterial();
					break;

				default:
					material = new MeshBasicMaterial();
					break;

			}

			material.name = data.name || '';

			function getTexture( textureObject ) {

1547 1548
				const sampler = effect.profile.samplers[ textureObject.id ];
				let image = null;
1549 1550 1551 1552 1553

				// get image

				if ( sampler !== undefined ) {

1554
					const surface = effect.profile.surfaces[ sampler.source ];
1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567
					image = getImage( surface.init_from );

				} else {

					console.warn( 'THREE.ColladaLoader: Undefined sampler. Access image directly (see #12530).' );
					image = getImage( textureObject.id );

				}

				// create texture if image is avaiable

				if ( image !== null ) {

1568
					const loader = getTextureLoader( image );
1569 1570 1571

					if ( loader !== undefined ) {

1572
						const texture = loader.load( image );
1573

1574
						const extra = textureObject.extra;
1575 1576 1577

						if ( extra !== undefined && extra.technique !== undefined && isEmpty( extra.technique ) === false ) {

1578
							const technique = extra.technique;
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

							texture.wrapS = technique.wrapU ? RepeatWrapping : ClampToEdgeWrapping;
							texture.wrapT = technique.wrapV ? RepeatWrapping : ClampToEdgeWrapping;

							texture.offset.set( technique.offsetU || 0, technique.offsetV || 0 );
							texture.repeat.set( technique.repeatU || 1, technique.repeatV || 1 );

						} else {

							texture.wrapS = RepeatWrapping;
							texture.wrapT = RepeatWrapping;

						}

						return texture;

					} else {

						console.warn( 'THREE.ColladaLoader: Loader for texture %s not found.', image );

						return null;

					}

				} else {

					console.warn( 'THREE.ColladaLoader: Couldn\'t create texture with ID:', textureObject.id );

					return null;

				}

			}

1613
			const parameters = technique.parameters;
1614

1615
			for ( const key in parameters ) {
1616

1617
				const parameter = parameters[ key ];
1618 1619 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

				switch ( key ) {

					case 'diffuse':
						if ( parameter.color ) material.color.fromArray( parameter.color );
						if ( parameter.texture ) material.map = getTexture( parameter.texture );
						break;
					case 'specular':
						if ( parameter.color && material.specular ) material.specular.fromArray( parameter.color );
						if ( parameter.texture ) material.specularMap = getTexture( parameter.texture );
						break;
					case 'bump':
						if ( parameter.texture ) material.normalMap = getTexture( parameter.texture );
						break;
					case 'ambient':
						if ( parameter.texture ) material.lightMap = getTexture( parameter.texture );
						break;
					case 'shininess':
						if ( parameter.float && material.shininess ) material.shininess = parameter.float;
						break;
					case 'emission':
						if ( parameter.color && material.emissive ) material.emissive.fromArray( parameter.color );
						if ( parameter.texture ) material.emissiveMap = getTexture( parameter.texture );
						break;

				}

			}

			//

1649 1650
			let transparent = parameters[ 'transparent' ];
			let transparency = parameters[ 'transparency' ];
1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685

			// <transparency> does not exist but <transparent>

			if ( transparency === undefined && transparent ) {

				transparency = {
					float: 1
				};

			}

			// <transparent> does not exist but <transparency>

			if ( transparent === undefined && transparency ) {

				transparent = {
					opaque: 'A_ONE',
					data: {
						color: [ 1, 1, 1, 1 ]
					} };

			}

			if ( transparent && transparency ) {

				// handle case if a texture exists but no color

				if ( transparent.data.texture ) {

					// we do not set an alpha map (see #13792)

					material.transparent = true;

				} else {

1686
					const color = transparent.data.color;
1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734

					switch ( transparent.opaque ) {

						case 'A_ONE':
							material.opacity = color[ 3 ] * transparency.float;
							break;
						case 'RGB_ZERO':
							material.opacity = 1 - ( color[ 0 ] * transparency.float );
							break;
						case 'A_ZERO':
							material.opacity = 1 - ( color[ 3 ] * transparency.float );
							break;
						case 'RGB_ONE':
							material.opacity = color[ 0 ] * transparency.float;
							break;
						default:
							console.warn( 'THREE.ColladaLoader: Invalid opaque type "%s" of transparent tag.', transparent.opaque );

					}

					if ( material.opacity < 1 ) material.transparent = true;

				}

			}

			//

			if ( extra !== undefined && extra.technique !== undefined && extra.technique.double_sided === 1 ) {

				material.side = DoubleSide;

			}

			return material;

		}

		function getMaterial( id ) {

			return getBuild( library.materials[ id ], buildMaterial );

		}

		// camera

		function parseCamera( xml ) {

1735
			const data = {
1736 1737 1738
				name: xml.getAttribute( 'name' )
			};

1739
			for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
1740

1741
				const child = xml.childNodes[ i ];
1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760

				if ( child.nodeType !== 1 ) continue;

				switch ( child.nodeName ) {

					case 'optics':
						data.optics = parseCameraOptics( child );
						break;

				}

			}

			library.cameras[ xml.getAttribute( 'id' ) ] = data;

		}

		function parseCameraOptics( xml ) {

1761
			for ( let i = 0; i < xml.childNodes.length; i ++ ) {
1762

1763
				const child = xml.childNodes[ i ];
1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779

				switch ( child.nodeName ) {

					case 'technique_common':
						return parseCameraTechnique( child );

				}

			}

			return {};

		}

		function parseCameraTechnique( xml ) {

1780
			const data = {};
1781

1782
			for ( let i = 0; i < xml.childNodes.length; i ++ ) {
1783

1784
				const child = xml.childNodes[ i ];
1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805

				switch ( child.nodeName ) {

					case 'perspective':
					case 'orthographic':

						data.technique = child.nodeName;
						data.parameters = parseCameraParameters( child );

						break;

				}

			}

			return data;

		}

		function parseCameraParameters( xml ) {

1806
			const data = {};
1807

1808
			for ( let i = 0; i < xml.childNodes.length; i ++ ) {
1809

1810
				const child = xml.childNodes[ i ];
1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833

				switch ( child.nodeName ) {

					case 'xfov':
					case 'yfov':
					case 'xmag':
					case 'ymag':
					case 'znear':
					case 'zfar':
					case 'aspect_ratio':
						data[ child.nodeName ] = parseFloat( child.textContent );
						break;

				}

			}

			return data;

		}

		function buildCamera( data ) {

1834
			let camera;
1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847

			switch ( data.optics.technique ) {

				case 'perspective':
					camera = new PerspectiveCamera(
						data.optics.parameters.yfov,
						data.optics.parameters.aspect_ratio,
						data.optics.parameters.znear,
						data.optics.parameters.zfar
					);
					break;

				case 'orthographic':
1848 1849 1850
					let ymag = data.optics.parameters.ymag;
					let xmag = data.optics.parameters.xmag;
					const aspectRatio = data.optics.parameters.aspect_ratio;
1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878

					xmag = ( xmag === undefined ) ? ( ymag * aspectRatio ) : xmag;
					ymag = ( ymag === undefined ) ? ( xmag / aspectRatio ) : ymag;

					xmag *= 0.5;
					ymag *= 0.5;

					camera = new OrthographicCamera(
						- xmag, xmag, ymag, - ymag, // left, right, top, bottom
						data.optics.parameters.znear,
						data.optics.parameters.zfar
					);
					break;

				default:
					camera = new PerspectiveCamera();
					break;

			}

			camera.name = data.name || '';

			return camera;

		}

		function getCamera( id ) {

1879
			const data = library.cameras[ id ];
1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896

			if ( data !== undefined ) {

				return getBuild( data, buildCamera );

			}

			console.warn( 'THREE.ColladaLoader: Couldn\'t find camera with ID:', id );

			return null;

		}

		// light

		function parseLight( xml ) {

1897
			let data = {};
1898

1899
			for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
1900

1901
				const child = xml.childNodes[ i ];
1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920

				if ( child.nodeType !== 1 ) continue;

				switch ( child.nodeName ) {

					case 'technique_common':
						data = parseLightTechnique( child );
						break;

				}

			}

			library.lights[ xml.getAttribute( 'id' ) ] = data;

		}

		function parseLightTechnique( xml ) {

1921
			const data = {};
1922

1923
			for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
1924

1925
				const child = xml.childNodes[ i ];
1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948

				if ( child.nodeType !== 1 ) continue;

				switch ( child.nodeName ) {

					case 'directional':
					case 'point':
					case 'spot':
					case 'ambient':

						data.technique = child.nodeName;
						data.parameters = parseLightParameters( child );

				}

			}

			return data;

		}

		function parseLightParameters( xml ) {

1949
			const data = {};
1950

1951
			for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
1952

1953
				const child = xml.childNodes[ i ];
1954 1955 1956 1957 1958 1959

				if ( child.nodeType !== 1 ) continue;

				switch ( child.nodeName ) {

					case 'color':
1960
						const array = parseFloats( child.textContent );
1961 1962 1963 1964 1965 1966 1967 1968
						data.color = new Color().fromArray( array );
						break;

					case 'falloff_angle':
						data.falloffAngle = parseFloat( child.textContent );
						break;

					case 'quadratic_attenuation':
1969
						const f = parseFloat( child.textContent );
1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982
						data.distance = f ? Math.sqrt( 1 / f ) : 0;
						break;

				}

			}

			return data;

		}

		function buildLight( data ) {

1983
			let light;
1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013

			switch ( data.technique ) {

				case 'directional':
					light = new DirectionalLight();
					break;

				case 'point':
					light = new PointLight();
					break;

				case 'spot':
					light = new SpotLight();
					break;

				case 'ambient':
					light = new AmbientLight();
					break;

			}

			if ( data.parameters.color ) light.color.copy( data.parameters.color );
			if ( data.parameters.distance ) light.distance = data.parameters.distance;

			return light;

		}

		function getLight( id ) {

2014
			const data = library.lights[ id ];
2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031

			if ( data !== undefined ) {

				return getBuild( data, buildLight );

			}

			console.warn( 'THREE.ColladaLoader: Couldn\'t find light with ID:', id );

			return null;

		}

		// geometry

		function parseGeometry( xml ) {

2032
			const data = {
2033 2034 2035 2036 2037 2038
				name: xml.getAttribute( 'name' ),
				sources: {},
				vertices: {},
				primitives: []
			};

2039
			const mesh = getElementsByTagName( xml, 'mesh' )[ 0 ];
2040 2041 2042 2043

			// the following tags inside geometry are not supported yet (see https://github.com/mrdoob/three.js/pull/12606): convex_mesh, spline, brep
			if ( mesh === undefined ) return;

2044
			for ( let i = 0; i < mesh.childNodes.length; i ++ ) {
2045

2046
				const child = mesh.childNodes[ i ];
2047 2048 2049

				if ( child.nodeType !== 1 ) continue;

2050
				const id = child.getAttribute( 'id' );
2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086

				switch ( child.nodeName ) {

					case 'source':
						data.sources[ id ] = parseSource( child );
						break;

					case 'vertices':
						// data.sources[ id ] = data.sources[ parseId( getElementsByTagName( child, 'input' )[ 0 ].getAttribute( 'source' ) ) ];
						data.vertices = parseGeometryVertices( child );
						break;

					case 'polygons':
						console.warn( 'THREE.ColladaLoader: Unsupported primitive type: ', child.nodeName );
						break;

					case 'lines':
					case 'linestrips':
					case 'polylist':
					case 'triangles':
						data.primitives.push( parseGeometryPrimitive( child ) );
						break;

					default:
						console.log( child );

				}

			}

			library.geometries[ xml.getAttribute( 'id' ) ] = data;

		}

		function parseSource( xml ) {

2087
			const data = {
2088 2089 2090 2091
				array: [],
				stride: 3
			};

2092
			for ( let i = 0; i < xml.childNodes.length; i ++ ) {
2093

2094
				const child = xml.childNodes[ i ];
2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108

				if ( child.nodeType !== 1 ) continue;

				switch ( child.nodeName ) {

					case 'float_array':
						data.array = parseFloats( child.textContent );
						break;

					case 'Name_array':
						data.array = parseStrings( child.textContent );
						break;

					case 'technique_common':
2109
						const accessor = getElementsByTagName( child, 'accessor' )[ 0 ];
2110 2111 2112 2113 2114 2115

						if ( accessor !== undefined ) {

							data.stride = parseInt( accessor.getAttribute( 'stride' ) );

						}
M
Mugen87 已提交
2116

2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128
						break;

				}

			}

			return data;

		}

		function parseGeometryVertices( xml ) {

2129
			const data = {};
2130

2131
			for ( let i = 0; i < xml.childNodes.length; i ++ ) {
2132

2133
				const child = xml.childNodes[ i ];
2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146

				if ( child.nodeType !== 1 ) continue;

				data[ child.getAttribute( 'semantic' ) ] = parseId( child.getAttribute( 'source' ) );

			}

			return data;

		}

		function parseGeometryPrimitive( xml ) {

2147
			const primitive = {
2148 2149 2150 2151 2152 2153 2154 2155
				type: xml.nodeName,
				material: xml.getAttribute( 'material' ),
				count: parseInt( xml.getAttribute( 'count' ) ),
				inputs: {},
				stride: 0,
				hasUV: false
			};

2156
			for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
2157

2158
				const child = xml.childNodes[ i ];
2159 2160 2161 2162 2163 2164

				if ( child.nodeType !== 1 ) continue;

				switch ( child.nodeName ) {

					case 'input':
2165 2166 2167 2168 2169
						const id = parseId( child.getAttribute( 'source' ) );
						const semantic = child.getAttribute( 'semantic' );
						const offset = parseInt( child.getAttribute( 'offset' ) );
						const set = parseInt( child.getAttribute( 'set' ) );
						const inputname = ( set > 0 ? semantic + set : semantic );
2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192
						primitive.inputs[ inputname ] = { id: id, offset: offset };
						primitive.stride = Math.max( primitive.stride, offset + 1 );
						if ( semantic === 'TEXCOORD' ) primitive.hasUV = true;
						break;

					case 'vcount':
						primitive.vcount = parseInts( child.textContent );
						break;

					case 'p':
						primitive.p = parseInts( child.textContent );
						break;

				}

			}

			return primitive;

		}

		function groupPrimitives( primitives ) {

2193
			const build = {};
2194

2195
			for ( let i = 0; i < primitives.length; i ++ ) {
2196

2197
				const primitive = primitives[ i ];
2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210

				if ( build[ primitive.type ] === undefined ) build[ primitive.type ] = [];

				build[ primitive.type ].push( primitive );

			}

			return build;

		}

		function checkUVCoordinates( primitives ) {

2211
			let count = 0;
2212

2213
			for ( let i = 0, l = primitives.length; i < l; i ++ ) {
2214

2215
				const primitive = primitives[ i ];
2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234

				if ( primitive.hasUV === true ) {

					count ++;

				}

			}

			if ( count > 0 && count < primitives.length ) {

				primitives.uvsNeedsFix = true;

			}

		}

		function buildGeometry( data ) {

2235
			const build = {};
2236

2237 2238 2239
			const sources = data.sources;
			const vertices = data.vertices;
			const primitives = data.primitives;
2240 2241 2242 2243 2244 2245

			if ( primitives.length === 0 ) return {};

			// our goal is to create one buffer geometry for a single type of primitives
			// first, we group all primitives by their type

2246
			const groupedPrimitives = groupPrimitives( primitives );
2247

2248
			for ( const type in groupedPrimitives ) {
2249

2250
				const primitiveType = groupedPrimitives[ type ];
2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267

				// second, ensure consistent uv coordinates for each type of primitives (polylist,triangles or lines)

				checkUVCoordinates( primitiveType );

				// third, create a buffer geometry for each type of primitives

				build[ type ] = buildGeometryType( primitiveType, sources, vertices );

			}

			return build;

		}

		function buildGeometryType( primitives, sources, vertices ) {

2268
			const build = {};
2269

2270 2271 2272 2273 2274
			const position = { array: [], stride: 0 };
			const normal = { array: [], stride: 0 };
			const uv = { array: [], stride: 0 };
			const uv2 = { array: [], stride: 0 };
			const color = { array: [], stride: 0 };
2275

2276 2277
			const skinIndex = { array: [], stride: 4 };
			const skinWeight = { array: [], stride: 4 };
2278

2279
			const geometry = new BufferGeometry();
2280

2281
			const materialKeys = [];
2282

2283
			let start = 0;
2284

2285
			for ( let p = 0; p < primitives.length; p ++ ) {
2286

2287 2288
				const primitive = primitives[ p ];
				const inputs = primitive.inputs;
2289 2290 2291

				// groups

2292
				let count = 0;
2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306

				switch ( primitive.type ) {

					case 'lines':
					case 'linestrips':
						count = primitive.count * 2;
						break;

					case 'triangles':
						count = primitive.count * 3;
						break;

					case 'polylist':

2307
						for ( let g = 0; g < primitive.count; g ++ ) {
2308

2309
							const vc = primitive.vcount[ g ];
2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348

							switch ( vc ) {

								case 3:
									count += 3; // single triangle
									break;

								case 4:
									count += 6; // quad, subdivided into two triangles
									break;

								default:
									count += ( vc - 2 ) * 3; // polylist with more than four vertices
									break;

							}

						}

						break;

					default:
						console.warn( 'THREE.ColladaLoader: Unknow primitive type:', primitive.type );

				}

				geometry.addGroup( start, count, p );
				start += count;

				// material

				if ( primitive.material ) {

					materialKeys.push( primitive.material );

				}

				// geometry data

2349
				for ( const name in inputs ) {
2350

2351
					const input = inputs[ name ];
2352 2353 2354 2355

					switch ( name )	{

						case 'VERTEX':
2356
							for ( const key in vertices ) {
2357

2358
								const id = vertices[ key ];
2359 2360 2361 2362

								switch ( key ) {

									case 'POSITION':
2363
										const prevLength = position.array.length;
2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377
										buildGeometryData( primitive, sources[ id ], input.offset, position.array );
										position.stride = sources[ id ].stride;

										if ( sources.skinWeights && sources.skinIndices ) {

											buildGeometryData( primitive, sources.skinIndices, input.offset, skinIndex.array );
											buildGeometryData( primitive, sources.skinWeights, input.offset, skinWeight.array );

										}

										// see #3803

										if ( primitive.hasUV === false && primitives.uvsNeedsFix === true ) {

2378
											const count = ( position.array.length - prevLength ) / position.stride;
2379

2380
											for ( let i = 0; i < count; i ++ ) {
2381 2382 2383 2384 2385 2386 2387 2388

												// fill missing uv coordinates

												uv.array.push( 0, 0 );

											}

										}
M
Mugen87 已提交
2389

2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417
										break;

									case 'NORMAL':
										buildGeometryData( primitive, sources[ id ], input.offset, normal.array );
										normal.stride = sources[ id ].stride;
										break;

									case 'COLOR':
										buildGeometryData( primitive, sources[ id ], input.offset, color.array );
										color.stride = sources[ id ].stride;
										break;

									case 'TEXCOORD':
										buildGeometryData( primitive, sources[ id ], input.offset, uv.array );
										uv.stride = sources[ id ].stride;
										break;

									case 'TEXCOORD1':
										buildGeometryData( primitive, sources[ id ], input.offset, uv2.array );
										uv.stride = sources[ id ].stride;
										break;

									default:
										console.warn( 'THREE.ColladaLoader: Semantic "%s" not handled in geometry build process.', key );

								}

							}
M
Mugen87 已提交
2418

2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448
							break;

						case 'NORMAL':
							buildGeometryData( primitive, sources[ input.id ], input.offset, normal.array );
							normal.stride = sources[ input.id ].stride;
							break;

						case 'COLOR':
							buildGeometryData( primitive, sources[ input.id ], input.offset, color.array );
							color.stride = sources[ input.id ].stride;
							break;

						case 'TEXCOORD':
							buildGeometryData( primitive, sources[ input.id ], input.offset, uv.array );
							uv.stride = sources[ input.id ].stride;
							break;

						case 'TEXCOORD1':
							buildGeometryData( primitive, sources[ input.id ], input.offset, uv2.array );
							uv2.stride = sources[ input.id ].stride;
							break;

					}

				}

			}

			// build geometry

2449 2450 2451 2452 2453 2454 2455 2456
			if ( position.array.length > 0 ) geometry.setAttribute( 'position', new Float32BufferAttribute( position.array, position.stride ) );
			if ( normal.array.length > 0 ) geometry.setAttribute( 'normal', new Float32BufferAttribute( normal.array, normal.stride ) );
			if ( color.array.length > 0 ) geometry.setAttribute( 'color', new Float32BufferAttribute( color.array, color.stride ) );
			if ( uv.array.length > 0 ) geometry.setAttribute( 'uv', new Float32BufferAttribute( uv.array, uv.stride ) );
			if ( uv2.array.length > 0 ) geometry.setAttribute( 'uv2', new Float32BufferAttribute( uv2.array, uv2.stride ) );

			if ( skinIndex.array.length > 0 ) geometry.setAttribute( 'skinIndex', new Float32BufferAttribute( skinIndex.array, skinIndex.stride ) );
			if ( skinWeight.array.length > 0 ) geometry.setAttribute( 'skinWeight', new Float32BufferAttribute( skinWeight.array, skinWeight.stride ) );
2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467

			build.data = geometry;
			build.type = primitives[ 0 ].type;
			build.materialKeys = materialKeys;

			return build;

		}

		function buildGeometryData( primitive, source, offset, array ) {

2468 2469 2470
			const indices = primitive.p;
			const stride = primitive.stride;
			const vcount = primitive.vcount;
2471 2472 2473

			function pushVector( i ) {

2474 2475
				let index = indices[ i + offset ] * sourceStride;
				const length = index + sourceStride;
2476 2477 2478 2479 2480 2481 2482 2483 2484

				for ( ; index < length; index ++ ) {

					array.push( sourceArray[ index ] );

				}

			}

2485 2486
			const sourceArray = source.array;
			const sourceStride = source.stride;
2487 2488 2489

			if ( primitive.vcount !== undefined ) {

2490
				let index = 0;
2491

2492
				for ( let i = 0, l = vcount.length; i < l; i ++ ) {
2493

2494
					const count = vcount[ i ];
2495 2496 2497

					if ( count === 4 ) {

2498 2499 2500 2501
						const a = index + stride * 0;
						const b = index + stride * 1;
						const c = index + stride * 2;
						const d = index + stride * 3;
2502 2503 2504 2505 2506 2507

						pushVector( a ); pushVector( b ); pushVector( d );
						pushVector( b ); pushVector( c ); pushVector( d );

					} else if ( count === 3 ) {

2508 2509 2510
						const a = index + stride * 0;
						const b = index + stride * 1;
						const c = index + stride * 2;
2511 2512 2513 2514 2515

						pushVector( a ); pushVector( b ); pushVector( c );

					} else if ( count > 4 ) {

2516
						for ( let k = 1, kl = ( count - 2 ); k <= kl; k ++ ) {
2517

2518 2519 2520
							const a = index + stride * 0;
							const b = index + stride * k;
							const c = index + stride * ( k + 1 );
2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533

							pushVector( a ); pushVector( b ); pushVector( c );

						}

					}

					index += stride * count;

				}

			} else {

2534
				for ( let i = 0, l = indices.length; i < l; i += stride ) {
2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553

					pushVector( i );

				}

			}

		}

		function getGeometry( id ) {

			return getBuild( library.geometries[ id ], buildGeometry );

		}

		// kinematics

		function parseKinematicsModel( xml ) {

2554
			const data = {
2555 2556 2557 2558 2559
				name: xml.getAttribute( 'name' ) || '',
				joints: {},
				links: []
			};

2560
			for ( let i = 0; i < xml.childNodes.length; i ++ ) {
2561

2562
				const child = xml.childNodes[ i ];
2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595

				if ( child.nodeType !== 1 ) continue;

				switch ( child.nodeName ) {

					case 'technique_common':
						parseKinematicsTechniqueCommon( child, data );
						break;

				}

			}

			library.kinematicsModels[ xml.getAttribute( 'id' ) ] = data;

		}

		function buildKinematicsModel( data ) {

			if ( data.build !== undefined ) return data.build;

			return data;

		}

		function getKinematicsModel( id ) {

			return getBuild( library.kinematicsModels[ id ], buildKinematicsModel );

		}

		function parseKinematicsTechniqueCommon( xml, data ) {

2596
			for ( let i = 0; i < xml.childNodes.length; i ++ ) {
2597

2598
				const child = xml.childNodes[ i ];
2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619

				if ( child.nodeType !== 1 ) continue;

				switch ( child.nodeName ) {

					case 'joint':
						data.joints[ child.getAttribute( 'sid' ) ] = parseKinematicsJoint( child );
						break;

					case 'link':
						data.links.push( parseKinematicsLink( child ) );
						break;

				}

			}

		}

		function parseKinematicsJoint( xml ) {

2620
			let data;
2621

2622
			for ( let i = 0; i < xml.childNodes.length; i ++ ) {
2623

2624
				const child = xml.childNodes[ i ];
2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642

				if ( child.nodeType !== 1 ) continue;

				switch ( child.nodeName ) {

					case 'prismatic':
					case 'revolute':
						data = parseKinematicsJointParameter( child );
						break;

				}

			}

			return data;

		}

2643
		function parseKinematicsJointParameter( xml ) {
2644

2645
			const data = {
2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658
				sid: xml.getAttribute( 'sid' ),
				name: xml.getAttribute( 'name' ) || '',
				axis: new Vector3(),
				limits: {
					min: 0,
					max: 0
				},
				type: xml.nodeName,
				static: false,
				zeroPosition: 0,
				middlePosition: 0
			};

2659
			for ( let i = 0; i < xml.childNodes.length; i ++ ) {
2660

2661
				const child = xml.childNodes[ i ];
2662 2663 2664 2665 2666 2667

				if ( child.nodeType !== 1 ) continue;

				switch ( child.nodeName ) {

					case 'axis':
2668
						const array = parseFloats( child.textContent );
2669 2670 2671
						data.axis.fromArray( array );
						break;
					case 'limits':
2672 2673
						const max = child.getElementsByTagName( 'max' )[ 0 ];
						const min = child.getElementsByTagName( 'min' )[ 0 ];
2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700

						data.limits.max = parseFloat( max.textContent );
						data.limits.min = parseFloat( min.textContent );
						break;

				}

			}

			// if min is equal to or greater than max, consider the joint static

			if ( data.limits.min >= data.limits.max ) {

				data.static = true;

			}

			// calculate middle position

			data.middlePosition = ( data.limits.min + data.limits.max ) / 2.0;

			return data;

		}

		function parseKinematicsLink( xml ) {

2701
			const data = {
2702 2703 2704 2705 2706 2707
				sid: xml.getAttribute( 'sid' ),
				name: xml.getAttribute( 'name' ) || '',
				attachments: [],
				transforms: []
			};

2708
			for ( let i = 0; i < xml.childNodes.length; i ++ ) {
2709

2710
				const child = xml.childNodes[ i ];
2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735

				if ( child.nodeType !== 1 ) continue;

				switch ( child.nodeName ) {

					case 'attachment_full':
						data.attachments.push( parseKinematicsAttachment( child ) );
						break;

					case 'matrix':
					case 'translate':
					case 'rotate':
						data.transforms.push( parseKinematicsTransform( child ) );
						break;

				}

			}

			return data;

		}

		function parseKinematicsAttachment( xml ) {

2736
			const data = {
2737 2738 2739 2740 2741
				joint: xml.getAttribute( 'joint' ).split( '/' ).pop(),
				transforms: [],
				links: []
			};

2742
			for ( let i = 0; i < xml.childNodes.length; i ++ ) {
2743

2744
				const child = xml.childNodes[ i ];
2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769

				if ( child.nodeType !== 1 ) continue;

				switch ( child.nodeName ) {

					case 'link':
						data.links.push( parseKinematicsLink( child ) );
						break;

					case 'matrix':
					case 'translate':
					case 'rotate':
						data.transforms.push( parseKinematicsTransform( child ) );
						break;

				}

			}

			return data;

		}

		function parseKinematicsTransform( xml ) {

2770
			const data = {
2771 2772 2773
				type: xml.nodeName
			};

2774
			const array = parseFloats( xml.textContent );
2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790

			switch ( data.type ) {

				case 'matrix':
					data.obj = new Matrix4();
					data.obj.fromArray( array ).transpose();
					break;

				case 'translate':
					data.obj = new Vector3();
					data.obj.fromArray( array );
					break;

				case 'rotate':
					data.obj = new Vector3();
					data.obj.fromArray( array );
M
Mugen87 已提交
2791
					data.angle = MathUtils.degToRad( array[ 3 ] );
2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803
					break;

			}

			return data;

		}

		// physics

		function parsePhysicsModel( xml ) {

2804
			const data = {
2805 2806 2807 2808
				name: xml.getAttribute( 'name' ) || '',
				rigidBodies: {}
			};

2809
			for ( let i = 0; i < xml.childNodes.length; i ++ ) {
2810

2811
				const child = xml.childNodes[ i ];
2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831

				if ( child.nodeType !== 1 ) continue;

				switch ( child.nodeName ) {

					case 'rigid_body':
						data.rigidBodies[ child.getAttribute( 'name' ) ] = {};
						parsePhysicsRigidBody( child, data.rigidBodies[ child.getAttribute( 'name' ) ] );
						break;

				}

			}

			library.physicsModels[ xml.getAttribute( 'id' ) ] = data;

		}

		function parsePhysicsRigidBody( xml, data ) {

2832
			for ( let i = 0; i < xml.childNodes.length; i ++ ) {
2833

2834
				const child = xml.childNodes[ i ];
2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851

				if ( child.nodeType !== 1 ) continue;

				switch ( child.nodeName ) {

					case 'technique_common':
						parsePhysicsTechniqueCommon( child, data );
						break;

				}

			}

		}

		function parsePhysicsTechniqueCommon( xml, data ) {

2852
			for ( let i = 0; i < xml.childNodes.length; i ++ ) {
2853

2854
				const child = xml.childNodes[ i ];
2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877

				if ( child.nodeType !== 1 ) continue;

				switch ( child.nodeName ) {

					case 'inertia':
						data.inertia = parseFloats( child.textContent );
						break;

					case 'mass':
						data.mass = parseFloats( child.textContent )[ 0 ];
						break;

				}

			}

		}

		// scene

		function parseKinematicsScene( xml ) {

2878
			const data = {
2879 2880 2881
				bindJointAxis: []
			};

2882
			for ( let i = 0; i < xml.childNodes.length; i ++ ) {
2883

2884
				const child = xml.childNodes[ i ];
2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903

				if ( child.nodeType !== 1 ) continue;

				switch ( child.nodeName ) {

					case 'bind_joint_axis':
						data.bindJointAxis.push( parseKinematicsBindJointAxis( child ) );
						break;

				}

			}

			library.kinematicsScenes[ parseId( xml.getAttribute( 'url' ) ) ] = data;

		}

		function parseKinematicsBindJointAxis( xml ) {

2904
			const data = {
2905 2906 2907
				target: xml.getAttribute( 'target' ).split( '/' ).pop()
			};

2908
			for ( let i = 0; i < xml.childNodes.length; i ++ ) {
2909

2910
				const child = xml.childNodes[ i ];
2911 2912 2913 2914 2915 2916

				if ( child.nodeType !== 1 ) continue;

				switch ( child.nodeName ) {

					case 'axis':
2917
						const param = child.getElementsByTagName( 'param' )[ 0 ];
2918
						data.axis = param.textContent;
2919
						const tmpJointIndex = data.axis.split( 'inst_' ).pop().split( 'axis' )[ 0 ];
2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946
						data.jointIndex = tmpJointIndex.substr( 0, tmpJointIndex.length - 1 );
						break;

				}

			}

			return data;

		}

		function buildKinematicsScene( data ) {

			if ( data.build !== undefined ) return data.build;

			return data;

		}

		function getKinematicsScene( id ) {

			return getBuild( library.kinematicsScenes[ id ], buildKinematicsScene );

		}

		function setupKinematics() {

2947 2948 2949
			const kinematicsModelId = Object.keys( library.kinematicsModels )[ 0 ];
			const kinematicsSceneId = Object.keys( library.kinematicsScenes )[ 0 ];
			const visualSceneId = Object.keys( library.visualScenes )[ 0 ];
2950 2951 2952

			if ( kinematicsModelId === undefined || kinematicsSceneId === undefined ) return;

2953 2954 2955
			const kinematicsModel = getKinematicsModel( kinematicsModelId );
			const kinematicsScene = getKinematicsScene( kinematicsSceneId );
			const visualScene = getVisualScene( visualSceneId );
2956

2957 2958
			const bindJointAxis = kinematicsScene.bindJointAxis;
			const jointMap = {};
2959

2960
			for ( let i = 0, l = bindJointAxis.length; i < l; i ++ ) {
2961

2962
				const axis = bindJointAxis[ i ];
2963 2964 2965

				// the result of the following query is an element of type 'translate', 'rotate','scale' or 'matrix'

2966
				const targetElement = collada.querySelector( '[sid="' + axis.target + '"]' );
2967 2968 2969

				if ( targetElement ) {

2970
					// get the parent of the transform element
2971

2972
					const parentVisualElement = targetElement.parentElement;
2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983

					// connect the joint of the kinematics model with the element in the visual scene

					connect( axis.jointIndex, parentVisualElement );

				}

			}

			function connect( jointIndex, visualElement ) {

2984 2985
				const visualElementName = visualElement.getAttribute( 'name' );
				const joint = kinematicsModel.joints[ jointIndex ];
2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003

				visualScene.traverse( function ( object ) {

					if ( object.name === visualElementName ) {

						jointMap[ jointIndex ] = {
							object: object,
							transforms: buildTransformList( visualElement ),
							joint: joint,
							position: joint.zeroPosition
						};

					}

				} );

			}

3004
			const m0 = new Matrix4();
3005 3006 3007 3008 3009 3010 3011

			kinematics = {

				joints: kinematicsModel && kinematicsModel.joints,

				getJointValue: function ( jointIndex ) {

3012
					const jointData = jointMap[ jointIndex ];
3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027

					if ( jointData ) {

						return jointData.position;

					} else {

						console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' doesn\'t exist.' );

					}

				},

				setJointValue: function ( jointIndex, value ) {

3028
					const jointData = jointMap[ jointIndex ];
3029 3030 3031

					if ( jointData ) {

3032
						const joint = jointData.joint;
3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043

						if ( value > joint.limits.max || value < joint.limits.min ) {

							console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' value ' + value + ' outside of limits (min: ' + joint.limits.min + ', max: ' + joint.limits.max + ').' );

						} else if ( joint.static ) {

							console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' is static.' );

						} else {

3044 3045 3046
							const object = jointData.object;
							const axis = joint.axis;
							const transforms = jointData.transforms;
3047 3048 3049 3050 3051

							matrix.identity();

							// each update, we have to apply all transforms in the correct order

3052
							for ( let i = 0; i < transforms.length; i ++ ) {
3053

3054
								const transform = transforms[ i ];
3055 3056 3057 3058 3059 3060 3061 3062

								// if there is a connection of the transform node with a joint, apply the joint value

								if ( transform.sid && transform.sid.indexOf( jointIndex ) !== - 1 ) {

									switch ( joint.type ) {

										case 'revolute':
M
Mugen87 已提交
3063
											matrix.multiply( m0.makeRotationAxis( axis, MathUtils.degToRad( value ) ) );
3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122
											break;

										case 'prismatic':
											matrix.multiply( m0.makeTranslation( axis.x * value, axis.y * value, axis.z * value ) );
											break;

										default:
											console.warn( 'THREE.ColladaLoader: Unknown joint type: ' + joint.type );
											break;

									}

								} else {

									switch ( transform.type ) {

										case 'matrix':
											matrix.multiply( transform.obj );
											break;

										case 'translate':
											matrix.multiply( m0.makeTranslation( transform.obj.x, transform.obj.y, transform.obj.z ) );
											break;

										case 'scale':
											matrix.scale( transform.obj );
											break;

										case 'rotate':
											matrix.multiply( m0.makeRotationAxis( transform.obj, transform.angle ) );
											break;

									}

								}

							}

							object.matrix.copy( matrix );
							object.matrix.decompose( object.position, object.quaternion, object.scale );

							jointMap[ jointIndex ].position = value;

						}

					} else {

						console.log( 'THREE.ColladaLoader: ' + jointIndex + ' does not exist.' );

					}

				}

			};

		}

		function buildTransformList( node ) {

3123
			const transforms = [];
3124

3125
			const xml = collada.querySelector( '[id="' + node.id + '"]' );
3126

3127
			for ( let i = 0; i < xml.childNodes.length; i ++ ) {
3128

3129
				const child = xml.childNodes[ i ];
3130 3131 3132

				if ( child.nodeType !== 1 ) continue;

3133 3134
				let array, vector;

3135 3136 3137
				switch ( child.nodeName ) {

					case 'matrix':
3138 3139
						array = parseFloats( child.textContent );
						const matrix = new Matrix4().fromArray( array ).transpose();
3140 3141 3142 3143 3144 3145 3146 3147 3148
						transforms.push( {
							sid: child.getAttribute( 'sid' ),
							type: child.nodeName,
							obj: matrix
						} );
						break;

					case 'translate':
					case 'scale':
3149 3150
						array = parseFloats( child.textContent );
						vector = new Vector3().fromArray( array );
3151 3152 3153 3154 3155 3156 3157 3158
						transforms.push( {
							sid: child.getAttribute( 'sid' ),
							type: child.nodeName,
							obj: vector
						} );
						break;

					case 'rotate':
3159 3160 3161
						array = parseFloats( child.textContent );
						vector = new Vector3().fromArray( array );
						const angle = MathUtils.degToRad( array[ 3 ] );
3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181
						transforms.push( {
							sid: child.getAttribute( 'sid' ),
							type: child.nodeName,
							obj: vector,
							angle: angle
						} );
						break;

				}

			}

			return transforms;

		}

		// nodes

		function prepareNodes( xml ) {

3182
			const elements = xml.getElementsByTagName( 'node' );
3183 3184 3185

			// ensure all node elements have id attributes

3186
			for ( let i = 0; i < elements.length; i ++ ) {
3187

3188
				const element = elements[ i ];
3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199

				if ( element.hasAttribute( 'id' ) === false ) {

					element.setAttribute( 'id', generateId() );

				}

			}

		}

3200 3201
		const matrix = new Matrix4();
		const vector = new Vector3();
3202 3203 3204

		function parseNode( xml ) {

3205
			const data = {
3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219
				name: xml.getAttribute( 'name' ) || '',
				type: xml.getAttribute( 'type' ),
				id: xml.getAttribute( 'id' ),
				sid: xml.getAttribute( 'sid' ),
				matrix: new Matrix4(),
				nodes: [],
				instanceCameras: [],
				instanceControllers: [],
				instanceLights: [],
				instanceGeometries: [],
				instanceNodes: [],
				transforms: {}
			};

3220
			for ( let i = 0; i < xml.childNodes.length; i ++ ) {
3221

3222
				const child = xml.childNodes[ i ];
3223 3224 3225

				if ( child.nodeType !== 1 ) continue;

3226 3227
				let array;

3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255
				switch ( child.nodeName ) {

					case 'node':
						data.nodes.push( child.getAttribute( 'id' ) );
						parseNode( child );
						break;

					case 'instance_camera':
						data.instanceCameras.push( parseId( child.getAttribute( 'url' ) ) );
						break;

					case 'instance_controller':
						data.instanceControllers.push( parseNodeInstance( child ) );
						break;

					case 'instance_light':
						data.instanceLights.push( parseId( child.getAttribute( 'url' ) ) );
						break;

					case 'instance_geometry':
						data.instanceGeometries.push( parseNodeInstance( child ) );
						break;

					case 'instance_node':
						data.instanceNodes.push( parseId( child.getAttribute( 'url' ) ) );
						break;

					case 'matrix':
3256
						array = parseFloats( child.textContent );
3257 3258 3259 3260 3261
						data.matrix.multiply( matrix.fromArray( array ).transpose() );
						data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
						break;

					case 'translate':
3262
						array = parseFloats( child.textContent );
3263 3264 3265 3266 3267 3268
						vector.fromArray( array );
						data.matrix.multiply( matrix.makeTranslation( vector.x, vector.y, vector.z ) );
						data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
						break;

					case 'rotate':
3269 3270
						array = parseFloats( child.textContent );
						const angle = MathUtils.degToRad( array[ 3 ] );
3271 3272 3273 3274 3275
						data.matrix.multiply( matrix.makeRotationAxis( vector.fromArray( array ), angle ) );
						data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
						break;

					case 'scale':
3276
						array = parseFloats( child.textContent );
3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306
						data.matrix.scale( vector.fromArray( array ) );
						data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
						break;

					case 'extra':
						break;

					default:
						console.log( child );

				}

			}

			if ( hasNode( data.id ) ) {

				console.warn( 'THREE.ColladaLoader: There is already a node with ID %s. Exclude current node from further processing.', data.id );

			} else {

				library.nodes[ data.id ] = data;

			}

			return data;

		}

		function parseNodeInstance( xml ) {

3307
			const data = {
3308 3309 3310 3311 3312
				id: parseId( xml.getAttribute( 'url' ) ),
				materials: {},
				skeletons: []
			};

3313
			for ( let i = 0; i < xml.childNodes.length; i ++ ) {
3314

3315
				const child = xml.childNodes[ i ];
3316 3317 3318 3319

				switch ( child.nodeName ) {

					case 'bind_material':
3320
						const instances = child.getElementsByTagName( 'instance_material' );
3321

3322
						for ( let j = 0; j < instances.length; j ++ ) {
3323

3324 3325 3326
							const instance = instances[ j ];
							const symbol = instance.getAttribute( 'symbol' );
							const target = instance.getAttribute( 'target' );
3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350

							data.materials[ symbol ] = parseId( target );

						}

						break;

					case 'skeleton':
						data.skeletons.push( parseId( child.textContent ) );
						break;

					default:
						break;

				}

			}

			return data;

		}

		function buildSkeleton( skeletons, joints ) {

3351 3352
			const boneData = [];
			const sortedBoneData = [];
3353

3354
			let i, j, data;
3355 3356 3357 3358 3359 3360

			// a skeleton can have multiple root bones. collada expresses this
			// situtation with multiple "skeleton" tags per controller instance

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

3361
				const skeleton = skeletons[ i ];
3362

3363
				let root;
3364 3365 3366 3367 3368 3369 3370 3371 3372 3373

				if ( hasNode( skeleton ) ) {

					root = getNode( skeleton );
					buildBoneHierarchy( root, joints, boneData );

				} else if ( hasVisualScene( skeleton ) ) {

					// handle case where the skeleton refers to the visual scene (#13335)

3374 3375
					const visualScene = library.visualScenes[ skeleton ];
					const children = visualScene.children;
3376

3377
					for ( let j = 0; j < children.length; j ++ ) {
3378

3379
						const child = children[ j ];
3380 3381 3382

						if ( child.type === 'JOINT' ) {

3383
							const root = getNode( child.id );
3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434
							buildBoneHierarchy( root, joints, boneData );

						}

					}

				} else {

					console.error( 'THREE.ColladaLoader: Unable to find root bone of skeleton with ID:', skeleton );

				}

			}

			// sort bone data (the order is defined in the corresponding controller)

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

				for ( j = 0; j < boneData.length; j ++ ) {

					data = boneData[ j ];

					if ( data.bone.name === joints[ i ].name ) {

						sortedBoneData[ i ] = data;
						data.processed = true;
						break;

					}

				}

			}

			// add unprocessed bone data at the end of the list

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

				data = boneData[ i ];

				if ( data.processed === false ) {

					sortedBoneData.push( data );
					data.processed = true;

				}

			}

			// setup arrays for skeleton creation

3435 3436
			const bones = [];
			const boneInverses = [];
3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458

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

				data = sortedBoneData[ i ];

				bones.push( data.bone );
				boneInverses.push( data.boneInverse );

			}

			return new Skeleton( bones, boneInverses );

		}

		function buildBoneHierarchy( root, joints, boneData ) {

			// setup bone data from visual scene

			root.traverse( function ( object ) {

				if ( object.isBone === true ) {

3459
					let boneInverse;
3460 3461 3462

					// retrieve the boneInverse from the controller data

3463
					for ( let i = 0; i < joints.length; i ++ ) {
3464

3465
						const joint = joints[ i ];
3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497

						if ( joint.name === object.name ) {

							boneInverse = joint.boneInverse;
							break;

						}

					}

					if ( boneInverse === undefined ) {

						// Unfortunately, there can be joints in the visual scene that are not part of the
						// corresponding controller. In this case, we have to create a dummy boneInverse matrix
						// for the respective bone. This bone won't affect any vertices, because there are no skin indices
						// and weights defined for it. But we still have to add the bone to the sorted bone list in order to
						// ensure a correct animation of the model.

						boneInverse = new Matrix4();

					}

					boneData.push( { bone: object, boneInverse: boneInverse, processed: false } );

				}

			} );

		}

		function buildNode( data ) {

3498
			const objects = [];
3499

3500 3501 3502 3503 3504 3505 3506 3507
			const matrix = data.matrix;
			const nodes = data.nodes;
			const type = data.type;
			const instanceCameras = data.instanceCameras;
			const instanceControllers = data.instanceControllers;
			const instanceLights = data.instanceLights;
			const instanceGeometries = data.instanceGeometries;
			const instanceNodes = data.instanceNodes;
3508 3509 3510

			// nodes

3511
			for ( let i = 0, l = nodes.length; i < l; i ++ ) {
3512 3513 3514 3515 3516 3517 3518

				objects.push( getNode( nodes[ i ] ) );

			}

			// instance cameras

3519
			for ( let i = 0, l = instanceCameras.length; i < l; i ++ ) {
3520

3521
				const instanceCamera = getCamera( instanceCameras[ i ] );
3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532

				if ( instanceCamera !== null ) {

					objects.push( instanceCamera.clone() );

				}

			}

			// instance controllers

3533
			for ( let i = 0, l = instanceControllers.length; i < l; i ++ ) {
3534

3535 3536 3537 3538
				const instance = instanceControllers[ i ];
				const controller = getController( instance.id );
				const geometries = getGeometry( controller.id );
				const newObjects = buildObjects( geometries, instance.materials );
3539

3540 3541
				const skeletons = instance.skeletons;
				const joints = controller.skin.joints;
3542

3543
				const skeleton = buildSkeleton( skeletons, joints );
3544

3545
				for ( let j = 0, jl = newObjects.length; j < jl; j ++ ) {
3546

3547
					const object = newObjects[ j ];
3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563

					if ( object.isSkinnedMesh ) {

						object.bind( skeleton, controller.skin.bindMatrix );
						object.normalizeSkinWeights();

					}

					objects.push( object );

				}

			}

			// instance lights

3564
			for ( let i = 0, l = instanceLights.length; i < l; i ++ ) {
3565

3566
				const instanceLight = getLight( instanceLights[ i ] );
3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577

				if ( instanceLight !== null ) {

					objects.push( instanceLight.clone() );

				}

			}

			// instance geometries

3578
			for ( let i = 0, l = instanceGeometries.length; i < l; i ++ ) {
3579

3580
				const instance = instanceGeometries[ i ];
3581 3582 3583 3584

				// a single geometry instance in collada can lead to multiple object3Ds.
				// this is the case when primitives are combined like triangles and lines

3585 3586
				const geometries = getGeometry( instance.id );
				const newObjects = buildObjects( geometries, instance.materials );
3587

3588
				for ( let j = 0, jl = newObjects.length; j < jl; j ++ ) {
3589 3590 3591 3592 3593 3594 3595 3596 3597

					objects.push( newObjects[ j ] );

				}

			}

			// instance nodes

3598
			for ( let i = 0, l = instanceNodes.length; i < l; i ++ ) {
3599 3600 3601 3602 3603

				objects.push( getNode( instanceNodes[ i ] ).clone() );

			}

3604
			let object;
3605 3606 3607 3608 3609 3610 3611 3612 3613

			if ( nodes.length === 0 && objects.length === 1 ) {

				object = objects[ 0 ];

			} else {

				object = ( type === 'JOINT' ) ? new Bone() : new Group();

3614
				for ( let i = 0; i < objects.length; i ++ ) {
3615 3616 3617 3618 3619 3620 3621

					object.add( objects[ i ] );

				}

			}

M
Mugen87 已提交
3622
			object.name = ( type === 'JOINT' ) ? data.sid : data.name;
3623 3624 3625 3626 3627 3628 3629
			object.matrix.copy( matrix );
			object.matrix.decompose( object.position, object.quaternion, object.scale );

			return object;

		}

3630
		const fallbackMaterial = new MeshBasicMaterial( { color: 0xff00ff } );
3631 3632 3633

		function resolveMaterialBinding( keys, instanceMaterials ) {

3634
			const materials = [];
3635

3636
			for ( let i = 0, l = keys.length; i < l; i ++ ) {
3637

3638
				const id = instanceMaterials[ keys[ i ] ];
3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658

				if ( id === undefined ) {

					console.warn( 'THREE.ColladaLoader: Material with key %s not found. Apply fallback material.', keys[ i ] );
					materials.push( fallbackMaterial );

				} else {

					materials.push( getMaterial( id ) );

				}

			}

			return materials;

		}

		function buildObjects( geometries, instanceMaterials ) {

3659
			const objects = [];
3660

3661
			for ( const type in geometries ) {
3662

3663
				const geometry = geometries[ type ];
3664

3665
				const materials = resolveMaterialBinding( geometry.materialKeys, instanceMaterials );
3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684

				// handle case if no materials are defined

				if ( materials.length === 0 ) {

					if ( type === 'lines' || type === 'linestrips' ) {

						materials.push( new LineBasicMaterial() );

					} else {

						materials.push( new MeshPhongMaterial() );

					}

				}

				// regard skinning

3685
				const skinning = ( geometry.data.attributes.skinIndex !== undefined );
3686 3687 3688

				if ( skinning ) {

3689
					for ( let i = 0, l = materials.length; i < l; i ++ ) {
3690 3691 3692 3693 3694 3695 3696 3697 3698

						materials[ i ].skinning = true;

					}

				}

				// choose between a single or multi materials (material array)

3699
				const material = ( materials.length === 1 ) ? materials[ 0 ] : materials;
3700 3701 3702

				// now create a specific 3D object

3703
				let object;
3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725

				switch ( type ) {

					case 'lines':
						object = new LineSegments( geometry.data, material );
						break;

					case 'linestrips':
						object = new Line( geometry.data, material );
						break;

					case 'triangles':
					case 'polylist':
						if ( skinning ) {

							object = new SkinnedMesh( geometry.data, material );

						} else {

							object = new Mesh( geometry.data, material );

						}
M
Mugen87 已提交
3726

3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754
						break;

				}

				objects.push( object );

			}

			return objects;

		}

		function hasNode( id ) {

			return library.nodes[ id ] !== undefined;

		}

		function getNode( id ) {

			return getBuild( library.nodes[ id ], buildNode );

		}

		// visual scenes

		function parseVisualScene( xml ) {

3755
			const data = {
3756 3757 3758 3759 3760 3761
				name: xml.getAttribute( 'name' ),
				children: []
			};

			prepareNodes( xml );

3762
			const elements = getElementsByTagName( xml, 'node' );
3763

3764
			for ( let i = 0; i < elements.length; i ++ ) {
3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775

				data.children.push( parseNode( elements[ i ] ) );

			}

			library.visualScenes[ xml.getAttribute( 'id' ) ] = data;

		}

		function buildVisualScene( data ) {

3776
			const group = new Group();
3777 3778
			group.name = data.name;

3779
			const children = data.children;
3780

3781
			for ( let i = 0; i < children.length; i ++ ) {
3782

3783
				const child = children[ i ];
3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808

				group.add( getNode( child.id ) );

			}

			return group;

		}

		function hasVisualScene( id ) {

			return library.visualScenes[ id ] !== undefined;

		}

		function getVisualScene( id ) {

			return getBuild( library.visualScenes[ id ], buildVisualScene );

		}

		// scenes

		function parseScene( xml ) {

3809
			const instance = getElementsByTagName( xml, 'instance_visual_scene' )[ 0 ];
3810 3811 3812 3813 3814 3815
			return getVisualScene( parseId( instance.getAttribute( 'url' ) ) );

		}

		function setupAnimations() {

3816
			const clips = library.clips;
3817 3818 3819 3820 3821 3822 3823

			if ( isEmpty( clips ) === true ) {

				if ( isEmpty( library.animations ) === false ) {

					// if there are animations but no clips, we create a default clip for playback

3824
					const tracks = [];
3825

3826
					for ( const id in library.animations ) {
3827

3828
						const animationTracks = getAnimation( id );
3829

3830
						for ( let i = 0, l = animationTracks.length; i < l; i ++ ) {
3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843

							tracks.push( animationTracks[ i ] );

						}

					}

					animations.push( new AnimationClip( 'default', - 1, tracks ) );

				}

			} else {

3844
				for ( const id in clips ) {
3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858

					animations.push( getAnimationClip( id ) );

				}

			}

		}

		// convert the parser error element into text with each child elements text
		// separated by new lines.

		function parserErrorToText( parserError ) {

3859 3860
			let result = '';
			const stack = [ parserError ];
3861 3862 3863

			while ( stack.length ) {

3864
				const node = stack.shift();
3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888

				if ( node.nodeType === Node.TEXT_NODE ) {

					result += node.textContent;

				} else {

					result += '\n';
					stack.push.apply( stack, node.childNodes );

				}

			}

			return result.trim();

		}

		if ( text.length === 0 ) {

			return { scene: new Scene() };

		}

3889
		const xml = new DOMParser().parseFromString( text, 'application/xml' );
3890

3891
		const collada = getElementsByTagName( xml, 'COLLADA' )[ 0 ];
3892

3893
		const parserError = xml.getElementsByTagName( 'parsererror' )[ 0 ];
3894 3895 3896 3897
		if ( parserError !== undefined ) {

			// Chrome will return parser error with a div in it

3898 3899
			const errorElement = getElementsByTagName( parserError, 'div' )[ 0 ];
			let errorText;
3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918

			if ( errorElement ) {

				errorText = errorElement.textContent;

			} else {

				errorText = parserErrorToText( parserError );

			}

			console.error( 'THREE.ColladaLoader: Failed to parse collada file.\n', errorText );

			return null;

		}

		// metadata

3919
		const version = collada.getAttribute( 'version' );
3920 3921
		console.log( 'THREE.ColladaLoader: File version', version );

3922 3923
		const asset = parseAsset( getElementsByTagName( collada, 'asset' )[ 0 ] );
		const textureLoader = new TextureLoader( this.manager );
3924 3925
		textureLoader.setPath( this.resourcePath || path ).setCrossOrigin( this.crossOrigin );

3926
		let tgaLoader;
3927 3928 3929 3930 3931 3932 3933 3934 3935 3936

		if ( TGALoader ) {

			tgaLoader = new TGALoader( this.manager );
			tgaLoader.setPath( this.resourcePath || path );

		}

		//

3937 3938 3939
		const animations = [];
		let kinematics = {};
		let count = 0;
3940 3941 3942

		//

3943
		const library = {
3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988
			animations: {},
			clips: {},
			controllers: {},
			images: {},
			effects: {},
			materials: {},
			cameras: {},
			lights: {},
			geometries: {},
			nodes: {},
			visualScenes: {},
			kinematicsModels: {},
			physicsModels: {},
			kinematicsScenes: {}
		};

		parseLibrary( collada, 'library_animations', 'animation', parseAnimation );
		parseLibrary( collada, 'library_animation_clips', 'animation_clip', parseAnimationClip );
		parseLibrary( collada, 'library_controllers', 'controller', parseController );
		parseLibrary( collada, 'library_images', 'image', parseImage );
		parseLibrary( collada, 'library_effects', 'effect', parseEffect );
		parseLibrary( collada, 'library_materials', 'material', parseMaterial );
		parseLibrary( collada, 'library_cameras', 'camera', parseCamera );
		parseLibrary( collada, 'library_lights', 'light', parseLight );
		parseLibrary( collada, 'library_geometries', 'geometry', parseGeometry );
		parseLibrary( collada, 'library_nodes', 'node', parseNode );
		parseLibrary( collada, 'library_visual_scenes', 'visual_scene', parseVisualScene );
		parseLibrary( collada, 'library_kinematics_models', 'kinematics_model', parseKinematicsModel );
		parseLibrary( collada, 'library_physics_models', 'physics_model', parsePhysicsModel );
		parseLibrary( collada, 'scene', 'instance_kinematics_scene', parseKinematicsScene );

		buildLibrary( library.animations, buildAnimation );
		buildLibrary( library.clips, buildAnimationClip );
		buildLibrary( library.controllers, buildController );
		buildLibrary( library.images, buildImage );
		buildLibrary( library.effects, buildEffect );
		buildLibrary( library.materials, buildMaterial );
		buildLibrary( library.cameras, buildCamera );
		buildLibrary( library.lights, buildLight );
		buildLibrary( library.geometries, buildGeometry );
		buildLibrary( library.visualScenes, buildVisualScene );

		setupAnimations();
		setupKinematics();

3989
		const scene = parseScene( getElementsByTagName( collada, 'scene' )[ 0 ] );
M
Mugen87 已提交
3990
		scene.animations = animations;
3991 3992 3993 3994 3995 3996 3997 3998 3999 4000

		if ( asset.upAxis === 'Z_UP' ) {

			scene.quaternion.setFromEuler( new Euler( - Math.PI / 2, 0, 0 ) );

		}

		scene.scale.multiplyScalar( asset.unit );

		return {
M
Mugen87 已提交
4001 4002 4003 4004 4005 4006
			get animations() {

				console.warn( 'THREE.ColladaLoader: Please access animations over scene.animations now.' );
				return animations;

			},
4007 4008 4009 4010 4011 4012 4013
			kinematics: kinematics,
			library: library,
			scene: scene
		};

	}

4014
}
4015 4016

export { ColladaLoader };