glTFLoader.js 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642
  1. /**
  2. * @author Tony Parisi / http://www.tonyparisi.com/
  3. */
  4. THREE.glTFLoader = function (showStatus) {
  5. this.useBufferGeometry = (THREE.glTFLoader.useBufferGeometry !== undefined ) ?
  6. THREE.glTFLoader.useBufferGeometry : true;
  7. this.meshesRequested = 0;
  8. this.meshesLoaded = 0;
  9. this.pendingMeshes = [];
  10. this.animationsRequested = 0;
  11. this.animationsLoaded = 0;
  12. this.animations = [];
  13. this.shadersRequested = 0;
  14. this.shadersLoaded = 0;
  15. this.shaders = {};
  16. THREE.Loader.call( this, showStatus );
  17. }
  18. THREE.glTFLoader.prototype = new THREE.Loader();
  19. THREE.glTFLoader.prototype.constructor = THREE.glTFLoader;
  20. THREE.glTFLoader.prototype.load = function( url, callback ) {
  21. var theLoader = this;
  22. // Utilities
  23. function RgbArraytoHex(colorArray) {
  24. if(!colorArray) return 0xFFFFFFFF;
  25. var r = Math.floor(colorArray[0] * 255),
  26. g = Math.floor(colorArray[1] * 255),
  27. b = Math.floor(colorArray[2] * 255),
  28. a = 255;
  29. var color = (a << 24) + (r << 16) + (g << 8) + b;
  30. return color;
  31. }
  32. function convertAxisAngleToQuaternion(rotations, count)
  33. {
  34. var q = new THREE.Quaternion;
  35. var axis = new THREE.Vector3;
  36. var euler = new THREE.Vector3;
  37. var i;
  38. for (i = 0; i < count; i++) {
  39. axis.set(rotations[i * 4], rotations[i * 4 + 1],
  40. rotations[i * 4 + 2]).normalize();
  41. var angle = rotations[i * 4 + 3];
  42. q.setFromAxisAngle(axis, angle);
  43. rotations[i * 4] = q.x;
  44. rotations[i * 4 + 1] = q.y;
  45. rotations[i * 4 + 2] = q.z;
  46. rotations[i * 4 + 3] = q.w;
  47. }
  48. }
  49. function componentsPerElementForGLType(glType) {
  50. switch (glType) {
  51. case WebGLRenderingContext.FLOAT :
  52. case WebGLRenderingContext.UNSIGNED_BYTE :
  53. case WebGLRenderingContext.UNSIGNED_SHORT :
  54. return 1;
  55. case WebGLRenderingContext.FLOAT_VEC2 :
  56. return 2;
  57. case WebGLRenderingContext.FLOAT_VEC3 :
  58. return 3;
  59. case WebGLRenderingContext.FLOAT_VEC4 :
  60. return 4;
  61. case WebGLRenderingContext.FLOAT_MAT4 :
  62. return 16;
  63. default:
  64. return null;
  65. }
  66. }
  67. function LoadTexture(src) {
  68. if(!src) { return null; }
  69. return THREE.ImageUtils.loadTexture(src);
  70. }
  71. // Geometry processing
  72. var ClassicGeometry = function() {
  73. if (theLoader.useBufferGeometry) {
  74. this.geometry = new THREE.BufferGeometry;
  75. }
  76. else {
  77. this.geometry = new THREE.Geometry;
  78. }
  79. this.totalAttributes = 0;
  80. this.loadedAttributes = 0;
  81. this.indicesLoaded = false;
  82. this.finished = false;
  83. this.onload = null;
  84. this.uvs = null;
  85. this.indexArray = null;
  86. };
  87. ClassicGeometry.prototype.constructor = ClassicGeometry;
  88. ClassicGeometry.prototype.buildArrayGeometry = function() {
  89. // Build indexed mesh
  90. var geometry = this.geometry;
  91. var normals = geometry.normals;
  92. var indexArray = this.indexArray;
  93. var uvs = this.uvs;
  94. var a, b, c;
  95. var i, l;
  96. var faceNormals = null;
  97. var faceTexcoords = null;
  98. for(i = 0, l = this.indexArray.length; i < l; i += 3) {
  99. a = indexArray[i];
  100. b = indexArray[i+1];
  101. c = indexArray[i+2];
  102. if(normals) {
  103. faceNormals = [normals[a], normals[b], normals[c]];
  104. }
  105. geometry.faces.push( new THREE.Face3( a, b, c, faceNormals, null, null ) );
  106. if(uvs) {
  107. geometry.faceVertexUvs[0].push([ uvs[a], uvs[b], uvs[c] ]);
  108. }
  109. }
  110. // Allow Three.js to calculate some values for us
  111. geometry.computeBoundingBox();
  112. geometry.computeBoundingSphere();
  113. geometry.computeFaceNormals();
  114. if(!normals) {
  115. geometry.computeVertexNormals();
  116. }
  117. }
  118. ClassicGeometry.prototype.buildBufferGeometry = function() {
  119. // Build indexed mesh
  120. var geometry = this.geometry;
  121. geometry.attributes.index = {
  122. itemSize: 1,
  123. array : this.indexArray
  124. };
  125. var offset = {
  126. start: 0,
  127. index: 0,
  128. count: this.indexArray.length
  129. };
  130. geometry.offsets.push( offset );
  131. geometry.computeBoundingSphere();
  132. }
  133. ClassicGeometry.prototype.checkFinished = function() {
  134. if(this.indexArray && this.loadedAttributes === this.totalAttributes) {
  135. if (theLoader.useBufferGeometry) {
  136. this.buildBufferGeometry();
  137. }
  138. else {
  139. this.buildArrayGeometry();
  140. }
  141. this.finished = true;
  142. if(this.onload) {
  143. this.onload();
  144. }
  145. }
  146. };
  147. // Delegate for processing index buffers
  148. var IndicesDelegate = function() {};
  149. IndicesDelegate.prototype.handleError = function(errorCode, info) {
  150. // FIXME: report error
  151. console.log("ERROR(IndicesDelegate):"+errorCode+":"+info);
  152. };
  153. IndicesDelegate.prototype.convert = function(resource, ctx) {
  154. return new Uint16Array(resource, 0, ctx.indices.count);
  155. };
  156. IndicesDelegate.prototype.resourceAvailable = function(glResource, ctx) {
  157. var geometry = ctx.geometry;
  158. geometry.indexArray = glResource;
  159. geometry.checkFinished();
  160. return true;
  161. };
  162. var indicesDelegate = new IndicesDelegate();
  163. var IndicesContext = function(indices, geometry) {
  164. this.indices = indices;
  165. this.geometry = geometry;
  166. };
  167. // Delegate for processing vertex attribute buffers
  168. var VertexAttributeDelegate = function() {};
  169. VertexAttributeDelegate.prototype.handleError = function(errorCode, info) {
  170. // FIXME: report error
  171. console.log("ERROR(VertexAttributeDelegate):"+errorCode+":"+info);
  172. };
  173. VertexAttributeDelegate.prototype.convert = function(resource, ctx) {
  174. return resource;
  175. };
  176. VertexAttributeDelegate.prototype.arrayResourceAvailable = function(glResource, ctx) {
  177. var geom = ctx.geometry;
  178. var attribute = ctx.attribute;
  179. var semantic = ctx.semantic;
  180. var floatArray;
  181. var i, l;
  182. //FIXME: Float32 is assumed here, but should be checked.
  183. if(semantic == "POSITION") {
  184. // TODO: Should be easy to take strides into account here
  185. floatArray = new Float32Array(glResource, 0, attribute.count * componentsPerElementForGLType(attribute.type));
  186. for(i = 0, l = floatArray.length; i < l; i += 3) {
  187. geom.geometry.vertices.push( new THREE.Vector3( floatArray[i], floatArray[i+1], floatArray[i+2] ) );
  188. }
  189. } else if(semantic == "NORMAL") {
  190. geom.geometry.normals = [];
  191. floatArray = new Float32Array(glResource, 0, attribute.count * componentsPerElementForGLType(attribute.type));
  192. for(i = 0, l = floatArray.length; i < l; i += 3) {
  193. geom.geometry.normals.push( new THREE.Vector3( floatArray[i], floatArray[i+1], floatArray[i+2] ) );
  194. }
  195. } else if ((semantic == "TEXCOORD_0") || (semantic == "TEXCOORD" )) {
  196. geom.uvs = [];
  197. floatArray = new Float32Array(glResource, 0, attribute.count * componentsPerElementForGLType(attribute.type));
  198. for(i = 0, l = floatArray.length; i < l; i += 2) {
  199. geom.uvs.push( new THREE.Vector2( floatArray[i], 1.0 - floatArray[i+1] ) );
  200. }
  201. }
  202. else if (semantic == "WEIGHT") {
  203. nComponents = componentsPerElementForGLType(attribute.type);
  204. floatArray = new Float32Array(glResource, 0, attribute.count * nComponents);
  205. for(i = 0, l = floatArray.length; i < l; i += 4) {
  206. geom.geometry.skinWeights.push( new THREE.Vector4( floatArray[i], floatArray[i+1], floatArray[i+2], floatArray[i+3] ) );
  207. }
  208. }
  209. else if (semantic == "JOINT") {
  210. nComponents = componentsPerElementForGLType(attribute.type);
  211. floatArray = new Float32Array(glResource, 0, attribute.count * nComponents);
  212. for(i = 0, l = floatArray.length; i < l; i += 4) {
  213. geom.geometry.skinIndices.push( new THREE.Vector4( floatArray[i], floatArray[i+1], floatArray[i+2], floatArray[i+3] ) );
  214. }
  215. }
  216. }
  217. VertexAttributeDelegate.prototype.bufferResourceAvailable = function(glResource, ctx) {
  218. var geom = ctx.geometry;
  219. var attribute = ctx.attribute;
  220. var semantic = ctx.semantic;
  221. var floatArray;
  222. var i, l;
  223. var nComponents;
  224. //FIXME: Float32 is assumed here, but should be checked.
  225. if(semantic == "POSITION") {
  226. // TODO: Should be easy to take strides into account here
  227. floatArray = new Float32Array(glResource, 0, attribute.count * componentsPerElementForGLType(attribute.type));
  228. geom.geometry.attributes.position = {
  229. itemSize: 3,
  230. array : floatArray
  231. };
  232. } else if(semantic == "NORMAL") {
  233. floatArray = new Float32Array(glResource, 0, attribute.count * componentsPerElementForGLType(attribute.type));
  234. geom.geometry.attributes.normal = {
  235. itemSize: 3,
  236. array : floatArray
  237. };
  238. } else if ((semantic == "TEXCOORD_0") || (semantic == "TEXCOORD" )) {
  239. nComponents = componentsPerElementForGLType(attribute.type);
  240. floatArray = new Float32Array(glResource, 0, attribute.count * nComponents);
  241. // N.B.: flip Y value... should we just set texture.flipY everywhere?
  242. for (i = 0; i < floatArray.length / 2; i++) {
  243. floatArray[i*2+1] = 1.0 - floatArray[i*2+1];
  244. }
  245. geom.geometry.attributes.uv = {
  246. itemSize: nComponents,
  247. array : floatArray
  248. };
  249. }
  250. else if (semantic == "WEIGHT") {
  251. nComponents = componentsPerElementForGLType(attribute.type);
  252. floatArray = new Float32Array(glResource, 0, attribute.count * nComponents);
  253. geom.geometry.attributes.skinWeight = {
  254. itemSize: nComponents,
  255. array : floatArray
  256. };
  257. }
  258. else if (semantic == "JOINT") {
  259. nComponents = componentsPerElementForGLType(attribute.type);
  260. floatArray = new Float32Array(glResource, 0, attribute.count * nComponents);
  261. geom.geometry.attributes.skinIndex = {
  262. itemSize: nComponents,
  263. array : floatArray
  264. };
  265. }
  266. }
  267. VertexAttributeDelegate.prototype.resourceAvailable = function(glResource, ctx) {
  268. if (theLoader.useBufferGeometry) {
  269. this.bufferResourceAvailable(glResource, ctx);
  270. }
  271. else {
  272. this.arrayResourceAvailable(glResource, ctx);
  273. }
  274. var geom = ctx.geometry;
  275. geom.loadedAttributes++;
  276. geom.checkFinished();
  277. return true;
  278. };
  279. var vertexAttributeDelegate = new VertexAttributeDelegate();
  280. var VertexAttributeContext = function(attribute, semantic, geometry) {
  281. this.attribute = attribute;
  282. this.semantic = semantic;
  283. this.geometry = geometry;
  284. };
  285. var Mesh = function() {
  286. this.primitives = [];
  287. this.materialsPending = [];
  288. this.loadedGeometry = 0;
  289. this.onCompleteCallbacks = [];
  290. };
  291. Mesh.prototype.addPrimitive = function(geometry, material) {
  292. var self = this;
  293. geometry.onload = function() {
  294. self.loadedGeometry++;
  295. self.checkComplete();
  296. };
  297. this.primitives.push({
  298. geometry: geometry,
  299. material: material,
  300. mesh: null
  301. });
  302. };
  303. Mesh.prototype.onComplete = function(callback) {
  304. this.onCompleteCallbacks.push(callback);
  305. this.checkComplete();
  306. };
  307. Mesh.prototype.checkComplete = function() {
  308. var self = this;
  309. if(this.onCompleteCallbacks.length && this.primitives.length == this.loadedGeometry) {
  310. this.onCompleteCallbacks.forEach(function(callback) {
  311. callback(self);
  312. });
  313. this.onCompleteCallbacks = [];
  314. }
  315. };
  316. Mesh.prototype.attachToNode = function(threeNode) {
  317. // Assumes that the geometry is complete
  318. this.primitives.forEach(function(primitive) {
  319. /*if(!primitive.mesh) {
  320. primitive.mesh = new THREE.Mesh(primitive.geometry, primitive.material);
  321. }*/
  322. var material = primitive.material;
  323. if (!(material instanceof THREE.Material)) {
  324. material = theLoader.createShaderMaterial(material);
  325. }
  326. var threeMesh = new THREE.Mesh(primitive.geometry.geometry, material);
  327. threeMesh.castShadow = true;
  328. threeNode.add(threeMesh);
  329. });
  330. };
  331. // Delayed-loaded material
  332. var Material = function(params) {
  333. this.params = params;
  334. };
  335. // Delegate for processing animation parameter buffers
  336. var AnimationParameterDelegate = function() {};
  337. AnimationParameterDelegate.prototype.handleError = function(errorCode, info) {
  338. // FIXME: report error
  339. console.log("ERROR(AnimationParameterDelegate):"+errorCode+":"+info);
  340. };
  341. AnimationParameterDelegate.prototype.convert = function(resource, ctx) {
  342. var parameter = ctx.parameter;
  343. var glResource = null;
  344. switch (parameter.type) {
  345. case WebGLRenderingContext.FLOAT :
  346. case WebGLRenderingContext.FLOAT_VEC2 :
  347. case WebGLRenderingContext.FLOAT_VEC3 :
  348. case WebGLRenderingContext.FLOAT_VEC4 :
  349. glResource = new Float32Array(resource, 0, parameter.count * componentsPerElementForGLType(parameter.type));
  350. break;
  351. default:
  352. break;
  353. }
  354. return glResource;
  355. };
  356. AnimationParameterDelegate.prototype.resourceAvailable = function(glResource, ctx) {
  357. var animation = ctx.animation;
  358. var parameter = ctx.parameter;
  359. parameter.data = glResource;
  360. animation.handleParameterLoaded(parameter);
  361. return true;
  362. };
  363. var animationParameterDelegate = new AnimationParameterDelegate();
  364. var AnimationParameterContext = function(parameter, animation) {
  365. this.parameter = parameter;
  366. this.animation = animation;
  367. };
  368. // Animations
  369. var Animation = function() {
  370. // create Three.js keyframe here
  371. this.totalParameters = 0;
  372. this.loadedParameters = 0;
  373. this.parameters = {};
  374. this.finishedLoading = false;
  375. this.onload = null;
  376. };
  377. Animation.prototype.constructor = Animation;
  378. Animation.prototype.handleParameterLoaded = function(parameter) {
  379. this.parameters[parameter.name] = parameter;
  380. this.loadedParameters++;
  381. this.checkFinished();
  382. };
  383. Animation.prototype.checkFinished = function() {
  384. if(this.loadedParameters === this.totalParameters) {
  385. // Build animation
  386. this.finishedLoading = true;
  387. if (this.onload) {
  388. this.onload();
  389. }
  390. }
  391. };
  392. // Delegate for processing inverse bind matrices buffer
  393. var InverseBindMatricesDelegate = function() {};
  394. InverseBindMatricesDelegate.prototype.handleError = function(errorCode, info) {
  395. // FIXME: report error
  396. console.log("ERROR(InverseBindMatricesDelegate):"+errorCode+":"+info);
  397. };
  398. InverseBindMatricesDelegate.prototype.convert = function(resource, ctx) {
  399. var parameter = ctx.parameter;
  400. var glResource = null;
  401. switch (parameter.type) {
  402. case WebGLRenderingContext.FLOAT_MAT4 :
  403. glResource = new Float32Array(resource, 0, parameter.count * componentsPerElementForGLType(parameter.type));
  404. break;
  405. default:
  406. break;
  407. }
  408. return glResource;
  409. };
  410. InverseBindMatricesDelegate.prototype.resourceAvailable = function(glResource, ctx) {
  411. var skin = ctx.skin;
  412. skin.inverseBindMatrices = glResource;
  413. return true;
  414. };
  415. var inverseBindMatricesDelegate = new InverseBindMatricesDelegate();
  416. var InverseBindMatricesContext = function(param, skin) {
  417. this.parameter = param;
  418. this.skin = skin;
  419. };
  420. // Delegate for processing shaders from external files
  421. var ShaderDelegate = function() {};
  422. ShaderDelegate.prototype.handleError = function(errorCode, info) {
  423. // FIXME: report error
  424. console.log("ERROR(ShaderDelegate):"+errorCode+":"+info);
  425. };
  426. ShaderDelegate.prototype.convert = function(resource, ctx) {
  427. return resource;
  428. }
  429. ShaderDelegate.prototype.resourceAvailable = function(data, ctx) {
  430. theLoader.shadersLoaded++;
  431. theLoader.shaders[ctx.id] = data;
  432. return true;
  433. };
  434. var shaderDelegate = new ShaderDelegate();
  435. var ShaderContext = function(id, path) {
  436. this.id = id;
  437. this.path = path;
  438. };
  439. // Resource management
  440. var ResourceEntry = function(entryID, object, description) {
  441. this.entryID = entryID;
  442. this.object = object;
  443. this.description = description;
  444. };
  445. var Resources = function() {
  446. this._entries = {};
  447. };
  448. Resources.prototype.setEntry = function(entryID, object, description) {
  449. if (!entryID) {
  450. console.error("No EntryID provided, cannot store", description);
  451. return;
  452. }
  453. if (this._entries[entryID]) {
  454. console.warn("entry["+entryID+"] is being overwritten");
  455. }
  456. this._entries[entryID] = new ResourceEntry(entryID, object, description );
  457. };
  458. Resources.prototype.getEntry = function(entryID) {
  459. return this._entries[entryID];
  460. };
  461. Resources.prototype.clearEntries = function() {
  462. this._entries = {};
  463. };
  464. LoadDelegate = function() {
  465. }
  466. LoadDelegate.prototype.loadCompleted = function(callback, obj) {
  467. callback.call(Window, obj);
  468. }
  469. // Loader
  470. var ThreeGLTFLoader = Object.create(glTFParser, {
  471. load: {
  472. enumerable: true,
  473. value: function(userInfo, options) {
  474. this.resources = new Resources();
  475. this.cameras = [];
  476. this.lights = [];
  477. this.animations = [];
  478. this.joints = {};
  479. this.skeltons = {};
  480. THREE.GLTFLoaderUtils.init();
  481. glTFParser.load.call(this, userInfo, options);
  482. }
  483. },
  484. cameras: {
  485. enumerable: true,
  486. writable: true,
  487. value : []
  488. },
  489. lights: {
  490. enumerable: true,
  491. writable: true,
  492. value : []
  493. },
  494. animations: {
  495. enumerable: true,
  496. writable: true,
  497. value : []
  498. },
  499. // Implement WebGLTFLoader handlers
  500. handleBuffer: {
  501. value: function(entryID, description, userInfo) {
  502. this.resources.setEntry(entryID, null, description);
  503. description.type = "ArrayBuffer";
  504. return true;
  505. }
  506. },
  507. handleBufferView: {
  508. value: function(entryID, description, userInfo) {
  509. this.resources.setEntry(entryID, null, description);
  510. var buffer = this.resources.getEntry(description.buffer);
  511. description.type = "ArrayBufferView";
  512. var bufferViewEntry = this.resources.getEntry(entryID);
  513. bufferViewEntry.buffer = buffer;
  514. return true;
  515. }
  516. },
  517. handleShader: {
  518. value: function(entryID, description, userInfo) {
  519. this.resources.setEntry(entryID, null, description);
  520. var shaderRequest = {
  521. id : entryID,
  522. path : description.path,
  523. };
  524. var shaderContext = new ShaderContext(entryID, description.path);
  525. theLoader.shadersRequested++;
  526. THREE.GLTFLoaderUtils.getFile(shaderRequest, shaderDelegate, shaderContext);
  527. return true;
  528. }
  529. },
  530. handleProgram: {
  531. value: function(entryID, description, userInfo) {
  532. this.resources.setEntry(entryID, null, description);
  533. return true;
  534. }
  535. },
  536. handleTechnique: {
  537. value: function(entryID, description, userInfo) {
  538. this.resources.setEntry(entryID, null, description);
  539. return true;
  540. }
  541. },
  542. createShaderMaterial : {
  543. value: function(material) {
  544. var fragmentShader = theLoader.shaders[material.params.fragmentShader];
  545. if (!fragmentShader) {
  546. console.log("ERROR: Missing fragment shader definition:", material.params.fragmentShader);
  547. return new THREE.MeshPhongMaterial;
  548. }
  549. var vertexShader = theLoader.shaders[material.params.vertexShader];
  550. if (!fragmentShader) {
  551. console.log("ERROR: Missing vertex shader definition:", material.params.vertexShader);
  552. return new THREE.MeshPhongMaterial;
  553. }
  554. var uniforms = {};
  555. var shaderMaterial = new THREE.ShaderMaterial( {
  556. fragmentShader: fragmentShader,
  557. vertexShader: vertexShader,
  558. uniforms: uniforms,
  559. } );
  560. return new THREE.MeshPhongMaterial(material.params);
  561. }
  562. },
  563. createShaderParams : {
  564. value: function(materialId, values, params, instanceProgram) {
  565. var program = this.resources.getEntry(instanceProgram.program);
  566. if (program) {
  567. params.fragmentShader = program.description.fragmentShader;
  568. params.vertexShader = program.description.vertexShader;
  569. params.attributes = instanceProgram.attributes;
  570. params.uniforms = instanceProgram.uniforms;
  571. }
  572. }
  573. },
  574. threeJSMaterialType : {
  575. value: function(materialId, technique, values, params) {
  576. var materialType = THREE.MeshPhongMaterial;
  577. var defaultPass = null;
  578. if (technique && technique.description && technique.description.passes)
  579. defaultPass = technique.description.passes.defaultPass;
  580. if (defaultPass) {
  581. if (defaultPass.details && defaultPass.details.commonProfile) {
  582. var profile = technique.description.passes.defaultPass.details.commonProfile;
  583. if (profile)
  584. {
  585. switch (profile.lightingModel)
  586. {
  587. case 'Blinn' :
  588. case 'Phong' :
  589. materialType = THREE.MeshPhongMaterial;
  590. break;
  591. case 'Lambert' :
  592. materialType = THREE.MeshLambertMaterial;
  593. break;
  594. default :
  595. materialType = THREE.MeshBasicMaterial;
  596. break;
  597. }
  598. if (profile.extras && profile.extras.doubleSided)
  599. {
  600. params.side = THREE.DoubleSide;
  601. }
  602. }
  603. }
  604. else if (defaultPass.instanceProgram) {
  605. var instanceProgram = defaultPass.instanceProgram;
  606. this.createShaderParams(materialId, values, params, instanceProgram);
  607. var loadshaders = true;
  608. if (loadshaders) {
  609. materialType = Material;
  610. }
  611. }
  612. }
  613. var texturePath = null;
  614. var textureParams = null;
  615. var diffuse = values.diffuse;
  616. if (diffuse)
  617. {
  618. var texture = diffuse;
  619. if (texture) {
  620. var textureEntry = this.resources.getEntry(texture);
  621. if (textureEntry) {
  622. {
  623. var imageEntry = this.resources.getEntry(textureEntry.description.source);
  624. if (imageEntry) {
  625. texturePath = imageEntry.description.path;
  626. }
  627. var samplerEntry = this.resources.getEntry(textureEntry.description.sampler);
  628. if (samplerEntry) {
  629. textureParams = samplerEntry.description;
  630. }
  631. }
  632. }
  633. }
  634. }
  635. var texture = LoadTexture(texturePath);
  636. if (texture && textureParams) {
  637. if (textureParams.wrapS == WebGLRenderingContext.REPEAT)
  638. texture.wrapS = THREE.RepeatWrapping;
  639. if (textureParams.wrapT == WebGLRenderingContext.REPEAT)
  640. texture.wrapT = THREE.RepeatWrapping;
  641. if (textureParams.magFilter == WebGLRenderingContext.LINEAR)
  642. texture.magFilter = THREE.LinearFilter;
  643. // if (textureParams.minFilter == "LINEAR")
  644. // texture.minFilter = THREE.LinearFilter;
  645. params.map = texture;
  646. }
  647. var envMapPath = null;
  648. var envMapParams = null;
  649. var reflective = values.reflective;
  650. if (reflective)
  651. {
  652. var texture = reflective;
  653. if (texture) {
  654. var textureEntry = this.resources.getEntry(texture);
  655. if (textureEntry) {
  656. {
  657. var imageEntry = this.resources.getEntry(textureEntry.description.source);
  658. if (imageEntry) {
  659. envMapPath = imageEntry.description.path;
  660. }
  661. var samplerEntry = this.resources.getEntry(textureEntry.description.sampler);
  662. if (samplerEntry) {
  663. envMapParams = samplerEntry.description;
  664. }
  665. }
  666. }
  667. }
  668. }
  669. var texture = LoadTexture(envMapPath);
  670. if (texture && envMapParams) {
  671. if (envMapParams.wrapS == WebGLRenderingContext.REPEAT)
  672. texture.wrapS = THREE.RepeatWrapping;
  673. if (envMapParams.wrapT == WebGLRenderingContext.REPEAT)
  674. texture.wrapT = THREE.RepeatWrapping;
  675. if (envMapParams.magFilter == WebGLRenderingContext.LINEAR)
  676. texture.magFilter = THREE.LinearFilter;
  677. // if (envMapParams.minFilter == WebGLRenderingContext.LINEAR)
  678. // texture.minFilter = THREE.LinearFilter;
  679. params.envMap = texture;
  680. }
  681. var shininess = values.shininesss || values.shininess; // N.B.: typo in converter!
  682. if (shininess)
  683. {
  684. shininess = shininess;
  685. }
  686. var diffuseColor = !texturePath ? diffuse : null;
  687. var opacity = 1.0;
  688. if (values.hasOwnProperty("transparency"))
  689. {
  690. var USE_A_ONE = true; // for now, hack because file format isn't telling us
  691. opacity = USE_A_ONE ? values.transparency : (1.0 - values.transparency);
  692. }
  693. // if (diffuseColor) diffuseColor = [0, 1, 0];
  694. params.color = RgbArraytoHex(diffuseColor);
  695. params.opacity = opacity;
  696. params.transparent = opacity < 1.0;
  697. // hack hack hack
  698. if (texturePath && texturePath.toLowerCase().indexOf(".png") != -1)
  699. params.transparent = true;
  700. if (!(shininess === undefined))
  701. {
  702. params.shininess = shininess;
  703. }
  704. if (!(values.ambient === undefined) && !(typeof(values.ambient) == 'string'))
  705. {
  706. params.ambient = RgbArraytoHex(values.ambient);
  707. }
  708. if (!(values.emission === undefined))
  709. {
  710. params.emissive = RgbArraytoHex(values.emission);
  711. }
  712. if (!(values.specular === undefined))
  713. {
  714. params.specular = RgbArraytoHex(values.specular);
  715. }
  716. return materialType;
  717. }
  718. },
  719. handleMaterial: {
  720. value: function(entryID, description, userInfo) {
  721. //this should be rewritten using the meta datas that actually create the shader.
  722. //here we will infer what needs to be pass to Three.js by looking inside the technique parameters.
  723. var technique = this.resources.getEntry(description.instanceTechnique.technique);
  724. var materialParams = {};
  725. var values = description.instanceTechnique.values;
  726. var materialType = this.threeJSMaterialType(entryID, technique, values, materialParams);
  727. var material = new materialType(materialParams);
  728. this.resources.setEntry(entryID, material, description);
  729. return true;
  730. }
  731. },
  732. handleMesh: {
  733. value: function(entryID, description, userInfo) {
  734. var mesh = new Mesh();
  735. this.resources.setEntry(entryID, mesh, description);
  736. var primitivesDescription = description.primitives;
  737. if (!primitivesDescription) {
  738. //FIXME: not implemented in delegate
  739. console.log("MISSING_PRIMITIVES for mesh:"+ entryID);
  740. return false;
  741. }
  742. for (var i = 0 ; i < primitivesDescription.length ; i++) {
  743. var primitiveDescription = primitivesDescription[i];
  744. if (primitiveDescription.primitive === WebGLRenderingContext.TRIANGLES) {
  745. var geometry = new ClassicGeometry();
  746. var materialEntry = this.resources.getEntry(primitiveDescription.material);
  747. mesh.addPrimitive(geometry, materialEntry.object);
  748. var indices = this.resources.getEntry(primitiveDescription.indices);
  749. var bufferEntry = this.resources.getEntry(indices.description.bufferView);
  750. var indicesObject = {
  751. bufferView : bufferEntry,
  752. byteOffset : indices.description.byteOffset,
  753. count : indices.description.count,
  754. id : indices.entryID,
  755. type : indices.description.type
  756. };
  757. var indicesContext = new IndicesContext(indicesObject, geometry);
  758. var alreadyProcessedIndices = THREE.GLTFLoaderUtils.getBuffer(indicesObject, indicesDelegate, indicesContext);
  759. /*if(alreadyProcessedIndices) {
  760. indicesDelegate.resourceAvailable(alreadyProcessedIndices, indicesContext);
  761. }*/
  762. // Load Vertex Attributes
  763. var allAttributes = Object.keys(primitiveDescription.attributes);
  764. allAttributes.forEach( function(semantic) {
  765. geometry.totalAttributes++;
  766. var attribute;
  767. var attributeID = primitiveDescription.attributes[semantic];
  768. var attributeEntry = this.resources.getEntry(attributeID);
  769. if (!attributeEntry) {
  770. //let's just use an anonymous object for the attribute
  771. attribute = description.attributes[attributeID];
  772. attribute.id = attributeID;
  773. this.resources.setEntry(attributeID, attribute, attribute);
  774. var bufferEntry = this.resources.getEntry(attribute.bufferView);
  775. attributeEntry = this.resources.getEntry(attributeID);
  776. } else {
  777. attribute = attributeEntry.object;
  778. attribute.id = attributeID;
  779. var bufferEntry = this.resources.getEntry(attribute.bufferView);
  780. }
  781. var attributeObject = {
  782. bufferView : bufferEntry,
  783. byteOffset : attribute.byteOffset,
  784. byteStride : attribute.byteStride,
  785. count : attribute.count,
  786. max : attribute.max,
  787. min : attribute.min,
  788. type : attribute.type,
  789. id : attributeID
  790. };
  791. var attribContext = new VertexAttributeContext(attributeObject, semantic, geometry);
  792. var alreadyProcessedAttribute = THREE.GLTFLoaderUtils.getBuffer(attributeObject, vertexAttributeDelegate, attribContext);
  793. /*if(alreadyProcessedAttribute) {
  794. vertexAttributeDelegate.resourceAvailable(alreadyProcessedAttribute, attribContext);
  795. }*/
  796. }, this);
  797. }
  798. }
  799. return true;
  800. }
  801. },
  802. handleCamera: {
  803. value: function(entryID, description, userInfo) {
  804. var camera;
  805. if (description.type == "perspective")
  806. {
  807. var znear = description.perspective.znear;
  808. var zfar = description.perspective.zfar;
  809. var yfov = description.perspective.yfov;
  810. var xfov = description.perspective.xfov;
  811. var aspect_ratio = description.perspective.aspect_ratio;
  812. if (!aspect_ratio)
  813. aspect_ratio = 1;
  814. if (yfov === undefined)
  815. {
  816. if (xfov)
  817. {
  818. // According to COLLADA spec...
  819. // aspect_ratio = xfov / yfov
  820. yfov = xfov / aspect_ratio;
  821. }
  822. }
  823. if (yfov)
  824. {
  825. camera = new THREE.PerspectiveCamera(yfov, aspect_ratio, znear, zfar);
  826. }
  827. }
  828. else
  829. {
  830. camera = new THREE.OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, znear, zfar );
  831. }
  832. if (camera)
  833. {
  834. this.resources.setEntry(entryID, camera, description);
  835. }
  836. return true;
  837. }
  838. },
  839. handleLight: {
  840. value: function(entryID, description, userInfo) {
  841. var light = null;
  842. var type = description.type;
  843. if (type && description[type])
  844. {
  845. var lparams = description[type];
  846. var color = RgbArraytoHex(lparams.color);
  847. switch (type) {
  848. case "directional" :
  849. light = new THREE.DirectionalLight(color);
  850. light.position.set(0, 0, 1);
  851. break;
  852. case "point" :
  853. light = new THREE.PointLight(color);
  854. break;
  855. case "spot " :
  856. light = new THREE.SpotLight(color);
  857. light.position.set(0, 0, 1);
  858. break;
  859. case "ambient" :
  860. light = new THREE.AmbientLight(color);
  861. break;
  862. }
  863. }
  864. if (light)
  865. {
  866. this.resources.setEntry(entryID, light, description);
  867. }
  868. return true;
  869. }
  870. },
  871. addPendingMesh: {
  872. value: function(mesh, threeNode) {
  873. theLoader.pendingMeshes.push({
  874. mesh: mesh,
  875. node: threeNode
  876. });
  877. }
  878. },
  879. handleNode: {
  880. value: function(entryID, description, userInfo) {
  881. var threeNode = null;
  882. if (description.jointId) {
  883. threeNode = new THREE.Bone();
  884. threeNode.jointId = description.jointId;
  885. this.joints[description.jointId] = entryID;
  886. }
  887. else {
  888. threeNode = new THREE.Object3D();
  889. }
  890. threeNode.name = description.name;
  891. this.resources.setEntry(entryID, threeNode, description);
  892. var m = description.matrix;
  893. if(m) {
  894. threeNode.matrixAutoUpdate = false;
  895. threeNode.applyMatrix(new THREE.Matrix4(
  896. m[0], m[4], m[8], m[12],
  897. m[1], m[5], m[9], m[13],
  898. m[2], m[6], m[10], m[14],
  899. m[3], m[7], m[11], m[15]
  900. ));
  901. }
  902. else {
  903. var t = description.translation;
  904. var r = description.rotation;
  905. var s = description.scale;
  906. var position = t ? new THREE.Vector3(t[0], t[1], t[2]) :
  907. new THREE.Vector3;
  908. if (r) {
  909. convertAxisAngleToQuaternion(r, 1);
  910. }
  911. var rotation = r ? new THREE.Quaternion(r[0], r[1], r[2], r[3]) :
  912. new THREE.Quaternion;
  913. var scale = s ? new THREE.Vector3(s[0], s[1], s[2]) :
  914. new THREE.Vector3;
  915. var matrix = new THREE.Matrix4;
  916. matrix.compose(position, rotation, scale);
  917. threeNode.matrixAutoUpdate = false;
  918. threeNode.applyMatrix(matrix);
  919. }
  920. var self = this;
  921. // Iterate through all node meshes and attach the appropriate objects
  922. //FIXME: decision needs to be made between these 2 ways, probably meshes will be discarded.
  923. var meshEntry;
  924. if (description.mesh) {
  925. meshEntry = this.resources.getEntry(description.mesh);
  926. theLoader.meshesRequested++;
  927. meshEntry.object.onComplete(function(mesh) {
  928. self.addPendingMesh(mesh, threeNode);
  929. theLoader.meshesLoaded++;
  930. theLoader.checkComplete();
  931. });
  932. }
  933. if (description.meshes) {
  934. description.meshes.forEach( function(meshID) {
  935. meshEntry = this.resources.getEntry(meshID);
  936. theLoader.meshesRequested++;
  937. meshEntry.object.onComplete(function(mesh) {
  938. self.addPendingMesh(mesh, threeNode);
  939. theLoader.meshesLoaded++;
  940. theLoader.checkComplete();
  941. });
  942. }, this);
  943. }
  944. if (description.instanceSkin) {
  945. var skinEntry = this.resources.getEntry(description.instanceSkin.skin);
  946. if (skinEntry) {
  947. var skin = skinEntry.object;
  948. description.instanceSkin.skin = skin;
  949. threeNode.instanceSkin = description.instanceSkin;
  950. var sources = description.instanceSkin.sources;
  951. skin.meshes = [];
  952. sources.forEach( function(meshID) {
  953. meshEntry = this.resources.getEntry(meshID);
  954. theLoader.meshesRequested++;
  955. meshEntry.object.onComplete(function(mesh) {
  956. skin.meshes.push(mesh);
  957. theLoader.meshesLoaded++;
  958. theLoader.checkComplete();
  959. });
  960. }, this);
  961. }
  962. }
  963. if (description.camera) {
  964. var cameraEntry = this.resources.getEntry(description.camera);
  965. if (cameraEntry) {
  966. threeNode.add(cameraEntry.object);
  967. this.cameras.push(cameraEntry.object);
  968. }
  969. }
  970. if (description.light) {
  971. var lightEntry = this.resources.getEntry(description.light);
  972. if (lightEntry) {
  973. threeNode.add(lightEntry.object);
  974. this.lights.push(lightEntry.object);
  975. }
  976. }
  977. return true;
  978. }
  979. },
  980. buildNodeHirerachy: {
  981. value: function(nodeEntryId, parentThreeNode) {
  982. var nodeEntry = this.resources.getEntry(nodeEntryId);
  983. var threeNode = nodeEntry.object;
  984. parentThreeNode.add(threeNode);
  985. var children = nodeEntry.description.children;
  986. if (children) {
  987. children.forEach( function(childID) {
  988. this.buildNodeHirerachy(childID, threeNode);
  989. }, this);
  990. }
  991. return threeNode;
  992. }
  993. },
  994. buildSkin: {
  995. value: function(node) {
  996. var skin = node.instanceSkin.skin;
  997. if (skin) {
  998. node.instanceSkin.skeletons.forEach(function(skeleton) {
  999. var nodeEntry = this.resources.getEntry(skeleton);
  1000. if (nodeEntry) {
  1001. var rootSkeleton = nodeEntry.object;
  1002. var dobones = true;
  1003. var i, len = skin.meshes.length;
  1004. for (i = 0; i < len; i++) {
  1005. var mesh = skin.meshes[i];
  1006. var threeMesh = null;
  1007. mesh.primitives.forEach(function(primitive) {
  1008. var material = primitive.material;
  1009. if (!(material instanceof THREE.Material)) {
  1010. material = this.createShaderMaterial(material);
  1011. }
  1012. threeMesh = new THREE.SkinnedMesh(primitive.geometry.geometry, material, false);
  1013. threeMesh.add(rootSkeleton);
  1014. var geometry = primitive.geometry.geometry;
  1015. var j;
  1016. if (geometry.vertices) {
  1017. for ( j = 0; j < geometry.vertices.length; j ++ ) {
  1018. geometry.vertices[j].applyMatrix4( skin.bindShapeMatrix );
  1019. }
  1020. }
  1021. else if (geometry.attributes.position) {
  1022. var a = geometry.attributes.position.array;
  1023. var v = new THREE.Vector3;
  1024. for ( j = 0; j < a.length / 3; j++ ) {
  1025. v.set(a[j * 3], a[j * 3 + 1], a[j * 3 + 2]);
  1026. v.applyMatrix4( skin.bindShapeMatrix );
  1027. a[j * 3] = v.x;
  1028. a[j * 3 + 1] = v.y;
  1029. a[j * 3 + 2] = v.z;
  1030. }
  1031. }
  1032. if (threeMesh && dobones) {
  1033. material.skinning = true;
  1034. threeMesh.boneInverses = [];
  1035. var jointsIds = skin.jointsIds;
  1036. var joints = [];
  1037. var i, len = jointsIds.length;
  1038. for (i = 0; i < len; i++) {
  1039. var jointId = jointsIds[i];
  1040. var nodeForJoint = this.joints[jointId];
  1041. var joint = this.resources.getEntry(nodeForJoint).object;
  1042. if (joint) {
  1043. joint.skin = threeMesh;
  1044. joints.push(joint);
  1045. threeMesh.bones.push(joint);
  1046. var m = skin.inverseBindMatrices;
  1047. var mat = new THREE.Matrix4(
  1048. m[i * 16 + 0], m[i * 16 + 4], m[i * 16 + 8], m[i * 16 + 12],
  1049. m[i * 16 + 1], m[i * 16 + 5], m[i * 16 + 9], m[i * 16 + 13],
  1050. m[i * 16 + 2], m[i * 16 + 6], m[i * 16 + 10], m[i * 16 + 14],
  1051. m[i * 16 + 3], m[i * 16 + 7], m[i * 16 + 11], m[i * 16 + 15]
  1052. );
  1053. threeMesh.boneInverses.push(mat);
  1054. threeMesh.pose();
  1055. } else {
  1056. console.log("WARNING: jointId:"+jointId+" cannot be found in skeleton:"+skeleton);
  1057. }
  1058. }
  1059. }
  1060. if (threeMesh) {
  1061. threeMesh.castShadow = true;
  1062. node.add(threeMesh);
  1063. }
  1064. }, this);
  1065. }
  1066. }
  1067. }, this);
  1068. }
  1069. }
  1070. },
  1071. buildSkins: {
  1072. value: function(node) {
  1073. if (node.instanceSkin)
  1074. this.buildSkin(node);
  1075. var children = node.children;
  1076. if (children) {
  1077. children.forEach( function(child) {
  1078. this.buildSkins(child);
  1079. }, this);
  1080. }
  1081. }
  1082. },
  1083. createMeshAnimations : {
  1084. value : function(root) {
  1085. this.buildSkins(root);
  1086. }
  1087. },
  1088. handleScene: {
  1089. value: function(entryID, description, userInfo) {
  1090. if (!description.nodes) {
  1091. console.log("ERROR: invalid file required nodes property is missing from scene");
  1092. return false;
  1093. }
  1094. description.nodes.forEach( function(nodeUID) {
  1095. this.buildNodeHirerachy(nodeUID, userInfo.rootObj);
  1096. }, this);
  1097. if (this.delegate) {
  1098. this.delegate.loadCompleted(userInfo.callback, userInfo.rootObj);
  1099. }
  1100. return true;
  1101. }
  1102. },
  1103. handleImage: {
  1104. value: function(entryID, description, userInfo) {
  1105. this.resources.setEntry(entryID, null, description);
  1106. return true;
  1107. }
  1108. },
  1109. addNodeAnimationChannel : {
  1110. value : function(name, channel, interp) {
  1111. if (!this.nodeAnimationChannels)
  1112. this.nodeAnimationChannels = {};
  1113. if (!this.nodeAnimationChannels[name]) {
  1114. this.nodeAnimationChannels[name] = [];
  1115. }
  1116. this.nodeAnimationChannels[name].push(interp);
  1117. },
  1118. },
  1119. createAnimations : {
  1120. value : function() {
  1121. for (var name in this.nodeAnimationChannels) {
  1122. var nodeAnimationChannels = this.nodeAnimationChannels[name];
  1123. var i, len = nodeAnimationChannels.length;
  1124. //console.log(" animation channels for node " + name);
  1125. //for (i = 0; i < len; i++) {
  1126. // console.log(nodeAnimationChannels[i]);
  1127. //}
  1128. var anim = new THREE.glTFAnimation(nodeAnimationChannels);
  1129. anim.name = "animation_" + name;
  1130. this.animations.push(anim);
  1131. }
  1132. }
  1133. },
  1134. buildAnimation: {
  1135. value : function(animation) {
  1136. var interps = [];
  1137. var i, len = animation.channels.length;
  1138. for (i = 0; i < len; i++) {
  1139. var channel = animation.channels[i];
  1140. var sampler = animation.samplers[channel.sampler];
  1141. if (sampler) {
  1142. var input = animation.parameters[sampler.input];
  1143. if (input && input.data) {
  1144. var output = animation.parameters[sampler.output];
  1145. if (output && output.data) {
  1146. var target = channel.target;
  1147. var node = this.resources.getEntry(target.id);
  1148. if (node) {
  1149. var path = target.path;
  1150. if (path == "rotation")
  1151. {
  1152. convertAxisAngleToQuaternion(output.data, output.count);
  1153. }
  1154. var interp = {
  1155. keys : input.data,
  1156. values : output.data,
  1157. count : input.count,
  1158. target : node.object,
  1159. path : path,
  1160. type : sampler.interpolation
  1161. };
  1162. this.addNodeAnimationChannel(target.id, channel, interp);
  1163. interps.push(interp);
  1164. }
  1165. }
  1166. }
  1167. }
  1168. }
  1169. }
  1170. },
  1171. handleAnimation: {
  1172. value: function(entryID, description, userInfo) {
  1173. var self = this;
  1174. theLoader.animationsRequested++;
  1175. var animation = new Animation();
  1176. animation.name = entryID;
  1177. animation.onload = function() {
  1178. // self.buildAnimation(animation);
  1179. theLoader.animationsLoaded++;
  1180. theLoader.animations.push(animation);
  1181. theLoader.checkComplete();
  1182. };
  1183. animation.channels = description.channels;
  1184. animation.samplers = description.samplers;
  1185. this.resources.setEntry(entryID, animation, description);
  1186. var parameters = description.parameters;
  1187. if (!parameters) {
  1188. //FIXME: not implemented in delegate
  1189. console.log("MISSING_PARAMETERS for animation:"+ entryID);
  1190. return false;
  1191. }
  1192. // Load parameter buffers
  1193. var params = Object.keys(parameters);
  1194. params.forEach( function(param) {
  1195. animation.totalParameters++;
  1196. var parameter = parameters[param];
  1197. var accessor = this.resources.getEntry(parameter);
  1198. if (!accessor)
  1199. debugger;
  1200. accessor = accessor.object;
  1201. var bufferView = this.resources.getEntry(accessor.bufferView);
  1202. var paramObject = {
  1203. bufferView : bufferView,
  1204. byteOffset : accessor.byteOffset,
  1205. count : accessor.count,
  1206. type : accessor.type,
  1207. id : accessor.bufferView,
  1208. name : param
  1209. };
  1210. var paramContext = new AnimationParameterContext(paramObject, animation);
  1211. var alreadyProcessedAttribute = THREE.GLTFLoaderUtils.getBuffer(paramObject, animationParameterDelegate, paramContext);
  1212. /*if(alreadyProcessedAttribute) {
  1213. vertexAttributeDelegate.resourceAvailable(alreadyProcessedAttribute, attribContext);
  1214. }*/
  1215. }, this);
  1216. return true;
  1217. }
  1218. },
  1219. handleAccessor: {
  1220. value: function(entryID, description, userInfo) {
  1221. // Save attribute entry
  1222. this.resources.setEntry(entryID, description, description);
  1223. return true;
  1224. }
  1225. },
  1226. handleSkin: {
  1227. value: function(entryID, description, userInfo) {
  1228. // Save skin entry
  1229. var skin = {
  1230. };
  1231. var m = description.bindShapeMatrix;
  1232. skin.bindShapeMatrix = new THREE.Matrix4(
  1233. m[0], m[4], m[8], m[12],
  1234. m[1], m[5], m[9], m[13],
  1235. m[2], m[6], m[10], m[14],
  1236. m[3], m[7], m[11], m[15]
  1237. );
  1238. skin.jointsIds = description.joints;
  1239. var inverseBindMatricesDescription = description.inverseBindMatrices;
  1240. skin.inverseBindMatricesDescription = inverseBindMatricesDescription;
  1241. skin.inverseBindMatricesDescription.id = entryID + "_inverseBindMatrices";
  1242. var bufferEntry = this.resources.getEntry(inverseBindMatricesDescription.bufferView);
  1243. var paramObject = {
  1244. bufferView : bufferEntry,
  1245. byteOffset : inverseBindMatricesDescription.byteOffset,
  1246. count : inverseBindMatricesDescription.count,
  1247. type : inverseBindMatricesDescription.type,
  1248. id : inverseBindMatricesDescription.bufferView,
  1249. name : skin.inverseBindMatricesDescription.id
  1250. };
  1251. var context = new InverseBindMatricesContext(paramObject, skin);
  1252. var alreadyProcessedAttribute = THREE.GLTFLoaderUtils.getBuffer(paramObject, inverseBindMatricesDelegate, context);
  1253. var bufferView = this.resources.getEntry(skin.inverseBindMatricesDescription.bufferView);
  1254. skin.inverseBindMatricesDescription.bufferView =
  1255. bufferView.object;
  1256. this.resources.setEntry(entryID, skin, description);
  1257. return true;
  1258. }
  1259. },
  1260. handleSampler: {
  1261. value: function(entryID, description, userInfo) {
  1262. // Save attribute entry
  1263. this.resources.setEntry(entryID, description, description);
  1264. return true;
  1265. }
  1266. },
  1267. handleTexture: {
  1268. value: function(entryID, description, userInfo) {
  1269. // Save attribute entry
  1270. this.resources.setEntry(entryID, null, description);
  1271. return true;
  1272. }
  1273. },
  1274. handleError: {
  1275. value: function(msg) {
  1276. throw new Error(msg);
  1277. return true;
  1278. }
  1279. },
  1280. _delegate: {
  1281. value: new LoadDelegate,
  1282. writable: true
  1283. },
  1284. delegate: {
  1285. enumerable: true,
  1286. get: function() {
  1287. return this._delegate;
  1288. },
  1289. set: function(value) {
  1290. this._delegate = value;
  1291. }
  1292. }
  1293. });
  1294. // Loader
  1295. var Context = function(rootObj, callback) {
  1296. this.rootObj = rootObj;
  1297. this.callback = callback;
  1298. };
  1299. var rootObj = new THREE.Object3D();
  1300. var self = this;
  1301. var loader = Object.create(ThreeGLTFLoader);
  1302. loader.initWithPath(url);
  1303. loader.load(new Context(rootObj,
  1304. function(obj) {
  1305. }),
  1306. null);
  1307. this.loader = loader;
  1308. this.callback = callback;
  1309. this.rootObj = rootObj;
  1310. return rootObj;
  1311. }
  1312. THREE.glTFLoader.prototype.callLoadedCallback = function() {
  1313. var result = {
  1314. scene : this.rootObj,
  1315. cameras : this.loader.cameras,
  1316. animations : this.loader.animations,
  1317. };
  1318. this.callback(result);
  1319. }
  1320. THREE.glTFLoader.prototype.checkComplete = function() {
  1321. if (this.meshesLoaded == this.meshesRequested
  1322. && this.shadersLoaded == this.shadersRequested
  1323. && this.animationsLoaded == this.animationsRequested)
  1324. {
  1325. for (var i = 0; i < this.pendingMeshes.length; i++) {
  1326. var pending = this.pendingMeshes[i];
  1327. pending.mesh.attachToNode(pending.node);
  1328. }
  1329. for (var i = 0; i < this.animationsLoaded; i++) {
  1330. var animation = this.animations[i];
  1331. this.loader.buildAnimation(animation);
  1332. }
  1333. this.loader.createAnimations();
  1334. this.loader.createMeshAnimations(this.rootObj);
  1335. this.callLoadedCallback();
  1336. }
  1337. }