babylon.glTF2FileLoader.js 110 KB

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