babylon.glTFFileLoader.js 100 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192
  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. }
  604. var attributes = primitive.attributes;
  605. var accessor = null;
  606. var buffer = null;
  607. // Set positions, normal and uvs
  608. for (var semantic in attributes) {
  609. // Link accessor and buffer view
  610. accessor = gltfRuntime.accessors[attributes[semantic]];
  611. buffer = BABYLON.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  612. if (semantic === "NORMAL") {
  613. tempVertexData.normals = new Float32Array(buffer.length);
  614. tempVertexData.normals.set(buffer);
  615. }
  616. else if (semantic === "POSITION") {
  617. if (GLTFFileLoader.HomogeneousCoordinates) {
  618. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  619. for (var j = 0; j < buffer.length; j += 4) {
  620. tempVertexData.positions[j] = buffer[j];
  621. tempVertexData.positions[j + 1] = buffer[j + 1];
  622. tempVertexData.positions[j + 2] = buffer[j + 2];
  623. }
  624. }
  625. else {
  626. tempVertexData.positions = new Float32Array(buffer.length);
  627. tempVertexData.positions.set(buffer);
  628. }
  629. verticesCounts.push(tempVertexData.positions.length);
  630. }
  631. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  632. var channel = Number(semantic.split("_")[1]);
  633. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  634. var uvs = new Float32Array(buffer.length);
  635. uvs.set(buffer);
  636. normalizeUVs(uvs);
  637. tempVertexData.set(uvs, uvKind);
  638. }
  639. else if (semantic === "JOINT") {
  640. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  641. tempVertexData.matricesIndices.set(buffer);
  642. }
  643. else if (semantic === "WEIGHT") {
  644. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  645. tempVertexData.matricesWeights.set(buffer);
  646. }
  647. else if (semantic === "COLOR") {
  648. tempVertexData.colors = new Float32Array(buffer.length);
  649. tempVertexData.colors.set(buffer);
  650. }
  651. }
  652. // Indices
  653. accessor = gltfRuntime.accessors[primitive.indices];
  654. if (accessor) {
  655. buffer = BABYLON.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  656. tempVertexData.indices = new Int32Array(buffer.length);
  657. tempVertexData.indices.set(buffer);
  658. indexCounts.push(tempVertexData.indices.length);
  659. }
  660. else {
  661. // Set indices on the fly
  662. var indices = [];
  663. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  664. indices.push(j);
  665. }
  666. tempVertexData.indices = new Int32Array(indices);
  667. indexCounts.push(tempVertexData.indices.length);
  668. }
  669. vertexData.merge(tempVertexData);
  670. tempVertexData = undefined;
  671. // Sub material
  672. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  673. multiMat.subMaterials.push(material === null ? BABYLON.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material);
  674. // Update vertices start and index start
  675. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  676. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  677. }
  678. }
  679. // Apply geometry
  680. geometry.setAllVerticesData(vertexData, false);
  681. newMesh.computeWorldMatrix(true);
  682. // Apply submeshes
  683. newMesh.subMeshes = [];
  684. var index = 0;
  685. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  686. var meshID = meshes[meshIndex];
  687. var mesh = gltfRuntime.meshes[meshID];
  688. if (!mesh) {
  689. continue;
  690. }
  691. for (var i = 0; i < mesh.primitives.length; i++) {
  692. if (mesh.primitives[i].mode !== 4) {
  693. }
  694. var subMesh = new BABYLON.SubMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  695. index++;
  696. }
  697. }
  698. // Finish
  699. return newMesh;
  700. };
  701. /**
  702. * Configure node transformation from position, rotation and scaling
  703. */
  704. var configureNode = function (newNode, position, rotation, scaling) {
  705. if (newNode.position) {
  706. newNode.position = position;
  707. }
  708. if (newNode.rotationQuaternion || newNode.rotation) {
  709. newNode.rotationQuaternion = rotation;
  710. }
  711. if (newNode.scaling) {
  712. newNode.scaling = scaling;
  713. }
  714. };
  715. /**
  716. * Configures node from transformation matrix
  717. */
  718. var configureNodeFromMatrix = function (newNode, node, parent) {
  719. if (node.matrix) {
  720. var position = new BABYLON.Vector3(0, 0, 0);
  721. var rotation = new BABYLON.Quaternion();
  722. var scaling = new BABYLON.Vector3(0, 0, 0);
  723. var mat = BABYLON.Matrix.FromArray(node.matrix);
  724. mat.decompose(scaling, rotation, position);
  725. configureNode(newNode, position, rotation, scaling);
  726. }
  727. else {
  728. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  729. }
  730. newNode.computeWorldMatrix(true);
  731. };
  732. /**
  733. * Imports a node
  734. */
  735. var importNode = function (gltfRuntime, node, id, parent) {
  736. var lastNode = null;
  737. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  738. if (gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name) === -1) {
  739. return null;
  740. }
  741. }
  742. // Meshes
  743. if (node.skin) {
  744. if (node.meshes) {
  745. var skin = gltfRuntime.skins[node.skin];
  746. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  747. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  748. if (newMesh.skeleton === null) {
  749. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  750. if (!skin.babylonSkeleton) {
  751. skin.babylonSkeleton = newMesh.skeleton;
  752. }
  753. }
  754. lastNode = newMesh;
  755. }
  756. }
  757. else if (node.meshes) {
  758. /**
  759. * Improve meshes property
  760. */
  761. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  762. lastNode = newMesh;
  763. }
  764. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  765. var light = gltfRuntime.lights[node.light];
  766. if (light) {
  767. if (light.type === "ambient") {
  768. var ambienLight = light[light.type];
  769. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  770. hemiLight.name = node.name;
  771. if (ambienLight.color) {
  772. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  773. }
  774. lastNode = hemiLight;
  775. }
  776. else if (light.type === "directional") {
  777. var directionalLight = light[light.type];
  778. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  779. dirLight.name = node.name;
  780. if (directionalLight.color) {
  781. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  782. }
  783. lastNode = dirLight;
  784. }
  785. else if (light.type === "point") {
  786. var pointLight = light[light.type];
  787. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  788. ptLight.name = node.name;
  789. if (pointLight.color) {
  790. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  791. }
  792. lastNode = ptLight;
  793. }
  794. else if (light.type === "spot") {
  795. var spotLight = light[light.type];
  796. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  797. spLight.name = node.name;
  798. if (spotLight.color) {
  799. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  800. }
  801. if (spotLight.fallOfAngle) {
  802. spLight.angle = spotLight.fallOfAngle;
  803. }
  804. if (spotLight.fallOffExponent) {
  805. spLight.exponent = spotLight.fallOffExponent;
  806. }
  807. lastNode = spLight;
  808. }
  809. }
  810. }
  811. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  812. var camera = gltfRuntime.cameras[node.camera];
  813. if (camera) {
  814. if (camera.type === "orthographic") {
  815. var orthographicCamera = camera[camera.type];
  816. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  817. orthoCamera.name = node.name;
  818. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  819. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  820. lastNode = orthoCamera;
  821. }
  822. else if (camera.type === "perspective") {
  823. var perspectiveCamera = camera[camera.type];
  824. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  825. persCamera.name = node.name;
  826. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  827. if (!perspectiveCamera.aspectRatio) {
  828. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  829. }
  830. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  831. persCamera.maxZ = perspectiveCamera.zfar;
  832. persCamera.minZ = perspectiveCamera.znear;
  833. }
  834. lastNode = persCamera;
  835. }
  836. }
  837. }
  838. // Empty node
  839. if (!node.jointName) {
  840. if (node.babylonNode) {
  841. return node.babylonNode;
  842. }
  843. else if (lastNode === null) {
  844. var dummy = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  845. node.babylonNode = dummy;
  846. lastNode = dummy;
  847. }
  848. }
  849. if (lastNode !== null) {
  850. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  851. configureNodeFromMatrix(lastNode, node, parent);
  852. }
  853. else {
  854. var translation = node.translation || [0, 0, 0];
  855. var rotation = node.rotation || [0, 0, 0, 1];
  856. var scale = node.scale || [1, 1, 1];
  857. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.RotationAxis(BABYLON.Vector3.FromArray(rotation).normalize(), rotation[3]), BABYLON.Vector3.FromArray(scale));
  858. }
  859. lastNode.updateCache(true);
  860. node.babylonNode = lastNode;
  861. }
  862. return lastNode;
  863. };
  864. /**
  865. * Traverses nodes and creates them
  866. */
  867. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  868. var node = gltfRuntime.nodes[id];
  869. var newNode = null;
  870. if (gltfRuntime.importOnlyMeshes && !meshIncluded) {
  871. if (gltfRuntime.importMeshesNames.indexOf(node.name) !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  872. meshIncluded = true;
  873. }
  874. else {
  875. meshIncluded = false;
  876. }
  877. }
  878. else {
  879. meshIncluded = true;
  880. }
  881. if (!node.jointName && meshIncluded) {
  882. newNode = importNode(gltfRuntime, node, id, parent);
  883. if (newNode !== null) {
  884. newNode.id = id;
  885. newNode.parent = parent;
  886. }
  887. }
  888. if (node.children) {
  889. for (var i = 0; i < node.children.length; i++) {
  890. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  891. }
  892. }
  893. };
  894. /**
  895. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  896. */
  897. var postLoad = function (gltfRuntime) {
  898. // Nodes
  899. var currentScene = gltfRuntime.currentScene;
  900. if (currentScene) {
  901. for (var i = 0; i < currentScene.nodes.length; i++) {
  902. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  903. }
  904. }
  905. else {
  906. for (var thing in gltfRuntime.scenes) {
  907. currentScene = gltfRuntime.scenes[thing];
  908. for (var i = 0; i < currentScene.nodes.length; i++) {
  909. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  910. }
  911. }
  912. }
  913. // Set animations
  914. loadAnimations(gltfRuntime);
  915. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  916. var skeleton = gltfRuntime.scene.skeletons[i];
  917. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  918. }
  919. };
  920. /**
  921. * onBind shaderrs callback to set uniforms and matrices
  922. */
  923. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  924. var materialValues = material.values || technique.parameters;
  925. for (var unif in unTreatedUniforms) {
  926. var uniform = unTreatedUniforms[unif];
  927. var type = uniform.type;
  928. if (type === BABYLON.EParameterType.FLOAT_MAT2 || type === BABYLON.EParameterType.FLOAT_MAT3 || type === BABYLON.EParameterType.FLOAT_MAT4) {
  929. if (uniform.semantic && !uniform.source && !uniform.node) {
  930. BABYLON.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  931. }
  932. else if (uniform.semantic && (uniform.source || uniform.node)) {
  933. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node);
  934. if (source === null) {
  935. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node);
  936. }
  937. if (source === null) {
  938. continue;
  939. }
  940. BABYLON.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  941. }
  942. }
  943. else {
  944. var value = materialValues[technique.uniforms[unif]];
  945. if (!value) {
  946. continue;
  947. }
  948. if (type === BABYLON.EParameterType.SAMPLER_2D) {
  949. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  950. if (texture === null || texture === undefined) {
  951. continue;
  952. }
  953. shaderMaterial.getEffect().setTexture(unif, texture);
  954. }
  955. else {
  956. BABYLON.GLTFUtils.SetUniform(shaderMaterial.getEffect(), unif, value, type);
  957. }
  958. }
  959. }
  960. onSuccess(shaderMaterial);
  961. };
  962. /**
  963. * Prepare uniforms to send the only one time
  964. * Loads the appropriate textures
  965. */
  966. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  967. var materialValues = material.values || technique.parameters;
  968. var techniqueUniforms = technique.uniforms;
  969. /**
  970. * Prepare values here (not matrices)
  971. */
  972. for (var unif in unTreatedUniforms) {
  973. var uniform = unTreatedUniforms[unif];
  974. var type = uniform.type;
  975. var value = materialValues[techniqueUniforms[unif]];
  976. if (value === undefined) {
  977. // In case the value is the same for all materials
  978. value = uniform.value;
  979. }
  980. if (!value) {
  981. continue;
  982. }
  983. var onLoadTexture = function (uniformName) {
  984. return function (texture) {
  985. if (uniform.value) {
  986. // Static uniform
  987. shaderMaterial.setTexture(uniformName, texture);
  988. delete unTreatedUniforms[uniformName];
  989. }
  990. };
  991. };
  992. // Texture (sampler2D)
  993. if (type === BABYLON.EParameterType.SAMPLER_2D) {
  994. BABYLON.GLTFFileLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  995. }
  996. else {
  997. if (uniform.value && BABYLON.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  998. // Static uniform
  999. delete unTreatedUniforms[unif];
  1000. }
  1001. }
  1002. }
  1003. };
  1004. /**
  1005. * Shader compilation failed
  1006. */
  1007. var onShaderCompileError = function (program, shaderMaterial, onError) {
  1008. return function (effect, error) {
  1009. BABYLON.Tools.Error("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  1010. shaderMaterial.dispose(true);
  1011. onError();
  1012. };
  1013. };
  1014. /**
  1015. * Shader compilation success
  1016. */
  1017. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  1018. return function (_) {
  1019. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  1020. shaderMaterial.onBind = function (mesh) {
  1021. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  1022. };
  1023. };
  1024. };
  1025. /**
  1026. * Returns the appropriate uniform if already handled by babylon
  1027. */
  1028. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  1029. for (var unif in technique.uniforms) {
  1030. var uniform = technique.uniforms[unif];
  1031. var uniformParameter = technique.parameters[uniform];
  1032. if (tokenizer.currentIdentifier === unif) {
  1033. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  1034. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1035. if (transformIndex !== -1) {
  1036. delete unTreatedUniforms[unif];
  1037. return babylonTransforms[transformIndex];
  1038. }
  1039. }
  1040. }
  1041. }
  1042. return tokenizer.currentIdentifier;
  1043. };
  1044. /**
  1045. * All shaders loaded. Create materials one by one
  1046. */
  1047. var importMaterials = function (gltfRuntime) {
  1048. // Create materials
  1049. for (var mat in gltfRuntime.materials) {
  1050. BABYLON.GLTFFileLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  1051. }
  1052. };
  1053. /**
  1054. * Implementation of the base glTF spec
  1055. */
  1056. var GLTFFileLoaderBase = (function () {
  1057. function GLTFFileLoaderBase() {
  1058. }
  1059. GLTFFileLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  1060. var gltfRuntime = {
  1061. extensions: {},
  1062. accessors: {},
  1063. buffers: {},
  1064. bufferViews: {},
  1065. meshes: {},
  1066. lights: {},
  1067. cameras: {},
  1068. nodes: {},
  1069. images: {},
  1070. textures: {},
  1071. shaders: {},
  1072. programs: {},
  1073. samplers: {},
  1074. techniques: {},
  1075. materials: {},
  1076. animations: {},
  1077. skins: {},
  1078. extensionsUsed: [],
  1079. scenes: {},
  1080. buffersCount: 0,
  1081. shaderscount: 0,
  1082. scene: scene,
  1083. rootUrl: rootUrl,
  1084. loadedBufferCount: 0,
  1085. loadedBufferViews: {},
  1086. loadedShaderCount: 0,
  1087. importOnlyMeshes: false,
  1088. dummyNodes: []
  1089. };
  1090. // Parse
  1091. if (parsedData.extensions) {
  1092. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  1093. }
  1094. if (parsedData.extensionsUsed) {
  1095. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  1096. }
  1097. if (parsedData.buffers) {
  1098. parseBuffers(parsedData.buffers, gltfRuntime);
  1099. }
  1100. if (parsedData.bufferViews) {
  1101. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  1102. }
  1103. if (parsedData.accessors) {
  1104. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  1105. }
  1106. if (parsedData.meshes) {
  1107. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  1108. }
  1109. if (parsedData.lights) {
  1110. parseObject(parsedData.lights, "lights", gltfRuntime);
  1111. }
  1112. if (parsedData.cameras) {
  1113. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  1114. }
  1115. if (parsedData.nodes) {
  1116. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  1117. }
  1118. if (parsedData.images) {
  1119. parseObject(parsedData.images, "images", gltfRuntime);
  1120. }
  1121. if (parsedData.textures) {
  1122. parseObject(parsedData.textures, "textures", gltfRuntime);
  1123. }
  1124. if (parsedData.shaders) {
  1125. parseShaders(parsedData.shaders, gltfRuntime);
  1126. }
  1127. if (parsedData.programs) {
  1128. parseObject(parsedData.programs, "programs", gltfRuntime);
  1129. }
  1130. if (parsedData.samplers) {
  1131. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  1132. }
  1133. if (parsedData.techniques) {
  1134. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  1135. }
  1136. if (parsedData.materials) {
  1137. parseObject(parsedData.materials, "materials", gltfRuntime);
  1138. }
  1139. if (parsedData.animations) {
  1140. parseObject(parsedData.animations, "animations", gltfRuntime);
  1141. }
  1142. if (parsedData.skins) {
  1143. parseObject(parsedData.skins, "skins", gltfRuntime);
  1144. }
  1145. if (parsedData.scenes) {
  1146. gltfRuntime.scenes = parsedData.scenes;
  1147. }
  1148. if (parsedData.scene && parsedData.scenes) {
  1149. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  1150. }
  1151. return gltfRuntime;
  1152. };
  1153. GLTFFileLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1154. var buffer = gltfRuntime.buffers[id];
  1155. if (BABYLON.GLTFUtils.IsBase64(buffer.uri)) {
  1156. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.GLTFUtils.DecodeBase64(buffer.uri))); });
  1157. }
  1158. else {
  1159. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, null, null, true, onError);
  1160. }
  1161. };
  1162. GLTFFileLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1163. var texture = gltfRuntime.textures[id];
  1164. if (!texture || !texture.source) {
  1165. onError();
  1166. return;
  1167. }
  1168. if (texture.babylonTexture) {
  1169. onSuccess(null);
  1170. return;
  1171. }
  1172. var source = gltfRuntime.images[texture.source];
  1173. if (BABYLON.GLTFUtils.IsBase64(source.uri)) {
  1174. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.GLTFUtils.DecodeBase64(source.uri))); });
  1175. }
  1176. else {
  1177. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, null, null, true, onError);
  1178. }
  1179. };
  1180. GLTFFileLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1181. var texture = gltfRuntime.textures[id];
  1182. if (texture.babylonTexture) {
  1183. onSuccess(texture.babylonTexture);
  1184. return;
  1185. }
  1186. var sampler = gltfRuntime.samplers[texture.sampler];
  1187. var createMipMaps = (sampler.minFilter === BABYLON.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  1188. (sampler.minFilter === BABYLON.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  1189. (sampler.minFilter === BABYLON.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  1190. (sampler.minFilter === BABYLON.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  1191. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1192. var blob = new Blob([buffer]);
  1193. var blobURL = URL.createObjectURL(blob);
  1194. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  1195. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  1196. newTexture.wrapU = BABYLON.GLTFUtils.GetWrapMode(sampler.wrapS);
  1197. newTexture.wrapV = BABYLON.GLTFUtils.GetWrapMode(sampler.wrapT);
  1198. newTexture.name = id;
  1199. texture.babylonTexture = newTexture;
  1200. onSuccess(newTexture);
  1201. };
  1202. GLTFFileLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1203. var shader = gltfRuntime.shaders[id];
  1204. if (BABYLON.GLTFUtils.IsBase64(shader.uri)) {
  1205. var shaderString = atob(shader.uri.split(",")[1]);
  1206. onSuccess(shaderString);
  1207. }
  1208. else {
  1209. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, null, null, false, onError);
  1210. }
  1211. };
  1212. GLTFFileLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1213. var material = gltfRuntime.materials[id];
  1214. var technique = gltfRuntime.techniques[material.technique];
  1215. if (!technique) {
  1216. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  1217. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  1218. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1219. onSuccess(defaultMaterial);
  1220. return;
  1221. }
  1222. var program = gltfRuntime.programs[technique.program];
  1223. var states = technique.states;
  1224. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  1225. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  1226. var newVertexShader = "";
  1227. var newPixelShader = "";
  1228. var vertexTokenizer = new Tokenizer(vertexShader);
  1229. var pixelTokenizer = new Tokenizer(pixelShader);
  1230. var unTreatedUniforms = {};
  1231. var uniforms = [];
  1232. var attributes = [];
  1233. var samplers = [];
  1234. // Fill uniform, sampler2D and attributes
  1235. for (var unif in technique.uniforms) {
  1236. var uniform = technique.uniforms[unif];
  1237. var uniformParameter = technique.parameters[uniform];
  1238. unTreatedUniforms[unif] = uniformParameter;
  1239. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  1240. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1241. if (transformIndex !== -1) {
  1242. uniforms.push(babylonTransforms[transformIndex]);
  1243. delete unTreatedUniforms[unif];
  1244. }
  1245. else {
  1246. uniforms.push(unif);
  1247. }
  1248. }
  1249. else if (uniformParameter.type === BABYLON.EParameterType.SAMPLER_2D) {
  1250. samplers.push(unif);
  1251. }
  1252. else {
  1253. uniforms.push(unif);
  1254. }
  1255. }
  1256. for (var attr in technique.attributes) {
  1257. var attribute = technique.attributes[attr];
  1258. var attributeParameter = technique.parameters[attribute];
  1259. if (attributeParameter.semantic) {
  1260. attributes.push(getAttribute(attributeParameter));
  1261. }
  1262. }
  1263. // Configure vertex shader
  1264. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  1265. var tokenType = vertexTokenizer.currentToken;
  1266. if (tokenType !== ETokenType.IDENTIFIER) {
  1267. newVertexShader += vertexTokenizer.currentString;
  1268. continue;
  1269. }
  1270. var foundAttribute = false;
  1271. for (var attr in technique.attributes) {
  1272. var attribute = technique.attributes[attr];
  1273. var attributeParameter = technique.parameters[attribute];
  1274. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  1275. newVertexShader += getAttribute(attributeParameter);
  1276. foundAttribute = true;
  1277. break;
  1278. }
  1279. }
  1280. if (foundAttribute) {
  1281. continue;
  1282. }
  1283. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  1284. }
  1285. // Configure pixel shader
  1286. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  1287. var tokenType = pixelTokenizer.currentToken;
  1288. if (tokenType !== ETokenType.IDENTIFIER) {
  1289. newPixelShader += pixelTokenizer.currentString;
  1290. continue;
  1291. }
  1292. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  1293. }
  1294. // Create shader material
  1295. var shaderPath = {
  1296. vertex: program.vertexShader + id,
  1297. fragment: program.fragmentShader + id
  1298. };
  1299. var options = {
  1300. attributes: attributes,
  1301. uniforms: uniforms,
  1302. samplers: samplers,
  1303. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  1304. };
  1305. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  1306. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  1307. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  1308. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  1309. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  1310. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1311. if (states && states.functions) {
  1312. var functions = states.functions;
  1313. if (functions.cullFace && functions.cullFace[0] !== BABYLON.ECullingType.BACK) {
  1314. shaderMaterial.backFaceCulling = false;
  1315. }
  1316. var blendFunc = functions.blendFuncSeparate;
  1317. if (blendFunc) {
  1318. 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) {
  1319. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  1320. }
  1321. else if (blendFunc[0] === BABYLON.EBlendingFunction.ONE && blendFunc[1] === BABYLON.EBlendingFunction.ONE && blendFunc[2] === BABYLON.EBlendingFunction.ZERO && blendFunc[3] === BABYLON.EBlendingFunction.ONE) {
  1322. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  1323. }
  1324. else if (blendFunc[0] === BABYLON.EBlendingFunction.SRC_ALPHA && blendFunc[1] === BABYLON.EBlendingFunction.ONE && blendFunc[2] === BABYLON.EBlendingFunction.ZERO && blendFunc[3] === BABYLON.EBlendingFunction.ONE) {
  1325. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  1326. }
  1327. 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) {
  1328. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  1329. }
  1330. else if (blendFunc[0] === BABYLON.EBlendingFunction.DST_COLOR && blendFunc[1] === BABYLON.EBlendingFunction.ZERO && blendFunc[2] === BABYLON.EBlendingFunction.ONE && blendFunc[3] === BABYLON.EBlendingFunction.ONE) {
  1331. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  1332. }
  1333. 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) {
  1334. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  1335. }
  1336. }
  1337. }
  1338. };
  1339. return GLTFFileLoaderBase;
  1340. }());
  1341. BABYLON.GLTFFileLoaderBase = GLTFFileLoaderBase;
  1342. /**
  1343. * glTF File Loader Plugin
  1344. */
  1345. var GLTFFileLoader = (function () {
  1346. function GLTFFileLoader() {
  1347. /**
  1348. * Public members
  1349. */
  1350. this.extensions = {
  1351. ".gltf": { isBinary: false },
  1352. ".glb": { isBinary: true }
  1353. };
  1354. }
  1355. GLTFFileLoader.RegisterExtension = function (extension) {
  1356. if (GLTFFileLoader.Extensions[extension.name]) {
  1357. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  1358. return;
  1359. }
  1360. GLTFFileLoader.Extensions[extension.name] = extension;
  1361. };
  1362. /**
  1363. * Import meshes
  1364. */
  1365. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onError) {
  1366. var _this = this;
  1367. scene.useRightHandedSystem = true;
  1368. var gltfRuntime = BABYLON.GLTFFileLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1369. gltfRuntime.importOnlyMeshes = true;
  1370. if (meshesNames === "") {
  1371. gltfRuntime.importMeshesNames = [];
  1372. }
  1373. else if (typeof meshesNames === "string") {
  1374. gltfRuntime.importMeshesNames = [meshesNames];
  1375. }
  1376. else if (meshesNames && !(meshesNames instanceof Array)) {
  1377. gltfRuntime.importMeshesNames = [meshesNames];
  1378. }
  1379. else {
  1380. gltfRuntime.importMeshesNames = [];
  1381. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  1382. }
  1383. // Create nodes
  1384. _this._createNodes(gltfRuntime);
  1385. var meshes = [];
  1386. var skeletons = [];
  1387. // Fill arrays of meshes and skeletons
  1388. for (var nde in gltfRuntime.nodes) {
  1389. var node = gltfRuntime.nodes[nde];
  1390. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  1391. meshes.push(node.babylonNode);
  1392. }
  1393. }
  1394. for (var skl in gltfRuntime.skins) {
  1395. var skin = gltfRuntime.skins[skl];
  1396. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  1397. skeletons.push(skin.babylonSkeleton);
  1398. }
  1399. }
  1400. // Load buffers, shaders, materials, etc.
  1401. _this._loadBuffersAsync(gltfRuntime, function () {
  1402. _this._loadShadersAsync(gltfRuntime, function () {
  1403. importMaterials(gltfRuntime);
  1404. postLoad(gltfRuntime);
  1405. if (!GLTFFileLoader.IncrementalLoading && onSuccess) {
  1406. onSuccess(meshes, null, skeletons);
  1407. }
  1408. });
  1409. });
  1410. if (GLTFFileLoader.IncrementalLoading && onSuccess) {
  1411. onSuccess(meshes, null, skeletons);
  1412. }
  1413. }, onError);
  1414. return true;
  1415. };
  1416. /**
  1417. * Load scene
  1418. */
  1419. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onError) {
  1420. var _this = this;
  1421. scene.useRightHandedSystem = true;
  1422. BABYLON.GLTFFileLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1423. // Load runtime extensios
  1424. BABYLON.GLTFFileLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  1425. // Create nodes
  1426. _this._createNodes(gltfRuntime);
  1427. // Load buffers, shaders, materials, etc.
  1428. _this._loadBuffersAsync(gltfRuntime, function () {
  1429. _this._loadShadersAsync(gltfRuntime, function () {
  1430. importMaterials(gltfRuntime);
  1431. postLoad(gltfRuntime);
  1432. if (!GLTFFileLoader.IncrementalLoading) {
  1433. onSuccess();
  1434. }
  1435. });
  1436. });
  1437. if (GLTFFileLoader.IncrementalLoading) {
  1438. onSuccess();
  1439. }
  1440. }, onError);
  1441. }, onError);
  1442. return true;
  1443. };
  1444. GLTFFileLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  1445. var hasShaders = false;
  1446. var processShader = function (sha, shader) {
  1447. BABYLON.GLTFFileLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  1448. gltfRuntime.loadedShaderCount++;
  1449. if (shaderString) {
  1450. BABYLON.Effect.ShadersStore[sha + (shader.type === BABYLON.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  1451. }
  1452. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  1453. onload();
  1454. }
  1455. }, function () {
  1456. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  1457. });
  1458. };
  1459. for (var sha in gltfRuntime.shaders) {
  1460. hasShaders = true;
  1461. var shader = gltfRuntime.shaders[sha];
  1462. if (shader) {
  1463. processShader.bind(this, sha, shader)();
  1464. }
  1465. else {
  1466. BABYLON.Tools.Error("No shader named: " + sha);
  1467. }
  1468. }
  1469. if (!hasShaders) {
  1470. onload();
  1471. }
  1472. };
  1473. ;
  1474. GLTFFileLoader.prototype._loadBuffersAsync = function (gltfRuntime, onload) {
  1475. var hasBuffers = false;
  1476. var processBuffer = function (buf, buffer) {
  1477. BABYLON.GLTFFileLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  1478. gltfRuntime.loadedBufferCount++;
  1479. if (bufferView) {
  1480. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  1481. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  1482. }
  1483. gltfRuntime.loadedBufferViews[buf] = bufferView;
  1484. }
  1485. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  1486. onload();
  1487. }
  1488. }, function () {
  1489. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  1490. });
  1491. };
  1492. for (var buf in gltfRuntime.buffers) {
  1493. hasBuffers = true;
  1494. var buffer = gltfRuntime.buffers[buf];
  1495. if (buffer) {
  1496. processBuffer.bind(this, buf, buffer)();
  1497. }
  1498. else {
  1499. BABYLON.Tools.Error("No buffer named: " + buf);
  1500. }
  1501. }
  1502. if (!hasBuffers) {
  1503. onload();
  1504. }
  1505. };
  1506. // Creates nodes before loading buffers and shaders
  1507. GLTFFileLoader.prototype._createNodes = function (gltfRuntime) {
  1508. var currentScene = gltfRuntime.currentScene;
  1509. if (currentScene) {
  1510. // Only one scene even if multiple scenes are defined
  1511. for (var i = 0; i < currentScene.nodes.length; i++) {
  1512. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1513. }
  1514. }
  1515. else {
  1516. // Load all scenes
  1517. for (var thing in gltfRuntime.scenes) {
  1518. currentScene = gltfRuntime.scenes[thing];
  1519. for (var i = 0; i < currentScene.nodes.length; i++) {
  1520. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1521. }
  1522. }
  1523. }
  1524. };
  1525. return GLTFFileLoader;
  1526. }());
  1527. /**
  1528. * Private members
  1529. */
  1530. // None
  1531. /**
  1532. * Static members
  1533. */
  1534. GLTFFileLoader.HomogeneousCoordinates = false;
  1535. GLTFFileLoader.IncrementalLoading = true;
  1536. GLTFFileLoader.Extensions = {};
  1537. BABYLON.GLTFFileLoader = GLTFFileLoader;
  1538. ;
  1539. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  1540. })(BABYLON || (BABYLON = {}));
  1541. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  1542. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  1543. var BABYLON;
  1544. (function (BABYLON) {
  1545. /**
  1546. * Utils functions for GLTF
  1547. */
  1548. var GLTFUtils = (function () {
  1549. function GLTFUtils() {
  1550. }
  1551. /**
  1552. * Sets the given "parameter" matrix
  1553. * @param scene: the {BABYLON.Scene} object
  1554. * @param source: the source node where to pick the matrix
  1555. * @param parameter: the GLTF technique parameter
  1556. * @param uniformName: the name of the shader's uniform
  1557. * @param shaderMaterial: the shader material
  1558. */
  1559. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  1560. var mat = null;
  1561. if (parameter.semantic === "MODEL") {
  1562. mat = source.getWorldMatrix();
  1563. }
  1564. else if (parameter.semantic === "PROJECTION") {
  1565. mat = scene.getProjectionMatrix();
  1566. }
  1567. else if (parameter.semantic === "VIEW") {
  1568. mat = scene.getViewMatrix();
  1569. }
  1570. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  1571. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  1572. }
  1573. else if (parameter.semantic === "MODELVIEW") {
  1574. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  1575. }
  1576. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  1577. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  1578. }
  1579. else if (parameter.semantic === "MODELINVERSE") {
  1580. mat = source.getWorldMatrix().invert();
  1581. }
  1582. else if (parameter.semantic === "VIEWINVERSE") {
  1583. mat = scene.getViewMatrix().invert();
  1584. }
  1585. else if (parameter.semantic === "PROJECTIONINVERSE") {
  1586. mat = scene.getProjectionMatrix().invert();
  1587. }
  1588. else if (parameter.semantic === "MODELVIEWINVERSE") {
  1589. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  1590. }
  1591. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  1592. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  1593. }
  1594. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  1595. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  1596. }
  1597. else {
  1598. debugger;
  1599. }
  1600. switch (parameter.type) {
  1601. case BABYLON.EParameterType.FLOAT_MAT2:
  1602. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  1603. break;
  1604. case BABYLON.EParameterType.FLOAT_MAT3:
  1605. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  1606. break;
  1607. case BABYLON.EParameterType.FLOAT_MAT4:
  1608. shaderMaterial.setMatrix(uniformName, mat);
  1609. break;
  1610. default: break;
  1611. }
  1612. };
  1613. /**
  1614. * Sets the given "parameter" matrix
  1615. * @param shaderMaterial: the shader material
  1616. * @param uniform: the name of the shader's uniform
  1617. * @param value: the value of the uniform
  1618. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  1619. */
  1620. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  1621. switch (type) {
  1622. case BABYLON.EParameterType.FLOAT:
  1623. shaderMaterial.setFloat(uniform, value);
  1624. return true;
  1625. case BABYLON.EParameterType.FLOAT_VEC2:
  1626. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  1627. return true;
  1628. case BABYLON.EParameterType.FLOAT_VEC3:
  1629. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  1630. return true;
  1631. case BABYLON.EParameterType.FLOAT_VEC4:
  1632. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  1633. return true;
  1634. default: return false;
  1635. }
  1636. };
  1637. /**
  1638. * If the uri is a base64 string
  1639. * @param uri: the uri to test
  1640. */
  1641. GLTFUtils.IsBase64 = function (uri) {
  1642. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  1643. };
  1644. /**
  1645. * Decode the base64 uri
  1646. * @param uri: the uri to decode
  1647. */
  1648. GLTFUtils.DecodeBase64 = function (uri) {
  1649. var decodedString = atob(uri.split(",")[1]);
  1650. var bufferLength = decodedString.length;
  1651. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  1652. for (var i = 0; i < bufferLength; i++) {
  1653. bufferView[i] = decodedString.charCodeAt(i);
  1654. }
  1655. return bufferView.buffer;
  1656. };
  1657. /**
  1658. * Returns the wrap mode of the texture
  1659. * @param mode: the mode value
  1660. */
  1661. GLTFUtils.GetWrapMode = function (mode) {
  1662. switch (mode) {
  1663. case BABYLON.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  1664. case BABYLON.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  1665. case BABYLON.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1666. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1667. }
  1668. };
  1669. /**
  1670. * Returns the byte stride giving an accessor
  1671. * @param accessor: the GLTF accessor objet
  1672. */
  1673. GLTFUtils.GetByteStrideFromType = function (accessor) {
  1674. // Needs this function since "byteStride" isn't requiered in glTF format
  1675. var type = accessor.type;
  1676. switch (type) {
  1677. case "VEC2": return 2;
  1678. case "VEC3": return 3;
  1679. case "VEC4": return 4;
  1680. case "MAT2": return 4;
  1681. case "MAT3": return 9;
  1682. case "MAT4": return 16;
  1683. default: return 1;
  1684. }
  1685. };
  1686. /**
  1687. * Returns the texture filter mode giving a mode value
  1688. * @param mode: the filter mode value
  1689. */
  1690. GLTFUtils.GetTextureFilterMode = function (mode) {
  1691. switch (mode) {
  1692. case BABYLON.ETextureFilterType.LINEAR:
  1693. case BABYLON.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  1694. case BABYLON.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  1695. case BABYLON.ETextureFilterType.NEAREST:
  1696. case BABYLON.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  1697. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1698. }
  1699. };
  1700. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  1701. var byteOffset = bufferView.byteOffset + byteOffset;
  1702. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  1703. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  1704. throw new Error("Buffer access is out of range");
  1705. }
  1706. var buffer = loadedBufferView.buffer;
  1707. byteOffset += loadedBufferView.byteOffset;
  1708. switch (componentType) {
  1709. case BABYLON.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  1710. case BABYLON.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  1711. case BABYLON.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  1712. case BABYLON.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  1713. default: return new Float32Array(buffer, byteOffset, byteLength);
  1714. }
  1715. };
  1716. /**
  1717. * Returns a buffer from its accessor
  1718. * @param gltfRuntime: the GLTF runtime
  1719. * @param accessor: the GLTF accessor
  1720. */
  1721. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  1722. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  1723. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  1724. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  1725. };
  1726. /**
  1727. * Decodes a buffer view into a string
  1728. * @param view: the buffer view
  1729. */
  1730. GLTFUtils.DecodeBufferToText = function (view) {
  1731. var result = "";
  1732. var length = view.byteLength;
  1733. for (var i = 0; i < length; ++i) {
  1734. result += String.fromCharCode(view[i]);
  1735. }
  1736. return result;
  1737. };
  1738. /**
  1739. * Returns the default material of gltf. Related to
  1740. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  1741. * @param scene: the Babylon.js scene
  1742. */
  1743. GLTFUtils.GetDefaultMaterial = function (scene) {
  1744. if (!GLTFUtils._DefaultMaterial) {
  1745. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  1746. "precision highp float;",
  1747. "",
  1748. "uniform mat4 worldView;",
  1749. "uniform mat4 projection;",
  1750. "",
  1751. "attribute vec3 position;",
  1752. "",
  1753. "void main(void)",
  1754. "{",
  1755. " gl_Position = projection * worldView * vec4(position, 1.0);",
  1756. "}"
  1757. ].join("\n");
  1758. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  1759. "precision highp float;",
  1760. "",
  1761. "uniform vec4 u_emission;",
  1762. "",
  1763. "void main(void)",
  1764. "{",
  1765. " gl_FragColor = u_emission;",
  1766. "}"
  1767. ].join("\n");
  1768. var shaderPath = {
  1769. vertex: "GLTFDefaultMaterial",
  1770. fragment: "GLTFDefaultMaterial"
  1771. };
  1772. var options = {
  1773. attributes: ["position"],
  1774. uniforms: ["worldView", "projection", "u_emission"],
  1775. samplers: [],
  1776. needAlphaBlending: false
  1777. };
  1778. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  1779. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  1780. }
  1781. return GLTFUtils._DefaultMaterial;
  1782. };
  1783. return GLTFUtils;
  1784. }());
  1785. // The GLTF default material
  1786. GLTFUtils._DefaultMaterial = null;
  1787. BABYLON.GLTFUtils = GLTFUtils;
  1788. })(BABYLON || (BABYLON = {}));
  1789. //# sourceMappingURL=babylon.glTFFileLoaderUtils.js.map
  1790. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  1791. var BABYLON;
  1792. (function (BABYLON) {
  1793. var GLTFFileLoaderExtension = (function () {
  1794. function GLTFFileLoaderExtension(name) {
  1795. this._name = name;
  1796. }
  1797. Object.defineProperty(GLTFFileLoaderExtension.prototype, "name", {
  1798. get: function () {
  1799. return this._name;
  1800. },
  1801. enumerable: true,
  1802. configurable: true
  1803. });
  1804. /**
  1805. * Defines an override for loading the runtime
  1806. * Return true to stop further extensions from loading the runtime
  1807. */
  1808. GLTFFileLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  1809. return false;
  1810. };
  1811. /**
  1812. * Defines an onverride for creating gltf runtime
  1813. * Return true to stop further extensions from creating the runtime
  1814. */
  1815. GLTFFileLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  1816. return false;
  1817. };
  1818. /**
  1819. * Defines an override for loading buffers
  1820. * Return true to stop further extensions from loading this buffer
  1821. */
  1822. GLTFFileLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1823. return false;
  1824. };
  1825. /**
  1826. * Defines an override for loading texture buffers
  1827. * Return true to stop further extensions from loading this texture data
  1828. */
  1829. GLTFFileLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1830. return false;
  1831. };
  1832. /**
  1833. * Defines an override for creating textures
  1834. * Return true to stop further extensions from loading this texture
  1835. */
  1836. GLTFFileLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1837. return false;
  1838. };
  1839. /**
  1840. * Defines an override for loading shader strings
  1841. * Return true to stop further extensions from loading this shader data
  1842. */
  1843. GLTFFileLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1844. return false;
  1845. };
  1846. /**
  1847. * Defines an override for loading materials
  1848. * Return true to stop further extensions from loading this material
  1849. */
  1850. GLTFFileLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1851. return false;
  1852. };
  1853. // ---------
  1854. // Utilities
  1855. // ---------
  1856. GLTFFileLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  1857. GLTFFileLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1858. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  1859. }, function () {
  1860. setTimeout(function () {
  1861. onSuccess(BABYLON.GLTFFileLoaderBase.CreateRuntime(JSON.parse(data), scene, rootUrl));
  1862. });
  1863. });
  1864. };
  1865. GLTFFileLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  1866. GLTFFileLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1867. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  1868. }, function () {
  1869. setTimeout(function () {
  1870. onSuccess();
  1871. });
  1872. });
  1873. };
  1874. GLTFFileLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1875. GLTFFileLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1876. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError);
  1877. }, function () {
  1878. BABYLON.GLTFFileLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError);
  1879. });
  1880. };
  1881. GLTFFileLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  1882. GLTFFileLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFFileLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  1883. };
  1884. GLTFFileLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1885. GLTFFileLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1886. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  1887. }, function () {
  1888. BABYLON.GLTFFileLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  1889. });
  1890. };
  1891. GLTFFileLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1892. GLTFFileLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1893. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  1894. }, function () {
  1895. BABYLON.GLTFFileLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  1896. });
  1897. };
  1898. GLTFFileLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1899. GLTFFileLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1900. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  1901. }, function () {
  1902. BABYLON.GLTFFileLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  1903. });
  1904. };
  1905. GLTFFileLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1906. GLTFFileLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1907. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  1908. }, function () {
  1909. BABYLON.GLTFFileLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  1910. });
  1911. };
  1912. GLTFFileLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  1913. for (var extensionName in BABYLON.GLTFFileLoader.Extensions) {
  1914. var loaderExtension = BABYLON.GLTFFileLoader.Extensions[extensionName];
  1915. if (func(loaderExtension)) {
  1916. return;
  1917. }
  1918. }
  1919. defaultFunc();
  1920. };
  1921. return GLTFFileLoaderExtension;
  1922. }());
  1923. BABYLON.GLTFFileLoaderExtension = GLTFFileLoaderExtension;
  1924. })(BABYLON || (BABYLON = {}));
  1925. //# sourceMappingURL=babylon.glTFFileLoaderExtension.js.map
  1926. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  1927. var __extends = (this && this.__extends) || function (d, b) {
  1928. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  1929. function __() { this.constructor = d; }
  1930. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1931. };
  1932. var BABYLON;
  1933. (function (BABYLON) {
  1934. var BinaryExtensionBufferName = "binary_glTF";
  1935. var EContentFormat;
  1936. (function (EContentFormat) {
  1937. EContentFormat[EContentFormat["JSON"] = 0] = "JSON";
  1938. })(EContentFormat || (EContentFormat = {}));
  1939. ;
  1940. ;
  1941. ;
  1942. ;
  1943. var GLTFBinaryExtension = (function (_super) {
  1944. __extends(GLTFBinaryExtension, _super);
  1945. function GLTFBinaryExtension() {
  1946. return _super.call(this, "KHR_binary_glTF") || this;
  1947. }
  1948. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  1949. var _this = this;
  1950. if (!(data instanceof ArrayBuffer)) {
  1951. return false;
  1952. }
  1953. setTimeout(function () {
  1954. _this._binary = _this._parseBinary(data);
  1955. if (!_this._binary) {
  1956. onError();
  1957. return true;
  1958. }
  1959. var gltfRuntime = BABYLON.GLTFFileLoaderBase.CreateRuntime(_this._binary.content, scene, rootUrl);
  1960. if (gltfRuntime.extensionsUsed.indexOf(_this.name) === -1) {
  1961. BABYLON.Tools.Warn("glTF binary file does not have " + _this.name + " specified in extensionsUsed");
  1962. gltfRuntime.extensionsUsed.push(_this.name);
  1963. }
  1964. onSuccess(gltfRuntime);
  1965. });
  1966. return true;
  1967. };
  1968. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1969. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  1970. return false;
  1971. }
  1972. if (id !== BinaryExtensionBufferName) {
  1973. return false;
  1974. }
  1975. onSuccess(this._binary.body);
  1976. return true;
  1977. };
  1978. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1979. var texture = gltfRuntime.textures[id];
  1980. var source = gltfRuntime.images[texture.source];
  1981. if (!source.extensions || !(this.name in source.extensions)) {
  1982. return false;
  1983. }
  1984. var sourceExt = source.extensions[this.name];
  1985. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  1986. var buffer = BABYLON.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, BABYLON.EComponentType.UNSIGNED_BYTE);
  1987. onSuccess(buffer);
  1988. return true;
  1989. };
  1990. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1991. var shader = gltfRuntime.shaders[id];
  1992. if (!shader.extensions || !(this.name in shader.extensions)) {
  1993. return false;
  1994. }
  1995. var binaryExtensionShader = shader.extensions[this.name];
  1996. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  1997. var shaderBytes = BABYLON.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, BABYLON.EComponentType.UNSIGNED_BYTE);
  1998. setTimeout(function () {
  1999. var shaderString = BABYLON.GLTFUtils.DecodeBufferToText(shaderBytes);
  2000. onSuccess(shaderString);
  2001. });
  2002. return true;
  2003. };
  2004. // Parses a glTF binary array buffer into its content and body
  2005. GLTFBinaryExtension.prototype._parseBinary = function (data) {
  2006. var binaryReader = new BinaryReader(data);
  2007. var magic = BABYLON.GLTFUtils.DecodeBufferToText(binaryReader.getUint8Array(4));
  2008. if (magic != "glTF") {
  2009. BABYLON.Tools.Error("Unexpected magic: " + magic);
  2010. return null;
  2011. }
  2012. var version = binaryReader.getUint32();
  2013. if (version != 1) {
  2014. BABYLON.Tools.Error("Unsupported version: " + version);
  2015. return null;
  2016. }
  2017. var length = binaryReader.getUint32();
  2018. if (length != data.byteLength) {
  2019. BABYLON.Tools.Error("Length in header does not match actual data length: " + length + " != " + data.byteLength);
  2020. return null;
  2021. }
  2022. var contentLength = binaryReader.getUint32();
  2023. var contentFormat = binaryReader.getUint32();
  2024. var content;
  2025. switch (contentFormat) {
  2026. case EContentFormat.JSON:
  2027. var jsonText = BABYLON.GLTFUtils.DecodeBufferToText(binaryReader.getUint8Array(contentLength));
  2028. content = JSON.parse(jsonText);
  2029. break;
  2030. default:
  2031. BABYLON.Tools.Error("Unexpected content format: " + contentFormat);
  2032. return null;
  2033. }
  2034. var body = binaryReader.getUint8Array();
  2035. return {
  2036. content: content,
  2037. body: body
  2038. };
  2039. };
  2040. ;
  2041. return GLTFBinaryExtension;
  2042. }(BABYLON.GLTFFileLoaderExtension));
  2043. BABYLON.GLTFBinaryExtension = GLTFBinaryExtension;
  2044. var BinaryReader = (function () {
  2045. function BinaryReader(arrayBuffer) {
  2046. this._arrayBuffer = arrayBuffer;
  2047. this._dataView = new DataView(arrayBuffer);
  2048. this._byteOffset = 0;
  2049. }
  2050. BinaryReader.prototype.getUint32 = function () {
  2051. var value = this._dataView.getUint32(this._byteOffset, true);
  2052. this._byteOffset += 4;
  2053. return value;
  2054. };
  2055. BinaryReader.prototype.getUint8Array = function (length) {
  2056. if (!length) {
  2057. length = this._arrayBuffer.byteLength - this._byteOffset;
  2058. }
  2059. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  2060. this._byteOffset += length;
  2061. return value;
  2062. };
  2063. return BinaryReader;
  2064. }());
  2065. BABYLON.GLTFFileLoader.RegisterExtension(new GLTFBinaryExtension());
  2066. })(BABYLON || (BABYLON = {}));
  2067. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  2068. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  2069. var __extends = (this && this.__extends) || function (d, b) {
  2070. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  2071. function __() { this.constructor = d; }
  2072. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2073. };
  2074. var BABYLON;
  2075. (function (BABYLON) {
  2076. ;
  2077. ;
  2078. ;
  2079. var GLTFMaterialCommonExtension = (function (_super) {
  2080. __extends(GLTFMaterialCommonExtension, _super);
  2081. function GLTFMaterialCommonExtension() {
  2082. return _super.call(this, "KHR_materials_common") || this;
  2083. }
  2084. GLTFMaterialCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2085. if (!gltfRuntime.extensions)
  2086. return false;
  2087. var extension = gltfRuntime.extensions[this.name];
  2088. if (!extension)
  2089. return false;
  2090. // Create lights
  2091. var lights = extension.lights;
  2092. if (lights) {
  2093. for (var thing in lights) {
  2094. var light = lights[thing];
  2095. switch (light.type) {
  2096. case "ambient":
  2097. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  2098. var ambient = light.ambient;
  2099. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  2100. break;
  2101. case "point":
  2102. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  2103. var point = light.point;
  2104. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  2105. break;
  2106. case "directional":
  2107. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  2108. var directional = light.directional;
  2109. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  2110. break;
  2111. case "spot":
  2112. var spot = light.spot;
  2113. 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);
  2114. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  2115. break;
  2116. default:
  2117. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  2118. break;
  2119. }
  2120. }
  2121. }
  2122. return false;
  2123. };
  2124. GLTFMaterialCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2125. var material = gltfRuntime.materials[id];
  2126. if (!material || !material.extensions)
  2127. return false;
  2128. var extension = material.extensions[this.name];
  2129. if (!extension)
  2130. return false;
  2131. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  2132. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  2133. if (extension.technique === "CONSTANT") {
  2134. standardMaterial.disableLighting = true;
  2135. }
  2136. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  2137. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  2138. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  2139. // Ambient
  2140. if (typeof extension.values.ambient === "string") {
  2141. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  2142. }
  2143. else {
  2144. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  2145. }
  2146. // Diffuse
  2147. if (typeof extension.values.diffuse === "string") {
  2148. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  2149. }
  2150. else {
  2151. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  2152. }
  2153. // Emission
  2154. if (typeof extension.values.emission === "string") {
  2155. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  2156. }
  2157. else {
  2158. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  2159. }
  2160. // Specular
  2161. if (typeof extension.values.specular === "string") {
  2162. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  2163. }
  2164. else {
  2165. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  2166. }
  2167. return true;
  2168. };
  2169. GLTFMaterialCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  2170. // Create buffer from texture url
  2171. BABYLON.GLTFFileLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  2172. // Create texture from buffer
  2173. BABYLON.GLTFFileLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  2174. }, onError);
  2175. };
  2176. return GLTFMaterialCommonExtension;
  2177. }(BABYLON.GLTFFileLoaderExtension));
  2178. BABYLON.GLTFMaterialCommonExtension = GLTFMaterialCommonExtension;
  2179. BABYLON.GLTFFileLoader.RegisterExtension(new GLTFMaterialCommonExtension());
  2180. })(BABYLON || (BABYLON = {}));
  2181. //# sourceMappingURL=babylon.glTFMaterialCommonExtension.js.map