babylon.glTF2FileLoader.js 115 KB

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