babylon.glTF1FileLoader.js 115 KB

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