babylon.glTFFileLoader.js 89 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985
  1. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  2. var BABYLON;
  3. (function (BABYLON) {
  4. /**
  5. * Enums
  6. */
  7. (function (EComponentType) {
  8. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  9. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  10. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  11. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  12. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  13. })(BABYLON.EComponentType || (BABYLON.EComponentType = {}));
  14. var EComponentType = BABYLON.EComponentType;
  15. (function (EShaderType) {
  16. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  17. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  18. })(BABYLON.EShaderType || (BABYLON.EShaderType = {}));
  19. var EShaderType = BABYLON.EShaderType;
  20. (function (EParameterType) {
  21. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  22. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  23. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  24. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  25. EParameterType[EParameterType["INT"] = 5124] = "INT";
  26. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  27. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  28. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  29. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  30. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  31. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  32. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  33. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  34. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  35. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  36. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  37. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  38. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  39. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  40. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  41. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  42. })(BABYLON.EParameterType || (BABYLON.EParameterType = {}));
  43. var EParameterType = BABYLON.EParameterType;
  44. (function (ETextureWrapMode) {
  45. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  46. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  47. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  48. })(BABYLON.ETextureWrapMode || (BABYLON.ETextureWrapMode = {}));
  49. var ETextureWrapMode = BABYLON.ETextureWrapMode;
  50. (function (ETextureFilterType) {
  51. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  52. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  53. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  54. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  55. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  56. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  57. })(BABYLON.ETextureFilterType || (BABYLON.ETextureFilterType = {}));
  58. var ETextureFilterType = BABYLON.ETextureFilterType;
  59. (function (ETextureFormat) {
  60. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  61. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  62. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  63. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  64. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  65. })(BABYLON.ETextureFormat || (BABYLON.ETextureFormat = {}));
  66. var ETextureFormat = BABYLON.ETextureFormat;
  67. (function (ECullingType) {
  68. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  69. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  70. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  71. })(BABYLON.ECullingType || (BABYLON.ECullingType = {}));
  72. var ECullingType = BABYLON.ECullingType;
  73. (function (EBlendingFunction) {
  74. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  75. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  76. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  77. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  78. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  79. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  80. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  81. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  82. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  83. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  84. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  85. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  86. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  87. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  88. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  89. })(BABYLON.EBlendingFunction || (BABYLON.EBlendingFunction = {}));
  90. var EBlendingFunction = BABYLON.EBlendingFunction;
  91. })(BABYLON || (BABYLON = {}));
  92. //# sourceMappingURL=babylon.glTFFileLoaderInterfaces.js.map
  93. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  94. var BABYLON;
  95. (function (BABYLON) {
  96. /**
  97. * Tokenizer. Used for shaders compatibility
  98. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  99. */
  100. var ETokenType;
  101. (function (ETokenType) {
  102. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  103. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  104. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  105. })(ETokenType || (ETokenType = {}));
  106. var Tokenizer = (function () {
  107. function Tokenizer(toParse) {
  108. this._pos = 0;
  109. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  110. this._toParse = toParse;
  111. this._maxPos = toParse.length;
  112. }
  113. Tokenizer.prototype.getNextToken = function () {
  114. if (this.isEnd())
  115. return ETokenType.END_OF_INPUT;
  116. this.currentString = this.read();
  117. this.currentToken = ETokenType.UNKNOWN;
  118. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  119. this.currentToken = ETokenType.IDENTIFIER;
  120. this.currentIdentifier = this.currentString;
  121. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  122. this.currentIdentifier += this.currentString;
  123. this.forward();
  124. }
  125. }
  126. return this.currentToken;
  127. };
  128. Tokenizer.prototype.peek = function () {
  129. return this._toParse[this._pos];
  130. };
  131. Tokenizer.prototype.read = function () {
  132. return this._toParse[this._pos++];
  133. };
  134. Tokenizer.prototype.forward = function () {
  135. this._pos++;
  136. };
  137. Tokenizer.prototype.isEnd = function () {
  138. return this._pos >= this._maxPos;
  139. };
  140. return Tokenizer;
  141. }());
  142. /**
  143. * Values
  144. */
  145. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  146. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  147. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  148. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  149. /**
  150. * Parse
  151. */
  152. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  153. for (var buf in parsedBuffers) {
  154. var parsedBuffer = parsedBuffers[buf];
  155. gltfRuntime.buffers[buf] = parsedBuffer;
  156. gltfRuntime.buffersCount++;
  157. }
  158. };
  159. var parseShaders = function (parsedShaders, gltfRuntime) {
  160. for (var sha in parsedShaders) {
  161. var parsedShader = parsedShaders[sha];
  162. gltfRuntime.shaders[sha] = parsedShader;
  163. gltfRuntime.shaderscount++;
  164. }
  165. };
  166. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  167. for (var object in parsedObjects) {
  168. var parsedObject = parsedObjects[object];
  169. gltfRuntime[runtimeProperty][object] = parsedObject;
  170. }
  171. };
  172. /**
  173. * Utils
  174. */
  175. var normalizeUVs = function (buffer) {
  176. if (!buffer) {
  177. return;
  178. }
  179. for (var i = 0; i < buffer.length / 2; i++) {
  180. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  181. }
  182. };
  183. var replaceInString = function (str, searchValue, replaceValue) {
  184. while (str.indexOf(searchValue) !== -1) {
  185. str = str.replace(searchValue, replaceValue);
  186. }
  187. return str;
  188. };
  189. var getAttribute = function (attributeParameter) {
  190. if (attributeParameter.semantic === "NORMAL") {
  191. return "normal";
  192. }
  193. else if (attributeParameter.semantic === "POSITION") {
  194. return "position";
  195. }
  196. else if (attributeParameter.semantic === "JOINT") {
  197. return "matricesIndices";
  198. }
  199. else if (attributeParameter.semantic === "WEIGHT") {
  200. return "matricesWeights";
  201. }
  202. else if (attributeParameter.semantic === "COLOR") {
  203. return "color";
  204. }
  205. else if (attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  206. var channel = Number(attributeParameter.semantic.split("_")[1]);
  207. return "uv" + (channel === 0 ? "" : channel + 1);
  208. }
  209. };
  210. /**
  211. * Returns the animation path (glTF -> Babylon)
  212. */
  213. var getAnimationPath = function (path) {
  214. var index = glTFAnimationPaths.indexOf(path);
  215. if (index !== -1) {
  216. return babylonAnimationPaths[index];
  217. }
  218. return path;
  219. };
  220. /**
  221. * Loads and creates animations
  222. */
  223. var loadAnimations = function (gltfRuntime) {
  224. for (var anim in gltfRuntime.animations) {
  225. var animation = gltfRuntime.animations[anim];
  226. var lastAnimation = null;
  227. for (var i = 0; i < animation.channels.length; i++) {
  228. // Get parameters and load buffers
  229. var channel = animation.channels[i];
  230. var sampler = animation.samplers[channel.sampler];
  231. if (!sampler) {
  232. continue;
  233. }
  234. var inputData = animation.parameters[sampler.input];
  235. var outputData = animation.parameters[sampler.output];
  236. var bufferInput = BABYLON.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  237. var bufferOutput = BABYLON.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  238. var targetID = channel.target.id;
  239. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  240. if (targetNode === null) {
  241. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  242. continue;
  243. }
  244. var isBone = targetNode instanceof BABYLON.Bone;
  245. // Get target path (position, rotation or scaling)
  246. var targetPath = channel.target.path;
  247. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  248. if (targetPathIndex !== -1) {
  249. targetPath = babylonAnimationPaths[targetPathIndex];
  250. }
  251. // Determine animation type
  252. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  253. if (!isBone) {
  254. if (targetPath === "rotationQuaternion") {
  255. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  256. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  257. }
  258. else {
  259. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  260. }
  261. }
  262. // Create animation and key frames
  263. var babylonAnimation = null;
  264. var keys = [];
  265. var arrayOffset = 0;
  266. var modifyKey = false;
  267. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  268. babylonAnimation = lastAnimation;
  269. modifyKey = true;
  270. }
  271. if (!modifyKey) {
  272. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  273. }
  274. // For each frame
  275. for (var j = 0; j < bufferInput.length; j++) {
  276. var value = null;
  277. if (targetPath === "rotationQuaternion") {
  278. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  279. arrayOffset += 4;
  280. }
  281. else {
  282. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  283. arrayOffset += 3;
  284. }
  285. if (isBone) {
  286. var bone = targetNode;
  287. var translation = BABYLON.Vector3.Zero();
  288. var rotationQuaternion = new BABYLON.Quaternion();
  289. var scaling = BABYLON.Vector3.Zero();
  290. // Warning on decompose
  291. var mat = bone.getBaseMatrix();
  292. if (modifyKey) {
  293. mat = lastAnimation.getKeys()[j].value;
  294. }
  295. mat.decompose(scaling, rotationQuaternion, translation);
  296. if (targetPath === "position") {
  297. translation = value;
  298. }
  299. else if (targetPath === "rotationQuaternion") {
  300. rotationQuaternion = value;
  301. // Y is Up
  302. if (GLTFFileLoader.MakeYUP) {
  303. rotationQuaternion = rotationQuaternion.multiply(new BABYLON.Quaternion(-0.707107, 0, 0, 0.707107));
  304. }
  305. }
  306. else {
  307. scaling = value;
  308. }
  309. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  310. }
  311. if (!modifyKey) {
  312. keys.push({
  313. frame: bufferInput[j],
  314. value: value
  315. });
  316. }
  317. else {
  318. lastAnimation.getKeys()[j].value = value;
  319. }
  320. }
  321. // Finish
  322. if (!modifyKey) {
  323. babylonAnimation.setKeys(keys);
  324. targetNode.animations.push(babylonAnimation);
  325. }
  326. lastAnimation = babylonAnimation;
  327. gltfRuntime.scene.stopAnimation(targetNode);
  328. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  329. }
  330. }
  331. };
  332. /**
  333. * Returns the bones transformation matrix
  334. */
  335. var configureBoneTransformation = function (node) {
  336. var mat = null;
  337. if (node.translation && node.rotation && node.scale) {
  338. var scale = BABYLON.Vector3.FromArray(node.scale);
  339. var rotation = BABYLON.Quaternion.FromArray(node.rotation);
  340. var position = BABYLON.Vector3.FromArray(node.translation);
  341. // Y is Up
  342. if (GLTFFileLoader.MakeYUP) {
  343. rotation = rotation.multiply(new BABYLON.Quaternion(-0.707107, 0, 0, 0.707107));
  344. }
  345. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  346. }
  347. else {
  348. mat = BABYLON.Matrix.FromArray(node.matrix);
  349. }
  350. return mat;
  351. };
  352. /**
  353. * Returns the parent bone
  354. */
  355. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  356. // Try to find
  357. for (var i = 0; i < newSkeleton.bones.length; i++) {
  358. if (newSkeleton.bones[i].id === jointName) {
  359. return newSkeleton.bones[i];
  360. }
  361. }
  362. // Not found, search in gltf nodes
  363. var nodes = gltfRuntime.nodes;
  364. for (var nde in nodes) {
  365. var node = nodes[nde];
  366. if (!node.jointName) {
  367. continue;
  368. }
  369. var children = node.children;
  370. for (var i = 0; i < children.length; i++) {
  371. var child = gltfRuntime.nodes[children[i]];
  372. if (!child.jointName) {
  373. continue;
  374. }
  375. if (child.jointName === jointName) {
  376. var mat = configureBoneTransformation(node);
  377. var bone = new BABYLON.Bone(node.name, newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  378. bone.id = nde;
  379. return bone;
  380. }
  381. }
  382. }
  383. return null;
  384. };
  385. /**
  386. * Returns the appropriate root node
  387. */
  388. var getNodeToRoot = function (nodesToRoot, id) {
  389. for (var i = 0; i < nodesToRoot.length; i++) {
  390. var nodeToRoot = nodesToRoot[i];
  391. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  392. var child = nodeToRoot.node.children[j];
  393. if (child === id) {
  394. return nodeToRoot.bone;
  395. }
  396. }
  397. }
  398. return null;
  399. };
  400. /**
  401. * Returns the node with the joint name
  402. */
  403. var getJointNode = function (gltfRuntime, jointName) {
  404. var nodes = gltfRuntime.nodes;
  405. var node = nodes[jointName];
  406. if (node) {
  407. return {
  408. node: node,
  409. id: jointName
  410. };
  411. }
  412. for (var nde in nodes) {
  413. node = nodes[nde];
  414. if (node.jointName === jointName) {
  415. return {
  416. node: node,
  417. id: nde
  418. };
  419. }
  420. }
  421. return null;
  422. };
  423. /**
  424. * Checks if a nodes is in joints
  425. */
  426. var nodeIsInJoints = function (skins, id) {
  427. for (var i = 0; i < skins.jointNames.length; i++) {
  428. if (skins.jointNames[i] === id) {
  429. return true;
  430. }
  431. }
  432. return false;
  433. };
  434. /**
  435. * Fills the nodes to root for bones and builds hierarchy
  436. */
  437. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  438. // Creates nodes for root
  439. for (var nde in gltfRuntime.nodes) {
  440. var node = gltfRuntime.nodes[nde];
  441. var id = nde;
  442. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  443. continue;
  444. }
  445. // Create node to root bone
  446. var mat = configureBoneTransformation(node);
  447. var bone = new BABYLON.Bone(node.name, newSkeleton, null, mat);
  448. bone.id = id;
  449. nodesToRoot.push({ bone: bone, node: node, id: id });
  450. }
  451. // Parenting
  452. for (var i = 0; i < nodesToRoot.length; i++) {
  453. var nodeToRoot = nodesToRoot[i];
  454. var children = nodeToRoot.node.children;
  455. for (var j = 0; j < children.length; j++) {
  456. var child = null;
  457. for (var k = 0; k < nodesToRoot.length; k++) {
  458. if (nodesToRoot[k].id === children[j]) {
  459. child = nodesToRoot[k];
  460. break;
  461. }
  462. }
  463. if (child) {
  464. child.bone._parent = nodeToRoot.bone;
  465. nodeToRoot.bone.children.push(child.bone);
  466. }
  467. }
  468. }
  469. };
  470. var printMat = function (m) {
  471. console.log(m[0] + "\t" + m[1] + "\t" + m[2] + "\t" + m[3] + "\n" +
  472. m[4] + "\t" + m[5] + "\t" + m[6] + "\t" + m[7] + "\n" +
  473. m[8] + "\t" + m[9] + "\t" + m[10] + "\t" + m[11] + "\n" +
  474. m[12] + "\t" + m[13] + "\t" + m[14] + "\t" + m[15] + "\n");
  475. };
  476. /**
  477. * Imports a skeleton
  478. */
  479. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  480. if (!newSkeleton) {
  481. newSkeleton = new BABYLON.Skeleton(skins.name, "", gltfRuntime.scene);
  482. }
  483. if (!skins.babylonSkeleton) {
  484. return newSkeleton;
  485. }
  486. // Matrices
  487. var accessor = gltfRuntime.accessors[skins.inverseBindMatrices];
  488. var buffer = BABYLON.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  489. var bindShapeMatrix = BABYLON.Matrix.FromArray(skins.bindShapeMatrix);
  490. // Find the root bones
  491. var nodesToRoot = [];
  492. var nodesToRootToAdd = [];
  493. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  494. newSkeleton.bones = [];
  495. if (nodesToRoot.length === 0) {
  496. newSkeleton.needInitialSkinMatrix = true;
  497. }
  498. // Joints
  499. for (var i = 0; i < skins.jointNames.length; i++) {
  500. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  501. var node = jointNode.node;
  502. if (!node) {
  503. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  504. continue;
  505. }
  506. var id = jointNode.id;
  507. // Optimize, if the bone already exists...
  508. var existingBone = gltfRuntime.scene.getBoneByID(id);
  509. if (existingBone) {
  510. newSkeleton.bones.push(existingBone);
  511. continue;
  512. }
  513. // Check if node already exists
  514. var foundBone = false;
  515. for (var j = 0; j < newSkeleton.bones.length; j++) {
  516. if (newSkeleton.bones[j].id === id) {
  517. foundBone = true;
  518. break;
  519. }
  520. }
  521. if (foundBone) {
  522. continue;
  523. }
  524. // Search for parent bone
  525. var parentBone = null;
  526. for (var j = 0; j < i; j++) {
  527. var joint = getJointNode(gltfRuntime, skins.jointNames[j]).node;
  528. if (!joint) {
  529. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  530. continue;
  531. }
  532. var children = joint.children;
  533. foundBone = false;
  534. for (var k = 0; k < children.length; k++) {
  535. if (children[k] === id) {
  536. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  537. foundBone = true;
  538. break;
  539. }
  540. }
  541. if (foundBone) {
  542. break;
  543. }
  544. }
  545. // Create bone
  546. var mat = configureBoneTransformation(node);
  547. if (!parentBone && nodesToRoot.length > 0) {
  548. parentBone = getNodeToRoot(nodesToRoot, id);
  549. if (parentBone) {
  550. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  551. nodesToRootToAdd.push(parentBone);
  552. }
  553. }
  554. }
  555. if (!parentBone && nodesToRoot.length === 0) {
  556. var inverseBindMatrix = BABYLON.Matrix.FromArray(buffer, i * 16);
  557. var invertMesh = BABYLON.Matrix.Invert(mesh.getWorldMatrix());
  558. mat = mat.multiply(mesh.getWorldMatrix());
  559. }
  560. var bone = new BABYLON.Bone(node.name, newSkeleton, parentBone, mat);
  561. bone.id = id;
  562. }
  563. // Polish
  564. var bones = newSkeleton.bones;
  565. newSkeleton.bones = [];
  566. for (var i = 0; i < skins.jointNames.length; i++) {
  567. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  568. if (!jointNode) {
  569. continue;
  570. }
  571. for (var j = 0; j < bones.length; j++) {
  572. if (bones[j].id === jointNode.id) {
  573. newSkeleton.bones.push(bones[j]);
  574. break;
  575. }
  576. }
  577. }
  578. // Finish
  579. newSkeleton.prepare();
  580. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  581. newSkeleton.bones.push(nodesToRootToAdd[i]);
  582. }
  583. return newSkeleton;
  584. };
  585. /**
  586. * Imports a mesh and its geometries
  587. */
  588. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  589. if (!newMesh) {
  590. newMesh = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  591. newMesh.id = id;
  592. }
  593. if (!node.babylonNode) {
  594. return newMesh;
  595. }
  596. var multiMat = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  597. if (!newMesh.material) {
  598. newMesh.material = multiMat;
  599. }
  600. var vertexData = new BABYLON.VertexData();
  601. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  602. var verticesStarts = [];
  603. var verticesCounts = [];
  604. var indexStarts = [];
  605. var indexCounts = [];
  606. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  607. var meshID = meshes[meshIndex];
  608. var mesh = gltfRuntime.meshes[meshID];
  609. if (!mesh) {
  610. continue;
  611. }
  612. // Positions, normals and UVs
  613. for (var i = 0; i < mesh.primitives.length; i++) {
  614. // Temporary vertex data
  615. var tempVertexData = new BABYLON.VertexData();
  616. var primitive = mesh.primitives[i];
  617. if (primitive.mode !== 4) {
  618. }
  619. var attributes = primitive.attributes;
  620. var accessor = null;
  621. var buffer = null;
  622. // Set positions, normal and uvs
  623. for (var semantic in attributes) {
  624. // Link accessor and buffer view
  625. accessor = gltfRuntime.accessors[attributes[semantic]];
  626. buffer = BABYLON.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  627. if (semantic === "NORMAL") {
  628. tempVertexData.normals = new Float32Array(buffer.length);
  629. tempVertexData.normals.set(buffer);
  630. }
  631. else if (semantic === "POSITION") {
  632. if (GLTFFileLoader.HomogeneousCoordinates) {
  633. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  634. for (var j = 0; j < buffer.length; j += 4) {
  635. tempVertexData.positions[j] = buffer[j];
  636. tempVertexData.positions[j + 1] = buffer[j + 1];
  637. tempVertexData.positions[j + 2] = buffer[j + 2];
  638. }
  639. }
  640. else {
  641. tempVertexData.positions = new Float32Array(buffer.length);
  642. tempVertexData.positions.set(buffer);
  643. }
  644. verticesCounts.push(tempVertexData.positions.length);
  645. }
  646. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  647. var channel = Number(semantic.split("_")[1]);
  648. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  649. var uvs = new Float32Array(buffer.length);
  650. uvs.set(buffer);
  651. normalizeUVs(uvs);
  652. tempVertexData.set(uvs, uvKind);
  653. }
  654. else if (semantic === "JOINT") {
  655. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  656. tempVertexData.matricesIndices.set(buffer);
  657. }
  658. else if (semantic === "WEIGHT") {
  659. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  660. tempVertexData.matricesWeights.set(buffer);
  661. }
  662. else if (semantic === "COLOR") {
  663. tempVertexData.colors = new Float32Array(buffer.length);
  664. tempVertexData.colors.set(buffer);
  665. }
  666. }
  667. // Indices
  668. accessor = gltfRuntime.accessors[primitive.indices];
  669. if (accessor) {
  670. buffer = BABYLON.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  671. tempVertexData.indices = new Int32Array(buffer.length);
  672. tempVertexData.indices.set(buffer);
  673. indexCounts.push(tempVertexData.indices.length);
  674. }
  675. else {
  676. // Set indices on the fly
  677. var indices = [];
  678. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  679. indices.push(j);
  680. }
  681. tempVertexData.indices = new Int32Array(indices);
  682. indexCounts.push(tempVertexData.indices.length);
  683. }
  684. vertexData.merge(tempVertexData);
  685. tempVertexData = undefined;
  686. // Sub material
  687. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  688. multiMat.subMaterials.push(material === null ? gltfRuntime.scene.defaultMaterial : material);
  689. // Update vertices start and index start
  690. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  691. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  692. }
  693. }
  694. // Apply geometry
  695. geometry.setAllVerticesData(vertexData, false);
  696. newMesh.computeWorldMatrix(true);
  697. // Apply submeshes
  698. newMesh.subMeshes = [];
  699. var index = 0;
  700. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  701. var meshID = meshes[meshIndex];
  702. var mesh = gltfRuntime.meshes[meshID];
  703. if (!mesh) {
  704. continue;
  705. }
  706. for (var i = 0; i < mesh.primitives.length; i++) {
  707. if (mesh.primitives[i].mode !== 4) {
  708. }
  709. var subMesh = new BABYLON.SubMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  710. index++;
  711. }
  712. }
  713. // Finish
  714. return newMesh;
  715. };
  716. /**
  717. * Configure node transformation from position, rotation and scaling
  718. */
  719. var configureNode = function (newNode, position, rotation, scaling) {
  720. if (newNode.position) {
  721. newNode.position = position;
  722. }
  723. if (newNode.rotationQuaternion || newNode.rotation) {
  724. newNode.rotationQuaternion = rotation;
  725. }
  726. if (newNode.scaling) {
  727. newNode.scaling = scaling;
  728. }
  729. };
  730. /**
  731. * Configures node from transformation matrix
  732. */
  733. var configureNodeFromMatrix = function (newNode, node) {
  734. if (node.matrix) {
  735. var position = new BABYLON.Vector3(0, 0, 0);
  736. var rotation = new BABYLON.Quaternion();
  737. var scaling = new BABYLON.Vector3(0, 0, 0);
  738. var mat = BABYLON.Matrix.FromArray(node.matrix);
  739. mat.decompose(scaling, rotation, position);
  740. // Y is Up
  741. if (GLTFFileLoader.MakeYUP) {
  742. rotation = rotation.multiply(new BABYLON.Quaternion(-0.707107, 0, 0, 0.707107));
  743. }
  744. configureNode(newNode, position, rotation, scaling);
  745. if (newNode instanceof BABYLON.TargetCamera) {
  746. newNode.setTarget(BABYLON.Vector3.Zero());
  747. }
  748. }
  749. else {
  750. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  751. }
  752. };
  753. /**
  754. * Imports a node
  755. */
  756. var importNode = function (gltfRuntime, node, id) {
  757. var lastNode = null;
  758. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  759. if (gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name) === -1) {
  760. return null;
  761. }
  762. }
  763. // Meshes
  764. if (node.skin) {
  765. if (node.meshes) {
  766. var skin = gltfRuntime.skins[node.skin];
  767. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  768. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  769. if (newMesh.skeleton === null) {
  770. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  771. if (!skin.babylonSkeleton) {
  772. skin.babylonSkeleton = newMesh.skeleton;
  773. }
  774. }
  775. if (newMesh.skeleton !== null) {
  776. newMesh.useBones = true;
  777. }
  778. lastNode = newMesh;
  779. }
  780. }
  781. else if (node.meshes) {
  782. /**
  783. * Improve meshes property
  784. */
  785. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  786. lastNode = newMesh;
  787. }
  788. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  789. var light = gltfRuntime.lights[node.light];
  790. if (light) {
  791. if (light.type === "ambient") {
  792. var ambienLight = light[light.type];
  793. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  794. hemiLight.name = node.name;
  795. if (ambienLight.color) {
  796. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  797. }
  798. lastNode = hemiLight;
  799. }
  800. else if (light.type === "directional") {
  801. var directionalLight = light[light.type];
  802. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  803. dirLight.name = node.name;
  804. if (directionalLight.color) {
  805. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  806. }
  807. lastNode = dirLight;
  808. }
  809. else if (light.type === "point") {
  810. var pointLight = light[light.type];
  811. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  812. ptLight.name = node.name;
  813. if (pointLight.color) {
  814. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  815. }
  816. lastNode = ptLight;
  817. }
  818. else if (light.type === "spot") {
  819. var spotLight = light[light.type];
  820. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  821. spLight.name = node.name;
  822. if (spotLight.color) {
  823. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  824. }
  825. if (spotLight.fallOfAngle) {
  826. spLight.angle = spotLight.fallOfAngle;
  827. }
  828. if (spotLight.fallOffExponent) {
  829. spLight.exponent = spotLight.fallOffExponent;
  830. }
  831. lastNode = spLight;
  832. }
  833. }
  834. }
  835. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  836. var camera = gltfRuntime.cameras[node.camera];
  837. if (camera) {
  838. if (camera.type === "orthographic") {
  839. var orthographicCamera = camera[camera.type];
  840. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  841. orthoCamera.name = node.name;
  842. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  843. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  844. lastNode = orthoCamera;
  845. }
  846. else if (camera.type === "perspective") {
  847. var perspectiveCamera = camera[camera.type];
  848. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  849. persCamera.name = node.name;
  850. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  851. if (!perspectiveCamera.aspectRatio) {
  852. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  853. }
  854. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  855. persCamera.maxZ = perspectiveCamera.zfar;
  856. persCamera.minZ = perspectiveCamera.znear;
  857. }
  858. lastNode = persCamera;
  859. }
  860. }
  861. }
  862. // Empty node
  863. if (!node.jointName) {
  864. if (node.babylonNode) {
  865. return node.babylonNode;
  866. }
  867. else if (lastNode === null) {
  868. var dummy = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  869. node.babylonNode = dummy;
  870. lastNode = dummy;
  871. }
  872. }
  873. if (lastNode !== null) {
  874. if (node.matrix) {
  875. configureNodeFromMatrix(lastNode, node);
  876. }
  877. else {
  878. configureNode(lastNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.RotationAxis(BABYLON.Vector3.FromArray(node.rotation).normalize(), node.rotation[3]), BABYLON.Vector3.FromArray(node.scale));
  879. }
  880. lastNode.updateCache(true);
  881. node.babylonNode = lastNode;
  882. }
  883. return lastNode;
  884. };
  885. /**
  886. * Traverses nodes and creates them
  887. */
  888. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  889. var node = gltfRuntime.nodes[id];
  890. var newNode = null;
  891. if (gltfRuntime.importOnlyMeshes && !meshIncluded) {
  892. if (gltfRuntime.importMeshesNames.indexOf(node.name) !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  893. meshIncluded = true;
  894. }
  895. else {
  896. meshIncluded = false;
  897. }
  898. }
  899. else {
  900. meshIncluded = true;
  901. }
  902. if (!node.jointName && meshIncluded) {
  903. newNode = importNode(gltfRuntime, node, id);
  904. if (newNode !== null) {
  905. newNode.id = id;
  906. newNode.parent = parent;
  907. }
  908. }
  909. for (var i = 0; i < node.children.length; i++) {
  910. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  911. }
  912. };
  913. /**
  914. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  915. */
  916. var postLoad = function (gltfRuntime) {
  917. // Nodes
  918. var currentScene = gltfRuntime.currentScene;
  919. for (var i = 0; i < currentScene.nodes.length; i++) {
  920. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  921. }
  922. // Set animations
  923. loadAnimations(gltfRuntime);
  924. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  925. var skeleton = gltfRuntime.scene.skeletons[i];
  926. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  927. }
  928. };
  929. /**
  930. * onBind shaderrs callback to set uniforms and matrices
  931. */
  932. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  933. for (var unif in unTreatedUniforms) {
  934. var uniform = unTreatedUniforms[unif];
  935. var type = uniform.type;
  936. if (type === BABYLON.EParameterType.FLOAT_MAT2 || type === BABYLON.EParameterType.FLOAT_MAT3 || type === BABYLON.EParameterType.FLOAT_MAT4) {
  937. if (uniform.semantic && !uniform.source && !uniform.node) {
  938. BABYLON.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  939. }
  940. else if (uniform.semantic && (uniform.source || uniform.node)) {
  941. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node);
  942. if (source === null) {
  943. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node);
  944. }
  945. if (source === null) {
  946. continue;
  947. }
  948. BABYLON.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  949. }
  950. }
  951. else {
  952. var value = material.values[technique.uniforms[unif]];
  953. if (!value) {
  954. continue;
  955. }
  956. if (type === BABYLON.EParameterType.SAMPLER_2D) {
  957. var texture = gltfRuntime.textures[value].babylonTexture;
  958. if (texture === null) {
  959. continue;
  960. }
  961. shaderMaterial.getEffect().setTexture(unif, texture);
  962. }
  963. else {
  964. BABYLON.GLTFUtils.SetUniform(shaderMaterial.getEffect(), unif, value, type);
  965. }
  966. }
  967. }
  968. onSuccess(shaderMaterial);
  969. };
  970. /**
  971. * Prepare uniforms to send the only one time
  972. * Loads the appropriate textures
  973. */
  974. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  975. var materialValues = material.values;
  976. var techniqueUniforms = technique.uniforms;
  977. /**
  978. * Prepare values here (not matrices)
  979. */
  980. for (var unif in unTreatedUniforms) {
  981. var uniform = unTreatedUniforms[unif];
  982. var type = uniform.type;
  983. var value = materialValues[techniqueUniforms[unif]] || uniform.value;
  984. if (!value) {
  985. continue;
  986. }
  987. var onLoadTexture = function (texture) {
  988. if (uniform.value) {
  989. // Static uniform
  990. shaderMaterial.setTexture(unif, texture);
  991. delete unTreatedUniforms[unif];
  992. }
  993. };
  994. // Texture (sampler2D)
  995. if (type === BABYLON.EParameterType.SAMPLER_2D) {
  996. BABYLON.GLTFFileLoaderExtension.LoadTextureAsync(gltfRuntime, value, onLoadTexture, function () { return onLoadTexture(null); });
  997. }
  998. else {
  999. if (uniform.value && BABYLON.GLTFUtils.SetUniform(shaderMaterial, unif, value, type)) {
  1000. // Static uniform
  1001. delete unTreatedUniforms[unif];
  1002. }
  1003. }
  1004. }
  1005. };
  1006. /**
  1007. * Shader compilation failed
  1008. */
  1009. var onShaderCompileError = function (program, shaderMaterial, onError) {
  1010. return function (effect, error) {
  1011. BABYLON.Tools.Error("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  1012. shaderMaterial.dispose(true);
  1013. onError();
  1014. };
  1015. };
  1016. /**
  1017. * Shader compilation success
  1018. */
  1019. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  1020. return function (_) {
  1021. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  1022. shaderMaterial.onBind = function (mesh) {
  1023. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  1024. };
  1025. };
  1026. };
  1027. /**
  1028. * Returns the appropriate uniform if already handled by babylon
  1029. */
  1030. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  1031. for (var unif in technique.uniforms) {
  1032. var uniform = technique.uniforms[unif];
  1033. var uniformParameter = technique.parameters[uniform];
  1034. if (tokenizer.currentIdentifier === unif) {
  1035. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  1036. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1037. if (transformIndex !== -1) {
  1038. delete unTreatedUniforms[unif];
  1039. return babylonTransforms[transformIndex];
  1040. }
  1041. }
  1042. }
  1043. }
  1044. return tokenizer.currentIdentifier;
  1045. };
  1046. /**
  1047. * All shaders loaded. Create materials one by one
  1048. */
  1049. var importMaterials = function (gltfRuntime) {
  1050. // Create materials
  1051. for (var mat in gltfRuntime.materials) {
  1052. BABYLON.GLTFFileLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  1053. }
  1054. };
  1055. /**
  1056. * Implementation of the base glTF spec
  1057. */
  1058. var GLTFFileLoaderBase = (function () {
  1059. function GLTFFileLoaderBase() {
  1060. }
  1061. GLTFFileLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  1062. var gltfRuntime = {
  1063. accessors: {},
  1064. buffers: {},
  1065. bufferViews: {},
  1066. meshes: {},
  1067. lights: {},
  1068. cameras: {},
  1069. nodes: {},
  1070. images: {},
  1071. textures: {},
  1072. shaders: {},
  1073. programs: {},
  1074. samplers: {},
  1075. techniques: {},
  1076. materials: {},
  1077. animations: {},
  1078. skins: {},
  1079. currentScene: {},
  1080. extensionsUsed: [],
  1081. buffersCount: 0,
  1082. shaderscount: 0,
  1083. scene: scene,
  1084. rootUrl: rootUrl,
  1085. loadedBufferCount: 0,
  1086. loadedBufferViews: {},
  1087. loadedShaderCount: 0,
  1088. importOnlyMeshes: false,
  1089. dummyNodes: []
  1090. };
  1091. // Parse
  1092. if (parsedData.extensionsUsed) {
  1093. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  1094. }
  1095. if (parsedData.buffers) {
  1096. parseBuffers(parsedData.buffers, gltfRuntime);
  1097. }
  1098. if (parsedData.bufferViews) {
  1099. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  1100. }
  1101. if (parsedData.accessors) {
  1102. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  1103. }
  1104. if (parsedData.meshes) {
  1105. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  1106. }
  1107. if (parsedData.lights) {
  1108. parseObject(parsedData.lights, "lights", gltfRuntime);
  1109. }
  1110. if (parsedData.cameras) {
  1111. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  1112. }
  1113. if (parsedData.nodes) {
  1114. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  1115. }
  1116. if (parsedData.images) {
  1117. parseObject(parsedData.images, "images", gltfRuntime);
  1118. }
  1119. if (parsedData.textures) {
  1120. parseObject(parsedData.textures, "textures", gltfRuntime);
  1121. }
  1122. if (parsedData.shaders) {
  1123. parseShaders(parsedData.shaders, gltfRuntime);
  1124. }
  1125. if (parsedData.programs) {
  1126. parseObject(parsedData.programs, "programs", gltfRuntime);
  1127. }
  1128. if (parsedData.samplers) {
  1129. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  1130. }
  1131. if (parsedData.techniques) {
  1132. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  1133. }
  1134. if (parsedData.materials) {
  1135. parseObject(parsedData.materials, "materials", gltfRuntime);
  1136. }
  1137. if (parsedData.animations) {
  1138. parseObject(parsedData.animations, "animations", gltfRuntime);
  1139. }
  1140. if (parsedData.skins) {
  1141. parseObject(parsedData.skins, "skins", gltfRuntime);
  1142. }
  1143. if (parsedData.scene && parsedData.scenes) {
  1144. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  1145. }
  1146. return gltfRuntime;
  1147. };
  1148. GLTFFileLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1149. var buffer = gltfRuntime.buffers[id];
  1150. if (BABYLON.GLTFUtils.IsBase64(buffer.uri)) {
  1151. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.GLTFUtils.DecodeBase64(buffer.uri))); });
  1152. }
  1153. else {
  1154. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, null, null, true, onError);
  1155. }
  1156. };
  1157. GLTFFileLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1158. var texture = gltfRuntime.textures[id];
  1159. if (!texture || !texture.source) {
  1160. onError();
  1161. return;
  1162. }
  1163. if (texture.babylonTexture) {
  1164. onSuccess(null);
  1165. return;
  1166. }
  1167. var source = gltfRuntime.images[texture.source];
  1168. if (BABYLON.GLTFUtils.IsBase64(source.uri)) {
  1169. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.GLTFUtils.DecodeBase64(source.uri))); });
  1170. }
  1171. else {
  1172. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, null, null, true, onError);
  1173. }
  1174. };
  1175. GLTFFileLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1176. var texture = gltfRuntime.textures[id];
  1177. if (texture.babylonTexture) {
  1178. onSuccess(texture.babylonTexture);
  1179. return;
  1180. }
  1181. var sampler = gltfRuntime.samplers[texture.sampler];
  1182. var createMipMaps = (sampler.minFilter === BABYLON.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  1183. (sampler.minFilter === BABYLON.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  1184. (sampler.minFilter === BABYLON.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  1185. (sampler.minFilter === BABYLON.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  1186. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1187. var blob = new Blob([buffer]);
  1188. var blobURL = URL.createObjectURL(blob);
  1189. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  1190. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  1191. newTexture.wrapU = BABYLON.GLTFUtils.GetWrapMode(sampler.wrapS);
  1192. newTexture.wrapV = BABYLON.GLTFUtils.GetWrapMode(sampler.wrapT);
  1193. newTexture.name = id;
  1194. texture.babylonTexture = newTexture;
  1195. onSuccess(newTexture);
  1196. };
  1197. GLTFFileLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1198. var shader = gltfRuntime.shaders[id];
  1199. if (BABYLON.GLTFUtils.IsBase64(shader.uri)) {
  1200. var shaderString = atob(shader.uri.split(",")[1]);
  1201. onSuccess(shaderString);
  1202. }
  1203. else {
  1204. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, null, null, false, onError);
  1205. }
  1206. };
  1207. GLTFFileLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1208. var material = gltfRuntime.materials[id];
  1209. var technique = gltfRuntime.techniques[material.technique];
  1210. if (!technique) {
  1211. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  1212. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  1213. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1214. onSuccess(defaultMaterial);
  1215. return;
  1216. }
  1217. var program = gltfRuntime.programs[technique.program];
  1218. var states = technique.states;
  1219. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  1220. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  1221. var newVertexShader = "";
  1222. var newPixelShader = "";
  1223. var vertexTokenizer = new Tokenizer(vertexShader);
  1224. var pixelTokenizer = new Tokenizer(pixelShader);
  1225. var unTreatedUniforms = {};
  1226. var uniforms = [];
  1227. var attributes = [];
  1228. var samplers = [];
  1229. // Fill uniform, sampler2D and attributes
  1230. for (var unif in technique.uniforms) {
  1231. var uniform = technique.uniforms[unif];
  1232. var uniformParameter = technique.parameters[uniform];
  1233. unTreatedUniforms[unif] = uniformParameter;
  1234. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  1235. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1236. if (transformIndex !== -1) {
  1237. uniforms.push(babylonTransforms[transformIndex]);
  1238. delete unTreatedUniforms[unif];
  1239. }
  1240. else {
  1241. uniforms.push(unif);
  1242. }
  1243. }
  1244. else if (uniformParameter.type === BABYLON.EParameterType.SAMPLER_2D) {
  1245. samplers.push(unif);
  1246. }
  1247. else {
  1248. uniforms.push(unif);
  1249. }
  1250. }
  1251. for (var attr in technique.attributes) {
  1252. var attribute = technique.attributes[attr];
  1253. var attributeParameter = technique.parameters[attribute];
  1254. if (attributeParameter.semantic) {
  1255. attributes.push(getAttribute(attributeParameter));
  1256. }
  1257. }
  1258. // Configure vertex shader
  1259. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  1260. var tokenType = vertexTokenizer.currentToken;
  1261. if (tokenType !== ETokenType.IDENTIFIER) {
  1262. newVertexShader += vertexTokenizer.currentString;
  1263. continue;
  1264. }
  1265. var foundAttribute = false;
  1266. for (var attr in technique.attributes) {
  1267. var attribute = technique.attributes[attr];
  1268. var attributeParameter = technique.parameters[attribute];
  1269. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  1270. newVertexShader += getAttribute(attributeParameter);
  1271. foundAttribute = true;
  1272. break;
  1273. }
  1274. }
  1275. if (foundAttribute) {
  1276. continue;
  1277. }
  1278. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  1279. }
  1280. // Configure pixel shader
  1281. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  1282. var tokenType = pixelTokenizer.currentToken;
  1283. if (tokenType !== ETokenType.IDENTIFIER) {
  1284. newPixelShader += pixelTokenizer.currentString;
  1285. continue;
  1286. }
  1287. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  1288. }
  1289. // Create shader material
  1290. var shaderPath = {
  1291. vertex: program.vertexShader + id,
  1292. fragment: program.fragmentShader + id
  1293. };
  1294. var options = {
  1295. attributes: attributes,
  1296. uniforms: uniforms,
  1297. samplers: samplers,
  1298. needAlphaBlending: states.functions && states.functions.blendEquationSeparate
  1299. };
  1300. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  1301. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  1302. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  1303. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  1304. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  1305. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1306. if (states.functions) {
  1307. var functions = states.functions;
  1308. if (functions.cullFace && functions.cullFace[0] !== BABYLON.ECullingType.BACK) {
  1309. shaderMaterial.backFaceCulling = false;
  1310. }
  1311. var blendFunc = functions.blendFuncSeparate;
  1312. if (blendFunc) {
  1313. if (blendFunc[0] === BABYLON.EBlendingFunction.SRC_ALPHA && blendFunc[1] === BABYLON.EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === BABYLON.EBlendingFunction.ONE && blendFunc[3] === BABYLON.EBlendingFunction.ONE) {
  1314. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  1315. }
  1316. else if (blendFunc[0] === BABYLON.EBlendingFunction.ONE && blendFunc[1] === BABYLON.EBlendingFunction.ONE && blendFunc[2] === BABYLON.EBlendingFunction.ZERO && blendFunc[3] === BABYLON.EBlendingFunction.ONE) {
  1317. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  1318. }
  1319. else if (blendFunc[0] === BABYLON.EBlendingFunction.SRC_ALPHA && blendFunc[1] === BABYLON.EBlendingFunction.ONE && blendFunc[2] === BABYLON.EBlendingFunction.ZERO && blendFunc[3] === BABYLON.EBlendingFunction.ONE) {
  1320. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  1321. }
  1322. else if (blendFunc[0] === BABYLON.EBlendingFunction.ZERO && blendFunc[1] === BABYLON.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === BABYLON.EBlendingFunction.ONE && blendFunc[3] === BABYLON.EBlendingFunction.ONE) {
  1323. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  1324. }
  1325. else if (blendFunc[0] === BABYLON.EBlendingFunction.DST_COLOR && blendFunc[1] === BABYLON.EBlendingFunction.ZERO && blendFunc[2] === BABYLON.EBlendingFunction.ONE && blendFunc[3] === BABYLON.EBlendingFunction.ONE) {
  1326. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  1327. }
  1328. else if (blendFunc[0] === BABYLON.EBlendingFunction.SRC_ALPHA && blendFunc[1] === BABYLON.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === BABYLON.EBlendingFunction.ONE && blendFunc[3] === BABYLON.EBlendingFunction.ONE) {
  1329. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  1330. }
  1331. }
  1332. }
  1333. };
  1334. return GLTFFileLoaderBase;
  1335. }());
  1336. BABYLON.GLTFFileLoaderBase = GLTFFileLoaderBase;
  1337. /**
  1338. * glTF File Loader Plugin
  1339. */
  1340. var GLTFFileLoader = (function () {
  1341. function GLTFFileLoader() {
  1342. /**
  1343. * Public members
  1344. */
  1345. this.extensions = {
  1346. ".gltf": { isBinary: false },
  1347. ".glb": { isBinary: true }
  1348. };
  1349. }
  1350. GLTFFileLoader.RegisterExtension = function (extension) {
  1351. if (GLTFFileLoader.Extensions[extension.name]) {
  1352. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  1353. return;
  1354. }
  1355. GLTFFileLoader.Extensions[extension.name] = extension;
  1356. };
  1357. /**
  1358. * Import meshes
  1359. */
  1360. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onError) {
  1361. var _this = this;
  1362. scene.useRightHandedSystem = true;
  1363. var gltfRuntime = BABYLON.GLTFFileLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1364. gltfRuntime.importOnlyMeshes = true;
  1365. if (meshesNames === "") {
  1366. gltfRuntime.importMeshesNames = [];
  1367. }
  1368. else if (typeof meshesNames === "string") {
  1369. gltfRuntime.importMeshesNames = [meshesNames];
  1370. }
  1371. else if (meshesNames && !(meshesNames instanceof Array)) {
  1372. gltfRuntime.importMeshesNames = [meshesNames];
  1373. }
  1374. else {
  1375. gltfRuntime.importMeshesNames = [];
  1376. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  1377. }
  1378. // Create nodes
  1379. _this._createNodes(gltfRuntime);
  1380. var meshes = [];
  1381. var skeletons = [];
  1382. // Fill arrays of meshes and skeletons
  1383. for (var nde in gltfRuntime.nodes) {
  1384. var node = gltfRuntime.nodes[nde];
  1385. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  1386. meshes.push(node.babylonNode);
  1387. }
  1388. }
  1389. for (var skl in gltfRuntime.skins) {
  1390. var skin = gltfRuntime.skins[skl];
  1391. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  1392. skeletons.push(skin.babylonSkeleton);
  1393. }
  1394. }
  1395. // Load buffers, shaders, materials, etc.
  1396. _this._loadBuffersAsync(gltfRuntime, function () {
  1397. _this._loadShadersAsync(gltfRuntime, function () {
  1398. importMaterials(gltfRuntime);
  1399. postLoad(gltfRuntime);
  1400. });
  1401. });
  1402. if (onSuccess) {
  1403. onSuccess(meshes, null, skeletons);
  1404. }
  1405. }, onError);
  1406. return true;
  1407. };
  1408. /**
  1409. * Load scene
  1410. */
  1411. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onError) {
  1412. var _this = this;
  1413. scene.useRightHandedSystem = true;
  1414. BABYLON.GLTFFileLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1415. // Create nodes
  1416. _this._createNodes(gltfRuntime);
  1417. // Load buffers, shaders, materials, etc.
  1418. _this._loadBuffersAsync(gltfRuntime, function () {
  1419. _this._loadShadersAsync(gltfRuntime, function () {
  1420. importMaterials(gltfRuntime);
  1421. postLoad(gltfRuntime);
  1422. });
  1423. });
  1424. onSuccess();
  1425. }, onError);
  1426. return true;
  1427. };
  1428. GLTFFileLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  1429. var hasShaders = false;
  1430. var processShader = function (sha, shader) {
  1431. BABYLON.GLTFFileLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  1432. gltfRuntime.loadedShaderCount++;
  1433. if (shaderString) {
  1434. BABYLON.Effect.ShadersStore[sha + (shader.type === BABYLON.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  1435. }
  1436. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  1437. onload();
  1438. }
  1439. }, function () {
  1440. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  1441. });
  1442. };
  1443. for (var sha in gltfRuntime.shaders) {
  1444. hasShaders = true;
  1445. var shader = gltfRuntime.shaders[sha];
  1446. if (shader) {
  1447. processShader.bind(this, sha, shader)();
  1448. }
  1449. else {
  1450. BABYLON.Tools.Error("No shader named: " + sha);
  1451. }
  1452. }
  1453. if (!hasShaders) {
  1454. onload();
  1455. }
  1456. };
  1457. ;
  1458. GLTFFileLoader.prototype._loadBuffersAsync = function (gltfRuntime, onload) {
  1459. var hasBuffers = false;
  1460. var processBuffer = function (buf, buffer) {
  1461. BABYLON.GLTFFileLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  1462. gltfRuntime.loadedBufferCount++;
  1463. if (bufferView) {
  1464. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  1465. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  1466. }
  1467. gltfRuntime.loadedBufferViews[buf] = bufferView;
  1468. }
  1469. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  1470. onload();
  1471. }
  1472. }, function () {
  1473. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  1474. });
  1475. };
  1476. for (var buf in gltfRuntime.buffers) {
  1477. hasBuffers = true;
  1478. var buffer = gltfRuntime.buffers[buf];
  1479. if (buffer) {
  1480. processBuffer.bind(this, buf, buffer)();
  1481. }
  1482. else {
  1483. BABYLON.Tools.Error("No buffer named: " + buf);
  1484. }
  1485. }
  1486. if (!hasBuffers) {
  1487. onload();
  1488. }
  1489. };
  1490. // Creates nodes before loading buffers and shaders
  1491. GLTFFileLoader.prototype._createNodes = function (gltfRuntime) {
  1492. var currentScene = gltfRuntime.currentScene;
  1493. for (var i = 0; i < currentScene.nodes.length; i++) {
  1494. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1495. }
  1496. };
  1497. /**
  1498. * Private members
  1499. */
  1500. // None
  1501. /**
  1502. * Static members
  1503. */
  1504. GLTFFileLoader.MakeYUP = false;
  1505. GLTFFileLoader.HomogeneousCoordinates = false;
  1506. GLTFFileLoader.Extensions = {};
  1507. return GLTFFileLoader;
  1508. }());
  1509. BABYLON.GLTFFileLoader = GLTFFileLoader;
  1510. ;
  1511. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  1512. })(BABYLON || (BABYLON = {}));
  1513. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  1514. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  1515. var BABYLON;
  1516. (function (BABYLON) {
  1517. /**
  1518. * Utils functions for GLTF
  1519. */
  1520. var GLTFUtils = (function () {
  1521. function GLTFUtils() {
  1522. }
  1523. /**
  1524. * Sets the given "parameter" matrix
  1525. * @param scene: the {BABYLON.Scene} object
  1526. * @param source: the source node where to pick the matrix
  1527. * @param parameter: the GLTF technique parameter
  1528. * @param uniformName: the name of the shader's uniform
  1529. * @param shaderMaterial: the shader material
  1530. */
  1531. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  1532. var mat = null;
  1533. if (parameter.semantic === "MODEL") {
  1534. mat = source.getWorldMatrix();
  1535. }
  1536. else if (parameter.semantic === "PROJECTION") {
  1537. mat = scene.getProjectionMatrix();
  1538. }
  1539. else if (parameter.semantic === "VIEW") {
  1540. mat = scene.getViewMatrix();
  1541. }
  1542. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  1543. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  1544. }
  1545. else if (parameter.semantic === "MODELVIEW") {
  1546. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  1547. }
  1548. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  1549. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  1550. }
  1551. else if (parameter.semantic === "MODELINVERSE") {
  1552. mat = source.getWorldMatrix().invert();
  1553. }
  1554. else if (parameter.semantic === "VIEWINVERSE") {
  1555. mat = scene.getViewMatrix().invert();
  1556. }
  1557. else if (parameter.semantic === "PROJECTIONINVERSE") {
  1558. mat = scene.getProjectionMatrix().invert();
  1559. }
  1560. else if (parameter.semantic === "MODELVIEWINVERSE") {
  1561. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  1562. }
  1563. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  1564. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  1565. }
  1566. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  1567. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  1568. }
  1569. else {
  1570. debugger;
  1571. }
  1572. switch (parameter.type) {
  1573. case BABYLON.EParameterType.FLOAT_MAT2:
  1574. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  1575. break;
  1576. case BABYLON.EParameterType.FLOAT_MAT3:
  1577. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  1578. break;
  1579. case BABYLON.EParameterType.FLOAT_MAT4:
  1580. shaderMaterial.setMatrix(uniformName, mat);
  1581. break;
  1582. default: break;
  1583. }
  1584. };
  1585. /**
  1586. * Sets the given "parameter" matrix
  1587. * @param shaderMaterial: the shader material
  1588. * @param uniform: the name of the shader's uniform
  1589. * @param value: the value of the uniform
  1590. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  1591. */
  1592. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  1593. switch (type) {
  1594. case BABYLON.EParameterType.FLOAT:
  1595. shaderMaterial.setFloat(uniform, value);
  1596. return true;
  1597. case BABYLON.EParameterType.FLOAT_VEC2:
  1598. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  1599. return true;
  1600. case BABYLON.EParameterType.FLOAT_VEC3:
  1601. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  1602. return true;
  1603. case BABYLON.EParameterType.FLOAT_VEC4:
  1604. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  1605. return true;
  1606. default: return false;
  1607. }
  1608. };
  1609. /**
  1610. * If the uri is a base64 string
  1611. * @param uri: the uri to test
  1612. */
  1613. GLTFUtils.IsBase64 = function (uri) {
  1614. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  1615. };
  1616. /**
  1617. * Decode the base64 uri
  1618. * @param uri: the uri to decode
  1619. */
  1620. GLTFUtils.DecodeBase64 = function (uri) {
  1621. var decodedString = atob(uri.split(",")[1]);
  1622. var bufferLength = decodedString.length;
  1623. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  1624. for (var i = 0; i < bufferLength; i++) {
  1625. bufferView[i] = decodedString.charCodeAt(i);
  1626. }
  1627. return bufferView.buffer;
  1628. };
  1629. /**
  1630. * Returns the wrap mode of the texture
  1631. * @param mode: the mode value
  1632. */
  1633. GLTFUtils.GetWrapMode = function (mode) {
  1634. switch (mode) {
  1635. case BABYLON.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  1636. case BABYLON.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  1637. case BABYLON.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1638. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1639. }
  1640. };
  1641. /**
  1642. * Returns the byte stride giving an accessor
  1643. * @param accessor: the GLTF accessor objet
  1644. */
  1645. GLTFUtils.GetByteStrideFromType = function (accessor) {
  1646. // Needs this function since "byteStride" isn't requiered in glTF format
  1647. var type = accessor.type;
  1648. switch (type) {
  1649. case "VEC2": return 2;
  1650. case "VEC3": return 3;
  1651. case "VEC4": return 4;
  1652. case "MAT2": return 4;
  1653. case "MAT3": return 9;
  1654. case "MAT4": return 16;
  1655. default: return 1;
  1656. }
  1657. };
  1658. /**
  1659. * Returns the texture filter mode giving a mode value
  1660. * @param mode: the filter mode value
  1661. */
  1662. GLTFUtils.GetTextureFilterMode = function (mode) {
  1663. switch (mode) {
  1664. case BABYLON.ETextureFilterType.LINEAR:
  1665. case BABYLON.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  1666. case BABYLON.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  1667. case BABYLON.ETextureFilterType.NEAREST:
  1668. case BABYLON.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  1669. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1670. }
  1671. };
  1672. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  1673. var byteOffset = bufferView.byteOffset + byteOffset;
  1674. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  1675. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  1676. throw new Error("Buffer access is out of range");
  1677. }
  1678. var buffer = loadedBufferView.buffer;
  1679. byteOffset += loadedBufferView.byteOffset;
  1680. switch (componentType) {
  1681. case BABYLON.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  1682. case BABYLON.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  1683. case BABYLON.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  1684. case BABYLON.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  1685. default: return new Float32Array(buffer, byteOffset, byteLength);
  1686. }
  1687. };
  1688. /**
  1689. * Returns a buffer from its accessor
  1690. * @param gltfRuntime: the GLTF runtime
  1691. * @param accessor: the GLTF accessor
  1692. */
  1693. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  1694. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  1695. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  1696. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  1697. };
  1698. /**
  1699. * Decodes a buffer view into a string
  1700. * @param view: the buffer view
  1701. */
  1702. GLTFUtils.DecodeBufferToText = function (view) {
  1703. var result = "";
  1704. var length = view.byteLength;
  1705. for (var i = 0; i < length; ++i) {
  1706. result += String.fromCharCode(view[i]);
  1707. }
  1708. return result;
  1709. };
  1710. return GLTFUtils;
  1711. }());
  1712. BABYLON.GLTFUtils = GLTFUtils;
  1713. })(BABYLON || (BABYLON = {}));
  1714. //# sourceMappingURL=babylon.glTFFileLoaderUtils.js.map
  1715. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  1716. var BABYLON;
  1717. (function (BABYLON) {
  1718. var GLTFFileLoaderExtension = (function () {
  1719. function GLTFFileLoaderExtension(name) {
  1720. this._name = name;
  1721. }
  1722. Object.defineProperty(GLTFFileLoaderExtension.prototype, "name", {
  1723. get: function () {
  1724. return this._name;
  1725. },
  1726. enumerable: true,
  1727. configurable: true
  1728. });
  1729. /**
  1730. * Defines an override for loading the runtime
  1731. * Return true to stop further extensions from loading the runtime
  1732. */
  1733. GLTFFileLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  1734. return false;
  1735. };
  1736. /**
  1737. * Defines an override for loading buffers
  1738. * Return true to stop further extensions from loading this buffer
  1739. */
  1740. GLTFFileLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1741. return false;
  1742. };
  1743. /**
  1744. * Defines an override for loading texture buffers
  1745. * Return true to stop further extensions from loading this texture data
  1746. */
  1747. GLTFFileLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1748. return false;
  1749. };
  1750. /**
  1751. * Defines an override for creating textures
  1752. * Return true to stop further extensions from loading this texture
  1753. */
  1754. GLTFFileLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1755. return false;
  1756. };
  1757. /**
  1758. * Defines an override for loading shader strings
  1759. * Return true to stop further extensions from loading this shader data
  1760. */
  1761. GLTFFileLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1762. return false;
  1763. };
  1764. /**
  1765. * Defines an override for loading materials
  1766. * Return true to stop further extensions from loading this material
  1767. */
  1768. GLTFFileLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1769. return false;
  1770. };
  1771. // ---------
  1772. // Utilities
  1773. // ---------
  1774. GLTFFileLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  1775. GLTFFileLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1776. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  1777. }, function () {
  1778. setTimeout(function () {
  1779. onSuccess(BABYLON.GLTFFileLoaderBase.CreateRuntime(JSON.parse(data), scene, rootUrl));
  1780. });
  1781. });
  1782. };
  1783. GLTFFileLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1784. GLTFFileLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1785. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError);
  1786. }, function () {
  1787. BABYLON.GLTFFileLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError);
  1788. });
  1789. };
  1790. GLTFFileLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  1791. GLTFFileLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFFileLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  1792. };
  1793. GLTFFileLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1794. GLTFFileLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1795. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  1796. }, function () {
  1797. BABYLON.GLTFFileLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  1798. });
  1799. };
  1800. GLTFFileLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1801. GLTFFileLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1802. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  1803. }, function () {
  1804. BABYLON.GLTFFileLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  1805. });
  1806. };
  1807. GLTFFileLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1808. GLTFFileLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1809. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  1810. }, function () {
  1811. BABYLON.GLTFFileLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  1812. });
  1813. };
  1814. GLTFFileLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1815. GLTFFileLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1816. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  1817. }, function () {
  1818. BABYLON.GLTFFileLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  1819. });
  1820. };
  1821. GLTFFileLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  1822. for (var extensionName in BABYLON.GLTFFileLoader.Extensions) {
  1823. var loaderExtension = BABYLON.GLTFFileLoader.Extensions[extensionName];
  1824. if (func(loaderExtension)) {
  1825. return;
  1826. }
  1827. }
  1828. defaultFunc();
  1829. };
  1830. return GLTFFileLoaderExtension;
  1831. }());
  1832. BABYLON.GLTFFileLoaderExtension = GLTFFileLoaderExtension;
  1833. })(BABYLON || (BABYLON = {}));
  1834. //# sourceMappingURL=babylon.glTFFileLoaderExtension.js.map
  1835. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  1836. var __extends = (this && this.__extends) || function (d, b) {
  1837. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  1838. function __() { this.constructor = d; }
  1839. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1840. };
  1841. var BABYLON;
  1842. (function (BABYLON) {
  1843. var BinaryExtensionBufferName = "binary_glTF";
  1844. var EContentFormat;
  1845. (function (EContentFormat) {
  1846. EContentFormat[EContentFormat["JSON"] = 0] = "JSON";
  1847. })(EContentFormat || (EContentFormat = {}));
  1848. ;
  1849. ;
  1850. ;
  1851. ;
  1852. var GLTFBinaryExtension = (function (_super) {
  1853. __extends(GLTFBinaryExtension, _super);
  1854. function GLTFBinaryExtension() {
  1855. _super.call(this, "KHR_binary_glTF");
  1856. }
  1857. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  1858. var _this = this;
  1859. if (!(data instanceof ArrayBuffer)) {
  1860. return false;
  1861. }
  1862. setTimeout(function () {
  1863. _this._binary = _this._parseBinary(data);
  1864. if (!_this._binary) {
  1865. onError();
  1866. return true;
  1867. }
  1868. var gltfRuntime = BABYLON.GLTFFileLoaderBase.CreateRuntime(_this._binary.content, scene, rootUrl);
  1869. if (gltfRuntime.extensionsUsed.indexOf(_this.name) === -1) {
  1870. BABYLON.Tools.Warn("glTF binary file does not have " + _this.name + " specified in extensionsUsed");
  1871. gltfRuntime.extensionsUsed.push(_this.name);
  1872. }
  1873. onSuccess(gltfRuntime);
  1874. });
  1875. return true;
  1876. };
  1877. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1878. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  1879. return false;
  1880. }
  1881. if (id !== BinaryExtensionBufferName) {
  1882. return false;
  1883. }
  1884. onSuccess(this._binary.body);
  1885. return true;
  1886. };
  1887. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1888. var texture = gltfRuntime.textures[id];
  1889. var source = gltfRuntime.images[texture.source];
  1890. if (!source.extensions || !(this.name in source.extensions)) {
  1891. return false;
  1892. }
  1893. var sourceExt = source.extensions[this.name];
  1894. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  1895. var buffer = BABYLON.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, BABYLON.EComponentType.UNSIGNED_BYTE);
  1896. onSuccess(buffer);
  1897. return true;
  1898. };
  1899. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1900. var shader = gltfRuntime.shaders[id];
  1901. if (!shader.extensions || !(this.name in shader.extensions)) {
  1902. return false;
  1903. }
  1904. var binaryExtensionShader = shader.extensions[this.name];
  1905. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  1906. var shaderBytes = BABYLON.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, BABYLON.EComponentType.UNSIGNED_BYTE);
  1907. setTimeout(function () {
  1908. var shaderString = BABYLON.GLTFUtils.DecodeBufferToText(shaderBytes);
  1909. onSuccess(shaderString);
  1910. });
  1911. return true;
  1912. };
  1913. // Parses a glTF binary array buffer into its content and body
  1914. GLTFBinaryExtension.prototype._parseBinary = function (data) {
  1915. var binaryReader = new BinaryReader(data);
  1916. var magic = BABYLON.GLTFUtils.DecodeBufferToText(binaryReader.getUint8Array(4));
  1917. if (magic != "glTF") {
  1918. BABYLON.Tools.Error("Unexpected magic: " + magic);
  1919. return null;
  1920. }
  1921. var version = binaryReader.getUint32();
  1922. if (version != 1) {
  1923. BABYLON.Tools.Error("Unsupported version: " + version);
  1924. return null;
  1925. }
  1926. var length = binaryReader.getUint32();
  1927. if (length != data.byteLength) {
  1928. BABYLON.Tools.Error("Length in header does not match actual data length: " + length + " != " + data.byteLength);
  1929. return null;
  1930. }
  1931. var contentLength = binaryReader.getUint32();
  1932. var contentFormat = binaryReader.getUint32();
  1933. var content;
  1934. switch (contentFormat) {
  1935. case EContentFormat.JSON:
  1936. var jsonText = BABYLON.GLTFUtils.DecodeBufferToText(binaryReader.getUint8Array(contentLength));
  1937. content = JSON.parse(jsonText);
  1938. break;
  1939. default:
  1940. BABYLON.Tools.Error("Unexpected content format: " + contentFormat);
  1941. return null;
  1942. }
  1943. var body = binaryReader.getUint8Array();
  1944. return {
  1945. content: content,
  1946. body: body
  1947. };
  1948. };
  1949. ;
  1950. return GLTFBinaryExtension;
  1951. }(BABYLON.GLTFFileLoaderExtension));
  1952. BABYLON.GLTFBinaryExtension = GLTFBinaryExtension;
  1953. var BinaryReader = (function () {
  1954. function BinaryReader(arrayBuffer) {
  1955. this._arrayBuffer = arrayBuffer;
  1956. this._dataView = new DataView(arrayBuffer);
  1957. this._byteOffset = 0;
  1958. }
  1959. BinaryReader.prototype.getUint32 = function () {
  1960. var value = this._dataView.getUint32(this._byteOffset, true);
  1961. this._byteOffset += 4;
  1962. return value;
  1963. };
  1964. BinaryReader.prototype.getUint8Array = function (length) {
  1965. if (!length) {
  1966. length = this._arrayBuffer.byteLength - this._byteOffset;
  1967. }
  1968. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  1969. this._byteOffset += length;
  1970. return value;
  1971. };
  1972. return BinaryReader;
  1973. }());
  1974. BABYLON.GLTFFileLoader.RegisterExtension(new GLTFBinaryExtension());
  1975. })(BABYLON || (BABYLON = {}));
  1976. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map