GLTFLoader.js 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811
  1. /**
  2. * @author Rich Tibbett / https://github.com/richtr
  3. * @author mrdoob / http://mrdoob.com/
  4. * @author Tony Parisi / http://www.tonyparisi.com/
  5. */
  6. THREE.GLTFLoader = ( function () {
  7. function GLTFLoader( manager ) {
  8. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  9. }
  10. GLTFLoader.prototype = {
  11. constructor: GLTFLoader,
  12. load: function ( url, onLoad, onProgress, onError ) {
  13. var scope = this;
  14. var path = this.path && ( typeof this.path === "string" ) ? this.path : THREE.Loader.prototype.extractUrlBase( url );
  15. var loader = new THREE.FileLoader( scope.manager );
  16. loader.load( url, function ( text ) {
  17. scope.parse( JSON.parse( text ), onLoad, path );
  18. }, onProgress, onError );
  19. },
  20. setCrossOrigin: function ( value ) {
  21. this.crossOrigin = value;
  22. },
  23. setPath: function ( value ) {
  24. this.path = value;
  25. },
  26. parse: function ( json, callback, path ) {
  27. console.time( 'GLTFLoader' );
  28. var parser = new GLTFParser( json, {
  29. path: path || this.path,
  30. crossOrigin: !! this.crossOrigin
  31. } );
  32. parser.parse( function ( scene, cameras, animations ) {
  33. console.timeEnd( 'GLTFLoader' );
  34. var glTF = {
  35. "scene": scene,
  36. "cameras": cameras,
  37. "animations": animations
  38. };
  39. callback( glTF );
  40. } );
  41. }
  42. };
  43. /* GLTFREGISTRY */
  44. function GLTFRegistry() {
  45. var objects = {};
  46. return {
  47. get: function ( key ) {
  48. return objects[ key ];
  49. },
  50. add: function ( key, object ) {
  51. objects[ key ] = object;
  52. },
  53. remove: function ( key ) {
  54. delete objects[ key ];
  55. },
  56. removeAll: function () {
  57. objects = {};
  58. },
  59. update: function ( scene, camera ) {
  60. for ( var name in objects ) {
  61. var object = objects[ name ];
  62. if ( object.update ) {
  63. object.update( scene, camera );
  64. }
  65. }
  66. }
  67. };
  68. }
  69. /* GLTFSHADERS */
  70. GLTFLoader.Shaders = new GLTFRegistry();
  71. /* GLTFSHADER */
  72. function GLTFShader( targetNode, allNodes ) {
  73. var scope = this;
  74. this.boundUniforms = {};
  75. // bind each uniform to its source node
  76. var uniforms = targetNode.material.uniforms;
  77. for ( var uniformId in uniforms ) {
  78. var uniform = uniforms[ uniformId ];
  79. if ( uniform.semantic ) {
  80. var sourceNodeRef = uniform.node;
  81. var sourceNode = targetNode;
  82. if ( sourceNodeRef ) {
  83. sourceNode = allNodes[ sourceNodeRef ];
  84. }
  85. scope.boundUniforms[ uniformId ] = {
  86. semantic: uniform.semantic,
  87. sourceNode: sourceNode,
  88. targetNode: targetNode,
  89. uniform: uniform
  90. };
  91. }
  92. }
  93. this._m4 = new THREE.Matrix4();
  94. }
  95. // Update - update all the uniform values
  96. GLTFShader.prototype.update = function ( scene, camera ) {
  97. // update scene graph
  98. scene.updateMatrixWorld();
  99. // update camera matrices and frustum
  100. camera.updateMatrixWorld();
  101. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  102. var boundUniforms = this.boundUniforms;
  103. for ( var name in boundUniforms ) {
  104. var boundUniform = boundUniforms[ name ];
  105. switch ( boundUniform.semantic ) {
  106. case "MODELVIEW":
  107. var m4 = boundUniform.uniform.value;
  108. m4.multiplyMatrices( camera.matrixWorldInverse, boundUniform.sourceNode.matrixWorld );
  109. break;
  110. case "MODELVIEWINVERSETRANSPOSE":
  111. var m3 = boundUniform.uniform.value;
  112. this._m4.multiplyMatrices( camera.matrixWorldInverse, boundUniform.sourceNode.matrixWorld );
  113. m3.getNormalMatrix( this._m4 );
  114. break;
  115. case "PROJECTION":
  116. var m4 = boundUniform.uniform.value;
  117. m4.copy( camera.projectionMatrix );
  118. break;
  119. case "JOINTMATRIX":
  120. var m4v = boundUniform.uniform.value;
  121. for ( var mi = 0; mi < m4v.length; mi ++ ) {
  122. // So it goes like this:
  123. // SkinnedMesh world matrix is already baked into MODELVIEW;
  124. // ransform joints to local space,
  125. // then transform using joint's inverse
  126. m4v[ mi ]
  127. .getInverse( boundUniform.sourceNode.matrixWorld )
  128. .multiply( boundUniform.targetNode.skeleton.bones[ mi ].matrixWorld )
  129. .multiply( boundUniform.targetNode.skeleton.boneInverses[ mi ] );
  130. }
  131. break;
  132. default :
  133. console.warn( "Unhandled shader semantic: " + boundUniform.semantic );
  134. break;
  135. }
  136. }
  137. };
  138. /* GLTFANIMATION */
  139. GLTFLoader.Animations = new GLTFRegistry();
  140. // Construction/initialization
  141. function GLTFAnimation( interps ) {
  142. this.running = false;
  143. this.loop = false;
  144. this.duration = 0;
  145. this.startTime = 0;
  146. this.interps = [];
  147. this.uuid = THREE.Math.generateUUID();
  148. if ( interps ) {
  149. this.createInterpolators( interps );
  150. }
  151. }
  152. GLTFAnimation.prototype.createInterpolators = function ( interps ) {
  153. for ( var i = 0, len = interps.length; i < len; i ++ ) {
  154. var interp = new GLTFInterpolator( interps[ i ] );
  155. this.interps.push( interp );
  156. this.duration = Math.max( this.duration, interp.duration );
  157. }
  158. };
  159. // Start/stop
  160. GLTFAnimation.prototype.play = function () {
  161. if ( this.running )
  162. return;
  163. this.startTime = Date.now();
  164. this.running = true;
  165. GLTFLoader.Animations.add( this.uuid, this );
  166. };
  167. GLTFAnimation.prototype.stop = function () {
  168. this.running = false;
  169. GLTFLoader.Animations.remove( this.uuid );
  170. };
  171. // Update - drive key frame evaluation
  172. GLTFAnimation.prototype.update = function () {
  173. if ( ! this.running ) return;
  174. var now = Date.now();
  175. var deltat = ( now - this.startTime ) / 1000;
  176. var t = deltat % this.duration;
  177. var nCycles = Math.floor( deltat / this.duration );
  178. var interps = this.interps;
  179. if ( nCycles >= 1 && ! this.loop ) {
  180. this.running = false;
  181. for ( var i = 0, l = interps.length; i < l; i ++ ) {
  182. interps[ i ].interp( this.duration );
  183. }
  184. this.stop();
  185. } else {
  186. for ( var i = 0, l = interps.length; i < l; i ++ ) {
  187. interps[ i ].interp( t );
  188. }
  189. }
  190. };
  191. /* GLTFINTERPOLATOR */
  192. function GLTFInterpolator( param ) {
  193. this.keys = param.keys;
  194. this.values = param.values;
  195. this.count = param.count;
  196. this.type = param.type;
  197. this.path = param.path;
  198. this.isRot = false;
  199. var node = param.target;
  200. node.updateMatrix();
  201. node.matrixAutoUpdate = true;
  202. this.targetNode = node;
  203. switch ( param.path ) {
  204. case "translation" :
  205. this.target = node.position;
  206. this.originalValue = node.position.clone();
  207. break;
  208. case "rotation" :
  209. this.target = node.quaternion;
  210. this.originalValue = node.quaternion.clone();
  211. this.isRot = true;
  212. break;
  213. case "scale" :
  214. this.target = node.scale;
  215. this.originalValue = node.scale.clone();
  216. break;
  217. }
  218. this.duration = this.keys[ this.count - 1 ];
  219. this.vec1 = new THREE.Vector3();
  220. this.vec2 = new THREE.Vector3();
  221. this.vec3 = new THREE.Vector3();
  222. this.quat1 = new THREE.Quaternion();
  223. this.quat2 = new THREE.Quaternion();
  224. this.quat3 = new THREE.Quaternion();
  225. }
  226. //Interpolation and tweening methods
  227. GLTFInterpolator.prototype.interp = function ( t ) {
  228. if ( t == this.keys[ 0 ] ) {
  229. if ( this.isRot ) {
  230. this.quat3.fromArray( this.values );
  231. } else {
  232. this.vec3.fromArray( this.values );
  233. }
  234. } else if ( t < this.keys[ 0 ] ) {
  235. if ( this.isRot ) {
  236. this.quat1.copy( this.originalValue );
  237. this.quat2.fromArray( this.values );
  238. THREE.Quaternion.slerp( this.quat1, this.quat2, this.quat3, t / this.keys[ 0 ] );
  239. } else {
  240. this.vec3.copy( this.originalValue );
  241. this.vec2.fromArray( this.values );
  242. this.vec3.lerp( this.vec2, t / this.keys[ 0 ] );
  243. }
  244. } else if ( t >= this.keys[ this.count - 1 ] ) {
  245. if ( this.isRot ) {
  246. this.quat3.fromArray( this.values, ( this.count - 1 ) * 4 );
  247. } else {
  248. this.vec3.fromArray( this.values, ( this.count - 1 ) * 3 );
  249. }
  250. } else {
  251. for ( var i = 0; i < this.count - 1; i ++ ) {
  252. var key1 = this.keys[ i ];
  253. var key2 = this.keys[ i + 1 ];
  254. if ( t >= key1 && t <= key2 ) {
  255. if ( this.isRot ) {
  256. this.quat1.fromArray( this.values, i * 4 );
  257. this.quat2.fromArray( this.values, ( i + 1 ) * 4 );
  258. THREE.Quaternion.slerp( this.quat1, this.quat2, this.quat3, ( t - key1 ) / ( key2 - key1 ) );
  259. } else {
  260. this.vec3.fromArray( this.values, i * 3 );
  261. this.vec2.fromArray( this.values, ( i + 1 ) * 3 );
  262. this.vec3.lerp( this.vec2, ( t - key1 ) / ( key2 - key1 ) );
  263. }
  264. }
  265. }
  266. }
  267. if ( this.target ) {
  268. if ( this.isRot ) {
  269. this.target.copy( this.quat3 );
  270. } else {
  271. this.target.copy( this.vec3 );
  272. }
  273. }
  274. };
  275. /*********************************/
  276. /********** INTERNALS ************/
  277. /*********************************/
  278. /* CONSTANTS */
  279. var WEBGL_CONSTANTS = {
  280. FLOAT: 5126,
  281. //FLOAT_MAT2: 35674,
  282. FLOAT_MAT3: 35675,
  283. FLOAT_MAT4: 35676,
  284. FLOAT_VEC2: 35664,
  285. FLOAT_VEC3: 35665,
  286. FLOAT_VEC4: 35666,
  287. LINEAR: 9729,
  288. REPEAT: 10497,
  289. SAMPLER_2D: 35678,
  290. TRIANGLES: 4,
  291. UNSIGNED_BYTE: 5121,
  292. UNSIGNED_SHORT: 5123,
  293. VERTEX_SHADER: 35633,
  294. FRAGMENT_SHADER: 35632
  295. };
  296. var WEBGL_TYPE = {
  297. 5126: Number,
  298. //35674: THREE.Matrix2,
  299. 35675: THREE.Matrix3,
  300. 35676: THREE.Matrix4,
  301. 35664: THREE.Vector2,
  302. 35665: THREE.Vector3,
  303. 35666: THREE.Vector4,
  304. 35678: THREE.Texture
  305. };
  306. var WEBGL_COMPONENT_TYPES = {
  307. 5120: Int8Array,
  308. 5121: Uint8Array,
  309. 5122: Int16Array,
  310. 5123: Uint16Array,
  311. 5125: Uint32Array,
  312. 5126: Float32Array
  313. };
  314. var WEBGL_FILTERS = {
  315. 9728: THREE.NearestFilter,
  316. 9729: THREE.LinearFilter,
  317. 9984: THREE.NearestMipMapNearestFilter,
  318. 9985: THREE.LinearMipMapNearestFilter,
  319. 9986: THREE.NearestMipMapLinearFilter,
  320. 9987: THREE.LinearMipMapLinearFilter
  321. };
  322. var WEBGL_WRAPPINGS = {
  323. 33071: THREE.ClampToEdgeWrapping,
  324. 33648: THREE.MirroredRepeatWrapping,
  325. 10497: THREE.RepeatWrapping
  326. };
  327. var WEBGL_TYPE_SIZES = {
  328. 'SCALAR': 1,
  329. 'VEC2': 2,
  330. 'VEC3': 3,
  331. 'VEC4': 4,
  332. 'MAT2': 4,
  333. 'MAT3': 9,
  334. 'MAT4': 16
  335. };
  336. /* UTILITY FUNCTIONS */
  337. function _each( object, callback, thisObj ) {
  338. if ( !object ) {
  339. return Promise.resolve();
  340. }
  341. var results;
  342. var fns = [];
  343. if ( Object.prototype.toString.call( object ) === '[object Array]' ) {
  344. results = [];
  345. var length = object.length;
  346. for ( var idx = 0; idx < length; idx ++ ) {
  347. var value = callback.call( thisObj || this, object[ idx ], idx );
  348. if ( value ) {
  349. fns.push( value );
  350. if ( value instanceof Promise ) {
  351. value.then( function( key, value ) {
  352. results[ idx ] = value;
  353. }.bind( this, key ));
  354. } else {
  355. results[ idx ] = value;
  356. }
  357. }
  358. }
  359. } else {
  360. results = {};
  361. for ( var key in object ) {
  362. if ( object.hasOwnProperty( key ) ) {
  363. var value = callback.call( thisObj || this, object[ key ], key );
  364. if ( value ) {
  365. fns.push( value );
  366. if ( value instanceof Promise ) {
  367. value.then( function( key, value ) {
  368. results[ key ] = value;
  369. }.bind( this, key ));
  370. } else {
  371. results[ key ] = value;
  372. }
  373. }
  374. }
  375. }
  376. }
  377. return Promise.all( fns ).then( function() {
  378. return results;
  379. });
  380. }
  381. function resolveURL( url, path ) {
  382. // Invalid URL
  383. if ( typeof url !== 'string' || url === '' )
  384. return '';
  385. // Absolute URL
  386. if ( /^https?:\/\//i.test( url ) ) {
  387. return url;
  388. }
  389. // Data URI
  390. if ( /^data:.*,.*$/i.test( url ) ) {
  391. return url;
  392. }
  393. // Relative URL
  394. return ( path || '' ) + url;
  395. }
  396. // Three.js seems too dependent on attribute names so globally
  397. // replace those in the shader code
  398. function replaceTHREEShaderAttributes( shaderText, technique ) {
  399. // Expected technique attributes
  400. var attributes = {};
  401. for ( var attributeId in technique.attributes ) {
  402. var pname = technique.attributes[ attributeId ];
  403. var param = technique.parameters[ pname ];
  404. var atype = param.type;
  405. var semantic = param.semantic;
  406. attributes[ attributeId ] = {
  407. type: atype,
  408. semantic: semantic
  409. };
  410. }
  411. // Figure out which attributes to change in technique
  412. var shaderParams = technique.parameters;
  413. var shaderAttributes = technique.attributes;
  414. var params = {};
  415. for ( var attributeId in attributes ) {
  416. var pname = shaderAttributes[ attributeId ];
  417. var shaderParam = shaderParams[ pname ];
  418. var semantic = shaderParam.semantic;
  419. if ( semantic ) {
  420. params[ attributeId ] = shaderParam;
  421. }
  422. }
  423. for ( var pname in params ) {
  424. var param = params[ pname ];
  425. var semantic = param.semantic;
  426. var regEx = new RegExp( "\\b" + pname + "\\b", "g" );
  427. switch ( semantic ) {
  428. case "POSITION":
  429. shaderText = shaderText.replace( regEx, 'position' );
  430. break;
  431. case "NORMAL":
  432. shaderText = shaderText.replace( regEx, 'normal' );
  433. break;
  434. case 'TEXCOORD_0':
  435. case 'TEXCOORD0':
  436. case 'TEXCOORD':
  437. shaderText = shaderText.replace( regEx, 'uv' );
  438. break;
  439. case "WEIGHT":
  440. shaderText = shaderText.replace( regEx, 'skinWeight' );
  441. break;
  442. case "JOINT":
  443. shaderText = shaderText.replace( regEx, 'skinIndex' );
  444. break;
  445. }
  446. }
  447. return shaderText;
  448. }
  449. // Deferred constructor for RawShaderMaterial types
  450. function DeferredShaderMaterial( params ) {
  451. this.isDeferredShaderMaterial = true;
  452. this.params = params;
  453. }
  454. DeferredShaderMaterial.prototype.create = function () {
  455. var uniforms = THREE.UniformsUtils.clone( this.params.uniforms );
  456. for ( var uniformId in this.params.uniforms ) {
  457. var originalUniform = this.params.uniforms[ uniformId ];
  458. if ( originalUniform.value instanceof THREE.Texture ) {
  459. uniforms[ uniformId ].value = originalUniform.value;
  460. uniforms[ uniformId ].value.needsUpdate = true;
  461. }
  462. uniforms[ uniformId ].semantic = originalUniform.semantic;
  463. uniforms[ uniformId ].node = originalUniform.node;
  464. }
  465. this.params.uniforms = uniforms;
  466. return new THREE.RawShaderMaterial( this.params );
  467. };
  468. /* GLTF PARSER */
  469. function GLTFParser( json, options ) {
  470. this.json = json || {};
  471. this.options = options || {};
  472. // loader object cache
  473. this.cache = new GLTFRegistry();
  474. }
  475. GLTFParser.prototype._withDependencies = function ( dependencies ) {
  476. var _dependencies = {};
  477. for ( var i = 0; i < dependencies.length; i ++ ) {
  478. var dependency = dependencies[ i ];
  479. var fnName = "load" + dependency.charAt( 0 ).toUpperCase() + dependency.slice( 1 );
  480. var cached = this.cache.get( dependency );
  481. if ( cached !== undefined ) {
  482. _dependencies[ dependency ] = cached;
  483. } else if ( this[ fnName ] ) {
  484. var fn = this[ fnName ]();
  485. this.cache.add( dependency, fn );
  486. _dependencies[ dependency ] = fn;
  487. }
  488. }
  489. return _each( _dependencies, function ( dependency ) {
  490. return dependency;
  491. } );
  492. };
  493. GLTFParser.prototype.parse = function ( callback ) {
  494. // Clear the loader cache
  495. this.cache.removeAll();
  496. // Fire the callback on complete
  497. this._withDependencies( [
  498. "scenes",
  499. "cameras",
  500. "animations"
  501. ] ).then( function ( dependencies ) {
  502. var scene = dependencies.scenes[ this.json.scene ];
  503. var cameras = [];
  504. for ( var name in dependencies.cameras ) {
  505. var camera = dependencies.cameras[ name ];
  506. cameras.push( camera );
  507. }
  508. var animations = [];
  509. for ( var name in dependencies.animations ) {
  510. var animation = dependencies.animations[ name ];
  511. animations.push( animation );
  512. }
  513. callback( scene, cameras, animations );
  514. }.bind( this ) );
  515. };
  516. GLTFParser.prototype.loadShaders = function () {
  517. return _each( this.json.shaders, function ( shader ) {
  518. return new Promise( function ( resolve ) {
  519. var loader = new THREE.FileLoader();
  520. loader.responseType = 'text';
  521. loader.load( resolveURL( shader.uri, this.options.path ), function ( shaderText ) {
  522. resolve( shaderText );
  523. } );
  524. }.bind( this ) );
  525. }.bind( this ) );
  526. };
  527. GLTFParser.prototype.loadBuffers = function () {
  528. return _each( this.json.buffers, function ( buffer ) {
  529. if ( buffer.type === 'arraybuffer' ) {
  530. return new Promise( function ( resolve ) {
  531. var loader = new THREE.FileLoader();
  532. loader.responseType = 'arraybuffer';
  533. loader.load( resolveURL( buffer.uri, this.options.path ), function ( buffer ) {
  534. resolve( buffer );
  535. } );
  536. }.bind( this ) );
  537. }
  538. }.bind( this ) );
  539. };
  540. GLTFParser.prototype.loadBufferViews = function () {
  541. return this._withDependencies( [
  542. "buffers"
  543. ] ).then( function ( dependencies ) {
  544. return _each( this.json.bufferViews, function ( bufferView ) {
  545. var arraybuffer = dependencies.buffers[ bufferView.buffer ];
  546. return arraybuffer.slice( bufferView.byteOffset, bufferView.byteOffset + bufferView.byteLength );
  547. } );
  548. }.bind( this ) );
  549. };
  550. GLTFParser.prototype.loadAccessors = function () {
  551. return this._withDependencies( [
  552. "bufferViews"
  553. ] ).then( function ( dependencies ) {
  554. return _each( this.json.accessors, function ( accessor ) {
  555. var arraybuffer = dependencies.bufferViews[ accessor.bufferView ];
  556. var itemSize = WEBGL_TYPE_SIZES[ accessor.type ];
  557. var TypedArray = WEBGL_COMPONENT_TYPES[ accessor.componentType ];
  558. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  559. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  560. var itemBytes = elementBytes * itemSize;
  561. // The buffer is not interleaved if the stride is the item size in bytes.
  562. if ( accessor.byteStride && accessor.byteStride !== itemBytes ) {
  563. // Use the full buffer if it's interleaved.
  564. var array = new TypedArray( arraybuffer );
  565. // Integer parameters to IB/IBA are in array elements, not bytes.
  566. var ib = new THREE.InterleavedBuffer( array, accessor.byteStride / elementBytes );
  567. return new THREE.InterleavedBufferAttribute( ib, itemSize, accessor.byteOffset / elementBytes );
  568. } else {
  569. array = new TypedArray( arraybuffer, accessor.byteOffset, accessor.count * itemSize );
  570. return new THREE.BufferAttribute( array, itemSize );
  571. }
  572. } );
  573. }.bind( this ) );
  574. };
  575. GLTFParser.prototype.loadTextures = function () {
  576. return _each( this.json.textures, function ( texture ) {
  577. if ( texture.source ) {
  578. return new Promise( function ( resolve ) {
  579. var source = this.json.images[ texture.source ];
  580. var textureLoader = THREE.Loader.Handlers.get( source.uri );
  581. if ( textureLoader === null ) {
  582. textureLoader = new THREE.TextureLoader();
  583. }
  584. textureLoader.crossOrigin = this.options.crossOrigin || false;
  585. textureLoader.load( resolveURL( source.uri, this.options.path ), function ( _texture ) {
  586. _texture.flipY = false;
  587. if ( texture.sampler ) {
  588. var sampler = this.json.samplers[ texture.sampler ];
  589. _texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ];
  590. _texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ];
  591. _texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ];
  592. _texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ];
  593. }
  594. resolve( _texture );
  595. }.bind( this ) );
  596. }.bind( this ) );
  597. }
  598. }.bind( this ) );
  599. };
  600. GLTFParser.prototype.loadMaterials = function () {
  601. return this._withDependencies( [
  602. "shaders",
  603. "textures"
  604. ] ).then( function ( dependencies ) {
  605. return _each( this.json.materials, function ( material ) {
  606. var materialType;
  607. var materialValues = {};
  608. var materialParams = {};
  609. var khr_material;
  610. if ( material.extensions && material.extensions.KHR_materials_common ) {
  611. khr_material = material.extensions.KHR_materials_common;
  612. } else if ( this.json.extensions && this.json.extensions.KHR_materials_common ) {
  613. khr_material = this.json.extensions.KHR_materials_common;
  614. }
  615. if ( khr_material ) {
  616. switch ( khr_material.technique ) {
  617. case 'BLINN' :
  618. case 'PHONG' :
  619. materialType = THREE.MeshPhongMaterial;
  620. break;
  621. case 'LAMBERT' :
  622. materialType = THREE.MeshLambertMaterial;
  623. break;
  624. case 'CONSTANT' :
  625. default :
  626. materialType = THREE.MeshBasicMaterial;
  627. break;
  628. }
  629. Object.assign( materialValues, khr_material.values );
  630. if ( khr_material.doubleSided || materialValues.doubleSided ) {
  631. materialParams.side = THREE.DoubleSide;
  632. }
  633. if ( khr_material.transparent || materialValues.transparent ) {
  634. materialParams.transparent = true;
  635. materialParams.opacity = ( materialValues.transparency !== undefined ) ? materialValues.transparency : 1;
  636. }
  637. } else if ( material.technique === undefined ) {
  638. materialType = THREE.MeshPhongMaterial;
  639. Object.assign( materialValues, material.values );
  640. } else {
  641. materialType = DeferredShaderMaterial;
  642. var technique = this.json.techniques[ material.technique ];
  643. materialParams.uniforms = {};
  644. var program = this.json.programs[ technique.program ];
  645. if ( program ) {
  646. materialParams.fragmentShader = dependencies.shaders[ program.fragmentShader ];
  647. if ( ! materialParams.fragmentShader ) {
  648. console.warn( "ERROR: Missing fragment shader definition:", program.fragmentShader );
  649. materialType = THREE.MeshPhongMaterial;
  650. }
  651. var vertexShader = dependencies.shaders[ program.vertexShader ];
  652. if ( ! vertexShader ) {
  653. console.warn( "ERROR: Missing vertex shader definition:", program.vertexShader );
  654. materialType = THREE.MeshPhongMaterial;
  655. }
  656. // IMPORTANT: FIX VERTEX SHADER ATTRIBUTE DEFINITIONS
  657. materialParams.vertexShader = replaceTHREEShaderAttributes( vertexShader, technique );
  658. var uniforms = technique.uniforms;
  659. for ( var uniformId in uniforms ) {
  660. var pname = uniforms[ uniformId ];
  661. var shaderParam = technique.parameters[ pname ];
  662. var ptype = shaderParam.type;
  663. if ( WEBGL_TYPE[ ptype ] ) {
  664. var pcount = shaderParam.count;
  665. var value = material.values[ pname ];
  666. var uvalue = new WEBGL_TYPE[ ptype ]();
  667. var usemantic = shaderParam.semantic;
  668. var unode = shaderParam.node;
  669. switch ( ptype ) {
  670. case WEBGL_CONSTANTS.FLOAT:
  671. uvalue = shaderParam.value;
  672. if ( pname == "transparency" ) {
  673. materialParams.transparent = true;
  674. }
  675. if ( value !== undefined ) {
  676. uvalue = value;
  677. }
  678. break;
  679. case WEBGL_CONSTANTS.FLOAT_VEC2:
  680. case WEBGL_CONSTANTS.FLOAT_VEC3:
  681. case WEBGL_CONSTANTS.FLOAT_VEC4:
  682. case WEBGL_CONSTANTS.FLOAT_MAT3:
  683. if ( shaderParam && shaderParam.value ) {
  684. uvalue.fromArray( shaderParam.value );
  685. }
  686. if ( value ) {
  687. uvalue.fromArray( value );
  688. }
  689. break;
  690. case WEBGL_CONSTANTS.FLOAT_MAT2:
  691. // what to do?
  692. console.warn( "FLOAT_MAT2 is not a supported uniform type" );
  693. break;
  694. case WEBGL_CONSTANTS.FLOAT_MAT4:
  695. if ( pcount ) {
  696. uvalue = new Array( pcount );
  697. for ( var mi = 0; mi < pcount; mi ++ ) {
  698. uvalue[ mi ] = new WEBGL_TYPE[ ptype ]();
  699. }
  700. if ( shaderParam && shaderParam.value ) {
  701. var m4v = shaderParam.value;
  702. uvalue.fromArray( m4v );
  703. }
  704. if ( value ) {
  705. uvalue.fromArray( value );
  706. }
  707. } else {
  708. if ( shaderParam && shaderParam.value ) {
  709. var m4 = shaderParam.value;
  710. uvalue.fromArray( m4 );
  711. }
  712. if ( value ) {
  713. uvalue.fromArray( value );
  714. }
  715. }
  716. break;
  717. case WEBGL_CONSTANTS.SAMPLER_2D:
  718. uvalue = value ? dependencies.textures[ value ] : null;
  719. break;
  720. }
  721. materialParams.uniforms[ uniformId ] = {
  722. value: uvalue,
  723. semantic: usemantic,
  724. node: unode
  725. };
  726. } else {
  727. throw new Error( "Unknown shader uniform param type: " + ptype );
  728. }
  729. }
  730. }
  731. }
  732. if ( Array.isArray( materialValues.diffuse ) ) {
  733. materialParams.color = new THREE.Color().fromArray( materialValues.diffuse );
  734. } else if ( typeof( materialValues.diffuse ) === 'string' ) {
  735. materialParams.map = dependencies.textures[ materialValues.diffuse ];
  736. }
  737. delete materialParams.diffuse;
  738. if ( typeof( materialValues.reflective ) === 'string' ) {
  739. materialParams.envMap = dependencies.textures[ materialValues.reflective ];
  740. }
  741. if ( typeof( materialValues.bump ) === 'string' ) {
  742. materialParams.bumpMap = dependencies.textures[ materialValues.bump ];
  743. }
  744. if ( Array.isArray( materialValues.emission ) ) {
  745. materialParams.emissive = new THREE.Color().fromArray( materialValues.emission );
  746. }
  747. if ( Array.isArray( materialValues.specular ) ) {
  748. materialParams.specular = new THREE.Color().fromArray( materialValues.specular );
  749. }
  750. if ( materialValues.shininess !== undefined ) {
  751. materialParams.shininess = materialValues.shininess;
  752. }
  753. var _material = new materialType( materialParams );
  754. _material.name = material.name;
  755. return _material;
  756. }.bind( this ) );
  757. }.bind( this ) );
  758. };
  759. GLTFParser.prototype.loadMeshes = function () {
  760. return this._withDependencies( [
  761. "accessors",
  762. "materials"
  763. ] ).then( function ( dependencies ) {
  764. return _each( this.json.meshes, function ( mesh ) {
  765. var group = new THREE.Object3D();
  766. group.name = mesh.name;
  767. var primitives = mesh.primitives;
  768. for ( var name in primitives ) {
  769. var primitive = primitives[ name ];
  770. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES || primitive.mode === undefined ) {
  771. var geometry = new THREE.BufferGeometry();
  772. var attributes = primitive.attributes;
  773. for ( var attributeId in attributes ) {
  774. var attributeEntry = attributes[ attributeId ];
  775. if ( ! attributeEntry ) return;
  776. var bufferAttribute = dependencies.accessors[ attributeEntry ];
  777. switch ( attributeId ) {
  778. case 'POSITION':
  779. geometry.addAttribute( 'position', bufferAttribute );
  780. break;
  781. case 'NORMAL':
  782. geometry.addAttribute( 'normal', bufferAttribute );
  783. break;
  784. case 'TEXCOORD_0':
  785. case 'TEXCOORD0':
  786. case 'TEXCOORD':
  787. geometry.addAttribute( 'uv', bufferAttribute );
  788. break;
  789. case 'WEIGHT':
  790. geometry.addAttribute( 'skinWeight', bufferAttribute );
  791. break;
  792. case 'JOINT':
  793. geometry.addAttribute( 'skinIndex', bufferAttribute );
  794. break;
  795. }
  796. }
  797. if ( primitive.indices ) {
  798. var indexArray = dependencies.accessors[ primitive.indices ];
  799. geometry.setIndex( indexArray );
  800. var offset = {
  801. start: 0,
  802. index: 0,
  803. count: indexArray.count
  804. };
  805. geometry.groups.push( offset );
  806. geometry.computeBoundingSphere();
  807. }
  808. var material = dependencies.materials[ primitive.material ];
  809. var meshNode = new THREE.Mesh( geometry, material );
  810. meshNode.castShadow = true;
  811. group.add( meshNode );
  812. } else {
  813. console.warn( "Non-triangular primitives are not supported" );
  814. }
  815. }
  816. return group;
  817. } );
  818. }.bind( this ) );
  819. };
  820. GLTFParser.prototype.loadCameras = function () {
  821. return _each( this.json.cameras, function ( camera ) {
  822. if ( camera.type == "perspective" && camera.perspective ) {
  823. var yfov = camera.perspective.yfov;
  824. var xfov = camera.perspective.xfov;
  825. var aspect_ratio = camera.perspective.aspect_ratio || 1;
  826. // According to COLLADA spec...
  827. // aspect_ratio = xfov / yfov
  828. xfov = ( xfov === undefined && yfov ) ? yfov * aspect_ratio : xfov;
  829. // According to COLLADA spec...
  830. // aspect_ratio = xfov / yfov
  831. // yfov = ( yfov === undefined && xfov ) ? xfov / aspect_ratio : yfov;
  832. var _camera = new THREE.PerspectiveCamera( THREE.Math.radToDeg( xfov ), aspect_ratio, camera.perspective.znear || 1, camera.perspective.zfar || 2e6 );
  833. _camera.name = camera.name;
  834. return _camera;
  835. } else if ( camera.type == "orthographic" && camera.orthographic ) {
  836. var _camera = new THREE.OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, camera.orthographic.znear, camera.orthographic.zfar );
  837. _camera.name = camera.name;
  838. return _camera;
  839. }
  840. }.bind( this ) );
  841. };
  842. GLTFParser.prototype.loadSkins = function () {
  843. var scope = this;
  844. return this._withDependencies( [
  845. "accessors"
  846. ] ).then( function ( dependencies ) {
  847. return _each( scope.json.skins, function ( skin ) {
  848. var _skin = {
  849. bindShapeMatrix: new THREE.Matrix4().fromArray( skin.bindShapeMatrix ),
  850. jointNames: skin.jointNames,
  851. inverseBindMatrices: dependencies.accessors[ skin.inverseBindMatrices ]
  852. };
  853. return _skin;
  854. } );
  855. } );
  856. };
  857. GLTFParser.prototype.loadAnimations = function () {
  858. var scope = this;
  859. return this._withDependencies( [
  860. "accessors",
  861. "nodes"
  862. ] ).then( function ( dependencies ) {
  863. return _each( scope.json.animations, function ( animation, animationId ) {
  864. var interps = [];
  865. for ( var channelId in animation.channels ) {
  866. var channel = animation.channels[ channelId ];
  867. var sampler = animation.samplers[ channel.sampler ];
  868. if ( sampler && animation.parameters ) {
  869. var target = channel.target;
  870. var name = target.id;
  871. var input = animation.parameters[ sampler.input ];
  872. var output = animation.parameters[ sampler.output ];
  873. var inputAccessor = dependencies.accessors[ input ];
  874. var outputAccessor = dependencies.accessors[ output ];
  875. var node = dependencies.nodes[ name ];
  876. if ( node ) {
  877. var interp = {
  878. keys: inputAccessor.array,
  879. values: outputAccessor.array,
  880. count: inputAccessor.count,
  881. target: node,
  882. path: target.path,
  883. type: sampler.interpolation
  884. };
  885. interps.push( interp );
  886. }
  887. }
  888. }
  889. var _animation = new GLTFAnimation( interps );
  890. _animation.name = "animation_" + animationId;
  891. return _animation;
  892. } );
  893. } );
  894. };
  895. GLTFParser.prototype.loadNodes = function () {
  896. return _each( this.json.nodes, function ( node ) {
  897. var matrix = new THREE.Matrix4();
  898. var _node;
  899. if ( node.jointName ) {
  900. _node = new THREE.Bone();
  901. _node.jointName = node.jointName;
  902. } else {
  903. _node = new THREE.Object3D();
  904. }
  905. _node.name = node.name;
  906. _node.matrixAutoUpdate = false;
  907. if ( node.matrix !== undefined ) {
  908. matrix.fromArray( node.matrix );
  909. _node.applyMatrix( matrix );
  910. } else {
  911. if ( node.translation !== undefined ) {
  912. _node.position.fromArray( node.translation );
  913. }
  914. if ( node.rotation !== undefined ) {
  915. _node.quaternion.fromArray( node.rotation );
  916. }
  917. if ( node.scale !== undefined ) {
  918. _node.scale.fromArray( node.scale );
  919. }
  920. }
  921. return _node;
  922. }.bind( this ) ).then( function ( __nodes ) {
  923. return this._withDependencies( [
  924. "meshes",
  925. "skins",
  926. "cameras",
  927. "extensions"
  928. ] ).then( function ( dependencies ) {
  929. return _each( __nodes, function ( _node, nodeId ) {
  930. var node = this.json.nodes[ nodeId ];
  931. if ( node.meshes !== undefined ) {
  932. for ( var meshId in node.meshes ) {
  933. var mesh = node.meshes[ meshId ];
  934. var group = dependencies.meshes[ mesh ];
  935. for ( var childrenId in group.children ) {
  936. var child = group.children[ childrenId ];
  937. // clone Mesh to add to _node
  938. var originalMaterial = child.material;
  939. var originalGeometry = child.geometry;
  940. var material;
  941. if ( originalMaterial.isDeferredShaderMaterial ) {
  942. originalMaterial = material = originalMaterial.create();
  943. } else {
  944. material = originalMaterial;
  945. }
  946. child = new THREE.Mesh( originalGeometry, material );
  947. child.castShadow = true;
  948. var skinEntry;
  949. if ( node.skin ) {
  950. skinEntry = dependencies.skins[ node.skin ];
  951. }
  952. // Replace Mesh with SkinnedMesh in library
  953. if ( skinEntry ) {
  954. var geometry = originalGeometry;
  955. var material = originalMaterial;
  956. material.skinning = true;
  957. child = new THREE.SkinnedMesh( geometry, material, false );
  958. child.castShadow = true;
  959. var bones = [];
  960. var boneInverses = [];
  961. for ( var i = 0, l = skinEntry.jointNames.length; i < l; i ++ ) {
  962. var jointId = skinEntry.jointNames[ i ];
  963. var jointNode = __nodes[ jointId ];
  964. if ( jointNode ) {
  965. jointNode.skin = child;
  966. bones.push( jointNode );
  967. var m = skinEntry.inverseBindMatrices.array;
  968. var mat = new THREE.Matrix4().fromArray( m, i * 16 );
  969. boneInverses.push( mat );
  970. } else {
  971. console.warn( "WARNING: joint: ''" + jointId + "' could not be found" );
  972. }
  973. }
  974. child.bind( new THREE.Skeleton( bones, boneInverses, false ), skinEntry.bindShapeMatrix );
  975. }
  976. _node.add( child );
  977. }
  978. }
  979. }
  980. if ( node.camera !== undefined ) {
  981. var camera = dependencies.cameras[ node.camera ];
  982. _node.add( camera );
  983. }
  984. if ( node.extensions && node.extensions.KHR_materials_common && node.extensions.KHR_materials_common.light ) {
  985. var light = dependencies.extensions.KHR_materials_common.lights[ node.extensions.KHR_materials_common.light ];
  986. _node.add( light );
  987. }
  988. return _node;
  989. }.bind( this ) );
  990. }.bind( this ) );
  991. }.bind( this ) );
  992. };
  993. GLTFParser.prototype.loadExtensions = function () {
  994. return _each( this.json.extensions, function ( extension, extensionId ) {
  995. switch ( extensionId ) {
  996. case "KHR_materials_common":
  997. var extensionNode = {
  998. lights: {}
  999. };
  1000. var lights = extension.lights;
  1001. for ( var lightId in lights ) {
  1002. var light = lights[ lightId ];
  1003. var lightNode;
  1004. var lightParams = light[ light.type ];
  1005. var color = new THREE.Color().fromArray( lightParams.color );
  1006. switch ( light.type ) {
  1007. case "directional":
  1008. lightNode = new THREE.DirectionalLight( color );
  1009. lightNode.position.set( 0, 0, 1 );
  1010. break;
  1011. case "point":
  1012. lightNode = new THREE.PointLight( color );
  1013. break;
  1014. case "spot ":
  1015. lightNode = new THREE.SpotLight( color );
  1016. lightNode.position.set( 0, 0, 1 );
  1017. break;
  1018. case "ambient":
  1019. lightNode = new THREE.AmbientLight( color );
  1020. break;
  1021. }
  1022. if ( lightNode ) {
  1023. extensionNode.lights[ lightId ] = lightNode;
  1024. }
  1025. }
  1026. return extensionNode;
  1027. break;
  1028. }
  1029. } );
  1030. };
  1031. GLTFParser.prototype.loadScenes = function () {
  1032. var scope = this;
  1033. // scene node hierachy builder
  1034. function buildNodeHierachy( nodeId, parentObject, allNodes ) {
  1035. var _node = allNodes[ nodeId ];
  1036. parentObject.add( _node );
  1037. var node = scope.json.nodes[ nodeId ];
  1038. if ( node.children ) {
  1039. var children = node.children;
  1040. for ( var i = 0, l = children.length; i < l; i ++ ) {
  1041. var child = children[ i ];
  1042. buildNodeHierachy( child, _node, allNodes );
  1043. }
  1044. }
  1045. }
  1046. return this._withDependencies( [
  1047. "nodes"
  1048. ] ).then( function ( dependencies ) {
  1049. return _each( scope.json.scenes, function ( scene ) {
  1050. var _scene = new THREE.Scene();
  1051. _scene.name = scene.name;
  1052. var nodes = scene.nodes;
  1053. for ( var i = 0, l = nodes.length; i < l; i ++ ) {
  1054. var nodeId = nodes[ i ];
  1055. buildNodeHierachy( nodeId, _scene, dependencies.nodes );
  1056. }
  1057. _scene.traverse( function ( child ) {
  1058. // Register raw material meshes with GLTFLoader.Shaders
  1059. if ( child.material && child.material.isRawShaderMaterial ) {
  1060. var xshader = new GLTFShader( child, dependencies.nodes );
  1061. GLTFLoader.Shaders.add( child.uuid, xshader );
  1062. }
  1063. } );
  1064. return _scene;
  1065. } );
  1066. } );
  1067. };
  1068. return GLTFLoader;
  1069. } )();