babylon.glTF2FileLoader.js 115 KB

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