babylon.glTF2FileLoader.js 122 KB

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