babylon.glTFFileLoader.js 91 KB

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