babylon.glTFFileLoader.js 100 KB

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