glTFLoader.js 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935
  1. /**
  2. * @author Tony Parisi / http://www.tonyparisi.com/
  3. */
  4. THREE.glTFLoader = function (showStatus) {
  5. this.meshesRequested = 0;
  6. this.meshesLoaded = 0;
  7. this.pendingMeshes = [];
  8. this.animationsRequested = 0;
  9. this.animationsLoaded = 0;
  10. this.animations = [];
  11. this.shadersRequested = 0;
  12. this.shadersLoaded = 0;
  13. this.shaders = {};
  14. this.loadRequests = [];
  15. THREE.glTFShaders.removeAll();
  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 componentsPerElementForGLType(type) {
  33. switch(type) {
  34. case "SCALAR" :
  35. nElements = 1;
  36. break;
  37. case "VEC2" :
  38. nElements = 2;
  39. break;
  40. case "VEC3" :
  41. nElements = 3;
  42. break;
  43. case "VEC4" :
  44. nElements = 4;
  45. break;
  46. case "MAT2" :
  47. nElements = 4;
  48. break;
  49. case "MAT3" :
  50. nElements = 9;
  51. break;
  52. case "MAT4" :
  53. nElements = 16;
  54. break;
  55. default :
  56. debugger;
  57. break;
  58. }
  59. return nElements;
  60. }
  61. function replaceShaderDefinitions(shader, material) {
  62. // Three.js seems too dependent on attribute names so globally
  63. // replace those in the shader code
  64. var program = material.params.program;
  65. var shaderParams = material.params.technique.parameters;
  66. var shaderAttributes = material.params.technique.attributes;
  67. var params = {};
  68. for (var attribute in material.params.attributes) {
  69. var pname = shaderAttributes[attribute];
  70. var shaderParam = shaderParams[pname];
  71. var semantic = shaderParam.semantic;
  72. if (semantic) {
  73. params[attribute] = shaderParam;
  74. }
  75. }
  76. var s = shader;
  77. var r = "";
  78. for (var pname in params) {
  79. var param = params[pname];
  80. var semantic = param.semantic;
  81. r = eval("/" + pname + "/g");
  82. switch (semantic) {
  83. case "POSITION" :
  84. s = s.replace(r, 'position');
  85. break;
  86. case "NORMAL" :
  87. s = s.replace(r, 'normal');
  88. break;
  89. case "TEXCOORD_0" :
  90. s = s.replace(r, 'uv');
  91. break;
  92. case "WEIGHT" :
  93. s = s.replace(r, 'skinWeight');
  94. break;
  95. case "JOINT" :
  96. s = s.replace(r, 'skinIndex');
  97. break;
  98. default :
  99. break;
  100. }
  101. }
  102. return s;
  103. }
  104. function replaceShaderSemantics(material) {
  105. var vertexShader = theLoader.shaders[material.params.vertexShader];
  106. if (vertexShader) {
  107. vertexShader = replaceShaderDefinitions(vertexShader, material);
  108. theLoader.shaders[material.params.vertexShader] = vertexShader;
  109. }
  110. }
  111. function createShaderMaterial(material) {
  112. // replace named attributes and uniforms with Three.js built-ins
  113. replaceShaderSemantics(material);
  114. var fragmentShader = theLoader.shaders[material.params.fragmentShader];
  115. if (!fragmentShader) {
  116. console.log("ERROR: Missing fragment shader definition:", material.params.fragmentShader);
  117. return new THREE.MeshPhongMaterial;
  118. }
  119. var vertexShader = theLoader.shaders[material.params.vertexShader];
  120. if (!vertexShader) {
  121. console.log("ERROR: Missing vertex shader definition:", material.params.vertexShader);
  122. return new THREE.MeshPhongMaterial;
  123. }
  124. // clone most uniforms but then clobber textures, we want them to
  125. // be reused
  126. var uniforms = THREE.UniformsUtils.clone(material.params.uniforms);
  127. for (uniform in material.params.uniforms) {
  128. var src = material.params.uniforms[uniform];
  129. var dst = uniforms[uniform];
  130. if (dst.type == "t") {
  131. dst.value = src.value;
  132. }
  133. }
  134. var shaderMaterial = new THREE.RawShaderMaterial( {
  135. fragmentShader: fragmentShader,
  136. vertexShader: vertexShader,
  137. uniforms: uniforms,
  138. transparent: material.params.transparent,
  139. } );
  140. // console.log("New shader material")
  141. return shaderMaterial;
  142. }
  143. function LoadTexture(src) {
  144. if(!src) { return null; }
  145. var isDataUriRegex = /^data:/;
  146. var loadImage = function(url, success, error) {
  147. var image = new Image();
  148. image.onload = function() {
  149. success(image);
  150. };
  151. if (typeof error !== 'undefined') {
  152. image.onerror = error;
  153. }
  154. image.src = url;
  155. };
  156. function loadImageFromTypedArray(uint8Array, format) {
  157. //>>includeStart('debug', pragmas.debug);
  158. if (!defined(uint8Array)) {
  159. throw new DeveloperError('uint8Array is required.');
  160. }
  161. if (!defined(format)) {
  162. throw new DeveloperError('format is required.');
  163. }
  164. //>>includeEnd('debug');
  165. var blob = new Blob([uint8Array], {
  166. type : format
  167. });
  168. };
  169. function decodeDataUriText(isBase64, data) {
  170. var result = decodeURIComponent(data);
  171. if (isBase64) {
  172. return atob(result);
  173. }
  174. return result;
  175. }
  176. function decodeDataUriArrayBuffer(isBase64, data) {
  177. var byteString = decodeDataUriText(isBase64, data);
  178. var buffer = new ArrayBuffer(byteString.length);
  179. var view = new Uint8Array(buffer);
  180. for (var i = 0; i < byteString.length; i++) {
  181. view[i] = byteString.charCodeAt(i);
  182. }
  183. return buffer;
  184. }
  185. function decodeDataUri(dataUriRegexResult, responseType) {
  186. responseType = typeof responseType !== 'undefined' ? responseType : '';
  187. var mimeType = dataUriRegexResult[1];
  188. var isBase64 = !!dataUriRegexResult[2];
  189. var data = dataUriRegexResult[3];
  190. switch (responseType) {
  191. case '':
  192. case 'text':
  193. return decodeDataUriText(isBase64, data);
  194. case 'ArrayBuffer':
  195. return decodeDataUriArrayBuffer(isBase64, data);
  196. case 'blob':
  197. var buffer = decodeDataUriArrayBuffer(isBase64, data);
  198. return new Blob([buffer], {
  199. type : mimeType
  200. });
  201. case 'document':
  202. var parser = new DOMParser();
  203. return parser.parseFromString(decodeDataUriText(isBase64, data), mimeType);
  204. case 'json':
  205. return JSON.parse(decodeDataUriText(isBase64, data));
  206. default:
  207. throw 'Unhandled responseType: ' + responseType;
  208. }
  209. }
  210. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  211. var dataUriRegexResult = dataUriRegex.exec(src);
  212. if (dataUriRegexResult !== null) {
  213. var texture = new THREE.Texture;
  214. var blob = decodeDataUri(dataUriRegexResult, 'blob');
  215. var blobUrl = window.URL.createObjectURL(blob);
  216. loadImage(blobUrl, function(img) {
  217. texture.image = img;
  218. texture.needsUpdate = true;
  219. });
  220. return texture;
  221. }
  222. return new THREE.TextureLoader().load(src);
  223. }
  224. function CreateTexture(resources, resource) {
  225. var texturePath = null;
  226. var textureParams = null;
  227. if (resource)
  228. {
  229. var texture = resource;
  230. if (texture) {
  231. var textureEntry = resources.getEntry(texture);
  232. if (textureEntry) {
  233. {
  234. var imageEntry = resources.getEntry(textureEntry.description.source);
  235. if (imageEntry) {
  236. texturePath = imageEntry.description.uri;
  237. }
  238. var samplerEntry = resources.getEntry(textureEntry.description.sampler);
  239. if (samplerEntry) {
  240. textureParams = samplerEntry.description;
  241. }
  242. }
  243. }
  244. }
  245. }
  246. var texture = LoadTexture(texturePath);
  247. if (texture && textureParams) {
  248. if (textureParams.wrapS == WebGLRenderingContext.REPEAT)
  249. texture.wrapS = THREE.RepeatWrapping;
  250. if (textureParams.wrapT == WebGLRenderingContext.REPEAT)
  251. texture.wrapT = THREE.RepeatWrapping;
  252. if (textureParams.magFilter == WebGLRenderingContext.LINEAR)
  253. texture.magFilter = THREE.LinearFilter;
  254. // if (textureParams.minFilter == "LINEAR")
  255. // texture.minFilter = THREE.LinearFilter;
  256. }
  257. return texture;
  258. }
  259. // Geometry processing
  260. var ClassicGeometry = function() {
  261. this.geometry = new THREE.BufferGeometry;
  262. this.totalAttributes = 0;
  263. this.loadedAttributes = 0;
  264. this.indicesLoaded = false;
  265. this.finished = false;
  266. this.onload = null;
  267. this.uvs = null;
  268. this.indexArray = null;
  269. };
  270. ClassicGeometry.prototype.constructor = ClassicGeometry;
  271. ClassicGeometry.prototype.buildBufferGeometry = function() {
  272. // Build indexed mesh
  273. var geometry = this.geometry;
  274. geometry.setIndex(new THREE.BufferAttribute( this.indexArray, 1 ) );
  275. var offset = {
  276. start: 0,
  277. index: 0,
  278. count: this.indexArray.length
  279. };
  280. geometry.groups.push( offset );
  281. geometry.computeBoundingSphere();
  282. }
  283. ClassicGeometry.prototype.checkFinished = function() {
  284. if(this.indexArray && this.loadedAttributes === this.totalAttributes) {
  285. this.buildBufferGeometry();
  286. this.finished = true;
  287. if(this.onload) {
  288. this.onload();
  289. }
  290. }
  291. };
  292. // Delegate for processing index buffers
  293. var IndicesDelegate = function() {};
  294. IndicesDelegate.prototype.handleError = function(errorCode, info) {
  295. // FIXME: report error
  296. console.log("ERROR(IndicesDelegate):"+errorCode+":"+info);
  297. };
  298. IndicesDelegate.prototype.convert = function(resource, ctx) {
  299. return new Uint16Array(resource, 0, ctx.indices.count);
  300. };
  301. IndicesDelegate.prototype.resourceAvailable = function(glResource, ctx) {
  302. var geometry = ctx.geometry;
  303. geometry.indexArray = glResource;
  304. geometry.checkFinished();
  305. return true;
  306. };
  307. var indicesDelegate = new IndicesDelegate();
  308. var IndicesContext = function(indices, geometry) {
  309. this.indices = indices;
  310. this.geometry = geometry;
  311. };
  312. // Delegate for processing vertex attribute buffers
  313. var VertexAttributeDelegate = function() {};
  314. VertexAttributeDelegate.prototype.handleError = function(errorCode, info) {
  315. // FIXME: report error
  316. console.log("ERROR(VertexAttributeDelegate):"+errorCode+":"+info);
  317. };
  318. VertexAttributeDelegate.prototype.convert = function(resource, ctx) {
  319. return resource;
  320. };
  321. VertexAttributeDelegate.prototype.bufferResourceAvailable = function(glResource, ctx) {
  322. var geom = ctx.geometry;
  323. var attribute = ctx.attribute;
  324. var semantic = ctx.semantic;
  325. var floatArray;
  326. var i, l;
  327. var nComponents;
  328. //FIXME: Float32 is assumed here, but should be checked.
  329. if (semantic == "POSITION") {
  330. // TODO: Should be easy to take strides into account here
  331. floatArray = new Float32Array(glResource, 0, attribute.count * componentsPerElementForGLType(attribute.type));
  332. geom.geometry.addAttribute( 'position', new THREE.BufferAttribute( floatArray, 3 ) );
  333. } else if (semantic == "NORMAL") {
  334. nComponents = componentsPerElementForGLType(attribute.type);
  335. floatArray = new Float32Array(glResource, 0, attribute.count * nComponents);
  336. geom.geometry.addAttribute( 'normal', new THREE.BufferAttribute( floatArray, 3 ) );
  337. } else if ((semantic == "TEXCOORD_0") || (semantic == "TEXCOORD" )) {
  338. nComponents = componentsPerElementForGLType(attribute.type);
  339. floatArray = new Float32Array(glResource, 0, attribute.count * nComponents);
  340. // N.B.: flip Y value... should we just set texture.flipY everywhere?
  341. for (i = 0; i < floatArray.length / 2; i++) {
  342. floatArray[i*2+1] = 1.0 - floatArray[i*2+1];
  343. }
  344. geom.geometry.addAttribute( 'uv', new THREE.BufferAttribute( floatArray, nComponents ) );
  345. }
  346. else if (semantic == "WEIGHT") {
  347. nComponents = componentsPerElementForGLType(attribute.type);
  348. floatArray = new Float32Array(glResource, 0, attribute.count * nComponents);
  349. geom.geometry.addAttribute( 'skinWeight', new THREE.BufferAttribute( floatArray, nComponents ) );
  350. }
  351. else if (semantic == "JOINT") {
  352. nComponents = componentsPerElementForGLType(attribute.type);
  353. floatArray = new Float32Array(glResource, 0, attribute.count * nComponents);
  354. geom.geometry.addAttribute( 'skinIndex', new THREE.BufferAttribute( floatArray, nComponents ) );
  355. }
  356. }
  357. VertexAttributeDelegate.prototype.resourceAvailable = function(glResource, ctx) {
  358. this.bufferResourceAvailable(glResource, ctx);
  359. var geom = ctx.geometry;
  360. geom.loadedAttributes++;
  361. geom.checkFinished();
  362. return true;
  363. };
  364. var vertexAttributeDelegate = new VertexAttributeDelegate();
  365. var VertexAttributeContext = function(attribute, semantic, geometry) {
  366. this.attribute = attribute;
  367. this.semantic = semantic;
  368. this.geometry = geometry;
  369. };
  370. var Mesh = function() {
  371. this.primitives = [];
  372. this.materialsPending = [];
  373. this.loadedGeometry = 0;
  374. this.onCompleteCallbacks = [];
  375. };
  376. Mesh.prototype.addPrimitive = function(geometry, material) {
  377. var self = this;
  378. geometry.onload = function() {
  379. self.loadedGeometry++;
  380. self.checkComplete();
  381. };
  382. this.primitives.push({
  383. geometry: geometry,
  384. material: material,
  385. mesh: null
  386. });
  387. };
  388. Mesh.prototype.onComplete = function(callback) {
  389. this.onCompleteCallbacks.push(callback);
  390. //this.checkComplete();
  391. };
  392. Mesh.prototype.checkComplete = function() {
  393. var self = this;
  394. if(this.onCompleteCallbacks.length && this.primitives.length == this.loadedGeometry) {
  395. this.onCompleteCallbacks.forEach(function(callback) {
  396. callback(self);
  397. });
  398. this.onCompleteCallbacks = [];
  399. }
  400. };
  401. Mesh.prototype.attachToNode = function(threeNode) {
  402. // Assumes that the geometry is complete
  403. var that = this;
  404. this.primitives.forEach(function(primitive) {
  405. /*if(!primitive.mesh) {
  406. primitive.mesh = new THREE.Mesh(primitive.geometry, primitive.material);
  407. }*/
  408. var material = primitive.material;
  409. var materialParams = material.params;
  410. if (!(material instanceof THREE.Material)) {
  411. material = createShaderMaterial(material);
  412. }
  413. if (!that.skin) {
  414. // console.log ("New mesh")
  415. var threeMesh = new THREE.Mesh(primitive.geometry.geometry, material);
  416. threeMesh.castShadow = true;
  417. threeNode.add(threeMesh);
  418. if (material instanceof THREE.ShaderMaterial) {
  419. var glTFShader = new THREE.glTFShader(material, materialParams, threeMesh, theLoader.rootObj);
  420. THREE.glTFShaders.add(glTFShader);
  421. }
  422. }
  423. });
  424. };
  425. // Delayed-loaded material
  426. var Material = function(params) {
  427. this.params = params;
  428. };
  429. // Delegate for processing animation parameter buffers
  430. var AnimationParameterDelegate = function() {};
  431. AnimationParameterDelegate.prototype.handleError = function(errorCode, info) {
  432. // FIXME: report error
  433. console.log("ERROR(AnimationParameterDelegate):"+errorCode+":"+info);
  434. };
  435. AnimationParameterDelegate.prototype.convert = function(resource, ctx) {
  436. var parameter = ctx.parameter;
  437. var glResource = null;
  438. switch (parameter.type) {
  439. case "SCALAR" :
  440. case "VEC2" :
  441. case "VEC3" :
  442. case "VEC4" :
  443. glResource = new Float32Array(resource, 0, parameter.count * componentsPerElementForGLType(parameter.type));
  444. break;
  445. default:
  446. break;
  447. }
  448. return glResource;
  449. };
  450. AnimationParameterDelegate.prototype.resourceAvailable = function(glResource, ctx) {
  451. var animation = ctx.animation;
  452. var parameter = ctx.parameter;
  453. parameter.data = glResource;
  454. animation.handleParameterLoaded(parameter);
  455. return true;
  456. };
  457. var animationParameterDelegate = new AnimationParameterDelegate();
  458. var AnimationParameterContext = function(parameter, animation) {
  459. this.parameter = parameter;
  460. this.animation = animation;
  461. };
  462. // Animations
  463. var Animation = function() {
  464. // create Three.js keyframe here
  465. this.totalParameters = 0;
  466. this.loadedParameters = 0;
  467. this.parameters = {};
  468. this.finishedLoading = false;
  469. this.onload = null;
  470. };
  471. Animation.prototype.constructor = Animation;
  472. Animation.prototype.handleParameterLoaded = function(parameter) {
  473. this.parameters[parameter.name] = parameter;
  474. this.loadedParameters++;
  475. this.checkFinished();
  476. };
  477. Animation.prototype.checkFinished = function() {
  478. if(this.loadedParameters === this.totalParameters) {
  479. // Build animation
  480. this.finishedLoading = true;
  481. if (this.onload) {
  482. this.onload();
  483. }
  484. }
  485. };
  486. // Delegate for processing inverse bind matrices buffer
  487. var InverseBindMatricesDelegate = function() {};
  488. InverseBindMatricesDelegate.prototype.handleError = function(errorCode, info) {
  489. // FIXME: report error
  490. console.log("ERROR(InverseBindMatricesDelegate):"+errorCode+":"+info);
  491. };
  492. InverseBindMatricesDelegate.prototype.convert = function(resource, ctx) {
  493. var parameter = ctx.parameter;
  494. var glResource = null;
  495. switch (parameter.type) {
  496. case "MAT4" :
  497. glResource = new Float32Array(resource, 0, parameter.count * componentsPerElementForGLType(parameter.type));
  498. break;
  499. default:
  500. break;
  501. }
  502. return glResource;
  503. };
  504. InverseBindMatricesDelegate.prototype.resourceAvailable = function(glResource, ctx) {
  505. var skin = ctx.skin;
  506. skin.inverseBindMatrices = glResource;
  507. return true;
  508. };
  509. var inverseBindMatricesDelegate = new InverseBindMatricesDelegate();
  510. var InverseBindMatricesContext = function(param, skin) {
  511. this.parameter = param;
  512. this.skin = skin;
  513. };
  514. // Delegate for processing shaders from external files
  515. var ShaderDelegate = function() {};
  516. ShaderDelegate.prototype.handleError = function(errorCode, info) {
  517. // FIXME: report error
  518. console.log("ERROR(ShaderDelegate):"+errorCode+":"+info);
  519. };
  520. ShaderDelegate.prototype.convert = function(resource, ctx) {
  521. return resource;
  522. }
  523. ShaderDelegate.prototype.resourceAvailable = function(data, ctx) {
  524. theLoader.shadersLoaded++;
  525. theLoader.shaders[ctx.id] = data;
  526. return true;
  527. };
  528. var shaderDelegate = new ShaderDelegate();
  529. var ShaderContext = function(id, path) {
  530. this.id = id;
  531. this.uri = path;
  532. };
  533. // Resource management
  534. var ResourceEntry = function(entryID, object, description) {
  535. this.entryID = entryID;
  536. this.object = object;
  537. this.description = description;
  538. };
  539. var Resources = function() {
  540. this._entries = {};
  541. };
  542. Resources.prototype.setEntry = function(entryID, object, description) {
  543. if (!entryID) {
  544. console.error("No EntryID provided, cannot store", description);
  545. return;
  546. }
  547. if (this._entries[entryID]) {
  548. console.warn("entry["+entryID+"] is being overwritten");
  549. }
  550. this._entries[entryID] = new ResourceEntry(entryID, object, description );
  551. };
  552. Resources.prototype.getEntry = function(entryID) {
  553. return this._entries[entryID];
  554. };
  555. Resources.prototype.clearEntries = function() {
  556. this._entries = {};
  557. };
  558. LoadDelegate = function() {
  559. }
  560. LoadDelegate.prototype.loadCompleted = function(callback, obj) {
  561. callback.call(Window, obj);
  562. }
  563. // Loader
  564. var ThreeGLTFLoader = Object.create(glTFParser, {
  565. load: {
  566. enumerable: true,
  567. value: function(userInfo, options) {
  568. this.resources = new Resources();
  569. this.cameras = [];
  570. this.lights = [];
  571. this.animations = [];
  572. this.joints = {};
  573. THREE.GLTFLoaderUtils.init();
  574. glTFParser.load.call(this, userInfo, options);
  575. }
  576. },
  577. cameras: {
  578. enumerable: true,
  579. writable: true,
  580. value : []
  581. },
  582. lights: {
  583. enumerable: true,
  584. writable: true,
  585. value : []
  586. },
  587. animations: {
  588. enumerable: true,
  589. writable: true,
  590. value : []
  591. },
  592. // Implement WebGLTFLoader handlers
  593. handleBuffer: {
  594. value: function(entryID, description, userInfo) {
  595. this.resources.setEntry(entryID, null, description);
  596. description.type = "ArrayBuffer";
  597. return true;
  598. }
  599. },
  600. handleBufferView: {
  601. value: function(entryID, description, userInfo) {
  602. this.resources.setEntry(entryID, null, description);
  603. var buffer = this.resources.getEntry(description.buffer);
  604. description.type = "ArrayBufferView";
  605. var bufferViewEntry = this.resources.getEntry(entryID);
  606. bufferViewEntry.buffer = buffer;
  607. return true;
  608. }
  609. },
  610. handleShader: {
  611. value: function(entryID, description, userInfo) {
  612. this.resources.setEntry(entryID, null, description);
  613. var shaderRequest = {
  614. id : entryID,
  615. uri : description.uri,
  616. };
  617. var shaderContext = new ShaderContext(entryID, description.uri);
  618. theLoader.shadersRequested++;
  619. THREE.GLTFLoaderUtils.getFile(shaderRequest, shaderDelegate, shaderContext);
  620. return true;
  621. }
  622. },
  623. handleProgram: {
  624. value: function(entryID, description, userInfo) {
  625. this.resources.setEntry(entryID, null, description);
  626. return true;
  627. }
  628. },
  629. handleTechnique: {
  630. value: function(entryID, description, userInfo) {
  631. description.refCount = 0;
  632. this.resources.setEntry(entryID, null, description);
  633. return true;
  634. }
  635. },
  636. createShaderParams : {
  637. value: function(materialId, values, params, programID, technique) {
  638. var program = this.resources.getEntry(programID);
  639. params.uniforms = {};
  640. params.attributes = {};
  641. params.program = program;
  642. params.technique = technique;
  643. if (program) {
  644. params.fragmentShader = program.description.fragmentShader;
  645. params.vertexShader = program.description.vertexShader;
  646. for (var uniform in technique.uniforms) {
  647. var pname = technique.uniforms[uniform];
  648. var shaderParam = technique.parameters[pname];
  649. var ptype = shaderParam.type;
  650. var pcount = shaderParam.count;
  651. var value = values[pname];
  652. var utype = "";
  653. var uvalue;
  654. var ulength;
  655. // THIS: for (n in WebGLRenderingContext) { z = WebGLRenderingContext[n]; idx[z] = n; }
  656. //console.log("shader uniform param type: ", ptype, "-", theLoader.idx[ptype])
  657. switch (ptype) {
  658. case WebGLRenderingContext.FLOAT :
  659. utype = "f";
  660. uvalue = shaderParam.value;
  661. if (pname == "transparency") {
  662. var USE_A_ONE = true; // for now, hack because file format isn't telling us
  663. var opacity = USE_A_ONE ? value : (1.0 - value);
  664. uvalue = opacity;
  665. params.transparent = true;
  666. }
  667. break;
  668. case WebGLRenderingContext.FLOAT_VEC2 :
  669. utype = "v2";
  670. uvalue = new THREE.Vector2;
  671. if (shaderParam && shaderParam.value) {
  672. var v2 = shaderParam.value;
  673. uvalue.fromArray(v2);
  674. }
  675. if (value) {
  676. uvalue.fromArray(value);
  677. }
  678. break;
  679. case WebGLRenderingContext.FLOAT_VEC3 :
  680. utype = "v3";
  681. uvalue = new THREE.Vector3;
  682. if (shaderParam && shaderParam.value) {
  683. var v3 = shaderParam.value;
  684. uvalue.fromArray(v3);
  685. }
  686. if (value) {
  687. uvalue.fromArray(value);
  688. }
  689. break;
  690. case WebGLRenderingContext.FLOAT_VEC4 :
  691. utype = "v4";
  692. uvalue = new THREE.Vector4;
  693. if (shaderParam && shaderParam.value) {
  694. var v4 = shaderParam.value;
  695. uvalue.fromArray(v4);
  696. }
  697. if (value) {
  698. uvalue.fromArray(value);
  699. }
  700. break;
  701. case WebGLRenderingContext.FLOAT_MAT2 :
  702. // what to do?
  703. console.log("Warning: FLOAT_MAT2");
  704. break;
  705. case WebGLRenderingContext.FLOAT_MAT3 :
  706. utype = "m3";
  707. uvalue = new THREE.Matrix3;
  708. if (shaderParam && shaderParam.value) {
  709. var m3 = shaderParam.value;
  710. uvalue.fromArray(m3);
  711. }
  712. if (value) {
  713. uvalue.fromArray(value);
  714. }
  715. break;
  716. case WebGLRenderingContext.FLOAT_MAT4 :
  717. if (pcount !== undefined) {
  718. utype = "m4v";
  719. uvalue = new Array(pcount);
  720. for (var mi = 0; mi < pcount; mi++) {
  721. uvalue[mi] = new THREE.Matrix4;
  722. }
  723. ulength = pcount;
  724. if (shaderParam && shaderParam.value) {
  725. var m4v = shaderParam.value;
  726. uvalue.fromArray(m4v);
  727. }
  728. if (value) {
  729. uvalue.fromArray(value);
  730. }
  731. }
  732. else {
  733. utype = "m4";
  734. uvalue = new THREE.Matrix4;
  735. if (shaderParam && shaderParam.value) {
  736. var m4 = shaderParam.value;
  737. uvalue.fromArray(m4);
  738. }
  739. if (value) {
  740. uvalue.fromArray(value);
  741. }
  742. }
  743. break;
  744. case WebGLRenderingContext.SAMPLER_2D :
  745. utype = "t";
  746. uvalue = value ? CreateTexture(this.resources, value) : null;
  747. break;
  748. default :
  749. throw new Error("Unknown shader uniform param type: " + ptype + " - " + theLoader.idx[ptype]);
  750. break;
  751. }
  752. var udecl = { type : utype, value : uvalue, length : ulength };
  753. params.uniforms[uniform] = udecl;
  754. }
  755. for (var attribute in technique.attributes) {
  756. var pname = technique.attributes[attribute];
  757. var param = technique.parameters[pname];
  758. var atype = param.type;
  759. var semantic = param.semantic;
  760. var adecl = { type : atype, semantic : semantic };
  761. params.attributes[attribute] = adecl;
  762. }
  763. }
  764. }
  765. },
  766. threeJSMaterialType : {
  767. value: function(materialId, material, params) {
  768. var extensions = material.extensions;
  769. var khr_material = extensions ? extensions.KHR_materials_common : null;
  770. var materialType = null;
  771. var values;
  772. if (khr_material) {
  773. switch (khr_material.technique)
  774. {
  775. case 'BLINN' :
  776. case 'PHONG' :
  777. materialType = THREE.MeshPhongMaterial;
  778. break;
  779. case 'LAMBERT' :
  780. materialType = THREE.MeshLambertMaterial;
  781. break;
  782. case 'CONSTANT' :
  783. default :
  784. materialType = THREE.MeshBasicMaterial;
  785. break;
  786. }
  787. if (khr_material.doubleSided)
  788. {
  789. params.side = THREE.DoubleSide;
  790. }
  791. if (khr_material.transparent)
  792. {
  793. params.transparent = true;
  794. }
  795. values = {};
  796. for (prop in khr_material.values) {
  797. values[prop] = khr_material.values[prop];
  798. }
  799. }
  800. else {
  801. var technique = material.technique ?
  802. this.resources.getEntry(material.technique) :
  803. null;
  804. values = material.values;
  805. var description = technique.description;
  806. if (++description.refCount > 1) {
  807. //console.log("refcount", description.refCount);
  808. }
  809. var programID = description.program;
  810. this.createShaderParams(materialId, values, params, programID, description);
  811. var loadshaders = true;
  812. if (loadshaders) {
  813. materialType = Material;
  814. }
  815. }
  816. if (values.diffuse && typeof(values.diffuse) == 'string') {
  817. params.map = CreateTexture(this.resources, values.diffuse);
  818. }
  819. if (values.reflective && typeof(values.reflective) == 'string') {
  820. params.envMap = CreateTexture(this.resources, values.reflective);
  821. }
  822. var shininess = values.shininesss || values.shininess; // N.B.: typo in converter!
  823. if (shininess)
  824. {
  825. shininess = shininess;
  826. }
  827. var diffuseColor = null;
  828. if (!params.map) {
  829. diffuseColor = values.diffuse;
  830. }
  831. var opacity = 1.0;
  832. if (values.hasOwnProperty("transparency"))
  833. {
  834. var USE_A_ONE = true; // for now, hack because file format isn't telling us
  835. opacity = USE_A_ONE ? values.transparency : (1.0 - values.transparency);
  836. }
  837. // if (diffuseColor) diffuseColor = [0, 1, 0];
  838. params.color = RgbArraytoHex(diffuseColor);
  839. params.opacity = opacity;
  840. params.transparent = opacity < 1.0;
  841. // hack hack hack
  842. if (params.map && params.map.sourceFile.toLowerCase().indexOf(".png") != -1)
  843. params.transparent = true;
  844. if (!(shininess === undefined))
  845. {
  846. params.shininess = Math.max( shininess, 1e-4 );
  847. }
  848. delete params.ambient;
  849. if (!(values.ambient === undefined) && !(typeof(values.ambient) == 'string'))
  850. {
  851. //params.ambient = RgbArraytoHex(values.ambient);
  852. }
  853. if (!(values.emission === undefined))
  854. {
  855. params.emissive = RgbArraytoHex(values.emission);
  856. }
  857. if (!(values.specular === undefined))
  858. {
  859. params.specular = RgbArraytoHex(values.specular);
  860. }
  861. return materialType;
  862. }
  863. },
  864. handleMaterial: {
  865. value: function(entryID, description, userInfo) {
  866. var params = {};
  867. var materialType = this.threeJSMaterialType(entryID, description, params);
  868. var material = new materialType(params);
  869. this.resources.setEntry(entryID, material, description);
  870. return true;
  871. }
  872. },
  873. handleMesh: {
  874. value: function(entryID, description, userInfo) {
  875. var mesh = new Mesh();
  876. this.resources.setEntry(entryID, mesh, description);
  877. var primitivesDescription = description.primitives;
  878. if (!primitivesDescription) {
  879. //FIXME: not implemented in delegate
  880. console.log("MISSING_PRIMITIVES for mesh:"+ entryID);
  881. return false;
  882. }
  883. for (var i = 0 ; i < primitivesDescription.length ; i++) {
  884. var primitiveDescription = primitivesDescription[i];
  885. if (primitiveDescription.mode === WebGLRenderingContext.TRIANGLES) {
  886. var geometry = new ClassicGeometry();
  887. var materialEntry = this.resources.getEntry(primitiveDescription.material);
  888. mesh.addPrimitive(geometry, materialEntry.object);
  889. var allAttributes = Object.keys(primitiveDescription.attributes);
  890. // count them first, async issues otherwise
  891. allAttributes.forEach( function(semantic) {
  892. geometry.totalAttributes++;
  893. }, this);
  894. var indices = this.resources.getEntry(primitiveDescription.indices);
  895. var bufferEntry = this.resources.getEntry(indices.description.bufferView);
  896. var indicesObject = {
  897. bufferView : bufferEntry,
  898. byteOffset : indices.description.byteOffset,
  899. count : indices.description.count,
  900. id : indices.entryID,
  901. componentType : indices.description.componentType,
  902. type : indices.description.type
  903. };
  904. var indicesContext = new IndicesContext(indicesObject, geometry);
  905. var loaddata = {
  906. indicesObject : indicesObject,
  907. indicesDelegate : indicesDelegate,
  908. indicesContext : indicesContext
  909. };
  910. theLoader.scheduleLoad(function(data) {
  911. var alreadyProcessedIndices =
  912. THREE.GLTFLoaderUtils.getBuffer(data.indicesObject,
  913. data.indicesDelegate, data.indicesContext);
  914. if (alreadyProcessedIndices) {
  915. data.indicesDelegate.resourceAvailable(
  916. alreadyProcessedIndices, data.indicesContext);
  917. }
  918. }, loaddata);
  919. // Load Vertex Attributes
  920. allAttributes.forEach( function(semantic) {
  921. var attribute;
  922. var attributeID = primitiveDescription.attributes[semantic];
  923. var attributeEntry = this.resources.getEntry(attributeID);
  924. if (!attributeEntry) {
  925. //let's just use an anonymous object for the attribute
  926. attribute = description.attributes[attributeID];
  927. attribute.id = attributeID;
  928. this.resources.setEntry(attributeID, attribute, attribute);
  929. var bufferEntry = this.resources.getEntry(attribute.bufferView);
  930. attributeEntry = this.resources.getEntry(attributeID);
  931. } else {
  932. attribute = attributeEntry.object;
  933. attribute.id = attributeID;
  934. var bufferEntry = this.resources.getEntry(attribute.bufferView);
  935. }
  936. var attributeObject = {
  937. bufferView : bufferEntry,
  938. byteOffset : attribute.byteOffset,
  939. byteStride : attribute.byteStride,
  940. count : attribute.count,
  941. max : attribute.max,
  942. min : attribute.min,
  943. componentType : attribute.componentType,
  944. type : attribute.type,
  945. id : attributeID
  946. };
  947. var attribContext = new VertexAttributeContext(attributeObject, semantic, geometry);
  948. var loaddata = {
  949. attributeObject : attributeObject,
  950. vertexAttributeDelegate : vertexAttributeDelegate,
  951. attribContext : attribContext
  952. };
  953. theLoader.scheduleLoad(function(data) {
  954. var alreadyProcessedAttribute =
  955. THREE.GLTFLoaderUtils.getBuffer(data.attributeObject,
  956. data.vertexAttributeDelegate, data.attribContext);
  957. if (alreadyProcessedAttribute) {
  958. data.vertexAttributeDelegate.resourceAvailable(
  959. alreadyProcessedAttribute, data.attribContext);
  960. }
  961. }, loaddata);
  962. }, this);
  963. }
  964. }
  965. return true;
  966. }
  967. },
  968. handleCamera: {
  969. value: function(entryID, description, userInfo) {
  970. var camera;
  971. if (description.type == "perspective")
  972. {
  973. var znear = description.perspective.znear;
  974. var zfar = description.perspective.zfar;
  975. var yfov = description.perspective.yfov;
  976. var xfov = description.perspective.xfov;
  977. var aspect_ratio = description.perspective.aspect_ratio;
  978. if (!aspect_ratio)
  979. aspect_ratio = 1;
  980. if (xfov === undefined) {
  981. if (yfov)
  982. {
  983. // According to COLLADA spec...
  984. // aspect_ratio = xfov / yfov
  985. xfov = yfov * aspect_ratio;
  986. }
  987. }
  988. if (yfov === undefined)
  989. {
  990. if (xfov)
  991. {
  992. // According to COLLADA spec...
  993. // aspect_ratio = xfov / yfov
  994. yfov = xfov / aspect_ratio;
  995. }
  996. }
  997. if (xfov)
  998. {
  999. xfov = THREE.Math.radToDeg(xfov);
  1000. camera = new THREE.PerspectiveCamera(xfov, aspect_ratio, znear, zfar);
  1001. }
  1002. }
  1003. else
  1004. {
  1005. camera = new THREE.OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, znear, zfar );
  1006. }
  1007. if (camera)
  1008. {
  1009. this.resources.setEntry(entryID, camera, description);
  1010. }
  1011. return true;
  1012. }
  1013. },
  1014. handleLight: {
  1015. value: function(entryID, description, userInfo) {
  1016. var light = null;
  1017. var type = description.type;
  1018. if (type && description[type])
  1019. {
  1020. var lparams = description[type];
  1021. var color = RgbArraytoHex(lparams.color);
  1022. switch (type) {
  1023. case "directional" :
  1024. light = new THREE.DirectionalLight(color);
  1025. light.position.set(0, 0, 1);
  1026. break;
  1027. case "point" :
  1028. light = new THREE.PointLight(color);
  1029. break;
  1030. case "spot " :
  1031. light = new THREE.SpotLight(color);
  1032. light.position.set(0, 0, 1);
  1033. break;
  1034. case "ambient" :
  1035. light = new THREE.AmbientLight(color);
  1036. break;
  1037. }
  1038. }
  1039. if (light)
  1040. {
  1041. this.resources.setEntry(entryID, light, description);
  1042. }
  1043. return true;
  1044. }
  1045. },
  1046. addPendingMesh: {
  1047. value: function(mesh, threeNode) {
  1048. theLoader.pendingMeshes.push({
  1049. mesh: mesh,
  1050. node: threeNode
  1051. });
  1052. }
  1053. },
  1054. handleNode: {
  1055. value: function(entryID, description, userInfo) {
  1056. var threeNode = null;
  1057. if (description.jointName) {
  1058. threeNode = new THREE.Bone();
  1059. threeNode.jointName = description.jointName;
  1060. this.joints[description.jointName] = entryID;
  1061. }
  1062. else {
  1063. threeNode = new THREE.Object3D();
  1064. }
  1065. threeNode.name = description.name;
  1066. threeNode.glTFID = entryID;
  1067. threeNode.glTF = description;
  1068. this.resources.setEntry(entryID, threeNode, description);
  1069. var m = description.matrix;
  1070. if(m) {
  1071. threeNode.matrixAutoUpdate = false;
  1072. threeNode.applyMatrix(new THREE.Matrix4().set(
  1073. m[0], m[4], m[8], m[12],
  1074. m[1], m[5], m[9], m[13],
  1075. m[2], m[6], m[10], m[14],
  1076. m[3], m[7], m[11], m[15]
  1077. ));
  1078. }
  1079. else {
  1080. var t = description.translation;
  1081. var r = description.rotation;
  1082. var s = description.scale;
  1083. var position = t ? new THREE.Vector3(t[0], t[1], t[2]) :
  1084. new THREE.Vector3;
  1085. var rotation = r ? new THREE.Quaternion(r[0], r[1], r[2], r[3]) :
  1086. new THREE.Quaternion;
  1087. var scale = s ? new THREE.Vector3(s[0], s[1], s[2]) :
  1088. new THREE.Vector3(1, 1, 1);
  1089. var matrix = new THREE.Matrix4;
  1090. matrix.compose(position, rotation, scale);
  1091. threeNode.matrixAutoUpdate = false;
  1092. threeNode.applyMatrix(matrix);
  1093. }
  1094. var self = this;
  1095. if (description.meshes) {
  1096. description.meshInstances = {};
  1097. var skinEntry;
  1098. if (description.skin) {
  1099. skinEntry = this.resources.getEntry(description.skin);
  1100. }
  1101. description.meshes.forEach( function(meshID) {
  1102. meshEntry = this.resources.getEntry(meshID);
  1103. theLoader.meshesRequested++;
  1104. meshEntry.object.onComplete(function(mesh) {
  1105. self.addPendingMesh(mesh, threeNode);
  1106. description.meshInstances[meshID] = meshEntry.object;
  1107. if (skinEntry) {
  1108. mesh.skin = skinEntry;
  1109. description.instanceSkin = skinEntry.object;
  1110. }
  1111. theLoader.meshesLoaded++;
  1112. theLoader.checkComplete();
  1113. });
  1114. }, this);
  1115. }
  1116. if (description.camera) {
  1117. var cameraEntry = this.resources.getEntry(description.camera);
  1118. if (cameraEntry) {
  1119. threeNode.add(cameraEntry.object);
  1120. this.cameras.push(cameraEntry.object);
  1121. }
  1122. }
  1123. if (description.extensions && description.extensions.KHR_materials_common
  1124. && description.extensions.KHR_materials_common.light) {
  1125. var lightID = description.extensions.KHR_materials_common.light;
  1126. var lightEntry = this.resources.getEntry(lightID);
  1127. if (lightEntry) {
  1128. threeNode.add(lightEntry.object);
  1129. this.lights.push(lightEntry.object);
  1130. }
  1131. }
  1132. return true;
  1133. }
  1134. },
  1135. handleExtension: {
  1136. value: function(entryID, description, userInfo) {
  1137. // console.log("Extension", entryID, description);
  1138. switch (entryID) {
  1139. case 'KHR_materials_common' :
  1140. var lights = description.lights;
  1141. for (lightID in lights) {
  1142. var light = lights[lightID];
  1143. this.handleLight(lightID, light);
  1144. }
  1145. break;
  1146. }
  1147. return true;
  1148. }
  1149. },
  1150. buildNodeHirerachy: {
  1151. value: function(nodeEntryId, parentThreeNode) {
  1152. var nodeEntry = this.resources.getEntry(nodeEntryId);
  1153. var threeNode = nodeEntry.object;
  1154. parentThreeNode.add(threeNode);
  1155. var children = nodeEntry.description.children;
  1156. if (children) {
  1157. children.forEach( function(childID) {
  1158. this.buildNodeHirerachy(childID, threeNode);
  1159. }, this);
  1160. }
  1161. return threeNode;
  1162. }
  1163. },
  1164. buildSkin: {
  1165. value: function(node) {
  1166. var glTF = node.glTF;
  1167. var skin = glTF.instanceSkin;
  1168. var skeletons = glTF.skeletons;
  1169. if (skin) {
  1170. skeletons.forEach(function(skeleton) {
  1171. var nodeEntry = this.resources.getEntry(skeleton);
  1172. if (nodeEntry) {
  1173. var rootSkeleton = nodeEntry.object;
  1174. node.add(rootSkeleton);
  1175. var dobones = true;
  1176. for (meshID in glTF.meshInstances) {
  1177. var mesh = glTF.meshInstances[meshID];
  1178. var threeMesh = null;
  1179. mesh.primitives.forEach(function(primitive) {
  1180. var material = primitive.material;
  1181. var materialParams = material.params;
  1182. if (!(material instanceof THREE.Material)) {
  1183. material = createShaderMaterial(material);
  1184. }
  1185. threeMesh = new THREE.SkinnedMesh(primitive.geometry.geometry, material, false);
  1186. var geometry = primitive.geometry.geometry;
  1187. var j;
  1188. /* if (geometry.vertices) {
  1189. for ( j = 0; j < geometry.vertices.length; j ++ ) {
  1190. geometry.vertices[j].applyMatrix4( skin.bindShapeMatrix );
  1191. }
  1192. }
  1193. else if (geometry.attributes.position) {
  1194. var a = geometry.attributes.position.array;
  1195. var v = new THREE.Vector3;
  1196. for ( j = 0; j < a.length / 3; j++ ) {
  1197. v.set(a[j * 3], a[j * 3 + 1], a[j * 3 + 2]);
  1198. v.applyMatrix4( skin.bindShapeMatrix );
  1199. a[j * 3] = v.x;
  1200. a[j * 3 + 1] = v.y;
  1201. a[j * 3 + 2] = v.z;
  1202. }
  1203. }*/
  1204. if (threeMesh && dobones) {
  1205. material.skinning = true;
  1206. var jointNames = skin.jointNames;
  1207. var joints = [];
  1208. var bones = [];
  1209. var boneInverses = [];
  1210. var i, len = jointNames.length;
  1211. for (i = 0; i < len; i++) {
  1212. var jointName = jointNames[i];
  1213. var nodeForJoint = this.joints[jointName];
  1214. var joint = this.resources.getEntry(nodeForJoint).object;
  1215. if (joint) {
  1216. joint.skin = threeMesh;
  1217. joints.push(joint);
  1218. bones.push(joint);
  1219. var m = skin.inverseBindMatrices;
  1220. var mat = new THREE.Matrix4().set(
  1221. m[i * 16 + 0], m[i * 16 + 4], m[i * 16 + 8], m[i * 16 + 12],
  1222. m[i * 16 + 1], m[i * 16 + 5], m[i * 16 + 9], m[i * 16 + 13],
  1223. m[i * 16 + 2], m[i * 16 + 6], m[i * 16 + 10], m[i * 16 + 14],
  1224. m[i * 16 + 3], m[i * 16 + 7], m[i * 16 + 11], m[i * 16 + 15]
  1225. );
  1226. boneInverses.push(mat);
  1227. } else {
  1228. console.log("WARNING: jointName:"+jointName+" cannot be found in skeleton:"+skeleton);
  1229. }
  1230. }
  1231. threeMesh.bind( new THREE.Skeleton( bones,
  1232. boneInverses, false ), skin.bindShapeMatrix );
  1233. //threeMesh.bindMode = "detached";
  1234. //threeMesh.normalizeSkinWeights();
  1235. //threeMesh.pose();
  1236. }
  1237. if (threeMesh) {
  1238. threeMesh.castShadow = true;
  1239. node.add(threeMesh);
  1240. if (material instanceof THREE.ShaderMaterial) {
  1241. materialParams.joints = joints;
  1242. var glTFShader = new THREE.glTFShader(material, materialParams, threeMesh, theLoader.rootObj);
  1243. THREE.glTFShaders.add(glTFShader);
  1244. }
  1245. }
  1246. }, this);
  1247. }
  1248. }
  1249. }, this);
  1250. }
  1251. }
  1252. },
  1253. buildSkins: {
  1254. value: function(node) {
  1255. if (node.glTF && node.glTF.instanceSkin)
  1256. this.buildSkin(node);
  1257. var children = node.children;
  1258. if (children) {
  1259. children.forEach( function(child) {
  1260. this.buildSkins(child);
  1261. }, this);
  1262. }
  1263. }
  1264. },
  1265. createMeshAnimations : {
  1266. value : function(root) {
  1267. this.buildSkins(root);
  1268. }
  1269. },
  1270. handleScene: {
  1271. value: function(entryID, description, userInfo) {
  1272. if (!description.nodes) {
  1273. console.log("ERROR: invalid file required nodes property is missing from scene");
  1274. return false;
  1275. }
  1276. description.nodes.forEach( function(nodeUID) {
  1277. this.buildNodeHirerachy(nodeUID, userInfo.rootObj);
  1278. }, this);
  1279. if (this.delegate) {
  1280. this.delegate.loadCompleted(userInfo.callback, userInfo.rootObj);
  1281. }
  1282. theLoader.loadAllAssets();
  1283. return true;
  1284. }
  1285. },
  1286. handleImage: {
  1287. value: function(entryID, description, userInfo) {
  1288. this.resources.setEntry(entryID, null, description);
  1289. return true;
  1290. }
  1291. },
  1292. addNodeAnimationChannel : {
  1293. value : function(name, channel, interp) {
  1294. if (!this.nodeAnimationChannels)
  1295. this.nodeAnimationChannels = {};
  1296. if (!this.nodeAnimationChannels[name]) {
  1297. this.nodeAnimationChannels[name] = [];
  1298. }
  1299. this.nodeAnimationChannels[name].push(interp);
  1300. },
  1301. },
  1302. createAnimations : {
  1303. value : function() {
  1304. for (var name in this.nodeAnimationChannels) {
  1305. var nodeAnimationChannels = this.nodeAnimationChannels[name];
  1306. var i, len = nodeAnimationChannels.length;
  1307. //console.log(" animation channels for node " + name);
  1308. //for (i = 0; i < len; i++) {
  1309. // console.log(nodeAnimationChannels[i]);
  1310. //}
  1311. var anim = new THREE.glTFAnimation(nodeAnimationChannels);
  1312. anim.name = "animation_" + name;
  1313. this.animations.push(anim);
  1314. }
  1315. }
  1316. },
  1317. buildAnimation: {
  1318. value : function(animation) {
  1319. var interps = [];
  1320. var i, len = animation.channels.length;
  1321. for (i = 0; i < len; i++) {
  1322. var channel = animation.channels[i];
  1323. var sampler = animation.samplers[channel.sampler];
  1324. if (sampler) {
  1325. var input = animation.parameters[sampler.input];
  1326. if (input && input.data) {
  1327. var output = animation.parameters[sampler.output];
  1328. if (output && output.data) {
  1329. var target = channel.target;
  1330. var node = this.resources.getEntry(target.id);
  1331. if (node) {
  1332. var path = target.path;
  1333. var interp = {
  1334. keys : input.data,
  1335. values : output.data,
  1336. count : input.count,
  1337. target : node.object,
  1338. path : path,
  1339. type : sampler.interpolation
  1340. };
  1341. this.addNodeAnimationChannel(target.id, channel, interp);
  1342. interps.push(interp);
  1343. }
  1344. }
  1345. }
  1346. }
  1347. }
  1348. }
  1349. },
  1350. handleAnimation: {
  1351. value: function(entryID, description, userInfo) {
  1352. var self = this;
  1353. theLoader.animationsRequested++;
  1354. var animation = new Animation();
  1355. animation.name = entryID;
  1356. animation.onload = function() {
  1357. // self.buildAnimation(animation);
  1358. theLoader.animationsLoaded++;
  1359. theLoader.animations.push(animation);
  1360. theLoader.checkComplete();
  1361. };
  1362. animation.channels = description.channels;
  1363. animation.samplers = description.samplers;
  1364. this.resources.setEntry(entryID, animation, description);
  1365. var parameters = description.parameters;
  1366. if (!parameters) {
  1367. //FIXME: not implemented in delegate
  1368. console.log("MISSING_PARAMETERS for animation:"+ entryID);
  1369. return false;
  1370. }
  1371. // Load parameter buffers
  1372. var params = Object.keys(parameters);
  1373. params.forEach( function(param) {
  1374. // async help
  1375. animation.totalParameters++;
  1376. }, this);
  1377. var params = Object.keys(parameters);
  1378. params.forEach( function(param) {
  1379. var parameter = parameters[param];
  1380. var accessor = this.resources.getEntry(parameter);
  1381. if (!accessor)
  1382. debugger;
  1383. accessor = accessor.object;
  1384. var bufferView = this.resources.getEntry(accessor.bufferView);
  1385. var paramObject = {
  1386. bufferView : bufferView,
  1387. byteOffset : accessor.byteOffset,
  1388. count : accessor.count,
  1389. componentType : accessor.componentType,
  1390. type : accessor.type,
  1391. id : accessor.bufferView,
  1392. name : param
  1393. };
  1394. var paramContext = new AnimationParameterContext(paramObject, animation);
  1395. var loaddata = {
  1396. paramObject : paramObject,
  1397. animationParameterDelegate : animationParameterDelegate,
  1398. paramContext : paramContext
  1399. };
  1400. theLoader.scheduleLoad(function(data) {
  1401. var alreadyProcessedAttribute =
  1402. THREE.GLTFLoaderUtils.getBuffer(data.paramObject,
  1403. data.animationParameterDelegate, data.paramContext);
  1404. if (alreadyProcessedAttribute) {
  1405. data.animationParameterDelegate.resourceAvailable(
  1406. alreadyProcessedAttribute, data.paramContext);
  1407. }
  1408. }, loaddata);
  1409. }, this);
  1410. return true;
  1411. }
  1412. },
  1413. handleAccessor: {
  1414. value: function(entryID, description, userInfo) {
  1415. // Save attribute entry
  1416. this.resources.setEntry(entryID, description, description);
  1417. return true;
  1418. }
  1419. },
  1420. handleSkin: {
  1421. value: function(entryID, description, userInfo) {
  1422. // Save skin entry
  1423. var skin = {
  1424. };
  1425. var m = description.bindShapeMatrix;
  1426. skin.bindShapeMatrix = new THREE.Matrix4().set(
  1427. m[0], m[4], m[8], m[12],
  1428. m[1], m[5], m[9], m[13],
  1429. m[2], m[6], m[10], m[14],
  1430. m[3], m[7], m[11], m[15]
  1431. );
  1432. skin.jointNames = description.jointNames;
  1433. var inverseBindMatricesDescription = this.resources.getEntry(description.inverseBindMatrices);
  1434. inverseBindMatricesDescription = inverseBindMatricesDescription.description;
  1435. skin.inverseBindMatricesDescription = inverseBindMatricesDescription;
  1436. skin.inverseBindMatricesDescription.id = description.inverseBindMatrices;
  1437. var bufferEntry = this.resources.getEntry(inverseBindMatricesDescription.bufferView);
  1438. var paramObject = {
  1439. bufferView : bufferEntry,
  1440. byteOffset : inverseBindMatricesDescription.byteOffset,
  1441. count : inverseBindMatricesDescription.count,
  1442. componentType : inverseBindMatricesDescription.componentType,
  1443. type : inverseBindMatricesDescription.type,
  1444. id : inverseBindMatricesDescription.bufferView,
  1445. name : skin.inverseBindMatricesDescription.id
  1446. };
  1447. var context = new InverseBindMatricesContext(paramObject, skin);
  1448. var loaddata = {
  1449. paramObject : paramObject,
  1450. inverseBindMatricesDelegate : inverseBindMatricesDelegate,
  1451. context : context
  1452. };
  1453. theLoader.scheduleLoad(function(data) {
  1454. var alreadyProcessedAttribute =
  1455. THREE.GLTFLoaderUtils.getBuffer(data.paramObject,
  1456. data.inverseBindMatricesDelegate, data.context);
  1457. if (alreadyProcessedAttribute) {
  1458. data.inverseBindMatricesDelegate.resourceAvailable(
  1459. alreadyProcessedAttribute, data.context);
  1460. }
  1461. }, loaddata);
  1462. var bufferView = this.resources.getEntry(skin.inverseBindMatricesDescription.bufferView);
  1463. skin.inverseBindMatricesDescription.bufferView =
  1464. bufferView.object;
  1465. this.resources.setEntry(entryID, skin, description);
  1466. return true;
  1467. }
  1468. },
  1469. handleSampler: {
  1470. value: function(entryID, description, userInfo) {
  1471. // Save attribute entry
  1472. this.resources.setEntry(entryID, description, description);
  1473. return true;
  1474. }
  1475. },
  1476. handleTexture: {
  1477. value: function(entryID, description, userInfo) {
  1478. // Save attribute entry
  1479. this.resources.setEntry(entryID, null, description);
  1480. return true;
  1481. }
  1482. },
  1483. handleError: {
  1484. value: function(msg) {
  1485. throw new Error(msg);
  1486. return true;
  1487. }
  1488. },
  1489. _delegate: {
  1490. value: new LoadDelegate,
  1491. writable: true
  1492. },
  1493. delegate: {
  1494. enumerable: true,
  1495. get: function() {
  1496. return this._delegate;
  1497. },
  1498. set: function(value) {
  1499. this._delegate = value;
  1500. }
  1501. }
  1502. });
  1503. // Loader
  1504. var Context = function(rootObj, callback) {
  1505. this.rootObj = rootObj;
  1506. this.callback = callback;
  1507. };
  1508. var rootObj = new THREE.Object3D();
  1509. var self = this;
  1510. var loader = Object.create(ThreeGLTFLoader);
  1511. loader.initWithPath(url);
  1512. loader.load(new Context(rootObj,
  1513. function(obj) {
  1514. }),
  1515. null);
  1516. this.loader = loader;
  1517. this.callback = callback;
  1518. this.rootObj = rootObj;
  1519. return rootObj;
  1520. }
  1521. THREE.glTFLoader.prototype.scheduleLoad = function(loadFn, data) {
  1522. this.loadRequests.push({fn: loadFn, data:data});
  1523. }
  1524. THREE.glTFLoader.prototype.loadAllAssets = function() {
  1525. for (var i = 0, len = this.loadRequests.length; i < len; i++) {
  1526. var request = this.loadRequests[i];
  1527. request.fn(request.data);
  1528. }
  1529. }
  1530. THREE.glTFLoader.prototype.callLoadedCallback = function() {
  1531. var result = {
  1532. scene : this.rootObj,
  1533. cameras : this.loader.cameras,
  1534. animations : this.loader.animations,
  1535. shaders : this.loader.shaders,
  1536. };
  1537. this.callback(result);
  1538. }
  1539. THREE.glTFLoader.prototype.checkComplete = function() {
  1540. if (this.meshesLoaded == this.meshesRequested
  1541. && this.shadersLoaded == this.shadersRequested
  1542. && this.animationsLoaded == this.animationsRequested)
  1543. {
  1544. for (var i = 0; i < this.pendingMeshes.length; i++) {
  1545. var pending = this.pendingMeshes[i];
  1546. pending.mesh.attachToNode(pending.node);
  1547. }
  1548. for (var i = 0; i < this.animationsLoaded; i++) {
  1549. var animation = this.animations[i];
  1550. this.loader.buildAnimation(animation);
  1551. }
  1552. this.loader.createAnimations();
  1553. this.loader.createMeshAnimations(this.rootObj);
  1554. THREE.glTFShaders.bindShaderParameters(this.rootObj);
  1555. this.callLoadedCallback();
  1556. }
  1557. }