GLTFLoader.js 34 KB

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