babylon.glTFFileLoader.js 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735
  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.flipFaces(true);
  735. newMesh.computeWorldMatrix(true);
  736. // Apply submeshes
  737. newMesh.subMeshes = [];
  738. var index = 0;
  739. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  740. var meshID = meshes[meshIndex];
  741. var mesh = gltfRuntime.meshes[meshID];
  742. if (!mesh) {
  743. continue;
  744. }
  745. for (var i = 0; i < mesh.primitives.length; i++) {
  746. if (mesh.primitives[i].mode !== 4) {
  747. }
  748. var subMesh = new BABYLON.SubMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  749. index++;
  750. }
  751. // If there is an extension for mesh, call it
  752. callExtension(gltfRuntime, id, mesh.name, mesh.extensions, newMesh);
  753. }
  754. // Finish
  755. return newMesh;
  756. };
  757. /**
  758. * Configure node transformation from position, rotation and scaling
  759. */
  760. var configureNode = function (newNode, position, rotation, scaling) {
  761. if (newNode.position) {
  762. newNode.position = position;
  763. }
  764. if (newNode.rotationQuaternion || newNode.rotation) {
  765. newNode.rotationQuaternion = rotation;
  766. }
  767. if (newNode.scaling) {
  768. newNode.scaling = scaling;
  769. }
  770. };
  771. /**
  772. * Configures node from transformation matrix
  773. */
  774. var configureNodeFromMatrix = function (newNode, node) {
  775. if (node.matrix) {
  776. var position = new BABYLON.Vector3(0, 0, 0);
  777. var rotation = new BABYLON.Quaternion();
  778. var scaling = new BABYLON.Vector3(0, 0, 0);
  779. var mat = BABYLON.Matrix.FromArray(node.matrix);
  780. mat.decompose(scaling, rotation, position);
  781. // Y is Up
  782. if (GLTFFileLoader.MakeYUP) {
  783. rotation = rotation.multiply(new BABYLON.Quaternion(-0.707107, 0, 0, 0.707107));
  784. }
  785. configureNode(newNode, position, rotation, scaling);
  786. if (newNode instanceof BABYLON.TargetCamera) {
  787. newNode.setTarget(BABYLON.Vector3.Zero());
  788. }
  789. }
  790. else {
  791. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  792. }
  793. };
  794. /**
  795. * Imports a node
  796. */
  797. var importNode = function (gltfRuntime, node, id) {
  798. var lastNode = null;
  799. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  800. if (gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name) === -1) {
  801. return null;
  802. }
  803. }
  804. // Meshes
  805. if (node.skin) {
  806. if (node.meshes) {
  807. var skin = gltfRuntime.skins[node.skin];
  808. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  809. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  810. if (newMesh.skeleton === null) {
  811. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  812. if (!skin.babylonSkeleton) {
  813. skin.babylonSkeleton = newMesh.skeleton;
  814. }
  815. }
  816. if (newMesh.skeleton !== null) {
  817. newMesh.useBones = true;
  818. }
  819. lastNode = newMesh;
  820. // If extension
  821. callExtension(gltfRuntime, node.skin, node.name, node.extensions, newMesh);
  822. }
  823. }
  824. else if (node.meshes) {
  825. /**
  826. * Improve meshes property
  827. */
  828. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  829. lastNode = newMesh;
  830. }
  831. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  832. var light = gltfRuntime.lights[node.light];
  833. if (light) {
  834. if (light.type === "ambient") {
  835. var ambienLight = light[light.type];
  836. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  837. hemiLight.name = node.name;
  838. if (ambienLight.color) {
  839. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  840. }
  841. lastNode = hemiLight;
  842. }
  843. else if (light.type === "directional") {
  844. var directionalLight = light[light.type];
  845. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  846. dirLight.name = node.name;
  847. if (directionalLight.color) {
  848. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  849. }
  850. lastNode = dirLight;
  851. }
  852. else if (light.type === "point") {
  853. var pointLight = light[light.type];
  854. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  855. ptLight.name = node.name;
  856. if (pointLight.color) {
  857. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  858. }
  859. lastNode = ptLight;
  860. }
  861. else if (light.type === "spot") {
  862. var spotLight = light[light.type];
  863. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  864. spLight.name = node.name;
  865. if (spotLight.color) {
  866. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  867. }
  868. if (spotLight.fallOfAngle) {
  869. spLight.angle = spotLight.fallOfAngle;
  870. }
  871. if (spotLight.fallOffExponent) {
  872. spLight.exponent = spotLight.fallOffExponent;
  873. }
  874. lastNode = spLight;
  875. }
  876. // If there is an extension for light, call it
  877. callExtension(gltfRuntime, node.light, light.name, light.extensions, lastNode);
  878. }
  879. }
  880. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  881. var camera = gltfRuntime.cameras[node.camera];
  882. if (camera) {
  883. if (camera.type === "orthographic") {
  884. var orthographicCamera = camera[camera.type];
  885. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  886. orthoCamera.name = node.name;
  887. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  888. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  889. lastNode = orthoCamera;
  890. }
  891. else if (camera.type === "perspective") {
  892. var perspectiveCamera = camera[camera.type];
  893. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  894. persCamera.name = node.name;
  895. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  896. if (!perspectiveCamera.aspectRatio) {
  897. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  898. }
  899. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  900. persCamera.maxZ = perspectiveCamera.zfar;
  901. persCamera.minZ = perspectiveCamera.znear;
  902. }
  903. lastNode = persCamera;
  904. }
  905. // If there is an extension for camera, call it
  906. callExtension(gltfRuntime, node.camera, camera.name, camera.extensions, lastNode);
  907. }
  908. }
  909. // Empty node
  910. if (!node.jointName) {
  911. if (node.babylonNode) {
  912. return node.babylonNode;
  913. }
  914. else if (lastNode === null) {
  915. var dummy = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  916. node.babylonNode = dummy;
  917. lastNode = dummy;
  918. }
  919. }
  920. if (lastNode !== null) {
  921. if (node.matrix) {
  922. configureNodeFromMatrix(lastNode, node);
  923. }
  924. else {
  925. configureNode(lastNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.RotationAxis(BABYLON.Vector3.FromArray(node.rotation).normalize(), node.rotation[3]), BABYLON.Vector3.FromArray(node.scale));
  926. }
  927. lastNode.updateCache(true);
  928. node.babylonNode = lastNode;
  929. }
  930. // If there is an extension for the current node, call it
  931. callExtension(gltfRuntime, id, node.name, node.extensions, lastNode);
  932. return lastNode;
  933. };
  934. /**
  935. * Traverses nodes and creates them
  936. */
  937. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  938. var node = gltfRuntime.nodes[id];
  939. var newNode = null;
  940. if (gltfRuntime.importOnlyMeshes && !meshIncluded) {
  941. if (gltfRuntime.importMeshesNames.indexOf(node.name) !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  942. meshIncluded = true;
  943. }
  944. else {
  945. meshIncluded = false;
  946. }
  947. }
  948. else {
  949. meshIncluded = true;
  950. }
  951. if (!node.jointName && meshIncluded) {
  952. newNode = importNode(gltfRuntime, node, id);
  953. if (newNode !== null) {
  954. newNode.id = id;
  955. newNode.parent = parent;
  956. }
  957. }
  958. for (var i = 0; i < node.children.length; i++) {
  959. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  960. }
  961. };
  962. /**
  963. * Buffers loaded, create nodes
  964. */
  965. var onBuffersLoaded = function (gltfRuntime) {
  966. // Nodes
  967. var currentScene = gltfRuntime.currentScene;
  968. for (var i = 0; i < currentScene.nodes.length; i++) {
  969. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  970. }
  971. // Set animations
  972. loadAnimations(gltfRuntime);
  973. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  974. var skeleton = gltfRuntime.scene.skeletons[i];
  975. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  976. }
  977. };
  978. /**
  979. * On a buffer is loaded
  980. */
  981. var onLoadBuffer = function (gltfRuntime, buf) {
  982. return function (data) {
  983. gltfRuntime.loadedBuffers++;
  984. if (!(data instanceof ArrayBuffer)) {
  985. BABYLON.Tools.Error("Buffer named " + buf + " is not an array buffer");
  986. }
  987. else if (data.byteLength != gltfRuntime.buffers[buf].byteLength) {
  988. BABYLON.Tools.Error("Buffer named " + buf + " is length " + data.byteLength + ". Expected: " + gltfRuntime.buffers[buf].byteLength); // Improve error message
  989. }
  990. gltfRuntime.arrayBuffers[buf] = data;
  991. if (gltfRuntime.loadedBuffers === gltfRuntime.buffersCount) {
  992. onBuffersLoaded(gltfRuntime);
  993. }
  994. };
  995. };
  996. /**
  997. * Error when loaded buffer
  998. */
  999. var onLoadBufferError = function (gltfRuntime, buf) {
  1000. return function () {
  1001. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + gltfRuntime.buffers[buf].uri);
  1002. };
  1003. };
  1004. /**
  1005. * Decode array buffer from base64
  1006. */
  1007. var decodeArrayBuffer = function (base64) {
  1008. var decodedString = atob(base64);
  1009. var bufferLength = decodedString.length;
  1010. var arraybuffer = new Uint8Array(new ArrayBuffer(bufferLength));
  1011. for (var i = 0; i < bufferLength; i++) {
  1012. arraybuffer[i] = decodedString.charCodeAt(i);
  1013. }
  1014. return arraybuffer.buffer;
  1015. };
  1016. /**
  1017. * Loads buffers (geometries)
  1018. */
  1019. var loadBuffers = function (gltfRuntime) {
  1020. for (var buf in gltfRuntime.buffers) {
  1021. var buffer = gltfRuntime.buffers[buf];
  1022. if (buffer) {
  1023. if (BABYLON.GLTFUtils.IsBase64(buffer.uri)) {
  1024. var arrayBuffer = decodeArrayBuffer(buffer.uri.split(",")[1]);
  1025. onLoadBuffer(gltfRuntime, buf)(arrayBuffer);
  1026. }
  1027. else {
  1028. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, onLoadBuffer(gltfRuntime, buf), null, null, true, onLoadBufferError(gltfRuntime, buf));
  1029. }
  1030. }
  1031. else {
  1032. BABYLON.Tools.Error("No buffer named : " + buf);
  1033. }
  1034. }
  1035. };
  1036. /**
  1037. * onBind shaderrs callback to set uniforms and matrices
  1038. */
  1039. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material) {
  1040. for (var unif in unTreatedUniforms) {
  1041. var uniform = unTreatedUniforms[unif];
  1042. var type = uniform.type;
  1043. if (type === BABYLON.EParameterType.FLOAT_MAT2 || type === BABYLON.EParameterType.FLOAT_MAT3 || type === BABYLON.EParameterType.FLOAT_MAT4) {
  1044. if (uniform.semantic && !uniform.source && !uniform.node) {
  1045. BABYLON.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  1046. }
  1047. else if (uniform.semantic && (uniform.source || uniform.node)) {
  1048. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node);
  1049. if (source === null) {
  1050. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node);
  1051. }
  1052. if (source === null) {
  1053. continue;
  1054. }
  1055. BABYLON.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  1056. }
  1057. }
  1058. else {
  1059. var value = material.values[technique.uniforms[unif]];
  1060. if (!value) {
  1061. continue;
  1062. }
  1063. if (type === BABYLON.EParameterType.SAMPLER_2D) {
  1064. var texture = gltfRuntime.textures[value].babylonTexture;
  1065. if (texture === null) {
  1066. continue;
  1067. }
  1068. shaderMaterial.getEffect().setTexture(unif, texture);
  1069. }
  1070. else {
  1071. BABYLON.GLTFUtils.SetUniform(shaderMaterial.getEffect(), unif, value, type);
  1072. }
  1073. }
  1074. }
  1075. };
  1076. /**
  1077. * Prepare uniforms to send the only one time
  1078. * Loads the appropriate textures
  1079. */
  1080. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  1081. var materialValues = material.values;
  1082. var techniqueUniforms = technique.uniforms;
  1083. /**
  1084. * Prepare values here (not matrices)
  1085. */
  1086. for (var unif in unTreatedUniforms) {
  1087. var uniform = unTreatedUniforms[unif];
  1088. var type = uniform.type;
  1089. var value = materialValues[techniqueUniforms[unif]] || uniform.value;
  1090. if (!value) {
  1091. continue;
  1092. }
  1093. // Texture (sampler2D)
  1094. if (type === BABYLON.EParameterType.SAMPLER_2D) {
  1095. var texture = gltfRuntime.textures[value];
  1096. var sampler = gltfRuntime.samplers[texture.sampler];
  1097. if (!texture || !texture.source) {
  1098. continue;
  1099. }
  1100. var source = gltfRuntime.images[texture.source];
  1101. var newTexture = null;
  1102. var createMipMaps = (sampler.minFilter === BABYLON.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  1103. (sampler.minFilter === BABYLON.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  1104. (sampler.minFilter === BABYLON.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  1105. (sampler.minFilter === BABYLON.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  1106. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1107. if (BABYLON.GLTFUtils.IsBase64(source.uri)) {
  1108. newTexture = new BABYLON.Texture(source.uri, gltfRuntime.scene, !createMipMaps, true, samplingMode, null, null, source.uri, true);
  1109. }
  1110. else {
  1111. newTexture = new BABYLON.Texture(gltfRuntime.rootUrl + source.uri, gltfRuntime.scene, !createMipMaps, true, samplingMode);
  1112. }
  1113. newTexture.wrapU = BABYLON.GLTFUtils.GetWrapMode(sampler.wrapS);
  1114. newTexture.wrapV = BABYLON.GLTFUtils.GetWrapMode(sampler.wrapT);
  1115. newTexture.name = value;
  1116. texture.babylonTexture = newTexture;
  1117. // If there is an extension for texture, sampler or image, call it
  1118. callExtension(gltfRuntime, value, texture.name, texture.extensions, newTexture);
  1119. callExtension(gltfRuntime, texture.sampler, sampler.name, sampler.extensions, newTexture);
  1120. callExtension(gltfRuntime, texture.source, source.name, source.extensions, newTexture);
  1121. if (uniform.value) {
  1122. // Static uniform
  1123. shaderMaterial.setTexture(unif, newTexture);
  1124. delete unTreatedUniforms[unif];
  1125. }
  1126. }
  1127. else {
  1128. if (uniform.value && BABYLON.GLTFUtils.SetUniform(shaderMaterial, unif, value, type)) {
  1129. // Static uniform
  1130. delete unTreatedUniforms[unif];
  1131. }
  1132. }
  1133. }
  1134. // If there is an extension, call it
  1135. callExtension(gltfRuntime, material.name, material.name, material.extensions, shaderMaterial);
  1136. };
  1137. /**
  1138. * Shader compilation failed
  1139. */
  1140. var onShaderCompileError = function (program, shaderMaterial) {
  1141. return function (effect, error) {
  1142. BABYLON.Tools.Error("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  1143. shaderMaterial.dispose(true);
  1144. };
  1145. };
  1146. /**
  1147. * Shader compilation success
  1148. */
  1149. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  1150. return function (_) {
  1151. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  1152. shaderMaterial.onBind = function (mesh) {
  1153. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material);
  1154. };
  1155. };
  1156. };
  1157. /**
  1158. * Returns the appropriate uniform if already handled by babylon
  1159. */
  1160. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  1161. for (var unif in technique.uniforms) {
  1162. var uniform = technique.uniforms[unif];
  1163. var uniformParameter = technique.parameters[uniform];
  1164. if (tokenizer.currentIdentifier === unif) {
  1165. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  1166. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1167. if (transformIndex !== -1) {
  1168. delete unTreatedUniforms[unif];
  1169. return babylonTransforms[transformIndex];
  1170. }
  1171. }
  1172. }
  1173. }
  1174. return tokenizer.currentIdentifier;
  1175. };
  1176. /**
  1177. * All shaders loaded. Create materials one by one
  1178. */
  1179. var onShadersLoaded = function (gltfRuntime) {
  1180. // Create materials
  1181. for (var mat in gltfRuntime.materials) {
  1182. var material = gltfRuntime.materials[mat];
  1183. if (extensionNeedToSkipDefaultBehavior(gltfRuntime, mat, material.name, material.extensions)) {
  1184. continue;
  1185. }
  1186. var technique = gltfRuntime.techniques[material.technique];
  1187. var program = gltfRuntime.programs[technique.program];
  1188. var states = technique.states;
  1189. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  1190. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  1191. var newVertexShader = "";
  1192. var newPixelShader = "";
  1193. var vertexTokenizer = new Tokenizer(vertexShader);
  1194. var pixelTokenizer = new Tokenizer(pixelShader);
  1195. var unTreatedUniforms = {};
  1196. var uniforms = [];
  1197. var attributes = [];
  1198. var samplers = [];
  1199. // Fill uniform, sampler2D and attributes
  1200. for (var unif in technique.uniforms) {
  1201. var uniform = technique.uniforms[unif];
  1202. var uniformParameter = technique.parameters[uniform];
  1203. unTreatedUniforms[unif] = uniformParameter;
  1204. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  1205. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1206. if (transformIndex !== -1) {
  1207. uniforms.push(babylonTransforms[transformIndex]);
  1208. delete unTreatedUniforms[unif];
  1209. }
  1210. else {
  1211. uniforms.push(unif);
  1212. }
  1213. }
  1214. else if (uniformParameter.type === BABYLON.EParameterType.SAMPLER_2D) {
  1215. samplers.push(unif);
  1216. }
  1217. else {
  1218. uniforms.push(unif);
  1219. }
  1220. }
  1221. for (var attr in technique.attributes) {
  1222. var attribute = technique.attributes[attr];
  1223. var attributeParameter = technique.parameters[attribute];
  1224. if (attributeParameter.semantic) {
  1225. attributes.push(getAttribute(attributeParameter));
  1226. }
  1227. }
  1228. // Configure vertex shader
  1229. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  1230. var tokenType = vertexTokenizer.currentToken;
  1231. if (tokenType !== ETokenType.IDENTIFIER) {
  1232. newVertexShader += vertexTokenizer.currentString;
  1233. continue;
  1234. }
  1235. var foundAttribute = false;
  1236. for (var attr in technique.attributes) {
  1237. var attribute = technique.attributes[attr];
  1238. var attributeParameter = technique.parameters[attribute];
  1239. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  1240. newVertexShader += getAttribute(attributeParameter);
  1241. foundAttribute = true;
  1242. break;
  1243. }
  1244. }
  1245. if (foundAttribute) {
  1246. continue;
  1247. }
  1248. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  1249. }
  1250. // Configure pixel shader
  1251. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  1252. var tokenType = pixelTokenizer.currentToken;
  1253. if (tokenType !== ETokenType.IDENTIFIER) {
  1254. newPixelShader += pixelTokenizer.currentString;
  1255. continue;
  1256. }
  1257. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  1258. }
  1259. // Create shader material
  1260. var shaderPath = {
  1261. vertex: program.vertexShader + mat,
  1262. fragment: program.fragmentShader + mat
  1263. };
  1264. var options = {
  1265. attributes: attributes,
  1266. uniforms: uniforms,
  1267. samplers: samplers,
  1268. needAlphaBlending: states.functions && states.functions.blendEquationSeparate
  1269. };
  1270. BABYLON.Effect.ShadersStore[program.vertexShader + mat + "VertexShader"] = newVertexShader;
  1271. BABYLON.Effect.ShadersStore[program.fragmentShader + mat + "PixelShader"] = newPixelShader;
  1272. var shaderMaterial = new BABYLON.ShaderMaterial(material.name, gltfRuntime.scene, shaderPath, options);
  1273. shaderMaterial.id = mat;
  1274. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial);
  1275. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  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. var parsedData = JSON.parse(data);
  1375. var gltfRuntime = this._createGlTFRuntime(parsedData, scene, rootUrl);
  1376. gltfRuntime.importOnlyMeshes = true;
  1377. if (meshesNames === "") {
  1378. gltfRuntime.importMeshesNames = [];
  1379. }
  1380. else if (typeof meshesNames === "string") {
  1381. gltfRuntime.importMeshesNames = [meshesNames];
  1382. }
  1383. else if (meshesNames && !(meshesNames instanceof Array)) {
  1384. gltfRuntime.importMeshesNames = [meshesNames];
  1385. }
  1386. else {
  1387. gltfRuntime.importMeshesNames = [];
  1388. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  1389. }
  1390. // Create nodes
  1391. this._createNodes(gltfRuntime);
  1392. // Fill arrays of meshes and skeletons
  1393. for (var nde in gltfRuntime.nodes) {
  1394. var node = gltfRuntime.nodes[nde];
  1395. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  1396. meshes.push(node.babylonNode);
  1397. }
  1398. }
  1399. for (var skl in gltfRuntime.skins) {
  1400. var skin = gltfRuntime.skins[skl];
  1401. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  1402. skeletons.push(skin.babylonSkeleton);
  1403. }
  1404. }
  1405. // Load shaders and buffers to apply
  1406. load(gltfRuntime);
  1407. return true;
  1408. };
  1409. /**
  1410. * Load scene
  1411. */
  1412. GLTFFileLoader.prototype.load = function (scene, data, rootUrl) {
  1413. var parsedData = JSON.parse(data);
  1414. var gltfRuntime = this._createGlTFRuntime(parsedData, scene, rootUrl);
  1415. // Create nodes
  1416. this._createNodes(gltfRuntime);
  1417. // Load shaders and buffers to apply
  1418. load(gltfRuntime);
  1419. // Finish
  1420. return true;
  1421. };
  1422. // Creates nodes before loading buffers and shaders
  1423. GLTFFileLoader.prototype._createNodes = function (gltfRuntime) {
  1424. var currentScene = gltfRuntime.currentScene;
  1425. for (var i = 0; i < currentScene.nodes.length; i++) {
  1426. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1427. }
  1428. // If there is an extension for scene, call it
  1429. callExtension(gltfRuntime, currentScene.name, currentScene.name, currentScene.extensions, gltfRuntime.scene);
  1430. };
  1431. // Creates the gltfRuntime
  1432. GLTFFileLoader.prototype._createGlTFRuntime = function (parsedData, scene, rootUrl) {
  1433. var gltfRuntime = {
  1434. accessors: {},
  1435. buffers: {},
  1436. bufferViews: {},
  1437. meshes: {},
  1438. lights: {},
  1439. cameras: {},
  1440. nodes: {},
  1441. images: {},
  1442. textures: {},
  1443. shaders: {},
  1444. programs: {},
  1445. samplers: {},
  1446. techniques: {},
  1447. materials: {},
  1448. animations: {},
  1449. skins: {},
  1450. currentScene: {},
  1451. extensionsUsed: [],
  1452. buffersCount: 0,
  1453. shaderscount: 0,
  1454. scene: scene,
  1455. dummyNodes: [],
  1456. loadedBuffers: 0,
  1457. loadedShaders: 0,
  1458. rootUrl: rootUrl,
  1459. importOnlyMeshes: false,
  1460. arrayBuffers: []
  1461. };
  1462. // Parse
  1463. if (parsedData.extensionsUsed) {
  1464. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  1465. }
  1466. if (parsedData.buffers) {
  1467. parseBuffers(parsedData.buffers, gltfRuntime);
  1468. }
  1469. if (parsedData.bufferViews) {
  1470. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  1471. }
  1472. if (parsedData.accessors) {
  1473. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  1474. }
  1475. if (parsedData.meshes) {
  1476. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  1477. }
  1478. if (parsedData.lights) {
  1479. parseObject(parsedData.lights, "lights", gltfRuntime);
  1480. }
  1481. if (parsedData.cameras) {
  1482. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  1483. }
  1484. if (parsedData.nodes) {
  1485. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  1486. }
  1487. if (parsedData.images) {
  1488. parseObject(parsedData.images, "images", gltfRuntime);
  1489. }
  1490. if (parsedData.textures) {
  1491. parseObject(parsedData.textures, "textures", gltfRuntime);
  1492. }
  1493. if (parsedData.shaders) {
  1494. parseShaders(parsedData.shaders, gltfRuntime);
  1495. }
  1496. if (parsedData.programs) {
  1497. parseObject(parsedData.programs, "programs", gltfRuntime);
  1498. }
  1499. if (parsedData.samplers) {
  1500. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  1501. }
  1502. if (parsedData.techniques) {
  1503. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  1504. }
  1505. if (parsedData.materials) {
  1506. parseObject(parsedData.materials, "materials", gltfRuntime);
  1507. }
  1508. if (parsedData.animations) {
  1509. parseObject(parsedData.animations, "animations", gltfRuntime);
  1510. }
  1511. if (parsedData.skins) {
  1512. parseObject(parsedData.skins, "skins", gltfRuntime);
  1513. }
  1514. if (parsedData.scene && parsedData.scenes) {
  1515. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  1516. }
  1517. return gltfRuntime;
  1518. };
  1519. /**
  1520. * Private members
  1521. */
  1522. // None
  1523. /**
  1524. * Static members
  1525. */
  1526. GLTFFileLoader.MakeYUP = false;
  1527. GLTFFileLoader.HomogeneousCoordinates = false;
  1528. GLTFFileLoader.Extensions = [];
  1529. return GLTFFileLoader;
  1530. }());
  1531. BABYLON.GLTFFileLoader = GLTFFileLoader;
  1532. ;
  1533. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  1534. })(BABYLON || (BABYLON = {}));
  1535. var BABYLON;
  1536. (function (BABYLON) {
  1537. /**
  1538. * Utils functions for GLTF
  1539. */
  1540. var GLTFUtils = (function () {
  1541. function GLTFUtils() {
  1542. }
  1543. /**
  1544. * Sets the given "parameter" matrix
  1545. * @param scene: the {BABYLON.Scene} object
  1546. * @param source: the source node where to pick the matrix
  1547. * @param parameter: the GLTF technique parameter
  1548. * @param uniformName: the name of the shader's uniform
  1549. * @param shaderMaterial: the shader material
  1550. */
  1551. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  1552. var mat = null;
  1553. if (parameter.semantic === "MODEL") {
  1554. mat = source.getWorldMatrix();
  1555. }
  1556. else if (parameter.semantic === "PROJECTION") {
  1557. mat = scene.getProjectionMatrix();
  1558. }
  1559. else if (parameter.semantic === "VIEW") {
  1560. mat = scene.getViewMatrix();
  1561. }
  1562. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  1563. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  1564. }
  1565. else if (parameter.semantic === "MODELVIEW") {
  1566. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  1567. }
  1568. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  1569. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  1570. }
  1571. else if (parameter.semantic === "MODELINVERSE") {
  1572. mat = source.getWorldMatrix().invert();
  1573. }
  1574. else if (parameter.semantic === "VIEWINVERSE") {
  1575. mat = scene.getViewMatrix().invert();
  1576. }
  1577. else if (parameter.semantic === "PROJECTIONINVERSE") {
  1578. mat = scene.getProjectionMatrix().invert();
  1579. }
  1580. else if (parameter.semantic === "MODELVIEWINVERSE") {
  1581. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  1582. }
  1583. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  1584. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  1585. }
  1586. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  1587. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  1588. }
  1589. else {
  1590. debugger;
  1591. }
  1592. switch (parameter.type) {
  1593. case BABYLON.EParameterType.FLOAT_MAT2:
  1594. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  1595. break;
  1596. case BABYLON.EParameterType.FLOAT_MAT3:
  1597. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  1598. break;
  1599. case BABYLON.EParameterType.FLOAT_MAT4:
  1600. shaderMaterial.setMatrix(uniformName, mat);
  1601. break;
  1602. default: break;
  1603. }
  1604. };
  1605. /**
  1606. * Sets the given "parameter" matrix
  1607. * @param shaderMaterial: the shader material
  1608. * @param uniform: the name of the shader's uniform
  1609. * @param value: the value of the uniform
  1610. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  1611. */
  1612. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  1613. switch (type) {
  1614. case BABYLON.EParameterType.FLOAT:
  1615. shaderMaterial.setFloat(uniform, value);
  1616. return true;
  1617. case BABYLON.EParameterType.FLOAT_VEC2:
  1618. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  1619. return true;
  1620. case BABYLON.EParameterType.FLOAT_VEC3:
  1621. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  1622. return true;
  1623. case BABYLON.EParameterType.FLOAT_VEC4:
  1624. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  1625. return true;
  1626. default: return false;
  1627. }
  1628. };
  1629. /**
  1630. * If the uri is a base64 string
  1631. * @param uri: the uri to test
  1632. */
  1633. GLTFUtils.IsBase64 = function (uri) {
  1634. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  1635. };
  1636. /**
  1637. * Returns the wrap mode of the texture
  1638. * @param mode: the mode value
  1639. */
  1640. GLTFUtils.GetWrapMode = function (mode) {
  1641. switch (mode) {
  1642. case BABYLON.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  1643. case BABYLON.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  1644. case BABYLON.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1645. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1646. }
  1647. };
  1648. /**
  1649. * Loads a texture from its name
  1650. * @param gltfRuntime: the gltf runtime
  1651. * @param name: the name of the texture
  1652. */
  1653. GLTFUtils.LoadTexture = function (gltfRuntime, name) {
  1654. var texture = gltfRuntime.textures[name];
  1655. if (!texture || !texture.source) {
  1656. return null;
  1657. }
  1658. if (texture.babylonTexture) {
  1659. return texture.babylonTexture;
  1660. }
  1661. var sampler = gltfRuntime.samplers[texture.sampler];
  1662. var source = gltfRuntime.images[texture.source];
  1663. var newTexture = null;
  1664. var createMipMaps = (sampler.minFilter === BABYLON.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  1665. (sampler.minFilter === BABYLON.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  1666. (sampler.minFilter === BABYLON.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  1667. (sampler.minFilter === BABYLON.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  1668. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1669. if (GLTFUtils.IsBase64(source.uri)) {
  1670. newTexture = new BABYLON.Texture(source.uri, gltfRuntime.scene, !createMipMaps, true, samplingMode, null, null, source.uri, true);
  1671. }
  1672. else {
  1673. newTexture = new BABYLON.Texture(gltfRuntime.rootUrl + source.uri, gltfRuntime.scene, !createMipMaps, true, samplingMode);
  1674. }
  1675. newTexture.wrapU = GLTFUtils.GetWrapMode(sampler.wrapS);
  1676. newTexture.wrapV = GLTFUtils.GetWrapMode(sampler.wrapT);
  1677. newTexture.name = name;
  1678. texture.babylonTexture = newTexture;
  1679. return newTexture;
  1680. };
  1681. /**
  1682. * Returns the byte stride giving an accessor
  1683. * @param accessor: the GLTF accessor objet
  1684. */
  1685. GLTFUtils.GetByteStrideFromType = function (accessor) {
  1686. // Needs this function since "byteStride" isn't requiered in glTF format
  1687. var type = accessor.type;
  1688. switch (type) {
  1689. case "VEC2": return 2;
  1690. case "VEC3": return 3;
  1691. case "VEC4": return 4;
  1692. case "MAT2": return 4;
  1693. case "MAT3": return 9;
  1694. case "MAT4": return 16;
  1695. default: return 1;
  1696. }
  1697. };
  1698. /**
  1699. * Returns the texture filter mode giving a mode value
  1700. * @param mode: the filter mode value
  1701. */
  1702. GLTFUtils.GetTextureFilterMode = function (mode) {
  1703. switch (mode) {
  1704. case BABYLON.ETextureFilterType.LINEAR:
  1705. case BABYLON.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  1706. case BABYLON.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  1707. case BABYLON.ETextureFilterType.NEAREST:
  1708. case BABYLON.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  1709. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1710. }
  1711. };
  1712. /**
  1713. * Returns a buffer from its accessor
  1714. * @param gltfRuntime: the GLTF runtime
  1715. * @param accessor: the GLTF accessor
  1716. */
  1717. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  1718. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  1719. var arrayBuffer = gltfRuntime.arrayBuffers[bufferView.buffer];
  1720. var byteOffset = accessor.byteOffset + bufferView.byteOffset;
  1721. var count = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  1722. switch (accessor.componentType) {
  1723. case BABYLON.EComponentType.BYTE: return new Int8Array(arrayBuffer, byteOffset, count);
  1724. case BABYLON.EComponentType.UNSIGNED_BYTE: return new Uint8Array(arrayBuffer, byteOffset, count);
  1725. case BABYLON.EComponentType.SHORT: return new Int16Array(arrayBuffer, byteOffset, count);
  1726. case BABYLON.EComponentType.UNSIGNED_SHORT: return new Uint16Array(arrayBuffer, byteOffset, count);
  1727. default: return new Float32Array(arrayBuffer, byteOffset, count);
  1728. }
  1729. };
  1730. return GLTFUtils;
  1731. }());
  1732. BABYLON.GLTFUtils = GLTFUtils;
  1733. })(BABYLON || (BABYLON = {}));