babylon.glTFFileLoader.js 78 KB

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