babylon.glTF2FileLoader.js 116 KB

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