babylon.glTF2FileLoader.js 123 KB

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