babylon.glTFFileLoader.js 90 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992
  1. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  2. var BABYLON;
  3. (function (BABYLON) {
  4. /**
  5. * Enums
  6. */
  7. var EComponentType;
  8. (function (EComponentType) {
  9. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  10. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  11. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  12. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  13. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  14. })(EComponentType = BABYLON.EComponentType || (BABYLON.EComponentType = {}));
  15. var EShaderType;
  16. (function (EShaderType) {
  17. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  18. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  19. })(EShaderType = BABYLON.EShaderType || (BABYLON.EShaderType = {}));
  20. var EParameterType;
  21. (function (EParameterType) {
  22. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  23. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  24. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  25. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  26. EParameterType[EParameterType["INT"] = 5124] = "INT";
  27. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  28. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  29. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  30. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  31. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  32. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  33. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  34. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  35. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  36. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  37. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  38. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  39. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  40. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  41. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  42. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  43. })(EParameterType = BABYLON.EParameterType || (BABYLON.EParameterType = {}));
  44. var ETextureWrapMode;
  45. (function (ETextureWrapMode) {
  46. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  47. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  48. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  49. })(ETextureWrapMode = BABYLON.ETextureWrapMode || (BABYLON.ETextureWrapMode = {}));
  50. var ETextureFilterType;
  51. (function (ETextureFilterType) {
  52. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  53. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  54. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  55. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  56. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  57. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  58. })(ETextureFilterType = BABYLON.ETextureFilterType || (BABYLON.ETextureFilterType = {}));
  59. var ETextureFormat;
  60. (function (ETextureFormat) {
  61. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  62. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  63. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  64. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  65. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  66. })(ETextureFormat = BABYLON.ETextureFormat || (BABYLON.ETextureFormat = {}));
  67. var ECullingType;
  68. (function (ECullingType) {
  69. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  70. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  71. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  72. })(ECullingType = BABYLON.ECullingType || (BABYLON.ECullingType = {}));
  73. var EBlendingFunction;
  74. (function (EBlendingFunction) {
  75. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  76. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  77. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  78. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  79. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  80. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  81. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  82. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  83. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  84. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  85. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  86. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  87. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  88. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  89. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  90. })(EBlendingFunction = BABYLON.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. var translation = node.translation || [0, 0, 0];
  879. var rotation = node.rotation || [0, 0, 0, 1];
  880. var scale = node.scale || [1, 1, 1];
  881. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.RotationAxis(BABYLON.Vector3.FromArray(rotation).normalize(), rotation[3]), BABYLON.Vector3.FromArray(scale));
  882. }
  883. lastNode.updateCache(true);
  884. node.babylonNode = lastNode;
  885. }
  886. return lastNode;
  887. };
  888. /**
  889. * Traverses nodes and creates them
  890. */
  891. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  892. var node = gltfRuntime.nodes[id];
  893. var newNode = null;
  894. if (gltfRuntime.importOnlyMeshes && !meshIncluded) {
  895. if (gltfRuntime.importMeshesNames.indexOf(node.name) !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  896. meshIncluded = true;
  897. }
  898. else {
  899. meshIncluded = false;
  900. }
  901. }
  902. else {
  903. meshIncluded = true;
  904. }
  905. if (!node.jointName && meshIncluded) {
  906. newNode = importNode(gltfRuntime, node, id);
  907. if (newNode !== null) {
  908. newNode.id = id;
  909. newNode.parent = parent;
  910. }
  911. }
  912. for (var i = 0; i < node.children.length; i++) {
  913. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  914. }
  915. };
  916. /**
  917. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  918. */
  919. var postLoad = function (gltfRuntime) {
  920. // Nodes
  921. var currentScene = gltfRuntime.currentScene;
  922. for (var i = 0; i < currentScene.nodes.length; i++) {
  923. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  924. }
  925. // Set animations
  926. loadAnimations(gltfRuntime);
  927. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  928. var skeleton = gltfRuntime.scene.skeletons[i];
  929. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  930. }
  931. };
  932. /**
  933. * onBind shaderrs callback to set uniforms and matrices
  934. */
  935. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  936. for (var unif in unTreatedUniforms) {
  937. var uniform = unTreatedUniforms[unif];
  938. var type = uniform.type;
  939. if (type === BABYLON.EParameterType.FLOAT_MAT2 || type === BABYLON.EParameterType.FLOAT_MAT3 || type === BABYLON.EParameterType.FLOAT_MAT4) {
  940. if (uniform.semantic && !uniform.source && !uniform.node) {
  941. BABYLON.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  942. }
  943. else if (uniform.semantic && (uniform.source || uniform.node)) {
  944. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node);
  945. if (source === null) {
  946. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node);
  947. }
  948. if (source === null) {
  949. continue;
  950. }
  951. BABYLON.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  952. }
  953. }
  954. else {
  955. var value = material.values[technique.uniforms[unif]];
  956. if (!value) {
  957. continue;
  958. }
  959. if (type === BABYLON.EParameterType.SAMPLER_2D) {
  960. var texture = gltfRuntime.textures[value].babylonTexture;
  961. if (texture === null) {
  962. continue;
  963. }
  964. shaderMaterial.getEffect().setTexture(unif, texture);
  965. }
  966. else {
  967. BABYLON.GLTFUtils.SetUniform(shaderMaterial.getEffect(), unif, value, type);
  968. }
  969. }
  970. }
  971. onSuccess(shaderMaterial);
  972. };
  973. /**
  974. * Prepare uniforms to send the only one time
  975. * Loads the appropriate textures
  976. */
  977. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  978. var materialValues = material.values;
  979. var techniqueUniforms = technique.uniforms;
  980. /**
  981. * Prepare values here (not matrices)
  982. */
  983. for (var unif in unTreatedUniforms) {
  984. var uniform = unTreatedUniforms[unif];
  985. var type = uniform.type;
  986. var value = materialValues[techniqueUniforms[unif]];
  987. if (value === undefined) {
  988. // In case the value is the same for all materials
  989. value = uniform.value;
  990. }
  991. if (!value) {
  992. continue;
  993. }
  994. var onLoadTexture = function (texture) {
  995. if (uniform.value) {
  996. // Static uniform
  997. shaderMaterial.setTexture(unif, texture);
  998. delete unTreatedUniforms[unif];
  999. }
  1000. };
  1001. // Texture (sampler2D)
  1002. if (type === BABYLON.EParameterType.SAMPLER_2D) {
  1003. BABYLON.GLTFFileLoaderExtension.LoadTextureAsync(gltfRuntime, value, onLoadTexture, function () { return onLoadTexture(null); });
  1004. }
  1005. else {
  1006. if (uniform.value && BABYLON.GLTFUtils.SetUniform(shaderMaterial, unif, value, type)) {
  1007. // Static uniform
  1008. delete unTreatedUniforms[unif];
  1009. }
  1010. }
  1011. }
  1012. };
  1013. /**
  1014. * Shader compilation failed
  1015. */
  1016. var onShaderCompileError = function (program, shaderMaterial, onError) {
  1017. return function (effect, error) {
  1018. BABYLON.Tools.Error("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  1019. shaderMaterial.dispose(true);
  1020. onError();
  1021. };
  1022. };
  1023. /**
  1024. * Shader compilation success
  1025. */
  1026. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  1027. return function (_) {
  1028. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  1029. shaderMaterial.onBind = function (mesh) {
  1030. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  1031. };
  1032. };
  1033. };
  1034. /**
  1035. * Returns the appropriate uniform if already handled by babylon
  1036. */
  1037. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  1038. for (var unif in technique.uniforms) {
  1039. var uniform = technique.uniforms[unif];
  1040. var uniformParameter = technique.parameters[uniform];
  1041. if (tokenizer.currentIdentifier === unif) {
  1042. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  1043. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1044. if (transformIndex !== -1) {
  1045. delete unTreatedUniforms[unif];
  1046. return babylonTransforms[transformIndex];
  1047. }
  1048. }
  1049. }
  1050. }
  1051. return tokenizer.currentIdentifier;
  1052. };
  1053. /**
  1054. * All shaders loaded. Create materials one by one
  1055. */
  1056. var importMaterials = function (gltfRuntime) {
  1057. // Create materials
  1058. for (var mat in gltfRuntime.materials) {
  1059. BABYLON.GLTFFileLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  1060. }
  1061. };
  1062. /**
  1063. * Implementation of the base glTF spec
  1064. */
  1065. var GLTFFileLoaderBase = (function () {
  1066. function GLTFFileLoaderBase() {
  1067. }
  1068. GLTFFileLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  1069. var gltfRuntime = {
  1070. accessors: {},
  1071. buffers: {},
  1072. bufferViews: {},
  1073. meshes: {},
  1074. lights: {},
  1075. cameras: {},
  1076. nodes: {},
  1077. images: {},
  1078. textures: {},
  1079. shaders: {},
  1080. programs: {},
  1081. samplers: {},
  1082. techniques: {},
  1083. materials: {},
  1084. animations: {},
  1085. skins: {},
  1086. currentScene: {},
  1087. extensionsUsed: [],
  1088. buffersCount: 0,
  1089. shaderscount: 0,
  1090. scene: scene,
  1091. rootUrl: rootUrl,
  1092. loadedBufferCount: 0,
  1093. loadedBufferViews: {},
  1094. loadedShaderCount: 0,
  1095. importOnlyMeshes: false,
  1096. dummyNodes: []
  1097. };
  1098. // Parse
  1099. if (parsedData.extensionsUsed) {
  1100. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  1101. }
  1102. if (parsedData.buffers) {
  1103. parseBuffers(parsedData.buffers, gltfRuntime);
  1104. }
  1105. if (parsedData.bufferViews) {
  1106. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  1107. }
  1108. if (parsedData.accessors) {
  1109. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  1110. }
  1111. if (parsedData.meshes) {
  1112. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  1113. }
  1114. if (parsedData.lights) {
  1115. parseObject(parsedData.lights, "lights", gltfRuntime);
  1116. }
  1117. if (parsedData.cameras) {
  1118. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  1119. }
  1120. if (parsedData.nodes) {
  1121. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  1122. }
  1123. if (parsedData.images) {
  1124. parseObject(parsedData.images, "images", gltfRuntime);
  1125. }
  1126. if (parsedData.textures) {
  1127. parseObject(parsedData.textures, "textures", gltfRuntime);
  1128. }
  1129. if (parsedData.shaders) {
  1130. parseShaders(parsedData.shaders, gltfRuntime);
  1131. }
  1132. if (parsedData.programs) {
  1133. parseObject(parsedData.programs, "programs", gltfRuntime);
  1134. }
  1135. if (parsedData.samplers) {
  1136. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  1137. }
  1138. if (parsedData.techniques) {
  1139. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  1140. }
  1141. if (parsedData.materials) {
  1142. parseObject(parsedData.materials, "materials", gltfRuntime);
  1143. }
  1144. if (parsedData.animations) {
  1145. parseObject(parsedData.animations, "animations", gltfRuntime);
  1146. }
  1147. if (parsedData.skins) {
  1148. parseObject(parsedData.skins, "skins", gltfRuntime);
  1149. }
  1150. if (parsedData.scene && parsedData.scenes) {
  1151. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  1152. }
  1153. return gltfRuntime;
  1154. };
  1155. GLTFFileLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1156. var buffer = gltfRuntime.buffers[id];
  1157. if (BABYLON.GLTFUtils.IsBase64(buffer.uri)) {
  1158. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.GLTFUtils.DecodeBase64(buffer.uri))); });
  1159. }
  1160. else {
  1161. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, null, null, true, onError);
  1162. }
  1163. };
  1164. GLTFFileLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1165. var texture = gltfRuntime.textures[id];
  1166. if (!texture || !texture.source) {
  1167. onError();
  1168. return;
  1169. }
  1170. if (texture.babylonTexture) {
  1171. onSuccess(null);
  1172. return;
  1173. }
  1174. var source = gltfRuntime.images[texture.source];
  1175. if (BABYLON.GLTFUtils.IsBase64(source.uri)) {
  1176. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.GLTFUtils.DecodeBase64(source.uri))); });
  1177. }
  1178. else {
  1179. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, null, null, true, onError);
  1180. }
  1181. };
  1182. GLTFFileLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1183. var texture = gltfRuntime.textures[id];
  1184. if (texture.babylonTexture) {
  1185. onSuccess(texture.babylonTexture);
  1186. return;
  1187. }
  1188. var sampler = gltfRuntime.samplers[texture.sampler];
  1189. var createMipMaps = (sampler.minFilter === BABYLON.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  1190. (sampler.minFilter === BABYLON.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  1191. (sampler.minFilter === BABYLON.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  1192. (sampler.minFilter === BABYLON.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  1193. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1194. var blob = new Blob([buffer]);
  1195. var blobURL = URL.createObjectURL(blob);
  1196. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  1197. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  1198. newTexture.wrapU = BABYLON.GLTFUtils.GetWrapMode(sampler.wrapS);
  1199. newTexture.wrapV = BABYLON.GLTFUtils.GetWrapMode(sampler.wrapT);
  1200. newTexture.name = id;
  1201. texture.babylonTexture = newTexture;
  1202. onSuccess(newTexture);
  1203. };
  1204. GLTFFileLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1205. var shader = gltfRuntime.shaders[id];
  1206. if (BABYLON.GLTFUtils.IsBase64(shader.uri)) {
  1207. var shaderString = atob(shader.uri.split(",")[1]);
  1208. onSuccess(shaderString);
  1209. }
  1210. else {
  1211. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, null, null, false, onError);
  1212. }
  1213. };
  1214. GLTFFileLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1215. var material = gltfRuntime.materials[id];
  1216. var technique = gltfRuntime.techniques[material.technique];
  1217. if (!technique) {
  1218. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  1219. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  1220. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1221. onSuccess(defaultMaterial);
  1222. return;
  1223. }
  1224. var program = gltfRuntime.programs[technique.program];
  1225. var states = technique.states;
  1226. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  1227. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  1228. var newVertexShader = "";
  1229. var newPixelShader = "";
  1230. var vertexTokenizer = new Tokenizer(vertexShader);
  1231. var pixelTokenizer = new Tokenizer(pixelShader);
  1232. var unTreatedUniforms = {};
  1233. var uniforms = [];
  1234. var attributes = [];
  1235. var samplers = [];
  1236. // Fill uniform, sampler2D and attributes
  1237. for (var unif in technique.uniforms) {
  1238. var uniform = technique.uniforms[unif];
  1239. var uniformParameter = technique.parameters[uniform];
  1240. unTreatedUniforms[unif] = uniformParameter;
  1241. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  1242. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1243. if (transformIndex !== -1) {
  1244. uniforms.push(babylonTransforms[transformIndex]);
  1245. delete unTreatedUniforms[unif];
  1246. }
  1247. else {
  1248. uniforms.push(unif);
  1249. }
  1250. }
  1251. else if (uniformParameter.type === BABYLON.EParameterType.SAMPLER_2D) {
  1252. samplers.push(unif);
  1253. }
  1254. else {
  1255. uniforms.push(unif);
  1256. }
  1257. }
  1258. for (var attr in technique.attributes) {
  1259. var attribute = technique.attributes[attr];
  1260. var attributeParameter = technique.parameters[attribute];
  1261. if (attributeParameter.semantic) {
  1262. attributes.push(getAttribute(attributeParameter));
  1263. }
  1264. }
  1265. // Configure vertex shader
  1266. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  1267. var tokenType = vertexTokenizer.currentToken;
  1268. if (tokenType !== ETokenType.IDENTIFIER) {
  1269. newVertexShader += vertexTokenizer.currentString;
  1270. continue;
  1271. }
  1272. var foundAttribute = false;
  1273. for (var attr in technique.attributes) {
  1274. var attribute = technique.attributes[attr];
  1275. var attributeParameter = technique.parameters[attribute];
  1276. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  1277. newVertexShader += getAttribute(attributeParameter);
  1278. foundAttribute = true;
  1279. break;
  1280. }
  1281. }
  1282. if (foundAttribute) {
  1283. continue;
  1284. }
  1285. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  1286. }
  1287. // Configure pixel shader
  1288. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  1289. var tokenType = pixelTokenizer.currentToken;
  1290. if (tokenType !== ETokenType.IDENTIFIER) {
  1291. newPixelShader += pixelTokenizer.currentString;
  1292. continue;
  1293. }
  1294. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  1295. }
  1296. // Create shader material
  1297. var shaderPath = {
  1298. vertex: program.vertexShader + id,
  1299. fragment: program.fragmentShader + id
  1300. };
  1301. var options = {
  1302. attributes: attributes,
  1303. uniforms: uniforms,
  1304. samplers: samplers,
  1305. needAlphaBlending: states.functions && states.functions.blendEquationSeparate
  1306. };
  1307. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  1308. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  1309. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  1310. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  1311. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  1312. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1313. if (states.functions) {
  1314. var functions = states.functions;
  1315. if (functions.cullFace && functions.cullFace[0] !== BABYLON.ECullingType.BACK) {
  1316. shaderMaterial.backFaceCulling = false;
  1317. }
  1318. var blendFunc = functions.blendFuncSeparate;
  1319. if (blendFunc) {
  1320. 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) {
  1321. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  1322. }
  1323. else if (blendFunc[0] === BABYLON.EBlendingFunction.ONE && blendFunc[1] === BABYLON.EBlendingFunction.ONE && blendFunc[2] === BABYLON.EBlendingFunction.ZERO && blendFunc[3] === BABYLON.EBlendingFunction.ONE) {
  1324. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  1325. }
  1326. else if (blendFunc[0] === BABYLON.EBlendingFunction.SRC_ALPHA && blendFunc[1] === BABYLON.EBlendingFunction.ONE && blendFunc[2] === BABYLON.EBlendingFunction.ZERO && blendFunc[3] === BABYLON.EBlendingFunction.ONE) {
  1327. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  1328. }
  1329. 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) {
  1330. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  1331. }
  1332. else if (blendFunc[0] === BABYLON.EBlendingFunction.DST_COLOR && blendFunc[1] === BABYLON.EBlendingFunction.ZERO && blendFunc[2] === BABYLON.EBlendingFunction.ONE && blendFunc[3] === BABYLON.EBlendingFunction.ONE) {
  1333. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  1334. }
  1335. 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) {
  1336. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  1337. }
  1338. }
  1339. }
  1340. };
  1341. return GLTFFileLoaderBase;
  1342. }());
  1343. BABYLON.GLTFFileLoaderBase = GLTFFileLoaderBase;
  1344. /**
  1345. * glTF File Loader Plugin
  1346. */
  1347. var GLTFFileLoader = (function () {
  1348. function GLTFFileLoader() {
  1349. /**
  1350. * Public members
  1351. */
  1352. this.extensions = {
  1353. ".gltf": { isBinary: false },
  1354. ".glb": { isBinary: true }
  1355. };
  1356. }
  1357. GLTFFileLoader.RegisterExtension = function (extension) {
  1358. if (GLTFFileLoader.Extensions[extension.name]) {
  1359. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  1360. return;
  1361. }
  1362. GLTFFileLoader.Extensions[extension.name] = extension;
  1363. };
  1364. /**
  1365. * Import meshes
  1366. */
  1367. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onError) {
  1368. var _this = this;
  1369. scene.useRightHandedSystem = true;
  1370. var gltfRuntime = BABYLON.GLTFFileLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1371. gltfRuntime.importOnlyMeshes = true;
  1372. if (meshesNames === "") {
  1373. gltfRuntime.importMeshesNames = [];
  1374. }
  1375. else if (typeof meshesNames === "string") {
  1376. gltfRuntime.importMeshesNames = [meshesNames];
  1377. }
  1378. else if (meshesNames && !(meshesNames instanceof Array)) {
  1379. gltfRuntime.importMeshesNames = [meshesNames];
  1380. }
  1381. else {
  1382. gltfRuntime.importMeshesNames = [];
  1383. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  1384. }
  1385. // Create nodes
  1386. _this._createNodes(gltfRuntime);
  1387. var meshes = [];
  1388. var skeletons = [];
  1389. // Fill arrays of meshes and skeletons
  1390. for (var nde in gltfRuntime.nodes) {
  1391. var node = gltfRuntime.nodes[nde];
  1392. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  1393. meshes.push(node.babylonNode);
  1394. }
  1395. }
  1396. for (var skl in gltfRuntime.skins) {
  1397. var skin = gltfRuntime.skins[skl];
  1398. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  1399. skeletons.push(skin.babylonSkeleton);
  1400. }
  1401. }
  1402. // Load buffers, shaders, materials, etc.
  1403. _this._loadBuffersAsync(gltfRuntime, function () {
  1404. _this._loadShadersAsync(gltfRuntime, function () {
  1405. importMaterials(gltfRuntime);
  1406. postLoad(gltfRuntime);
  1407. });
  1408. });
  1409. if (onSuccess) {
  1410. onSuccess(meshes, null, skeletons);
  1411. }
  1412. }, onError);
  1413. return true;
  1414. };
  1415. /**
  1416. * Load scene
  1417. */
  1418. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onError) {
  1419. var _this = this;
  1420. scene.useRightHandedSystem = true;
  1421. BABYLON.GLTFFileLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1422. // Create nodes
  1423. _this._createNodes(gltfRuntime);
  1424. // Load buffers, shaders, materials, etc.
  1425. _this._loadBuffersAsync(gltfRuntime, function () {
  1426. _this._loadShadersAsync(gltfRuntime, function () {
  1427. importMaterials(gltfRuntime);
  1428. postLoad(gltfRuntime);
  1429. });
  1430. });
  1431. onSuccess();
  1432. }, onError);
  1433. return true;
  1434. };
  1435. GLTFFileLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  1436. var hasShaders = false;
  1437. var processShader = function (sha, shader) {
  1438. BABYLON.GLTFFileLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  1439. gltfRuntime.loadedShaderCount++;
  1440. if (shaderString) {
  1441. BABYLON.Effect.ShadersStore[sha + (shader.type === BABYLON.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  1442. }
  1443. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  1444. onload();
  1445. }
  1446. }, function () {
  1447. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  1448. });
  1449. };
  1450. for (var sha in gltfRuntime.shaders) {
  1451. hasShaders = true;
  1452. var shader = gltfRuntime.shaders[sha];
  1453. if (shader) {
  1454. processShader.bind(this, sha, shader)();
  1455. }
  1456. else {
  1457. BABYLON.Tools.Error("No shader named: " + sha);
  1458. }
  1459. }
  1460. if (!hasShaders) {
  1461. onload();
  1462. }
  1463. };
  1464. ;
  1465. GLTFFileLoader.prototype._loadBuffersAsync = function (gltfRuntime, onload) {
  1466. var hasBuffers = false;
  1467. var processBuffer = function (buf, buffer) {
  1468. BABYLON.GLTFFileLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  1469. gltfRuntime.loadedBufferCount++;
  1470. if (bufferView) {
  1471. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  1472. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  1473. }
  1474. gltfRuntime.loadedBufferViews[buf] = bufferView;
  1475. }
  1476. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  1477. onload();
  1478. }
  1479. }, function () {
  1480. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  1481. });
  1482. };
  1483. for (var buf in gltfRuntime.buffers) {
  1484. hasBuffers = true;
  1485. var buffer = gltfRuntime.buffers[buf];
  1486. if (buffer) {
  1487. processBuffer.bind(this, buf, buffer)();
  1488. }
  1489. else {
  1490. BABYLON.Tools.Error("No buffer named: " + buf);
  1491. }
  1492. }
  1493. if (!hasBuffers) {
  1494. onload();
  1495. }
  1496. };
  1497. // Creates nodes before loading buffers and shaders
  1498. GLTFFileLoader.prototype._createNodes = function (gltfRuntime) {
  1499. var currentScene = gltfRuntime.currentScene;
  1500. for (var i = 0; i < currentScene.nodes.length; i++) {
  1501. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1502. }
  1503. };
  1504. return GLTFFileLoader;
  1505. }());
  1506. /**
  1507. * Private members
  1508. */
  1509. // None
  1510. /**
  1511. * Static members
  1512. */
  1513. GLTFFileLoader.MakeYUP = false;
  1514. GLTFFileLoader.HomogeneousCoordinates = false;
  1515. GLTFFileLoader.Extensions = {};
  1516. BABYLON.GLTFFileLoader = GLTFFileLoader;
  1517. ;
  1518. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  1519. })(BABYLON || (BABYLON = {}));
  1520. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  1521. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  1522. var BABYLON;
  1523. (function (BABYLON) {
  1524. /**
  1525. * Utils functions for GLTF
  1526. */
  1527. var GLTFUtils = (function () {
  1528. function GLTFUtils() {
  1529. }
  1530. /**
  1531. * Sets the given "parameter" matrix
  1532. * @param scene: the {BABYLON.Scene} object
  1533. * @param source: the source node where to pick the matrix
  1534. * @param parameter: the GLTF technique parameter
  1535. * @param uniformName: the name of the shader's uniform
  1536. * @param shaderMaterial: the shader material
  1537. */
  1538. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  1539. var mat = null;
  1540. if (parameter.semantic === "MODEL") {
  1541. mat = source.getWorldMatrix();
  1542. }
  1543. else if (parameter.semantic === "PROJECTION") {
  1544. mat = scene.getProjectionMatrix();
  1545. }
  1546. else if (parameter.semantic === "VIEW") {
  1547. mat = scene.getViewMatrix();
  1548. }
  1549. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  1550. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  1551. }
  1552. else if (parameter.semantic === "MODELVIEW") {
  1553. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  1554. }
  1555. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  1556. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  1557. }
  1558. else if (parameter.semantic === "MODELINVERSE") {
  1559. mat = source.getWorldMatrix().invert();
  1560. }
  1561. else if (parameter.semantic === "VIEWINVERSE") {
  1562. mat = scene.getViewMatrix().invert();
  1563. }
  1564. else if (parameter.semantic === "PROJECTIONINVERSE") {
  1565. mat = scene.getProjectionMatrix().invert();
  1566. }
  1567. else if (parameter.semantic === "MODELVIEWINVERSE") {
  1568. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  1569. }
  1570. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  1571. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  1572. }
  1573. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  1574. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  1575. }
  1576. else {
  1577. debugger;
  1578. }
  1579. switch (parameter.type) {
  1580. case BABYLON.EParameterType.FLOAT_MAT2:
  1581. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  1582. break;
  1583. case BABYLON.EParameterType.FLOAT_MAT3:
  1584. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  1585. break;
  1586. case BABYLON.EParameterType.FLOAT_MAT4:
  1587. shaderMaterial.setMatrix(uniformName, mat);
  1588. break;
  1589. default: break;
  1590. }
  1591. };
  1592. /**
  1593. * Sets the given "parameter" matrix
  1594. * @param shaderMaterial: the shader material
  1595. * @param uniform: the name of the shader's uniform
  1596. * @param value: the value of the uniform
  1597. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  1598. */
  1599. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  1600. switch (type) {
  1601. case BABYLON.EParameterType.FLOAT:
  1602. shaderMaterial.setFloat(uniform, value);
  1603. return true;
  1604. case BABYLON.EParameterType.FLOAT_VEC2:
  1605. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  1606. return true;
  1607. case BABYLON.EParameterType.FLOAT_VEC3:
  1608. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  1609. return true;
  1610. case BABYLON.EParameterType.FLOAT_VEC4:
  1611. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  1612. return true;
  1613. default: return false;
  1614. }
  1615. };
  1616. /**
  1617. * If the uri is a base64 string
  1618. * @param uri: the uri to test
  1619. */
  1620. GLTFUtils.IsBase64 = function (uri) {
  1621. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  1622. };
  1623. /**
  1624. * Decode the base64 uri
  1625. * @param uri: the uri to decode
  1626. */
  1627. GLTFUtils.DecodeBase64 = function (uri) {
  1628. var decodedString = atob(uri.split(",")[1]);
  1629. var bufferLength = decodedString.length;
  1630. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  1631. for (var i = 0; i < bufferLength; i++) {
  1632. bufferView[i] = decodedString.charCodeAt(i);
  1633. }
  1634. return bufferView.buffer;
  1635. };
  1636. /**
  1637. * Returns the wrap mode of the texture
  1638. * @param mode: the mode value
  1639. */
  1640. GLTFUtils.GetWrapMode = function (mode) {
  1641. switch (mode) {
  1642. case BABYLON.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  1643. case BABYLON.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  1644. case BABYLON.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1645. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1646. }
  1647. };
  1648. /**
  1649. * Returns the byte stride giving an accessor
  1650. * @param accessor: the GLTF accessor objet
  1651. */
  1652. GLTFUtils.GetByteStrideFromType = function (accessor) {
  1653. // Needs this function since "byteStride" isn't requiered in glTF format
  1654. var type = accessor.type;
  1655. switch (type) {
  1656. case "VEC2": return 2;
  1657. case "VEC3": return 3;
  1658. case "VEC4": return 4;
  1659. case "MAT2": return 4;
  1660. case "MAT3": return 9;
  1661. case "MAT4": return 16;
  1662. default: return 1;
  1663. }
  1664. };
  1665. /**
  1666. * Returns the texture filter mode giving a mode value
  1667. * @param mode: the filter mode value
  1668. */
  1669. GLTFUtils.GetTextureFilterMode = function (mode) {
  1670. switch (mode) {
  1671. case BABYLON.ETextureFilterType.LINEAR:
  1672. case BABYLON.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  1673. case BABYLON.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  1674. case BABYLON.ETextureFilterType.NEAREST:
  1675. case BABYLON.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  1676. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1677. }
  1678. };
  1679. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  1680. var byteOffset = bufferView.byteOffset + byteOffset;
  1681. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  1682. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  1683. throw new Error("Buffer access is out of range");
  1684. }
  1685. var buffer = loadedBufferView.buffer;
  1686. byteOffset += loadedBufferView.byteOffset;
  1687. switch (componentType) {
  1688. case BABYLON.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  1689. case BABYLON.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  1690. case BABYLON.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  1691. case BABYLON.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  1692. default: return new Float32Array(buffer, byteOffset, byteLength);
  1693. }
  1694. };
  1695. /**
  1696. * Returns a buffer from its accessor
  1697. * @param gltfRuntime: the GLTF runtime
  1698. * @param accessor: the GLTF accessor
  1699. */
  1700. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  1701. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  1702. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  1703. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  1704. };
  1705. /**
  1706. * Decodes a buffer view into a string
  1707. * @param view: the buffer view
  1708. */
  1709. GLTFUtils.DecodeBufferToText = function (view) {
  1710. var result = "";
  1711. var length = view.byteLength;
  1712. for (var i = 0; i < length; ++i) {
  1713. result += String.fromCharCode(view[i]);
  1714. }
  1715. return result;
  1716. };
  1717. return GLTFUtils;
  1718. }());
  1719. BABYLON.GLTFUtils = GLTFUtils;
  1720. })(BABYLON || (BABYLON = {}));
  1721. //# sourceMappingURL=babylon.glTFFileLoaderUtils.js.map
  1722. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  1723. var BABYLON;
  1724. (function (BABYLON) {
  1725. var GLTFFileLoaderExtension = (function () {
  1726. function GLTFFileLoaderExtension(name) {
  1727. this._name = name;
  1728. }
  1729. Object.defineProperty(GLTFFileLoaderExtension.prototype, "name", {
  1730. get: function () {
  1731. return this._name;
  1732. },
  1733. enumerable: true,
  1734. configurable: true
  1735. });
  1736. /**
  1737. * Defines an override for loading the runtime
  1738. * Return true to stop further extensions from loading the runtime
  1739. */
  1740. GLTFFileLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  1741. return false;
  1742. };
  1743. /**
  1744. * Defines an override for loading buffers
  1745. * Return true to stop further extensions from loading this buffer
  1746. */
  1747. GLTFFileLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1748. return false;
  1749. };
  1750. /**
  1751. * Defines an override for loading texture buffers
  1752. * Return true to stop further extensions from loading this texture data
  1753. */
  1754. GLTFFileLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1755. return false;
  1756. };
  1757. /**
  1758. * Defines an override for creating textures
  1759. * Return true to stop further extensions from loading this texture
  1760. */
  1761. GLTFFileLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1762. return false;
  1763. };
  1764. /**
  1765. * Defines an override for loading shader strings
  1766. * Return true to stop further extensions from loading this shader data
  1767. */
  1768. GLTFFileLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1769. return false;
  1770. };
  1771. /**
  1772. * Defines an override for loading materials
  1773. * Return true to stop further extensions from loading this material
  1774. */
  1775. GLTFFileLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1776. return false;
  1777. };
  1778. // ---------
  1779. // Utilities
  1780. // ---------
  1781. GLTFFileLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  1782. GLTFFileLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1783. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  1784. }, function () {
  1785. setTimeout(function () {
  1786. onSuccess(BABYLON.GLTFFileLoaderBase.CreateRuntime(JSON.parse(data), scene, rootUrl));
  1787. });
  1788. });
  1789. };
  1790. GLTFFileLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1791. GLTFFileLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1792. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError);
  1793. }, function () {
  1794. BABYLON.GLTFFileLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError);
  1795. });
  1796. };
  1797. GLTFFileLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  1798. GLTFFileLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFFileLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  1799. };
  1800. GLTFFileLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1801. GLTFFileLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1802. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  1803. }, function () {
  1804. BABYLON.GLTFFileLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  1805. });
  1806. };
  1807. GLTFFileLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1808. GLTFFileLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1809. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  1810. }, function () {
  1811. BABYLON.GLTFFileLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  1812. });
  1813. };
  1814. GLTFFileLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1815. GLTFFileLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1816. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  1817. }, function () {
  1818. BABYLON.GLTFFileLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  1819. });
  1820. };
  1821. GLTFFileLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1822. GLTFFileLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1823. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  1824. }, function () {
  1825. BABYLON.GLTFFileLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  1826. });
  1827. };
  1828. GLTFFileLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  1829. for (var extensionName in BABYLON.GLTFFileLoader.Extensions) {
  1830. var loaderExtension = BABYLON.GLTFFileLoader.Extensions[extensionName];
  1831. if (func(loaderExtension)) {
  1832. return;
  1833. }
  1834. }
  1835. defaultFunc();
  1836. };
  1837. return GLTFFileLoaderExtension;
  1838. }());
  1839. BABYLON.GLTFFileLoaderExtension = GLTFFileLoaderExtension;
  1840. })(BABYLON || (BABYLON = {}));
  1841. //# sourceMappingURL=babylon.glTFFileLoaderExtension.js.map
  1842. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  1843. var __extends = (this && this.__extends) || function (d, b) {
  1844. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  1845. function __() { this.constructor = d; }
  1846. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1847. };
  1848. var BABYLON;
  1849. (function (BABYLON) {
  1850. var BinaryExtensionBufferName = "binary_glTF";
  1851. var EContentFormat;
  1852. (function (EContentFormat) {
  1853. EContentFormat[EContentFormat["JSON"] = 0] = "JSON";
  1854. })(EContentFormat || (EContentFormat = {}));
  1855. ;
  1856. ;
  1857. ;
  1858. ;
  1859. var GLTFBinaryExtension = (function (_super) {
  1860. __extends(GLTFBinaryExtension, _super);
  1861. function GLTFBinaryExtension() {
  1862. return _super.call(this, "KHR_binary_glTF") || this;
  1863. }
  1864. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  1865. var _this = this;
  1866. if (!(data instanceof ArrayBuffer)) {
  1867. return false;
  1868. }
  1869. setTimeout(function () {
  1870. _this._binary = _this._parseBinary(data);
  1871. if (!_this._binary) {
  1872. onError();
  1873. return true;
  1874. }
  1875. var gltfRuntime = BABYLON.GLTFFileLoaderBase.CreateRuntime(_this._binary.content, scene, rootUrl);
  1876. if (gltfRuntime.extensionsUsed.indexOf(_this.name) === -1) {
  1877. BABYLON.Tools.Warn("glTF binary file does not have " + _this.name + " specified in extensionsUsed");
  1878. gltfRuntime.extensionsUsed.push(_this.name);
  1879. }
  1880. onSuccess(gltfRuntime);
  1881. });
  1882. return true;
  1883. };
  1884. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1885. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  1886. return false;
  1887. }
  1888. if (id !== BinaryExtensionBufferName) {
  1889. return false;
  1890. }
  1891. onSuccess(this._binary.body);
  1892. return true;
  1893. };
  1894. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1895. var texture = gltfRuntime.textures[id];
  1896. var source = gltfRuntime.images[texture.source];
  1897. if (!source.extensions || !(this.name in source.extensions)) {
  1898. return false;
  1899. }
  1900. var sourceExt = source.extensions[this.name];
  1901. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  1902. var buffer = BABYLON.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, BABYLON.EComponentType.UNSIGNED_BYTE);
  1903. onSuccess(buffer);
  1904. return true;
  1905. };
  1906. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1907. var shader = gltfRuntime.shaders[id];
  1908. if (!shader.extensions || !(this.name in shader.extensions)) {
  1909. return false;
  1910. }
  1911. var binaryExtensionShader = shader.extensions[this.name];
  1912. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  1913. var shaderBytes = BABYLON.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, BABYLON.EComponentType.UNSIGNED_BYTE);
  1914. setTimeout(function () {
  1915. var shaderString = BABYLON.GLTFUtils.DecodeBufferToText(shaderBytes);
  1916. onSuccess(shaderString);
  1917. });
  1918. return true;
  1919. };
  1920. // Parses a glTF binary array buffer into its content and body
  1921. GLTFBinaryExtension.prototype._parseBinary = function (data) {
  1922. var binaryReader = new BinaryReader(data);
  1923. var magic = BABYLON.GLTFUtils.DecodeBufferToText(binaryReader.getUint8Array(4));
  1924. if (magic != "glTF") {
  1925. BABYLON.Tools.Error("Unexpected magic: " + magic);
  1926. return null;
  1927. }
  1928. var version = binaryReader.getUint32();
  1929. if (version != 1) {
  1930. BABYLON.Tools.Error("Unsupported version: " + version);
  1931. return null;
  1932. }
  1933. var length = binaryReader.getUint32();
  1934. if (length != data.byteLength) {
  1935. BABYLON.Tools.Error("Length in header does not match actual data length: " + length + " != " + data.byteLength);
  1936. return null;
  1937. }
  1938. var contentLength = binaryReader.getUint32();
  1939. var contentFormat = binaryReader.getUint32();
  1940. var content;
  1941. switch (contentFormat) {
  1942. case EContentFormat.JSON:
  1943. var jsonText = BABYLON.GLTFUtils.DecodeBufferToText(binaryReader.getUint8Array(contentLength));
  1944. content = JSON.parse(jsonText);
  1945. break;
  1946. default:
  1947. BABYLON.Tools.Error("Unexpected content format: " + contentFormat);
  1948. return null;
  1949. }
  1950. var body = binaryReader.getUint8Array();
  1951. return {
  1952. content: content,
  1953. body: body
  1954. };
  1955. };
  1956. ;
  1957. return GLTFBinaryExtension;
  1958. }(BABYLON.GLTFFileLoaderExtension));
  1959. BABYLON.GLTFBinaryExtension = GLTFBinaryExtension;
  1960. var BinaryReader = (function () {
  1961. function BinaryReader(arrayBuffer) {
  1962. this._arrayBuffer = arrayBuffer;
  1963. this._dataView = new DataView(arrayBuffer);
  1964. this._byteOffset = 0;
  1965. }
  1966. BinaryReader.prototype.getUint32 = function () {
  1967. var value = this._dataView.getUint32(this._byteOffset, true);
  1968. this._byteOffset += 4;
  1969. return value;
  1970. };
  1971. BinaryReader.prototype.getUint8Array = function (length) {
  1972. if (!length) {
  1973. length = this._arrayBuffer.byteLength - this._byteOffset;
  1974. }
  1975. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  1976. this._byteOffset += length;
  1977. return value;
  1978. };
  1979. return BinaryReader;
  1980. }());
  1981. BABYLON.GLTFFileLoader.RegisterExtension(new GLTFBinaryExtension());
  1982. })(BABYLON || (BABYLON = {}));
  1983. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map