GLTFLoader.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758
  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. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  567. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  568. var itemBytes = elementBytes * itemSize;
  569. // The buffer is not interleaved if the stride is the item size in bytes.
  570. if ( accessor.byteStride && accessor.byteStride !== itemBytes ) {
  571. // Use the full buffer if it's interleaved.
  572. var array = new TypedArray( arraybuffer );
  573. // Integer parameters to IB/IBA are in array elements, not bytes.
  574. var ib = new THREE.InterleavedBuffer( array, accessor.byteStride / elementBytes );
  575. return new THREE.InterleavedBufferAttribute( ib, itemSize, accessor.byteOffset / elementBytes );
  576. } else {
  577. array = new TypedArray( arraybuffer, accessor.byteOffset, accessor.count * itemSize );
  578. return new THREE.BufferAttribute( array, itemSize );
  579. }
  580. });
  581. }.bind( this ));
  582. };
  583. GLTFParser.prototype.loadTextures = function() {
  584. return _each( this.json.textures, function( texture, textureId ) {
  585. if ( texture.source ) {
  586. return new Promise( function( resolve ) {
  587. var source = this.json.images[ texture.source ];
  588. var textureLoader = THREE.Loader.Handlers.get( source.uri );
  589. if ( textureLoader === null ) {
  590. textureLoader = new THREE.TextureLoader();
  591. }
  592. textureLoader.crossOrigin = this.options.crossOrigin || false;
  593. textureLoader.load( resolveURL( source.uri, this.options.path ), function( _texture ) {
  594. _texture.flipY = false;
  595. if ( texture.sampler ) {
  596. var sampler = this.json.samplers[ texture.sampler ];
  597. _texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ];
  598. _texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ];
  599. _texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ];
  600. _texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ];
  601. }
  602. resolve( _texture );
  603. }.bind( this ));
  604. }.bind( this ));
  605. }
  606. }.bind( this ));
  607. };
  608. GLTFParser.prototype.loadMaterials = function() {
  609. return this._withDependencies([
  610. "shaders",
  611. "textures"
  612. ]).then( function( dependencies ) {
  613. return _each( this.json.materials, function( material, materialId ) {
  614. var materialType;
  615. var materialValues = {};
  616. var materialParams = {};
  617. var khr_material;
  618. if ( material.extensions && material.extensions.KHR_materials_common ) {
  619. khr_material = material.extensions.KHR_materials_common;
  620. } else if ( this.json.extensions && this.json.extensions.KHR_materials_common ) {
  621. khr_material = this.json.extensions.KHR_materials_common;
  622. }
  623. if ( khr_material ) {
  624. switch ( khr_material.technique )
  625. {
  626. case 'BLINN' :
  627. case 'PHONG' :
  628. materialType = THREE.MeshPhongMaterial;
  629. break;
  630. case 'LAMBERT' :
  631. materialType = THREE.MeshLambertMaterial;
  632. break;
  633. case 'CONSTANT' :
  634. default :
  635. materialType = THREE.MeshBasicMaterial;
  636. break;
  637. }
  638. _each( khr_material.values, function( value, prop ) {
  639. materialValues[ prop ] = value;
  640. });
  641. if ( khr_material.doubleSided || materialValues.doubleSided ) {
  642. materialParams.side = THREE.DoubleSide;
  643. }
  644. if ( khr_material.transparent || materialValues.transparent ) {
  645. materialParams.transparent = true;
  646. materialParams.opacity = ( materialValues.transparency !== undefined ) ? materialValues.transparency : 1;
  647. }
  648. } else if ( material.technique === undefined ) {
  649. materialType = THREE.MeshPhongMaterial;
  650. _each( material.values, function( value, prop ) {
  651. materialValues[ prop ] = value;
  652. });
  653. } else {
  654. materialType = DeferredShaderMaterial;
  655. var technique = this.json.techniques[ material.technique ];
  656. materialParams.uniforms = {};
  657. var program = this.json.programs[ technique.program ];
  658. if ( program ) {
  659. materialParams.fragmentShader = dependencies.shaders[ program.fragmentShader ];
  660. if ( ! materialParams.fragmentShader ) {
  661. console.warn( "ERROR: Missing fragment shader definition:", program.fragmentShader );
  662. materialType = THREE.MeshPhongMaterial;
  663. }
  664. var vertexShader = dependencies.shaders[ program.vertexShader ];
  665. if ( ! vertexShader ) {
  666. console.warn( "ERROR: Missing vertex shader definition:", program.vertexShader );
  667. materialType = THREE.MeshPhongMaterial;
  668. }
  669. // IMPORTANT: FIX VERTEX SHADER ATTRIBUTE DEFINITIONS
  670. materialParams.vertexShader = replaceTHREEShaderAttributes( vertexShader, technique );
  671. var uniforms = technique.uniforms;
  672. _each( uniforms, function( pname, uniformId ) {
  673. var shaderParam = technique.parameters[ pname ];
  674. var ptype = shaderParam.type;
  675. if ( WEBGL_TYPE[ ptype ] ) {
  676. var pcount = shaderParam.count;
  677. var value = material.values[ pname ];
  678. var uvalue = new WEBGL_TYPE[ ptype ]();
  679. var usemantic = shaderParam.semantic;
  680. var unode = shaderParam.node;
  681. switch ( ptype ) {
  682. case WEBGL_CONSTANTS.FLOAT:
  683. uvalue = shaderParam.value;
  684. if ( pname == "transparency" ) {
  685. materialParams.transparent = true;
  686. }
  687. if ( value !== undefined ) {
  688. uvalue = value;
  689. }
  690. break;
  691. case WEBGL_CONSTANTS.FLOAT_VEC2:
  692. case WEBGL_CONSTANTS.FLOAT_VEC3:
  693. case WEBGL_CONSTANTS.FLOAT_VEC4:
  694. case WEBGL_CONSTANTS.FLOAT_MAT3:
  695. if ( shaderParam && shaderParam.value ) {
  696. uvalue.fromArray( shaderParam.value );
  697. }
  698. if ( value ) {
  699. uvalue.fromArray( value );
  700. }
  701. break;
  702. case WEBGL_CONSTANTS.FLOAT_MAT2:
  703. // what to do?
  704. console.warn("FLOAT_MAT2 is not a supported uniform type");
  705. break;
  706. case WEBGL_CONSTANTS.FLOAT_MAT4:
  707. if ( pcount ) {
  708. uvalue = new Array( pcount );
  709. for ( var mi = 0; mi < pcount; mi ++ ) {
  710. uvalue[ mi ] = new WEBGL_TYPE[ ptype ]();
  711. }
  712. if ( shaderParam && shaderParam.value ) {
  713. var m4v = shaderParam.value;
  714. uvalue.fromArray( m4v );
  715. }
  716. if ( value ) {
  717. uvalue.fromArray( value );
  718. }
  719. } else {
  720. if ( shaderParam && shaderParam.value ) {
  721. var m4 = shaderParam.value;
  722. uvalue.fromArray( m4 );
  723. }
  724. if ( value ) {
  725. uvalue.fromArray( value );
  726. }
  727. }
  728. break;
  729. case WEBGL_CONSTANTS.SAMPLER_2D:
  730. uvalue = value ? dependencies.textures[ value ] : null;
  731. break;
  732. }
  733. materialParams.uniforms[ uniformId ] = {
  734. value: uvalue,
  735. semantic: usemantic,
  736. node: unode
  737. };
  738. } else {
  739. throw new Error( "Unknown shader uniform param type: " + ptype );
  740. }
  741. });
  742. }
  743. }
  744. if ( Array.isArray( materialValues.diffuse ) ) {
  745. materialParams.color = new THREE.Color().fromArray( materialValues.diffuse );
  746. } else if ( typeof( materialValues.diffuse ) === 'string' ) {
  747. materialParams.map = dependencies.textures[ materialValues.diffuse ];
  748. }
  749. delete materialParams.diffuse;
  750. if ( typeof( materialValues.reflective ) === 'string' ) {
  751. materialParams.envMap = dependencies.textures[ materialValues.reflective ];
  752. }
  753. if ( typeof( materialValues.bump ) === 'string' ) {
  754. materialParams.bumpMap = dependencies.textures[ materialValues.bump ];
  755. }
  756. if ( Array.isArray( materialValues.emission ) ) {
  757. materialParams.emissive = new THREE.Color().fromArray( materialValues.emission );
  758. }
  759. if ( Array.isArray( materialValues.specular ) ) {
  760. materialParams.specular = new THREE.Color().fromArray( materialValues.specular );
  761. }
  762. if ( materialValues.shininess !== undefined ) {
  763. materialParams.shininess = materialValues.shininess;
  764. }
  765. var _material = new materialType( materialParams );
  766. _material.name = material.name;
  767. return _material;
  768. }.bind( this ));
  769. }.bind( this ));
  770. };
  771. GLTFParser.prototype.loadMeshes = function() {
  772. return this._withDependencies([
  773. "accessors",
  774. "materials"
  775. ]).then( function( dependencies ) {
  776. return _each( this.json.meshes, function( mesh, meshId ) {
  777. var group = new THREE.Object3D();
  778. group.name = mesh.name;
  779. var primitives = mesh.primitives;
  780. _each( primitives, function( primitive ) {
  781. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES || primitive.mode === undefined ) {
  782. var geometry = new THREE.BufferGeometry();
  783. var attributes = primitive.attributes;
  784. _each( attributes, function( attributeEntry, attributeId ) {
  785. if ( !attributeEntry ) {
  786. return;
  787. }
  788. var bufferAttribute = dependencies.accessors[ attributeEntry ];
  789. switch ( attributeId ) {
  790. case 'POSITION':
  791. geometry.addAttribute( 'position', bufferAttribute );
  792. break;
  793. case 'NORMAL':
  794. geometry.addAttribute( 'normal', bufferAttribute );
  795. break;
  796. case 'TEXCOORD_0':
  797. case 'TEXCOORD0':
  798. case 'TEXCOORD':
  799. geometry.addAttribute( 'uv', bufferAttribute );
  800. break;
  801. case 'WEIGHT':
  802. geometry.addAttribute( 'skinWeight', bufferAttribute );
  803. break;
  804. case 'JOINT':
  805. geometry.addAttribute( 'skinIndex', bufferAttribute );
  806. break;
  807. }
  808. });
  809. if ( primitive.indices ) {
  810. var indexArray = dependencies.accessors[ primitive.indices ];
  811. geometry.setIndex( indexArray );
  812. var offset = {
  813. start: 0,
  814. index: 0,
  815. count: indexArray.count
  816. };
  817. geometry.groups.push( offset );
  818. geometry.computeBoundingSphere();
  819. }
  820. var material = dependencies.materials[ primitive.material ];
  821. var meshNode = new THREE.Mesh( geometry, material );
  822. meshNode.castShadow = true;
  823. group.add( meshNode );
  824. } else {
  825. console.warn("Non-triangular primitives are not supported");
  826. }
  827. });
  828. return group;
  829. });
  830. }.bind( this ));
  831. };
  832. GLTFParser.prototype.loadCameras = function() {
  833. return _each( this.json.cameras, function( camera, cameraId ) {
  834. if ( camera.type == "perspective" && camera.perspective ) {
  835. var yfov = camera.perspective.yfov;
  836. var xfov = camera.perspective.xfov;
  837. var aspect_ratio = camera.perspective.aspect_ratio || 1;
  838. // According to COLLADA spec...
  839. // aspect_ratio = xfov / yfov
  840. xfov = ( xfov === undefined && yfov ) ? yfov * aspect_ratio : xfov;
  841. // According to COLLADA spec...
  842. // aspect_ratio = xfov / yfov
  843. // yfov = ( yfov === undefined && xfov ) ? xfov / aspect_ratio : yfov;
  844. var _camera = new THREE.PerspectiveCamera( THREE.Math.radToDeg( xfov ), aspect_ratio, camera.perspective.znear || 1, camera.perspective.zfar || 2e6 );
  845. _camera.name = camera.name;
  846. return _camera;
  847. } else if ( camera.type == "orthographic" && camera.orthographic ) {
  848. var _camera = new THREE.OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, camera.orthographic.znear, camera.orthographic.zfar );
  849. _camera.name = camera.name;
  850. return _camera;
  851. }
  852. }.bind( this ));
  853. };
  854. GLTFParser.prototype.loadSkins = function() {
  855. return this._withDependencies([
  856. "accessors"
  857. ]).then( function( dependencies ) {
  858. return _each( this.json.skins, function( skin, skinId ) {
  859. var _skin = {
  860. bindShapeMatrix: new THREE.Matrix4().fromArray( skin.bindShapeMatrix ),
  861. jointNames: skin.jointNames,
  862. inverseBindMatrices: dependencies.accessors[ skin.inverseBindMatrices ]
  863. };
  864. return _skin;
  865. });
  866. }.bind( this ));
  867. };
  868. GLTFParser.prototype.loadAnimations = function() {
  869. return this._withDependencies([
  870. "accessors",
  871. "nodes"
  872. ]).then( function( dependencies ) {
  873. return _each( this.json.animations, function( animation, animationId ) {
  874. var interps = [];
  875. _each( animation.channels, function( channel ) {
  876. var sampler = animation.samplers[ channel.sampler ];
  877. if (sampler && animation.parameters) {
  878. var target = channel.target;
  879. var name = target.id;
  880. var input = animation.parameters[sampler.input];
  881. var output = animation.parameters[sampler.output];
  882. var inputAccessor = dependencies.accessors[ input ];
  883. var outputAccessor = dependencies.accessors[ output ];
  884. var node = dependencies.nodes[ name ];
  885. if ( node ) {
  886. var interp = {
  887. keys : inputAccessor.array,
  888. values : outputAccessor.array,
  889. count : inputAccessor.count,
  890. target : node,
  891. path : target.path,
  892. type : sampler.interpolation
  893. };
  894. interps.push( interp );
  895. }
  896. }
  897. });
  898. var _animation = new GLTFAnimation(interps);
  899. _animation.name = "animation_" + animationId;
  900. return _animation;
  901. });
  902. }.bind( this ));
  903. };
  904. GLTFParser.prototype.loadNodes = function() {
  905. return _each( this.json.nodes, function( node, nodeId ) {
  906. var matrix = new THREE.Matrix4();
  907. var _node;
  908. if ( node.jointName ) {
  909. _node = new THREE.Bone();
  910. _node.jointName = node.jointName;
  911. } else {
  912. _node = new THREE.Object3D()
  913. }
  914. _node.name = node.name;
  915. _node.matrixAutoUpdate = false;
  916. if ( node.matrix !== undefined ) {
  917. matrix.fromArray( node.matrix );
  918. _node.applyMatrix( matrix );
  919. } else {
  920. if ( node.translation !== undefined ) {
  921. _node.position.fromArray( node.translation );
  922. }
  923. if ( node.rotation !== undefined ) {
  924. _node.quaternion.fromArray( node.rotation );
  925. }
  926. if ( node.scale !== undefined ) {
  927. _node.scale.fromArray( node.scale );
  928. }
  929. }
  930. return _node;
  931. }.bind( this )).then( function( __nodes ) {
  932. return this._withDependencies([
  933. "meshes",
  934. "skins",
  935. "cameras",
  936. "extensions"
  937. ]).then( function( dependencies ) {
  938. return _each( __nodes, function( _node, nodeId ) {
  939. var node = this.json.nodes[ nodeId ];
  940. if ( node.meshes !== undefined ) {
  941. _each( node.meshes, function( meshId ) {
  942. var group = dependencies.meshes[ meshId ];
  943. _each( group.children, function( mesh ) {
  944. // clone Mesh to add to _node
  945. var originalMaterial = mesh.material;
  946. var originalGeometry = mesh.geometry;
  947. var material;
  948. if(originalMaterial.isDeferredShaderMaterial) {
  949. originalMaterial = material = originalMaterial.create();
  950. } else {
  951. material = originalMaterial;
  952. }
  953. mesh = new THREE.Mesh( originalGeometry, material );
  954. mesh.castShadow = true;
  955. var skinEntry;
  956. if ( node.skin ) {
  957. skinEntry = dependencies.skins[ node.skin ];
  958. }
  959. // Replace Mesh with SkinnedMesh in library
  960. if (skinEntry) {
  961. var geometry = originalGeometry;
  962. var material = originalMaterial;
  963. material.skinning = true;
  964. mesh = new THREE.SkinnedMesh( geometry, material, false );
  965. mesh.castShadow = true;
  966. var bones = [];
  967. var boneInverses = [];
  968. _each( skinEntry.jointNames, function( jointId, i ) {
  969. var jointNode = __nodes[ jointId ];
  970. if ( jointNode ) {
  971. jointNode.skin = mesh;
  972. bones.push(jointNode);
  973. var m = skinEntry.inverseBindMatrices.array;
  974. var mat = new THREE.Matrix4().fromArray( m, i * 16 );
  975. boneInverses.push(mat);
  976. } else {
  977. console.warn( "WARNING: joint: ''" + jointId + "' could not be found" );
  978. }
  979. });
  980. mesh.bind( new THREE.Skeleton( bones, boneInverses, false ), skinEntry.bindShapeMatrix );
  981. }
  982. _node.add( mesh );
  983. });
  984. });
  985. }
  986. if ( node.camera !== undefined ) {
  987. var camera = dependencies.cameras[ node.camera ];
  988. _node.add( camera );
  989. }
  990. if (node.extensions && node.extensions.KHR_materials_common
  991. && node.extensions.KHR_materials_common.light) {
  992. var light = dependencies.extensions.KHR_materials_common.lights[ node.extensions.KHR_materials_common.light ];
  993. _node.add(light);
  994. }
  995. return _node;
  996. }.bind( this ));
  997. }.bind( this ));
  998. }.bind( this ));
  999. };
  1000. GLTFParser.prototype.loadExtensions = function() {
  1001. return _each( this.json.extensions, function( extension, extensionId ) {
  1002. switch ( extensionId ) {
  1003. case "KHR_materials_common":
  1004. var extensionNode = {
  1005. lights: {}
  1006. };
  1007. var lights = extension.lights;
  1008. _each( lights, function( light, lightID ) {
  1009. var lightNode;
  1010. var lightParams = light[light.type];
  1011. var color = new THREE.Color().fromArray( lightParams.color );
  1012. switch ( light.type ) {
  1013. case "directional":
  1014. lightNode = new THREE.DirectionalLight( color );
  1015. lightNode.position.set( 0, 0, 1 );
  1016. break;
  1017. case "point":
  1018. lightNode = new THREE.PointLight( color );
  1019. break;
  1020. case "spot ":
  1021. lightNode = new THREE.SpotLight( color );
  1022. lightNode.position.set( 0, 0, 1 );
  1023. break;
  1024. case "ambient":
  1025. lightNode = new THREE.AmbientLight( color );
  1026. break;
  1027. }
  1028. if ( lightNode ) {
  1029. extensionNode.lights[ lightID ] = lightNode;
  1030. }
  1031. });
  1032. return extensionNode;
  1033. break;
  1034. }
  1035. }.bind( this ));
  1036. };
  1037. GLTFParser.prototype.loadScenes = function() {
  1038. // scene node hierachy builder
  1039. var buildNodeHierachy = function( nodeId, parentObject, allNodes ) {
  1040. var _node = allNodes[ nodeId ];
  1041. parentObject.add( _node );
  1042. var node = this.json.nodes[ nodeId ];
  1043. if ( node.children ) {
  1044. _each( node.children, function( child ) {
  1045. buildNodeHierachy( child, _node, allNodes );
  1046. });
  1047. }
  1048. }.bind( this );
  1049. return this._withDependencies([
  1050. "nodes"
  1051. ]).then( function( dependencies ) {
  1052. return _each( this.json.scenes, function( scene, sceneId ) {
  1053. var _scene = new THREE.Scene();
  1054. _scene.name = scene.name;
  1055. _each( scene.nodes, function( nodeId ) {
  1056. buildNodeHierachy( nodeId, _scene, dependencies.nodes );
  1057. });
  1058. _scene.traverse( function( child ) {
  1059. // Register raw material meshes with GLTFLoader.Shaders
  1060. if (child.material && child.material.isRawShaderMaterial) {
  1061. var xshader = new GLTFShader( child, dependencies.nodes );
  1062. THREE.GLTFLoader.Shaders.add( child.uuid, xshader );
  1063. }
  1064. });
  1065. return _scene;
  1066. });
  1067. }.bind( this ));
  1068. };
  1069. })();