babylon.glTF2FileLoader.js 111 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180
  1. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  2. var BABYLON;
  3. (function (BABYLON) {
  4. var GLTFLoaderCoordinateSystemMode;
  5. (function (GLTFLoaderCoordinateSystemMode) {
  6. // Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene (scene.useRightHandedSystem).
  7. // NOTE: When scene.useRightHandedSystem is false, an additional transform will be added to the root to transform the data from right-handed to left-handed.
  8. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  9. // The glTF right-handed data is not transformed in any form and is loaded directly.
  10. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["PASS_THROUGH"] = 1] = "PASS_THROUGH";
  11. // Sets the useRightHandedSystem flag on the scene.
  12. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 2] = "FORCE_RIGHT_HANDED";
  13. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  14. var GLTFFileLoader = /** @class */ (function () {
  15. function GLTFFileLoader() {
  16. // V2 options
  17. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  18. this.compileMaterials = false;
  19. this.compileShadowGenerators = false;
  20. this.useClipPlane = false;
  21. this.name = "gltf";
  22. this.extensions = {
  23. ".gltf": { isBinary: false },
  24. ".glb": { isBinary: true }
  25. };
  26. }
  27. GLTFFileLoader.prototype.dispose = function () {
  28. if (this._loader) {
  29. this._loader.dispose();
  30. }
  31. };
  32. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  33. try {
  34. var loaderData = GLTFFileLoader._parse(data);
  35. if (this.onParsed) {
  36. this.onParsed(loaderData);
  37. }
  38. this._loader = this._getLoader(loaderData);
  39. this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  40. }
  41. catch (e) {
  42. onError(e.message);
  43. }
  44. };
  45. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  46. try {
  47. var loaderData = GLTFFileLoader._parse(data);
  48. if (this.onParsed) {
  49. this.onParsed(loaderData);
  50. }
  51. this._loader = this._getLoader(loaderData);
  52. this._loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  53. }
  54. catch (e) {
  55. onError(e.message);
  56. }
  57. };
  58. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  59. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  60. };
  61. GLTFFileLoader.prototype.createPlugin = function () {
  62. return new GLTFFileLoader();
  63. };
  64. GLTFFileLoader._parse = function (data) {
  65. if (data instanceof ArrayBuffer) {
  66. return GLTFFileLoader._parseBinary(data);
  67. }
  68. return {
  69. json: JSON.parse(data),
  70. bin: null
  71. };
  72. };
  73. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  74. var loaderVersion = { major: 2, minor: 0 };
  75. var asset = loaderData.json.asset || {};
  76. var version = GLTFFileLoader._parseVersion(asset.version);
  77. if (!version) {
  78. throw new Error("Invalid version: " + asset.version);
  79. }
  80. if (asset.minVersion !== undefined) {
  81. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  82. if (!minVersion) {
  83. throw new Error("Invalid minimum version: " + asset.minVersion);
  84. }
  85. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  86. throw new Error("Incompatible minimum version: " + asset.minVersion);
  87. }
  88. }
  89. var createLoaders = {
  90. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  91. 2: GLTFFileLoader.CreateGLTFLoaderV2
  92. };
  93. var createLoader = createLoaders[version.major];
  94. if (!createLoader) {
  95. throw new Error("Unsupported version: " + asset.version);
  96. }
  97. return createLoader(this);
  98. };
  99. GLTFFileLoader._parseBinary = function (data) {
  100. var Binary = {
  101. Magic: 0x46546C67
  102. };
  103. var binaryReader = new BinaryReader(data);
  104. var magic = binaryReader.readUint32();
  105. if (magic !== Binary.Magic) {
  106. throw new Error("Unexpected magic: " + magic);
  107. }
  108. var version = binaryReader.readUint32();
  109. switch (version) {
  110. case 1: return GLTFFileLoader._parseV1(binaryReader);
  111. case 2: return GLTFFileLoader._parseV2(binaryReader);
  112. }
  113. throw new Error("Unsupported version: " + version);
  114. };
  115. GLTFFileLoader._parseV1 = function (binaryReader) {
  116. var ContentFormat = {
  117. JSON: 0
  118. };
  119. var length = binaryReader.readUint32();
  120. if (length != binaryReader.getLength()) {
  121. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  122. }
  123. var contentLength = binaryReader.readUint32();
  124. var contentFormat = binaryReader.readUint32();
  125. var content;
  126. switch (contentFormat) {
  127. case ContentFormat.JSON: {
  128. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  129. break;
  130. }
  131. default: {
  132. throw new Error("Unexpected content format: " + contentFormat);
  133. }
  134. }
  135. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  136. var body = binaryReader.readUint8Array(bytesRemaining);
  137. return {
  138. json: content,
  139. bin: body
  140. };
  141. };
  142. GLTFFileLoader._parseV2 = function (binaryReader) {
  143. var ChunkFormat = {
  144. JSON: 0x4E4F534A,
  145. BIN: 0x004E4942
  146. };
  147. var length = binaryReader.readUint32();
  148. if (length !== binaryReader.getLength()) {
  149. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  150. }
  151. // JSON chunk
  152. var chunkLength = binaryReader.readUint32();
  153. var chunkFormat = binaryReader.readUint32();
  154. if (chunkFormat !== ChunkFormat.JSON) {
  155. throw new Error("First chunk format is not JSON");
  156. }
  157. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  158. // Look for BIN chunk
  159. var bin = null;
  160. while (binaryReader.getPosition() < binaryReader.getLength()) {
  161. var chunkLength_1 = binaryReader.readUint32();
  162. var chunkFormat_1 = binaryReader.readUint32();
  163. switch (chunkFormat_1) {
  164. case ChunkFormat.JSON: {
  165. throw new Error("Unexpected JSON chunk");
  166. }
  167. case ChunkFormat.BIN: {
  168. bin = binaryReader.readUint8Array(chunkLength_1);
  169. break;
  170. }
  171. default: {
  172. // ignore unrecognized chunkFormat
  173. binaryReader.skipBytes(chunkLength_1);
  174. break;
  175. }
  176. }
  177. }
  178. return {
  179. json: json,
  180. bin: bin
  181. };
  182. };
  183. GLTFFileLoader._parseVersion = function (version) {
  184. var match = (version + "").match(/^(\d+)\.(\d+)$/);
  185. if (!match) {
  186. return null;
  187. }
  188. return {
  189. major: parseInt(match[1]),
  190. minor: parseInt(match[2])
  191. };
  192. };
  193. GLTFFileLoader._compareVersion = function (a, b) {
  194. if (a.major > b.major)
  195. return 1;
  196. if (a.major < b.major)
  197. return -1;
  198. if (a.minor > b.minor)
  199. return 1;
  200. if (a.minor < b.minor)
  201. return -1;
  202. return 0;
  203. };
  204. GLTFFileLoader._decodeBufferToText = function (buffer) {
  205. var result = "";
  206. var length = buffer.byteLength;
  207. for (var i = 0; i < length; i++) {
  208. result += String.fromCharCode(buffer[i]);
  209. }
  210. return result;
  211. };
  212. // V1 options
  213. GLTFFileLoader.HomogeneousCoordinates = false;
  214. GLTFFileLoader.IncrementalLoading = true;
  215. return GLTFFileLoader;
  216. }());
  217. BABYLON.GLTFFileLoader = GLTFFileLoader;
  218. var BinaryReader = /** @class */ (function () {
  219. function BinaryReader(arrayBuffer) {
  220. this._arrayBuffer = arrayBuffer;
  221. this._dataView = new DataView(arrayBuffer);
  222. this._byteOffset = 0;
  223. }
  224. BinaryReader.prototype.getPosition = function () {
  225. return this._byteOffset;
  226. };
  227. BinaryReader.prototype.getLength = function () {
  228. return this._arrayBuffer.byteLength;
  229. };
  230. BinaryReader.prototype.readUint32 = function () {
  231. var value = this._dataView.getUint32(this._byteOffset, true);
  232. this._byteOffset += 4;
  233. return value;
  234. };
  235. BinaryReader.prototype.readUint8Array = function (length) {
  236. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  237. this._byteOffset += length;
  238. return value;
  239. };
  240. BinaryReader.prototype.skipBytes = function (length) {
  241. this._byteOffset += length;
  242. };
  243. return BinaryReader;
  244. }());
  245. if (BABYLON.SceneLoader) {
  246. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  247. }
  248. })(BABYLON || (BABYLON = {}));
  249. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  250. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  251. var BABYLON;
  252. (function (BABYLON) {
  253. var GLTF2;
  254. (function (GLTF2) {
  255. /**
  256. * Enums
  257. */
  258. var EComponentType;
  259. (function (EComponentType) {
  260. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  261. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  262. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  263. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  264. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  265. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  266. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  267. var EMeshPrimitiveMode;
  268. (function (EMeshPrimitiveMode) {
  269. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  270. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  271. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  272. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  273. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  274. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  275. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  276. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  277. var ETextureMagFilter;
  278. (function (ETextureMagFilter) {
  279. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  280. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  281. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  282. var ETextureMinFilter;
  283. (function (ETextureMinFilter) {
  284. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  285. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  286. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  287. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  288. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  289. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  290. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  291. var ETextureWrapMode;
  292. (function (ETextureWrapMode) {
  293. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  294. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  295. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  296. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  297. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  298. })(BABYLON || (BABYLON = {}));
  299. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  300. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  301. var BABYLON;
  302. (function (BABYLON) {
  303. var GLTF2;
  304. (function (GLTF2) {
  305. var GLTFLoaderTracker = /** @class */ (function () {
  306. function GLTFLoaderTracker(onComplete) {
  307. this._pendingCount = 0;
  308. this._callback = onComplete;
  309. }
  310. GLTFLoaderTracker.prototype._addPendingData = function (data) {
  311. this._pendingCount++;
  312. };
  313. GLTFLoaderTracker.prototype._removePendingData = function (data) {
  314. if (--this._pendingCount === 0) {
  315. this._callback();
  316. }
  317. };
  318. return GLTFLoaderTracker;
  319. }());
  320. var GLTFLoader = /** @class */ (function () {
  321. function GLTFLoader(parent) {
  322. this._disposed = false;
  323. this._renderReady = false;
  324. this._requests = new Array();
  325. this._renderReadyObservable = new BABYLON.Observable();
  326. // Count of pending work that needs to complete before the asset is rendered.
  327. this._renderPendingCount = 0;
  328. // Count of pending work that needs to complete before the loader is disposed.
  329. this._loaderPendingCount = 0;
  330. this._loaderTrackers = new Array();
  331. this._parent = parent;
  332. if (!GLTFLoader._progressEventFactory) {
  333. if (typeof window["ProgressEvent"] === "function") {
  334. GLTFLoader._progressEventFactory = GLTFLoader._createProgressEventByConstructor;
  335. }
  336. else {
  337. GLTFLoader._progressEventFactory = GLTFLoader._createProgressEventByDocument;
  338. }
  339. }
  340. }
  341. GLTFLoader.RegisterExtension = function (extension) {
  342. if (GLTFLoader.Extensions[extension.name]) {
  343. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  344. return;
  345. }
  346. GLTFLoader.Extensions[extension.name] = extension;
  347. // Keep the order of registration so that extensions registered first are called first.
  348. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  349. };
  350. GLTFLoader._createProgressEventByConstructor = function (name, data) {
  351. return new ProgressEvent(name, data);
  352. };
  353. GLTFLoader._createProgressEventByDocument = function (name, data) {
  354. var event = document.createEvent("ProgressEvent");
  355. event.initProgressEvent(name, false, false, data.lengthComputable, data.loaded, data.total);
  356. return event;
  357. };
  358. GLTFLoader.prototype.dispose = function () {
  359. if (this._disposed) {
  360. return;
  361. }
  362. this._disposed = true;
  363. // Abort requests that are not complete
  364. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  365. var request = _a[_i];
  366. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  367. request.abort();
  368. }
  369. }
  370. // Revoke object urls created during load
  371. if (this._gltf.textures) {
  372. for (var _b = 0, _c = this._gltf.textures; _b < _c.length; _b++) {
  373. var texture = _c[_b];
  374. if (texture.url) {
  375. URL.revokeObjectURL(texture.url);
  376. }
  377. }
  378. }
  379. };
  380. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  381. var _this = this;
  382. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  383. onSuccess(_this._getMeshes(), [], _this._getSkeletons());
  384. }, onProgress, onError);
  385. };
  386. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  387. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  388. };
  389. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  390. var _this = this;
  391. this._tryCatchOnError(function () {
  392. _this._loadData(data);
  393. _this._babylonScene = scene;
  394. _this._rootUrl = rootUrl;
  395. _this._successCallback = onSuccess;
  396. _this._progressCallback = onProgress;
  397. _this._errorCallback = onError;
  398. _this._addPendingData(_this);
  399. _this._loadDefaultScene(nodeNames);
  400. _this._loadAnimations();
  401. _this._removePendingData(_this);
  402. });
  403. };
  404. GLTFLoader.prototype._onProgress = function () {
  405. if (!this._progressCallback) {
  406. return;
  407. }
  408. var loaded = 0;
  409. var total = 0;
  410. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  411. var request = _a[_i];
  412. if (!request._loaded || !request._total) {
  413. return;
  414. }
  415. loaded += request._loaded;
  416. total += request._total;
  417. }
  418. this._progressCallback(GLTFLoader._progressEventFactory("GLTFLoaderProgress", {
  419. lengthComputable: true,
  420. loaded: loaded,
  421. total: total
  422. }));
  423. };
  424. GLTFLoader.prototype._executeWhenRenderReady = function (func) {
  425. if (this._renderReady) {
  426. func();
  427. }
  428. else {
  429. this._renderReadyObservable.add(func);
  430. }
  431. };
  432. GLTFLoader.prototype._onRenderReady = function () {
  433. this._rootNode.babylonMesh.setEnabled(true);
  434. this._startAnimations();
  435. this._successCallback();
  436. this._renderReadyObservable.notifyObservers(this);
  437. };
  438. GLTFLoader.prototype._onComplete = function () {
  439. if (this._parent.onComplete) {
  440. this._parent.onComplete();
  441. }
  442. this.dispose();
  443. };
  444. GLTFLoader.prototype._loadData = function (data) {
  445. this._gltf = data.json;
  446. // Assign the index of each object for convinience.
  447. GLTFLoader._AssignIndices(this._gltf.accessors);
  448. GLTFLoader._AssignIndices(this._gltf.animations);
  449. GLTFLoader._AssignIndices(this._gltf.buffers);
  450. GLTFLoader._AssignIndices(this._gltf.bufferViews);
  451. GLTFLoader._AssignIndices(this._gltf.images);
  452. GLTFLoader._AssignIndices(this._gltf.materials);
  453. GLTFLoader._AssignIndices(this._gltf.meshes);
  454. GLTFLoader._AssignIndices(this._gltf.nodes);
  455. GLTFLoader._AssignIndices(this._gltf.scenes);
  456. GLTFLoader._AssignIndices(this._gltf.skins);
  457. GLTFLoader._AssignIndices(this._gltf.textures);
  458. if (data.bin) {
  459. var buffers = this._gltf.buffers;
  460. if (buffers && buffers[0] && !buffers[0].uri) {
  461. var binaryBuffer = buffers[0];
  462. if (binaryBuffer.byteLength != data.bin.byteLength) {
  463. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  464. }
  465. binaryBuffer.loadedData = data.bin;
  466. }
  467. else {
  468. BABYLON.Tools.Warn("Unexpected BIN chunk");
  469. }
  470. }
  471. };
  472. GLTFLoader.prototype._getMeshes = function () {
  473. var meshes = new Array();
  474. // Root mesh is always first.
  475. meshes.push(this._rootNode.babylonMesh);
  476. var nodes = this._gltf.nodes;
  477. if (nodes) {
  478. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  479. var node = nodes_1[_i];
  480. if (node.babylonMesh) {
  481. meshes.push(node.babylonMesh);
  482. }
  483. }
  484. }
  485. return meshes;
  486. };
  487. GLTFLoader.prototype._getSkeletons = function () {
  488. var skeletons = new Array();
  489. var skins = this._gltf.skins;
  490. if (skins) {
  491. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  492. var skin = skins_1[_i];
  493. if (skin.babylonSkeleton) {
  494. skeletons.push(skin.babylonSkeleton);
  495. }
  496. }
  497. }
  498. return skeletons;
  499. };
  500. GLTFLoader.prototype._getAnimationTargets = function () {
  501. var targets = new Array();
  502. var animations = this._gltf.animations;
  503. if (animations) {
  504. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  505. var animation = animations_1[_i];
  506. targets.push.apply(targets, animation.targets);
  507. }
  508. }
  509. return targets;
  510. };
  511. GLTFLoader.prototype._startAnimations = function () {
  512. for (var _i = 0, _a = this._getAnimationTargets(); _i < _a.length; _i++) {
  513. var target = _a[_i];
  514. this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true);
  515. }
  516. };
  517. GLTFLoader.prototype._loadDefaultScene = function (nodeNames) {
  518. var scene = GLTFLoader._GetProperty(this._gltf.scenes, this._gltf.scene || 0);
  519. if (!scene) {
  520. throw new Error("Failed to find scene " + (this._gltf.scene || 0));
  521. }
  522. this._loadScene("#/scenes/" + scene.index, scene, nodeNames);
  523. };
  524. GLTFLoader.prototype._loadScene = function (context, scene, nodeNames) {
  525. this._rootNode = { babylonMesh: new BABYLON.Mesh("__root__", this._babylonScene) };
  526. switch (this._parent.coordinateSystemMode) {
  527. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  528. if (!this._babylonScene.useRightHandedSystem) {
  529. this._rootNode.babylonMesh.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  530. this._rootNode.babylonMesh.scaling = new BABYLON.Vector3(1, 1, -1);
  531. }
  532. break;
  533. }
  534. case BABYLON.GLTFLoaderCoordinateSystemMode.PASS_THROUGH: {
  535. // do nothing
  536. break;
  537. }
  538. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  539. this._babylonScene.useRightHandedSystem = true;
  540. break;
  541. }
  542. default: {
  543. BABYLON.Tools.Error("Invalid coordinate system mode " + this._parent.coordinateSystemMode);
  544. return;
  545. }
  546. }
  547. if (this._parent.onMeshLoaded) {
  548. this._parent.onMeshLoaded(this._rootNode.babylonMesh);
  549. }
  550. var nodeIndices = scene.nodes;
  551. this._traverseNodes(context, nodeIndices, function (node, parentNode) {
  552. node.parent = parentNode;
  553. return true;
  554. }, this._rootNode);
  555. if (nodeNames) {
  556. if (!(nodeNames instanceof Array)) {
  557. nodeNames = [nodeNames];
  558. }
  559. var filteredNodeIndices_1 = new Array();
  560. this._traverseNodes(context, nodeIndices, function (node) {
  561. if (nodeNames.indexOf(node.name) !== -1) {
  562. filteredNodeIndices_1.push(node.index);
  563. return false;
  564. }
  565. return true;
  566. }, this._rootNode);
  567. nodeIndices = filteredNodeIndices_1;
  568. }
  569. for (var _i = 0, nodeIndices_1 = nodeIndices; _i < nodeIndices_1.length; _i++) {
  570. var index = nodeIndices_1[_i];
  571. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  572. if (!node) {
  573. throw new Error(context + ": Failed to find node " + index);
  574. }
  575. this._loadNode("#/nodes/" + index, node);
  576. }
  577. // Disable the root mesh until the asset is ready to render.
  578. this._rootNode.babylonMesh.setEnabled(false);
  579. };
  580. GLTFLoader.prototype._loadNode = function (context, node) {
  581. if (GLTF2.GLTFLoaderExtension.LoadNode(this, context, node)) {
  582. return;
  583. }
  584. node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  585. node.babylonMesh.hasVertexAlpha = true;
  586. this._loadTransform(node);
  587. if (node.mesh != null) {
  588. var mesh = GLTFLoader._GetProperty(this._gltf.meshes, node.mesh);
  589. if (!mesh) {
  590. throw new Error(context + ": Failed to find mesh " + node.mesh);
  591. }
  592. this._loadMesh("#/meshes/" + node.mesh, node, mesh);
  593. }
  594. node.babylonMesh.parent = node.parent ? node.parent.babylonMesh : null;
  595. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  596. node.babylonAnimationTargets.push(node.babylonMesh);
  597. if (node.skin != null) {
  598. var skin = GLTFLoader._GetProperty(this._gltf.skins, node.skin);
  599. if (!skin) {
  600. throw new Error(context + ": Failed to find skin " + node.skin);
  601. }
  602. node.babylonMesh.skeleton = this._loadSkin("#/skins/" + node.skin, skin);
  603. }
  604. if (node.camera != null) {
  605. // TODO: handle cameras
  606. }
  607. if (node.children) {
  608. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  609. var index = _a[_i];
  610. var childNode = GLTFLoader._GetProperty(this._gltf.nodes, index);
  611. if (!childNode) {
  612. throw new Error(context + ": Failed to find child node " + index);
  613. }
  614. this._loadNode("#/nodes/" + index, childNode);
  615. }
  616. }
  617. if (this._parent.onMeshLoaded) {
  618. this._parent.onMeshLoaded(node.babylonMesh);
  619. }
  620. };
  621. GLTFLoader.prototype._loadMesh = function (context, node, mesh) {
  622. var _this = this;
  623. var primitives = mesh.primitives;
  624. if (!primitives || primitives.length === 0) {
  625. throw new Error(context + ": Primitives are missing");
  626. }
  627. this._createMorphTargets(context, node, mesh);
  628. this._loadAllVertexDataAsync(context, mesh, function () {
  629. _this._loadMorphTargets(context, node, mesh);
  630. var vertexData = new BABYLON.VertexData();
  631. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  632. var primitive = primitives_1[_i];
  633. vertexData.merge(primitive.vertexData);
  634. }
  635. new BABYLON.Geometry(node.babylonMesh.name, _this._babylonScene, vertexData, false, node.babylonMesh);
  636. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  637. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  638. node.babylonMesh.subMeshes = [];
  639. var verticesStart = 0;
  640. var indicesStart = 0;
  641. for (var index = 0; index < primitives.length; index++) {
  642. var vertexData_1 = primitives[index].vertexData;
  643. var verticesCount = vertexData_1.positions.length;
  644. var indicesCount = vertexData_1.indices.length;
  645. BABYLON.SubMesh.AddToMesh(index, verticesStart, verticesCount, indicesStart, indicesCount, node.babylonMesh);
  646. verticesStart += verticesCount;
  647. indicesStart += indicesCount;
  648. }
  649. ;
  650. });
  651. var multiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, this._babylonScene);
  652. node.babylonMesh.material = multiMaterial;
  653. var subMaterials = multiMaterial.subMaterials;
  654. var _loop_1 = function (index) {
  655. var primitive = primitives[index];
  656. if (primitive.material == null) {
  657. subMaterials[index] = this_1._getDefaultMaterial();
  658. }
  659. else {
  660. var material = GLTFLoader._GetProperty(this_1._gltf.materials, primitive.material);
  661. if (!material) {
  662. throw new Error(context + ": Failed to find material " + primitive.material);
  663. }
  664. this_1._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  665. if (isNew && _this._parent.onMaterialLoaded) {
  666. _this._parent.onMaterialLoaded(babylonMaterial);
  667. }
  668. subMaterials[index] = babylonMaterial;
  669. });
  670. }
  671. };
  672. var this_1 = this;
  673. for (var index = 0; index < primitives.length; index++) {
  674. _loop_1(index);
  675. }
  676. ;
  677. };
  678. GLTFLoader.prototype._loadAllVertexDataAsync = function (context, mesh, onSuccess) {
  679. var primitives = mesh.primitives;
  680. var numRemainingPrimitives = primitives.length;
  681. var _loop_2 = function (index) {
  682. var primitive = primitives[index];
  683. this_2._loadVertexDataAsync(context + "/primitive/" + index, mesh, primitive, function (vertexData) {
  684. primitive.vertexData = vertexData;
  685. if (--numRemainingPrimitives === 0) {
  686. onSuccess();
  687. }
  688. });
  689. };
  690. var this_2 = this;
  691. for (var index = 0; index < primitives.length; index++) {
  692. _loop_2(index);
  693. }
  694. };
  695. /**
  696. * Converts a data bufferview into a Float4 Texture Coordinate Array, based on the accessor component type
  697. * @param {ArrayBufferView} data
  698. * @param {IGLTFAccessor} accessor
  699. */
  700. GLTFLoader.prototype._convertToFloat4TextureCoordArray = function (context, data, accessor) {
  701. if (accessor.componentType == GLTF2.EComponentType.FLOAT) {
  702. return data;
  703. }
  704. var buffer = data;
  705. var factor = 1;
  706. switch (accessor.componentType) {
  707. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  708. factor = 1 / 255;
  709. break;
  710. }
  711. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  712. factor = 1 / 65535;
  713. break;
  714. }
  715. default: {
  716. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  717. }
  718. }
  719. var result = new Float32Array(accessor.count * 2);
  720. for (var i = 0; i < result.length; ++i) {
  721. result[i] = buffer[i] * factor;
  722. }
  723. return result;
  724. };
  725. /**
  726. * Converts a data bufferview into a Float4 Color Array, based on the accessor component type
  727. * @param {ArrayBufferView} data
  728. * @param {IGLTFAccessor} accessor
  729. */
  730. GLTFLoader.prototype._convertToFloat4ColorArray = function (context, data, accessor) {
  731. var colorComponentCount = GLTFLoader._GetNumComponents(accessor.type);
  732. if (colorComponentCount === 4 && accessor.componentType === GLTF2.EComponentType.FLOAT) {
  733. return data;
  734. }
  735. var buffer = data;
  736. var factor = 1;
  737. switch (accessor.componentType) {
  738. case GLTF2.EComponentType.FLOAT: {
  739. factor = 1;
  740. break;
  741. }
  742. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  743. factor = 1 / 255;
  744. break;
  745. }
  746. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  747. factor = 1 / 65535;
  748. break;
  749. }
  750. default: {
  751. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  752. }
  753. }
  754. var result = new Float32Array(accessor.count * 4);
  755. if (colorComponentCount === 4) {
  756. for (var i = 0; i < result.length; ++i) {
  757. result[i] = buffer[i] * factor;
  758. }
  759. }
  760. else {
  761. var offset = 0;
  762. for (var i = 0; i < result.length; ++i) {
  763. if ((i + 1) % 4 === 0) {
  764. result[i] = 1;
  765. }
  766. else {
  767. result[i] = buffer[offset++] * factor;
  768. }
  769. }
  770. }
  771. return result;
  772. };
  773. GLTFLoader.prototype._loadVertexDataAsync = function (context, mesh, primitive, onSuccess) {
  774. var _this = this;
  775. var attributes = primitive.attributes;
  776. if (!attributes) {
  777. throw new Error(context + ": Attributes are missing");
  778. }
  779. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  780. // TODO: handle other primitive modes
  781. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  782. }
  783. var vertexData = new BABYLON.VertexData();
  784. var numRemainingAttributes = Object.keys(attributes).length;
  785. var _loop_3 = function (attribute) {
  786. var accessor = GLTFLoader._GetProperty(this_3._gltf.accessors, attributes[attribute]);
  787. if (!accessor) {
  788. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  789. }
  790. this_3._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  791. switch (attribute) {
  792. case "POSITION": {
  793. vertexData.positions = data;
  794. break;
  795. }
  796. case "NORMAL": {
  797. vertexData.normals = data;
  798. break;
  799. }
  800. case "TANGENT": {
  801. vertexData.tangents = data;
  802. break;
  803. }
  804. case "TEXCOORD_0": {
  805. vertexData.uvs = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  806. break;
  807. }
  808. case "TEXCOORD_1": {
  809. vertexData.uvs2 = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  810. break;
  811. }
  812. case "JOINTS_0": {
  813. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  814. break;
  815. }
  816. case "WEIGHTS_0": {
  817. //TODO: need to add support for normalized weights.
  818. vertexData.matricesWeights = data;
  819. break;
  820. }
  821. case "COLOR_0": {
  822. vertexData.colors = _this._convertToFloat4ColorArray(context, data, accessor);
  823. break;
  824. }
  825. default: {
  826. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  827. break;
  828. }
  829. }
  830. if (--numRemainingAttributes === 0) {
  831. if (primitive.indices == null) {
  832. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  833. for (var i = 0; i < vertexData.indices.length; i++) {
  834. vertexData.indices[i] = i;
  835. }
  836. onSuccess(vertexData);
  837. }
  838. else {
  839. var indicesAccessor = GLTFLoader._GetProperty(_this._gltf.accessors, primitive.indices);
  840. if (!indicesAccessor) {
  841. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  842. }
  843. _this._loadAccessorAsync("#/accessors/" + indicesAccessor.index, indicesAccessor, function (data) {
  844. vertexData.indices = data;
  845. onSuccess(vertexData);
  846. });
  847. }
  848. }
  849. });
  850. };
  851. var this_3 = this;
  852. for (var attribute in attributes) {
  853. _loop_3(attribute);
  854. }
  855. };
  856. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh) {
  857. var primitives = mesh.primitives;
  858. var targets = primitives[0].targets;
  859. if (!targets) {
  860. return;
  861. }
  862. for (var _i = 0, primitives_2 = primitives; _i < primitives_2.length; _i++) {
  863. var primitive = primitives_2[_i];
  864. if (!primitive.targets || primitive.targets.length != targets.length) {
  865. throw new Error(context + ": All primitives are required to list the same number of targets");
  866. }
  867. }
  868. var morphTargetManager = new BABYLON.MorphTargetManager();
  869. node.babylonMesh.morphTargetManager = morphTargetManager;
  870. for (var index = 0; index < targets.length; index++) {
  871. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  872. morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  873. }
  874. };
  875. GLTFLoader.prototype._loadMorphTargets = function (context, node, mesh) {
  876. var morphTargetManager = node.babylonMesh.morphTargetManager;
  877. if (!morphTargetManager) {
  878. return;
  879. }
  880. this._loadAllMorphTargetVertexDataAsync(context, node, mesh, function () {
  881. var numTargets = morphTargetManager.numTargets;
  882. for (var index = 0; index < numTargets; index++) {
  883. var vertexData = new BABYLON.VertexData();
  884. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  885. var primitive = _a[_i];
  886. vertexData.merge(primitive.targetsVertexData[index], { tangentLength: 3 });
  887. }
  888. if (!vertexData.positions) {
  889. throw new Error(context + ": Positions are missing");
  890. }
  891. var target = morphTargetManager.getTarget(index);
  892. target.setPositions(vertexData.positions);
  893. target.setNormals(vertexData.normals);
  894. target.setTangents(vertexData.tangents);
  895. }
  896. });
  897. };
  898. GLTFLoader.prototype._loadAllMorphTargetVertexDataAsync = function (context, node, mesh, onSuccess) {
  899. var numRemainingTargets = mesh.primitives.length * node.babylonMesh.morphTargetManager.numTargets;
  900. var _loop_4 = function (primitive) {
  901. var targets = primitive.targets;
  902. primitive.targetsVertexData = new Array(targets.length);
  903. var _loop_5 = function (index) {
  904. this_4._loadMorphTargetVertexDataAsync(context + "/targets/" + index, primitive.vertexData, targets[index], function (vertexData) {
  905. primitive.targetsVertexData[index] = vertexData;
  906. if (--numRemainingTargets === 0) {
  907. onSuccess();
  908. }
  909. });
  910. };
  911. for (var index = 0; index < targets.length; index++) {
  912. _loop_5(index);
  913. }
  914. };
  915. var this_4 = this;
  916. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  917. var primitive = _a[_i];
  918. _loop_4(primitive);
  919. }
  920. };
  921. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, vertexData, attributes, onSuccess) {
  922. var targetVertexData = new BABYLON.VertexData();
  923. var numRemainingAttributes = Object.keys(attributes).length;
  924. var _loop_6 = function (attribute) {
  925. var accessor = GLTFLoader._GetProperty(this_5._gltf.accessors, attributes[attribute]);
  926. if (!accessor) {
  927. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  928. }
  929. this_5._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  930. // glTF stores morph target information as deltas while babylon.js expects the final data.
  931. // As a result we have to add the original data to the delta to calculate the final data.
  932. var values = data;
  933. switch (attribute) {
  934. case "POSITION": {
  935. for (var i = 0; i < values.length; i++) {
  936. values[i] += vertexData.positions[i];
  937. }
  938. targetVertexData.positions = values;
  939. break;
  940. }
  941. case "NORMAL": {
  942. for (var i = 0; i < values.length; i++) {
  943. values[i] += vertexData.normals[i];
  944. }
  945. targetVertexData.normals = values;
  946. break;
  947. }
  948. case "TANGENT": {
  949. // Tangent data for morph targets is stored as xyz delta.
  950. // The vertexData.tangent is stored as xyzw.
  951. // So we need to skip every fourth vertexData.tangent.
  952. for (var i = 0, j = 0; i < values.length; i++, j++) {
  953. values[i] += vertexData.tangents[j];
  954. if ((i + 1) % 3 == 0) {
  955. j++;
  956. }
  957. }
  958. targetVertexData.tangents = values;
  959. break;
  960. }
  961. default: {
  962. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  963. break;
  964. }
  965. }
  966. if (--numRemainingAttributes === 0) {
  967. onSuccess(targetVertexData);
  968. }
  969. });
  970. };
  971. var this_5 = this;
  972. for (var attribute in attributes) {
  973. _loop_6(attribute);
  974. }
  975. };
  976. GLTFLoader.prototype._loadTransform = function (node) {
  977. var position = BABYLON.Vector3.Zero();
  978. var rotation = BABYLON.Quaternion.Identity();
  979. var scaling = BABYLON.Vector3.One();
  980. if (node.matrix) {
  981. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  982. matrix.decompose(scaling, rotation, position);
  983. }
  984. else {
  985. if (node.translation)
  986. position = BABYLON.Vector3.FromArray(node.translation);
  987. if (node.rotation)
  988. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  989. if (node.scale)
  990. scaling = BABYLON.Vector3.FromArray(node.scale);
  991. }
  992. node.babylonMesh.position = position;
  993. node.babylonMesh.rotationQuaternion = rotation;
  994. node.babylonMesh.scaling = scaling;
  995. };
  996. GLTFLoader.prototype._loadSkin = function (context, skin) {
  997. var _this = this;
  998. if (skin.babylonSkeleton) {
  999. return skin.babylonSkeleton;
  1000. }
  1001. var skeletonId = "skeleton" + skin.index;
  1002. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  1003. if (skin.inverseBindMatrices == null) {
  1004. this._loadBones(context, skin, null);
  1005. }
  1006. else {
  1007. var accessor = GLTFLoader._GetProperty(this._gltf.accessors, skin.inverseBindMatrices);
  1008. if (!accessor) {
  1009. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  1010. }
  1011. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  1012. _this._loadBones(context, skin, data);
  1013. });
  1014. }
  1015. return skin.babylonSkeleton;
  1016. };
  1017. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  1018. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  1019. node.babylonBones = node.babylonBones || {};
  1020. node.babylonBones[skin.index] = babylonBone;
  1021. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  1022. node.babylonAnimationTargets.push(babylonBone);
  1023. return babylonBone;
  1024. };
  1025. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatrixData) {
  1026. var babylonBones = {};
  1027. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  1028. var index = _a[_i];
  1029. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  1030. if (!node) {
  1031. throw new Error(context + ": Failed to find joint " + index);
  1032. }
  1033. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  1034. }
  1035. };
  1036. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  1037. var babylonBone = babylonBones[node.index];
  1038. if (babylonBone) {
  1039. return babylonBone;
  1040. }
  1041. var boneIndex = skin.joints.indexOf(node.index);
  1042. var baseMatrix = BABYLON.Matrix.Identity();
  1043. if (inverseBindMatrixData && boneIndex !== -1) {
  1044. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  1045. baseMatrix.invertToRef(baseMatrix);
  1046. }
  1047. var babylonParentBone = null;
  1048. if (node.index !== skin.skeleton && node.parent && node.parent !== this._rootNode) {
  1049. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  1050. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  1051. }
  1052. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  1053. babylonBones[node.index] = babylonBone;
  1054. return babylonBone;
  1055. };
  1056. GLTFLoader.prototype._getNodeMatrix = function (node) {
  1057. return node.matrix ?
  1058. BABYLON.Matrix.FromArray(node.matrix) :
  1059. BABYLON.Matrix.Compose(node.scale ? BABYLON.Vector3.FromArray(node.scale) : BABYLON.Vector3.One(), node.rotation ? BABYLON.Quaternion.FromArray(node.rotation) : BABYLON.Quaternion.Identity(), node.translation ? BABYLON.Vector3.FromArray(node.translation) : BABYLON.Vector3.Zero());
  1060. };
  1061. GLTFLoader.prototype._traverseNodes = function (context, indices, action, parentNode) {
  1062. if (parentNode === void 0) { parentNode = null; }
  1063. for (var _i = 0, indices_1 = indices; _i < indices_1.length; _i++) {
  1064. var index = indices_1[_i];
  1065. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  1066. if (!node) {
  1067. throw new Error(context + ": Failed to find node " + index);
  1068. }
  1069. this._traverseNode(context, node, action, parentNode);
  1070. }
  1071. };
  1072. GLTFLoader.prototype._traverseNode = function (context, node, action, parentNode) {
  1073. if (parentNode === void 0) { parentNode = null; }
  1074. if (GLTF2.GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  1075. return;
  1076. }
  1077. if (!action(node, parentNode)) {
  1078. return;
  1079. }
  1080. if (node.children) {
  1081. this._traverseNodes(context, node.children, action, node);
  1082. }
  1083. };
  1084. GLTFLoader.prototype._loadAnimations = function () {
  1085. var animations = this._gltf.animations;
  1086. if (!animations) {
  1087. return;
  1088. }
  1089. for (var index = 0; index < animations.length; index++) {
  1090. var animation = animations[index];
  1091. this._loadAnimation("#/animations/" + index, animation);
  1092. }
  1093. };
  1094. GLTFLoader.prototype._loadAnimation = function (context, animation) {
  1095. animation.targets = [];
  1096. for (var index = 0; index < animation.channels.length; index++) {
  1097. var channel = GLTFLoader._GetProperty(animation.channels, index);
  1098. if (!channel) {
  1099. throw new Error(context + ": Failed to find channel " + index);
  1100. }
  1101. var sampler = GLTFLoader._GetProperty(animation.samplers, channel.sampler);
  1102. if (!sampler) {
  1103. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  1104. }
  1105. this._loadAnimationChannel(animation, context + "/channels/" + index, channel, context + "/samplers/" + channel.sampler, sampler);
  1106. }
  1107. };
  1108. GLTFLoader.prototype._loadAnimationChannel = function (animation, channelContext, channel, samplerContext, sampler) {
  1109. var targetNode = GLTFLoader._GetProperty(this._gltf.nodes, channel.target.node);
  1110. if (!targetNode) {
  1111. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  1112. }
  1113. var targetPath;
  1114. var animationType;
  1115. switch (channel.target.path) {
  1116. case "translation": {
  1117. targetPath = "position";
  1118. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  1119. break;
  1120. }
  1121. case "rotation": {
  1122. targetPath = "rotationQuaternion";
  1123. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  1124. break;
  1125. }
  1126. case "scale": {
  1127. targetPath = "scaling";
  1128. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  1129. break;
  1130. }
  1131. case "weights": {
  1132. targetPath = "influence";
  1133. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  1134. break;
  1135. }
  1136. default: {
  1137. throw new Error(channelContext + ": Invalid target path " + channel.target.path);
  1138. }
  1139. }
  1140. var inputData;
  1141. var outputData;
  1142. var checkSuccess = function () {
  1143. if (!inputData || !outputData) {
  1144. return;
  1145. }
  1146. var outputBufferOffset = 0;
  1147. var getNextOutputValue;
  1148. switch (targetPath) {
  1149. case "position": {
  1150. getNextOutputValue = function () {
  1151. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  1152. outputBufferOffset += 3;
  1153. return value;
  1154. };
  1155. break;
  1156. }
  1157. case "rotationQuaternion": {
  1158. getNextOutputValue = function () {
  1159. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  1160. outputBufferOffset += 4;
  1161. return value;
  1162. };
  1163. break;
  1164. }
  1165. case "scaling": {
  1166. getNextOutputValue = function () {
  1167. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  1168. outputBufferOffset += 3;
  1169. return value;
  1170. };
  1171. break;
  1172. }
  1173. case "influence": {
  1174. getNextOutputValue = function () {
  1175. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  1176. var value = new Array(numTargets);
  1177. for (var i = 0; i < numTargets; i++) {
  1178. value[i] = outputData[outputBufferOffset++];
  1179. }
  1180. return value;
  1181. };
  1182. break;
  1183. }
  1184. }
  1185. var getNextKey;
  1186. switch (sampler.interpolation) {
  1187. case "LINEAR": {
  1188. getNextKey = function (frameIndex) { return ({
  1189. frame: inputData[frameIndex],
  1190. value: getNextOutputValue()
  1191. }); };
  1192. break;
  1193. }
  1194. case "CUBICSPLINE": {
  1195. getNextKey = function (frameIndex) { return ({
  1196. frame: inputData[frameIndex],
  1197. inTangent: getNextOutputValue(),
  1198. value: getNextOutputValue(),
  1199. outTangent: getNextOutputValue()
  1200. }); };
  1201. break;
  1202. }
  1203. default: {
  1204. throw new Error(samplerContext + ": Invalid interpolation " + sampler.interpolation);
  1205. }
  1206. }
  1207. ;
  1208. var keys;
  1209. if (inputData.length === 1) {
  1210. var key = getNextKey(0);
  1211. keys = [
  1212. { frame: key.frame, value: key.value },
  1213. { frame: key.frame + 1, value: key.value }
  1214. ];
  1215. }
  1216. else {
  1217. keys = new Array(inputData.length);
  1218. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  1219. keys[frameIndex] = getNextKey(frameIndex);
  1220. }
  1221. }
  1222. if (targetPath === "influence") {
  1223. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  1224. var _loop_7 = function (targetIndex) {
  1225. var morphTarget = morphTargetManager.getTarget(targetIndex);
  1226. var animationName = (animation.name || "anim" + animation.index) + "_" + targetIndex;
  1227. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  1228. babylonAnimation.setKeys(keys.map(function (key) { return ({
  1229. frame: key.frame,
  1230. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  1231. value: key.value[targetIndex],
  1232. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  1233. }); }));
  1234. morphTarget.animations.push(babylonAnimation);
  1235. animation.targets.push(morphTarget);
  1236. };
  1237. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  1238. _loop_7(targetIndex);
  1239. }
  1240. }
  1241. else {
  1242. var animationName = animation.name || "anim" + animation.index;
  1243. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  1244. babylonAnimation.setKeys(keys);
  1245. if (targetNode.babylonAnimationTargets) {
  1246. for (var _i = 0, _a = targetNode.babylonAnimationTargets; _i < _a.length; _i++) {
  1247. var target = _a[_i];
  1248. target.animations.push(babylonAnimation.clone());
  1249. animation.targets.push(target);
  1250. }
  1251. }
  1252. }
  1253. };
  1254. var inputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.input);
  1255. if (!inputAccessor) {
  1256. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  1257. }
  1258. this._loadAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor, function (data) {
  1259. inputData = data;
  1260. checkSuccess();
  1261. });
  1262. var outputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.output);
  1263. if (!outputAccessor) {
  1264. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  1265. }
  1266. this._loadAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor, function (data) {
  1267. outputData = data;
  1268. checkSuccess();
  1269. });
  1270. };
  1271. GLTFLoader.prototype._loadBufferAsync = function (context, buffer, onSuccess) {
  1272. var _this = this;
  1273. this._addPendingData(buffer);
  1274. if (buffer.loadedData) {
  1275. onSuccess(buffer.loadedData);
  1276. this._removePendingData(buffer);
  1277. }
  1278. else if (buffer.loadedObservable) {
  1279. buffer.loadedObservable.add(function (buffer) {
  1280. onSuccess(buffer.loadedData);
  1281. _this._removePendingData(buffer);
  1282. });
  1283. }
  1284. else {
  1285. if (!buffer.uri) {
  1286. throw new Error(context + ": Uri is missing");
  1287. }
  1288. buffer.loadedObservable = new BABYLON.Observable();
  1289. buffer.loadedObservable.add(function (buffer) {
  1290. onSuccess(buffer.loadedData);
  1291. _this._removePendingData(buffer);
  1292. });
  1293. this._loadUriAsync(context, buffer.uri, function (data) {
  1294. buffer.loadedData = data;
  1295. buffer.loadedObservable.notifyObservers(buffer);
  1296. buffer.loadedObservable = undefined;
  1297. });
  1298. }
  1299. };
  1300. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView, onSuccess) {
  1301. var buffer = GLTFLoader._GetProperty(this._gltf.buffers, bufferView.buffer);
  1302. if (!buffer) {
  1303. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  1304. }
  1305. this._loadBufferAsync("#/buffers/" + buffer.index, buffer, function (bufferData) {
  1306. var data;
  1307. try {
  1308. data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  1309. }
  1310. catch (e) {
  1311. throw new Error(context + ": " + e.message);
  1312. }
  1313. onSuccess(data);
  1314. });
  1315. };
  1316. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor, onSuccess) {
  1317. var _this = this;
  1318. if (accessor.sparse) {
  1319. throw new Error(context + ": Sparse accessors are not currently supported");
  1320. }
  1321. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, accessor.bufferView);
  1322. if (!bufferView) {
  1323. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  1324. }
  1325. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, function (bufferViewData) {
  1326. var numComponents = GLTFLoader._GetNumComponents(accessor.type);
  1327. if (numComponents === 0) {
  1328. throw new Error(context + ": Invalid type " + accessor.type);
  1329. }
  1330. var data;
  1331. var byteOffset = accessor.byteOffset || 0;
  1332. var byteStride = bufferView.byteStride;
  1333. try {
  1334. switch (accessor.componentType) {
  1335. case GLTF2.EComponentType.BYTE: {
  1336. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  1337. break;
  1338. }
  1339. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  1340. data = _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  1341. break;
  1342. }
  1343. case GLTF2.EComponentType.SHORT: {
  1344. data = _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  1345. break;
  1346. }
  1347. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  1348. data = _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  1349. break;
  1350. }
  1351. case GLTF2.EComponentType.UNSIGNED_INT: {
  1352. data = _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  1353. break;
  1354. }
  1355. case GLTF2.EComponentType.FLOAT: {
  1356. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  1357. break;
  1358. }
  1359. default: {
  1360. throw new Error(context + ": Invalid component type " + accessor.componentType);
  1361. }
  1362. }
  1363. }
  1364. catch (e) {
  1365. throw new Error(context + ": " + e);
  1366. }
  1367. onSuccess(data);
  1368. });
  1369. };
  1370. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  1371. byteOffset += data.byteOffset;
  1372. var targetLength = count * numComponents;
  1373. if (byteStride == null || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  1374. return new typedArray(data.buffer, byteOffset, targetLength);
  1375. }
  1376. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  1377. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  1378. var targetBuffer = new typedArray(targetLength);
  1379. var sourceIndex = 0;
  1380. var targetIndex = 0;
  1381. while (targetIndex < targetLength) {
  1382. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  1383. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  1384. targetIndex++;
  1385. }
  1386. sourceIndex += elementStride;
  1387. }
  1388. return targetBuffer;
  1389. };
  1390. GLTFLoader.prototype._addPendingData = function (data) {
  1391. if (!this._renderReady) {
  1392. this._renderPendingCount++;
  1393. }
  1394. this._addLoaderPendingData(data);
  1395. };
  1396. GLTFLoader.prototype._removePendingData = function (data) {
  1397. var _this = this;
  1398. if (!this._renderReady) {
  1399. if (--this._renderPendingCount === 0) {
  1400. this._addLoaderPendingData(this);
  1401. this._compileMaterialsAsync(function () {
  1402. _this._compileShadowGeneratorsAsync(function () {
  1403. _this._removeLoaderPendingData(_this);
  1404. _this._renderReady = true;
  1405. _this._onRenderReady();
  1406. });
  1407. });
  1408. }
  1409. }
  1410. this._removeLoaderPendingData(data);
  1411. };
  1412. GLTFLoader.prototype._addLoaderPendingData = function (data) {
  1413. this._loaderPendingCount++;
  1414. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  1415. var tracker = _a[_i];
  1416. tracker._addPendingData(data);
  1417. }
  1418. };
  1419. GLTFLoader.prototype._removeLoaderPendingData = function (data) {
  1420. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  1421. var tracker = _a[_i];
  1422. tracker._removePendingData(data);
  1423. }
  1424. if (--this._loaderPendingCount === 0) {
  1425. this._onComplete();
  1426. }
  1427. };
  1428. GLTFLoader.prototype._whenAction = function (action, onComplete) {
  1429. var _this = this;
  1430. var tracker = new GLTFLoaderTracker(function () {
  1431. _this._loaderTrackers.splice(_this._loaderTrackers.indexOf(tracker), 1);
  1432. onComplete();
  1433. });
  1434. this._loaderTrackers.push(tracker);
  1435. this._addLoaderPendingData(tracker);
  1436. action();
  1437. this._removeLoaderPendingData(tracker);
  1438. };
  1439. GLTFLoader.prototype._getDefaultMaterial = function () {
  1440. if (!this._defaultMaterial) {
  1441. var id = "__gltf_default";
  1442. var material = this._babylonScene.getMaterialByName(id);
  1443. if (!material) {
  1444. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  1445. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1446. material.metallic = 1;
  1447. material.roughness = 1;
  1448. }
  1449. this._defaultMaterial = material;
  1450. }
  1451. return this._defaultMaterial;
  1452. };
  1453. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (context, material) {
  1454. var babylonMaterial = material.babylonMaterial;
  1455. // Ensure metallic workflow
  1456. babylonMaterial.metallic = 1;
  1457. babylonMaterial.roughness = 1;
  1458. var properties = material.pbrMetallicRoughness;
  1459. if (!properties) {
  1460. return;
  1461. }
  1462. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  1463. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  1464. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  1465. if (properties.baseColorTexture) {
  1466. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.baseColorTexture.index);
  1467. if (!texture) {
  1468. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  1469. }
  1470. babylonMaterial.albedoTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.baseColorTexture.texCoord);
  1471. }
  1472. if (properties.metallicRoughnessTexture) {
  1473. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.metallicRoughnessTexture.index);
  1474. if (!texture) {
  1475. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  1476. }
  1477. babylonMaterial.metallicTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.metallicRoughnessTexture.texCoord);
  1478. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  1479. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  1480. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  1481. }
  1482. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  1483. };
  1484. GLTFLoader.prototype._loadMaterial = function (context, material, assign) {
  1485. if (material.babylonMaterial) {
  1486. assign(material.babylonMaterial, false);
  1487. return;
  1488. }
  1489. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  1490. return;
  1491. }
  1492. this._createPbrMaterial(material);
  1493. this._loadMaterialBaseProperties(context, material);
  1494. this._loadMaterialMetallicRoughnessProperties(context, material);
  1495. assign(material.babylonMaterial, true);
  1496. };
  1497. GLTFLoader.prototype._createPbrMaterial = function (material) {
  1498. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  1499. babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1500. material.babylonMaterial = babylonMaterial;
  1501. };
  1502. GLTFLoader.prototype._loadMaterialBaseProperties = function (context, material) {
  1503. var babylonMaterial = material.babylonMaterial;
  1504. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  1505. if (material.doubleSided) {
  1506. babylonMaterial.backFaceCulling = false;
  1507. babylonMaterial.twoSidedLighting = true;
  1508. }
  1509. if (material.normalTexture) {
  1510. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.normalTexture.index);
  1511. if (!texture) {
  1512. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  1513. }
  1514. babylonMaterial.bumpTexture = this._loadTexture("#/textures/" + texture.index, texture, material.normalTexture.texCoord);
  1515. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  1516. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  1517. if (material.normalTexture.scale != null) {
  1518. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  1519. }
  1520. }
  1521. if (material.occlusionTexture) {
  1522. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.occlusionTexture.index);
  1523. if (!texture) {
  1524. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  1525. }
  1526. babylonMaterial.ambientTexture = this._loadTexture("#/textures/" + texture.index, texture, material.occlusionTexture.texCoord);
  1527. babylonMaterial.useAmbientInGrayScale = true;
  1528. if (material.occlusionTexture.strength != null) {
  1529. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  1530. }
  1531. }
  1532. if (material.emissiveTexture) {
  1533. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.emissiveTexture.index);
  1534. if (!texture) {
  1535. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  1536. }
  1537. babylonMaterial.emissiveTexture = this._loadTexture("#/textures/" + texture.index, texture, material.emissiveTexture.texCoord);
  1538. }
  1539. };
  1540. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, colorFactor) {
  1541. var babylonMaterial = material.babylonMaterial;
  1542. var alphaMode = material.alphaMode || "OPAQUE";
  1543. switch (alphaMode) {
  1544. case "OPAQUE": {
  1545. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  1546. break;
  1547. }
  1548. case "MASK": {
  1549. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  1550. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  1551. if (colorFactor) {
  1552. if (colorFactor[3] == 0) {
  1553. babylonMaterial.alphaCutOff = 1;
  1554. }
  1555. else {
  1556. babylonMaterial.alphaCutOff /= colorFactor[3];
  1557. }
  1558. }
  1559. if (babylonMaterial.albedoTexture) {
  1560. babylonMaterial.albedoTexture.hasAlpha = true;
  1561. }
  1562. break;
  1563. }
  1564. case "BLEND": {
  1565. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  1566. if (colorFactor) {
  1567. babylonMaterial.alpha = colorFactor[3];
  1568. }
  1569. if (babylonMaterial.albedoTexture) {
  1570. babylonMaterial.albedoTexture.hasAlpha = true;
  1571. babylonMaterial.useAlphaFromAlbedoTexture = true;
  1572. }
  1573. break;
  1574. }
  1575. default: {
  1576. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  1577. }
  1578. }
  1579. };
  1580. GLTFLoader.prototype._loadTexture = function (context, texture, coordinatesIndex) {
  1581. var _this = this;
  1582. var sampler = (texture.sampler == null ? {} : GLTFLoader._GetProperty(this._gltf.samplers, texture.sampler));
  1583. if (!sampler) {
  1584. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  1585. }
  1586. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  1587. var samplingMode = GLTFLoader._GetTextureSamplingMode(sampler.magFilter, sampler.minFilter);
  1588. this._addPendingData(texture);
  1589. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, noMipMaps, false, samplingMode, function () {
  1590. _this._tryCatchOnError(function () {
  1591. _this._removePendingData(texture);
  1592. });
  1593. }, function (message) {
  1594. _this._tryCatchOnError(function () {
  1595. throw new Error(context + ": " + message);
  1596. });
  1597. });
  1598. if (texture.url) {
  1599. babylonTexture.updateURL(texture.url);
  1600. }
  1601. else if (texture.dataReadyObservable) {
  1602. texture.dataReadyObservable.add(function (texture) {
  1603. babylonTexture.updateURL(texture.url);
  1604. });
  1605. }
  1606. else {
  1607. texture.dataReadyObservable = new BABYLON.Observable();
  1608. texture.dataReadyObservable.add(function (texture) {
  1609. babylonTexture.updateURL(texture.url);
  1610. });
  1611. var image_1 = GLTFLoader._GetProperty(this._gltf.images, texture.source);
  1612. if (!image_1) {
  1613. throw new Error(context + ": Failed to find source " + texture.source);
  1614. }
  1615. this._loadImageAsync("#/images/" + image_1.index, image_1, function (data) {
  1616. texture.url = URL.createObjectURL(new Blob([data], { type: image_1.mimeType }));
  1617. texture.dataReadyObservable.notifyObservers(texture);
  1618. texture.dataReadyObservable = undefined;
  1619. });
  1620. }
  1621. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  1622. babylonTexture.wrapU = GLTFLoader._GetTextureWrapMode(sampler.wrapS);
  1623. babylonTexture.wrapV = GLTFLoader._GetTextureWrapMode(sampler.wrapT);
  1624. babylonTexture.name = texture.name || "texture" + texture.index;
  1625. if (this._parent.onTextureLoaded) {
  1626. this._parent.onTextureLoaded(babylonTexture);
  1627. }
  1628. return babylonTexture;
  1629. };
  1630. GLTFLoader.prototype._loadImageAsync = function (context, image, onSuccess) {
  1631. if (image.uri) {
  1632. this._loadUriAsync(context, image.uri, onSuccess);
  1633. }
  1634. else {
  1635. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, image.bufferView);
  1636. if (!bufferView) {
  1637. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  1638. }
  1639. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, onSuccess);
  1640. }
  1641. };
  1642. GLTFLoader.prototype._loadUriAsync = function (context, uri, onSuccess) {
  1643. var _this = this;
  1644. if (GLTF2.GLTFUtils.IsBase64(uri)) {
  1645. onSuccess(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(uri)));
  1646. return;
  1647. }
  1648. if (!GLTF2.GLTFUtils.ValidateUri(uri)) {
  1649. throw new Error(context + ": Uri '" + uri + "' is invalid");
  1650. }
  1651. var request = BABYLON.Tools.LoadFile(this._rootUrl + uri, function (data) {
  1652. _this._tryCatchOnError(function () {
  1653. onSuccess(new Uint8Array(data));
  1654. });
  1655. }, function (event) {
  1656. _this._tryCatchOnError(function () {
  1657. if (request && !_this._renderReady) {
  1658. request._loaded = event.loaded;
  1659. request._total = event.total;
  1660. _this._onProgress();
  1661. }
  1662. });
  1663. }, this._babylonScene.database, true, function (request) {
  1664. _this._tryCatchOnError(function () {
  1665. throw new Error(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""));
  1666. });
  1667. });
  1668. if (request) {
  1669. request._loaded = null;
  1670. request._total = null;
  1671. this._requests.push(request);
  1672. }
  1673. };
  1674. GLTFLoader.prototype._tryCatchOnError = function (handler) {
  1675. if (this._disposed) {
  1676. return;
  1677. }
  1678. try {
  1679. handler();
  1680. }
  1681. catch (e) {
  1682. BABYLON.Tools.Error("glTF Loader: " + e.message);
  1683. if (this._errorCallback) {
  1684. this._errorCallback(e.message);
  1685. }
  1686. this.dispose();
  1687. }
  1688. };
  1689. GLTFLoader._AssignIndices = function (array) {
  1690. if (array) {
  1691. for (var index = 0; index < array.length; index++) {
  1692. array[index].index = index;
  1693. }
  1694. }
  1695. };
  1696. GLTFLoader._GetProperty = function (array, index) {
  1697. if (!array || index == undefined || !array[index]) {
  1698. return null;
  1699. }
  1700. return array[index];
  1701. };
  1702. GLTFLoader._GetTextureWrapMode = function (mode) {
  1703. // Set defaults if undefined
  1704. mode = mode == undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  1705. switch (mode) {
  1706. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  1707. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  1708. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1709. default:
  1710. BABYLON.Tools.Warn("Invalid texture wrap mode (" + mode + ")");
  1711. return BABYLON.Texture.WRAP_ADDRESSMODE;
  1712. }
  1713. };
  1714. GLTFLoader._GetTextureSamplingMode = function (magFilter, minFilter) {
  1715. // Set defaults if undefined
  1716. magFilter = magFilter == undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  1717. minFilter = minFilter == undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  1718. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  1719. switch (minFilter) {
  1720. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  1721. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  1722. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  1723. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  1724. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  1725. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  1726. default:
  1727. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  1728. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  1729. }
  1730. }
  1731. else {
  1732. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  1733. BABYLON.Tools.Warn("Invalid texture magnification filter (" + magFilter + ")");
  1734. }
  1735. switch (minFilter) {
  1736. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  1737. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  1738. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  1739. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  1740. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  1741. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  1742. default:
  1743. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  1744. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  1745. }
  1746. }
  1747. };
  1748. GLTFLoader._GetNumComponents = function (type) {
  1749. switch (type) {
  1750. case "SCALAR": return 1;
  1751. case "VEC2": return 2;
  1752. case "VEC3": return 3;
  1753. case "VEC4": return 4;
  1754. case "MAT2": return 4;
  1755. case "MAT3": return 9;
  1756. case "MAT4": return 16;
  1757. }
  1758. return 0;
  1759. };
  1760. GLTFLoader.prototype._compileMaterialAsync = function (babylonMaterial, babylonMesh, onSuccess) {
  1761. var _this = this;
  1762. if (!this._parent.compileMaterials) {
  1763. onSuccess();
  1764. return;
  1765. }
  1766. if (this._parent.useClipPlane) {
  1767. babylonMaterial.forceCompilation(babylonMesh, function () {
  1768. babylonMaterial.forceCompilation(babylonMesh, function () {
  1769. _this._tryCatchOnError(onSuccess);
  1770. }, { clipPlane: true });
  1771. });
  1772. }
  1773. else {
  1774. babylonMaterial.forceCompilation(babylonMesh, function () {
  1775. _this._tryCatchOnError(onSuccess);
  1776. });
  1777. }
  1778. };
  1779. GLTFLoader.prototype._compileMaterialsAsync = function (onSuccess) {
  1780. if (!this._parent.compileMaterials || !this._gltf.materials) {
  1781. onSuccess();
  1782. return;
  1783. }
  1784. var meshes = this._getMeshes();
  1785. var remaining = 0;
  1786. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  1787. var mesh = meshes_1[_i];
  1788. if (mesh.material instanceof BABYLON.MultiMaterial) {
  1789. for (var _a = 0, _b = mesh.material.subMaterials; _a < _b.length; _a++) {
  1790. var subMaterial = _b[_a];
  1791. if (subMaterial) {
  1792. remaining++;
  1793. }
  1794. }
  1795. }
  1796. }
  1797. if (remaining === 0) {
  1798. onSuccess();
  1799. return;
  1800. }
  1801. for (var _c = 0, meshes_2 = meshes; _c < meshes_2.length; _c++) {
  1802. var mesh = meshes_2[_c];
  1803. if (mesh.material instanceof BABYLON.MultiMaterial) {
  1804. for (var _d = 0, _e = mesh.material.subMaterials; _d < _e.length; _d++) {
  1805. var subMaterial = _e[_d];
  1806. if (subMaterial) {
  1807. this._compileMaterialAsync(subMaterial, mesh, function () {
  1808. if (--remaining === 0) {
  1809. onSuccess();
  1810. }
  1811. });
  1812. }
  1813. }
  1814. }
  1815. }
  1816. };
  1817. GLTFLoader.prototype._compileShadowGeneratorsAsync = function (onSuccess) {
  1818. var _this = this;
  1819. if (!this._parent.compileShadowGenerators) {
  1820. onSuccess();
  1821. return;
  1822. }
  1823. var lights = this._babylonScene.lights;
  1824. var remaining = 0;
  1825. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  1826. var light = lights_1[_i];
  1827. var generator = light.getShadowGenerator();
  1828. if (generator) {
  1829. remaining++;
  1830. }
  1831. }
  1832. if (remaining === 0) {
  1833. onSuccess();
  1834. return;
  1835. }
  1836. for (var _a = 0, lights_2 = lights; _a < lights_2.length; _a++) {
  1837. var light = lights_2[_a];
  1838. var generator = light.getShadowGenerator();
  1839. if (generator) {
  1840. generator.forceCompilation(function () {
  1841. if (--remaining === 0) {
  1842. _this._tryCatchOnError(onSuccess);
  1843. }
  1844. });
  1845. }
  1846. }
  1847. };
  1848. GLTFLoader.Extensions = {};
  1849. return GLTFLoader;
  1850. }());
  1851. GLTF2.GLTFLoader = GLTFLoader;
  1852. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  1853. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1854. })(BABYLON || (BABYLON = {}));
  1855. //# sourceMappingURL=babylon.glTFLoader.js.map
  1856. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  1857. var BABYLON;
  1858. (function (BABYLON) {
  1859. var GLTF2;
  1860. (function (GLTF2) {
  1861. /**
  1862. * Utils functions for GLTF
  1863. */
  1864. var GLTFUtils = /** @class */ (function () {
  1865. function GLTFUtils() {
  1866. }
  1867. /**
  1868. * If the uri is a base64 string
  1869. * @param uri: the uri to test
  1870. */
  1871. GLTFUtils.IsBase64 = function (uri) {
  1872. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  1873. };
  1874. /**
  1875. * Decode the base64 uri
  1876. * @param uri: the uri to decode
  1877. */
  1878. GLTFUtils.DecodeBase64 = function (uri) {
  1879. var decodedString = atob(uri.split(",")[1]);
  1880. var bufferLength = decodedString.length;
  1881. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  1882. for (var i = 0; i < bufferLength; i++) {
  1883. bufferView[i] = decodedString.charCodeAt(i);
  1884. }
  1885. return bufferView.buffer;
  1886. };
  1887. GLTFUtils.ValidateUri = function (uri) {
  1888. return (uri.indexOf("..") === -1);
  1889. };
  1890. return GLTFUtils;
  1891. }());
  1892. GLTF2.GLTFUtils = GLTFUtils;
  1893. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1894. })(BABYLON || (BABYLON = {}));
  1895. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  1896. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  1897. var BABYLON;
  1898. (function (BABYLON) {
  1899. var GLTF2;
  1900. (function (GLTF2) {
  1901. var GLTFLoaderExtension = /** @class */ (function () {
  1902. function GLTFLoaderExtension() {
  1903. this.enabled = true;
  1904. }
  1905. GLTFLoaderExtension.prototype._traverseNode = function (loader, context, node, action, parentNode) { return false; };
  1906. GLTFLoaderExtension.prototype._loadNode = function (loader, context, node) { return false; };
  1907. GLTFLoaderExtension.prototype._loadMaterial = function (loader, context, material, assign) { return false; };
  1908. GLTFLoaderExtension.prototype._loadExtension = function (context, property, action) {
  1909. var _this = this;
  1910. if (!property.extensions) {
  1911. return false;
  1912. }
  1913. var extension = property.extensions[this.name];
  1914. if (!extension) {
  1915. return false;
  1916. }
  1917. // Clear out the extension before executing the action to avoid recursing into the same property.
  1918. property.extensions[this.name] = undefined;
  1919. action(context + "extensions/" + this.name, extension, function () {
  1920. // Restore the extension after completing the action.
  1921. property.extensions[_this.name] = extension;
  1922. });
  1923. return true;
  1924. };
  1925. GLTFLoaderExtension.TraverseNode = function (loader, context, node, action, parentNode) {
  1926. return this._ApplyExtensions(function (extension) { return extension._traverseNode(loader, context, node, action, parentNode); });
  1927. };
  1928. GLTFLoaderExtension.LoadNode = function (loader, context, node) {
  1929. return this._ApplyExtensions(function (extension) { return extension._loadNode(loader, context, node); });
  1930. };
  1931. GLTFLoaderExtension.LoadMaterial = function (loader, context, material, assign) {
  1932. return this._ApplyExtensions(function (extension) { return extension._loadMaterial(loader, context, material, assign); });
  1933. };
  1934. GLTFLoaderExtension._ApplyExtensions = function (action) {
  1935. var extensions = GLTFLoaderExtension._Extensions;
  1936. if (!extensions) {
  1937. return false;
  1938. }
  1939. for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
  1940. var extension = extensions_1[_i];
  1941. if (extension.enabled && action(extension)) {
  1942. return true;
  1943. }
  1944. }
  1945. return false;
  1946. };
  1947. //
  1948. // Utilities
  1949. //
  1950. GLTFLoaderExtension._Extensions = [];
  1951. return GLTFLoaderExtension;
  1952. }());
  1953. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  1954. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1955. })(BABYLON || (BABYLON = {}));
  1956. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  1957. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  1958. var __extends = (this && this.__extends) || (function () {
  1959. var extendStatics = Object.setPrototypeOf ||
  1960. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  1961. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  1962. return function (d, b) {
  1963. extendStatics(d, b);
  1964. function __() { this.constructor = d; }
  1965. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1966. };
  1967. })();
  1968. var BABYLON;
  1969. (function (BABYLON) {
  1970. var GLTF2;
  1971. (function (GLTF2) {
  1972. var Extensions;
  1973. (function (Extensions) {
  1974. // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension.
  1975. var MSFTLOD = /** @class */ (function (_super) {
  1976. __extends(MSFTLOD, _super);
  1977. function MSFTLOD() {
  1978. var _this = _super !== null && _super.apply(this, arguments) || this;
  1979. /**
  1980. * Specify the minimal delay between LODs in ms (default = 250)
  1981. */
  1982. _this.Delay = 250;
  1983. return _this;
  1984. }
  1985. Object.defineProperty(MSFTLOD.prototype, "name", {
  1986. get: function () {
  1987. return "MSFT_lod";
  1988. },
  1989. enumerable: true,
  1990. configurable: true
  1991. });
  1992. MSFTLOD.prototype._traverseNode = function (loader, context, node, action, parentNode) {
  1993. return this._loadExtension(context, node, function (context, extension, onComplete) {
  1994. for (var i = extension.ids.length - 1; i >= 0; i--) {
  1995. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, extension.ids[i]);
  1996. if (!lodNode) {
  1997. throw new Error(context + ": Failed to find node " + extension.ids[i]);
  1998. }
  1999. loader._traverseNode(context, lodNode, action, parentNode);
  2000. }
  2001. loader._traverseNode(context, node, action, parentNode);
  2002. onComplete();
  2003. });
  2004. };
  2005. MSFTLOD.prototype._loadNode = function (loader, context, node) {
  2006. var _this = this;
  2007. return this._loadExtension(context, node, function (context, extension, onComplete) {
  2008. var nodes = [node];
  2009. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  2010. var index = _a[_i];
  2011. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, index);
  2012. if (!lodNode) {
  2013. throw new Error(context + ": Failed to find node " + index);
  2014. }
  2015. nodes.push(lodNode);
  2016. }
  2017. loader._addLoaderPendingData(node);
  2018. _this._loadNodeLOD(loader, context, nodes, nodes.length - 1, function () {
  2019. loader._removeLoaderPendingData(node);
  2020. onComplete();
  2021. });
  2022. });
  2023. };
  2024. MSFTLOD.prototype._loadNodeLOD = function (loader, context, nodes, index, onComplete) {
  2025. var _this = this;
  2026. loader._whenAction(function () {
  2027. loader._loadNode(context, nodes[index]);
  2028. }, function () {
  2029. if (index !== nodes.length - 1) {
  2030. var previousNode = nodes[index + 1];
  2031. previousNode.babylonMesh.setEnabled(false);
  2032. }
  2033. if (index === 0) {
  2034. onComplete();
  2035. return;
  2036. }
  2037. setTimeout(function () {
  2038. loader._tryCatchOnError(function () {
  2039. _this._loadNodeLOD(loader, context, nodes, index - 1, onComplete);
  2040. });
  2041. }, _this.Delay);
  2042. });
  2043. };
  2044. MSFTLOD.prototype._loadMaterial = function (loader, context, material, assign) {
  2045. var _this = this;
  2046. return this._loadExtension(context, material, function (context, extension, onComplete) {
  2047. var materials = [material];
  2048. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  2049. var index = _a[_i];
  2050. var lodMaterial = GLTF2.GLTFLoader._GetProperty(loader._gltf.materials, index);
  2051. if (!lodMaterial) {
  2052. throw new Error(context + ": Failed to find material " + index);
  2053. }
  2054. materials.push(lodMaterial);
  2055. }
  2056. loader._addLoaderPendingData(material);
  2057. _this._loadMaterialLOD(loader, context, materials, materials.length - 1, assign, function () {
  2058. loader._removeLoaderPendingData(material);
  2059. onComplete();
  2060. });
  2061. });
  2062. };
  2063. MSFTLOD.prototype._loadMaterialLOD = function (loader, context, materials, index, assign, onComplete) {
  2064. var _this = this;
  2065. loader._loadMaterial(context, materials[index], function (babylonMaterial, isNew) {
  2066. if (index === materials.length - 1) {
  2067. assign(babylonMaterial, isNew);
  2068. // Load the next LOD when the loader is ready to render.
  2069. loader._executeWhenRenderReady(function () {
  2070. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  2071. });
  2072. }
  2073. else {
  2074. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  2075. assign(babylonMaterial, isNew);
  2076. if (index === 0) {
  2077. onComplete();
  2078. }
  2079. else {
  2080. setTimeout(function () {
  2081. loader._tryCatchOnError(function () {
  2082. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  2083. });
  2084. }, _this.Delay);
  2085. }
  2086. });
  2087. }
  2088. });
  2089. };
  2090. return MSFTLOD;
  2091. }(GLTF2.GLTFLoaderExtension));
  2092. Extensions.MSFTLOD = MSFTLOD;
  2093. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  2094. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  2095. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2096. })(BABYLON || (BABYLON = {}));
  2097. //# sourceMappingURL=MSFT_lod.js.map
  2098. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  2099. var __extends = (this && this.__extends) || (function () {
  2100. var extendStatics = Object.setPrototypeOf ||
  2101. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2102. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2103. return function (d, b) {
  2104. extendStatics(d, b);
  2105. function __() { this.constructor = d; }
  2106. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2107. };
  2108. })();
  2109. var BABYLON;
  2110. (function (BABYLON) {
  2111. var GLTF2;
  2112. (function (GLTF2) {
  2113. var Extensions;
  2114. (function (Extensions) {
  2115. var KHRMaterialsPbrSpecularGlossiness = /** @class */ (function (_super) {
  2116. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  2117. function KHRMaterialsPbrSpecularGlossiness() {
  2118. return _super !== null && _super.apply(this, arguments) || this;
  2119. }
  2120. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  2121. get: function () {
  2122. return "KHR_materials_pbrSpecularGlossiness";
  2123. },
  2124. enumerable: true,
  2125. configurable: true
  2126. });
  2127. KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterial = function (loader, context, material, assign) {
  2128. var _this = this;
  2129. return this._loadExtension(context, material, function (context, extension, onComplete) {
  2130. loader._createPbrMaterial(material);
  2131. loader._loadMaterialBaseProperties(context, material);
  2132. _this._loadSpecularGlossinessProperties(loader, context, material, extension);
  2133. assign(material.babylonMaterial, true);
  2134. onComplete();
  2135. });
  2136. };
  2137. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, context, material, properties) {
  2138. var babylonMaterial = material.babylonMaterial;
  2139. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  2140. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  2141. babylonMaterial.microSurface = properties.glossinessFactor == null ? 1 : properties.glossinessFactor;
  2142. if (properties.diffuseTexture) {
  2143. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.diffuseTexture.index);
  2144. if (!texture) {
  2145. throw new Error(context + ": Failed to find diffuse texture " + properties.diffuseTexture.index);
  2146. }
  2147. babylonMaterial.albedoTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.diffuseTexture.texCoord);
  2148. }
  2149. if (properties.specularGlossinessTexture) {
  2150. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.specularGlossinessTexture.index);
  2151. if (!texture) {
  2152. throw new Error(context + ": Failed to find diffuse texture " + properties.specularGlossinessTexture.index);
  2153. }
  2154. babylonMaterial.reflectivityTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.specularGlossinessTexture.texCoord);
  2155. babylonMaterial.reflectivityTexture.hasAlpha = true;
  2156. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  2157. }
  2158. loader._loadMaterialAlphaProperties(context, material, properties.diffuseFactor);
  2159. };
  2160. return KHRMaterialsPbrSpecularGlossiness;
  2161. }(GLTF2.GLTFLoaderExtension));
  2162. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  2163. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  2164. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  2165. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2166. })(BABYLON || (BABYLON = {}));
  2167. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map