babylon.glTF2FileLoader.js 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647
  1. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  2. var BABYLON;
  3. (function (BABYLON) {
  4. var GLTFLoaderCoordinateSystemMode;
  5. (function (GLTFLoaderCoordinateSystemMode) {
  6. // Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene (scene.useRightHandedSystem).
  7. // NOTE: When scene.useRightHandedSystem is false, an additional transform will be added to the root to transform the data from right-handed to left-handed.
  8. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  9. // The glTF right-handed data is not transformed in any form and is loaded directly.
  10. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["PASS_THROUGH"] = 1] = "PASS_THROUGH";
  11. // Sets the useRightHandedSystem flag on the scene.
  12. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 2] = "FORCE_RIGHT_HANDED";
  13. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  14. var GLTFFileLoader = (function () {
  15. function GLTFFileLoader() {
  16. // V2 options
  17. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  18. this.name = "gltf";
  19. this.extensions = {
  20. ".gltf": { isBinary: false },
  21. ".glb": { isBinary: true }
  22. };
  23. }
  24. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  25. var loaderData = GLTFFileLoader._parse(data, onError);
  26. if (!loaderData) {
  27. return;
  28. }
  29. var loader = this._getLoader(loaderData, onError);
  30. if (!loader) {
  31. return;
  32. }
  33. loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  34. };
  35. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  36. var loaderData = GLTFFileLoader._parse(data, onError);
  37. if (!loaderData) {
  38. return;
  39. }
  40. var loader = this._getLoader(loaderData, onError);
  41. if (!loader) {
  42. return;
  43. }
  44. return loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  45. };
  46. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  47. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  48. };
  49. GLTFFileLoader._parse = function (data, onError) {
  50. if (data instanceof ArrayBuffer) {
  51. return GLTFFileLoader._parseBinary(data, onError);
  52. }
  53. try {
  54. return {
  55. json: JSON.parse(data),
  56. bin: null
  57. };
  58. }
  59. catch (e) {
  60. onError(e.message);
  61. return null;
  62. }
  63. };
  64. GLTFFileLoader.prototype._getLoader = function (loaderData, onError) {
  65. var loaderVersion = { major: 2, minor: 0 };
  66. var asset = loaderData.json.asset || {};
  67. var version = GLTFFileLoader._parseVersion(asset.version);
  68. if (!version) {
  69. onError("Invalid version: " + asset.version);
  70. return null;
  71. }
  72. if (asset.minVersion !== undefined) {
  73. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  74. if (!minVersion) {
  75. onError("Invalid minimum version: " + asset.minVersion);
  76. return null;
  77. }
  78. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  79. onError("Incompatible minimum version: " + asset.minVersion);
  80. return null;
  81. }
  82. }
  83. var createLoaders = {
  84. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  85. 2: GLTFFileLoader.CreateGLTFLoaderV2
  86. };
  87. var createLoader = createLoaders[version.major];
  88. if (!createLoader) {
  89. onError("Unsupported version: " + asset.version);
  90. return null;
  91. }
  92. return createLoader(this);
  93. };
  94. GLTFFileLoader._parseBinary = function (data, onError) {
  95. var Binary = {
  96. Magic: 0x46546C67
  97. };
  98. var binaryReader = new BinaryReader(data);
  99. var magic = binaryReader.readUint32();
  100. if (magic !== Binary.Magic) {
  101. onError("Unexpected magic: " + magic);
  102. return null;
  103. }
  104. var version = binaryReader.readUint32();
  105. switch (version) {
  106. case 1: return GLTFFileLoader._parseV1(binaryReader, onError);
  107. case 2: return GLTFFileLoader._parseV2(binaryReader, onError);
  108. }
  109. onError("Unsupported version: " + version);
  110. return null;
  111. };
  112. GLTFFileLoader._parseV1 = function (binaryReader, onError) {
  113. var ContentFormat = {
  114. JSON: 0
  115. };
  116. var length = binaryReader.readUint32();
  117. if (length != binaryReader.getLength()) {
  118. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  119. return null;
  120. }
  121. var contentLength = binaryReader.readUint32();
  122. var contentFormat = binaryReader.readUint32();
  123. var content;
  124. switch (contentFormat) {
  125. case ContentFormat.JSON:
  126. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  127. break;
  128. default:
  129. onError("Unexpected content format: " + contentFormat);
  130. return null;
  131. }
  132. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  133. var body = binaryReader.readUint8Array(bytesRemaining);
  134. return {
  135. json: content,
  136. bin: body
  137. };
  138. };
  139. GLTFFileLoader._parseV2 = function (binaryReader, onError) {
  140. var ChunkFormat = {
  141. JSON: 0x4E4F534A,
  142. BIN: 0x004E4942
  143. };
  144. var length = binaryReader.readUint32();
  145. if (length !== binaryReader.getLength()) {
  146. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  147. return null;
  148. }
  149. // JSON chunk
  150. var chunkLength = binaryReader.readUint32();
  151. var chunkFormat = binaryReader.readUint32();
  152. if (chunkFormat !== ChunkFormat.JSON) {
  153. onError("First chunk format is not JSON");
  154. return null;
  155. }
  156. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  157. // Look for BIN chunk
  158. var bin = null;
  159. while (binaryReader.getPosition() < binaryReader.getLength()) {
  160. chunkLength = binaryReader.readUint32();
  161. chunkFormat = binaryReader.readUint32();
  162. switch (chunkFormat) {
  163. case ChunkFormat.JSON:
  164. onError("Unexpected JSON chunk");
  165. return null;
  166. case ChunkFormat.BIN:
  167. bin = binaryReader.readUint8Array(chunkLength);
  168. break;
  169. default:
  170. // ignore unrecognized chunkFormat
  171. binaryReader.skipBytes(chunkLength);
  172. break;
  173. }
  174. }
  175. return {
  176. json: json,
  177. bin: bin
  178. };
  179. };
  180. GLTFFileLoader._parseVersion = function (version) {
  181. if (!version) {
  182. return null;
  183. }
  184. var parts = version.split(".");
  185. if (parts.length != 2) {
  186. return null;
  187. }
  188. var major = +parts[0];
  189. if (isNaN(major)) {
  190. return null;
  191. }
  192. var minor = +parts[1];
  193. if (isNaN(minor)) {
  194. return null;
  195. }
  196. return {
  197. major: major,
  198. minor: minor
  199. };
  200. };
  201. GLTFFileLoader._compareVersion = function (a, b) {
  202. if (a.major > b.major)
  203. return 1;
  204. if (a.major < b.major)
  205. return -1;
  206. if (a.minor > b.minor)
  207. return 1;
  208. if (a.minor < b.minor)
  209. return -1;
  210. return 0;
  211. };
  212. GLTFFileLoader._decodeBufferToText = function (view) {
  213. var result = "";
  214. var length = view.byteLength;
  215. for (var i = 0; i < length; ++i) {
  216. result += String.fromCharCode(view[i]);
  217. }
  218. return result;
  219. };
  220. // V1 options
  221. GLTFFileLoader.HomogeneousCoordinates = false;
  222. GLTFFileLoader.IncrementalLoading = true;
  223. return GLTFFileLoader;
  224. }());
  225. BABYLON.GLTFFileLoader = GLTFFileLoader;
  226. var BinaryReader = (function () {
  227. function BinaryReader(arrayBuffer) {
  228. this._arrayBuffer = arrayBuffer;
  229. this._dataView = new DataView(arrayBuffer);
  230. this._byteOffset = 0;
  231. }
  232. BinaryReader.prototype.getPosition = function () {
  233. return this._byteOffset;
  234. };
  235. BinaryReader.prototype.getLength = function () {
  236. return this._arrayBuffer.byteLength;
  237. };
  238. BinaryReader.prototype.readUint32 = function () {
  239. var value = this._dataView.getUint32(this._byteOffset, true);
  240. this._byteOffset += 4;
  241. return value;
  242. };
  243. BinaryReader.prototype.readUint8Array = function (length) {
  244. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  245. this._byteOffset += length;
  246. return value;
  247. };
  248. BinaryReader.prototype.skipBytes = function (length) {
  249. this._byteOffset += length;
  250. };
  251. return BinaryReader;
  252. }());
  253. if (BABYLON.SceneLoader) {
  254. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  255. }
  256. })(BABYLON || (BABYLON = {}));
  257. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  258. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  259. var BABYLON;
  260. (function (BABYLON) {
  261. var GLTF2;
  262. (function (GLTF2) {
  263. /**
  264. * Enums
  265. */
  266. var EComponentType;
  267. (function (EComponentType) {
  268. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  269. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  270. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  271. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  272. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  273. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  274. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  275. var EMeshPrimitiveMode;
  276. (function (EMeshPrimitiveMode) {
  277. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  278. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  279. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  280. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  281. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  282. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  283. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  284. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  285. var ETextureMagFilter;
  286. (function (ETextureMagFilter) {
  287. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  288. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  289. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  290. var ETextureMinFilter;
  291. (function (ETextureMinFilter) {
  292. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  293. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  294. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  295. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  296. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  297. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  298. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  299. var ETextureWrapMode;
  300. (function (ETextureWrapMode) {
  301. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  302. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  303. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  304. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  305. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  306. })(BABYLON || (BABYLON = {}));
  307. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  308. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  309. var BABYLON;
  310. (function (BABYLON) {
  311. var GLTF2;
  312. (function (GLTF2) {
  313. var GLTFLoader = (function () {
  314. function GLTFLoader(parent) {
  315. this._renderReady = false;
  316. this._disposed = false;
  317. this._objectURLs = new Array();
  318. this._blockPendingTracking = false;
  319. // Observable with boolean indicating success or error.
  320. this._renderReadyObservable = new BABYLON.Observable();
  321. // Count of pending work that needs to complete before the asset is rendered.
  322. this._renderPendingCount = 0;
  323. // Count of pending work that needs to complete before the loader is cleared.
  324. this._loaderPendingCount = 0;
  325. this._parent = parent;
  326. }
  327. GLTFLoader.RegisterExtension = function (extension) {
  328. if (GLTFLoader.Extensions[extension.name]) {
  329. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  330. return;
  331. }
  332. GLTFLoader.Extensions[extension.name] = extension;
  333. // Keep the order of registration so that extensions registered first are called first.
  334. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  335. };
  336. Object.defineProperty(GLTFLoader.prototype, "gltf", {
  337. get: function () {
  338. return this._gltf;
  339. },
  340. enumerable: true,
  341. configurable: true
  342. });
  343. Object.defineProperty(GLTFLoader.prototype, "babylonScene", {
  344. get: function () {
  345. return this._babylonScene;
  346. },
  347. enumerable: true,
  348. configurable: true
  349. });
  350. GLTFLoader.prototype.executeWhenRenderReady = function (func) {
  351. if (this._renderReady) {
  352. func();
  353. }
  354. else {
  355. this._renderReadyObservable.add(func);
  356. }
  357. };
  358. GLTFLoader.prototype.dispose = function () {
  359. if (this._disposed) {
  360. return;
  361. }
  362. this._disposed = true;
  363. // Revoke object urls created during load
  364. this._objectURLs.forEach(function (url) { return URL.revokeObjectURL(url); });
  365. this._objectURLs.length = 0;
  366. this._gltf = undefined;
  367. this._babylonScene = undefined;
  368. this._rootUrl = undefined;
  369. this._defaultMaterial = undefined;
  370. this._successCallback = undefined;
  371. this._errorCallback = undefined;
  372. this._renderReady = false;
  373. this._renderReadyObservable.clear();
  374. this._renderPendingCount = 0;
  375. this._loaderPendingCount = 0;
  376. };
  377. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  378. var _this = this;
  379. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  380. onSuccess(_this._getMeshes(), null, _this._getSkeletons());
  381. }, onProgress, onError);
  382. };
  383. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  384. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  385. };
  386. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  387. this._loadData(data);
  388. this._babylonScene = scene;
  389. this._rootUrl = rootUrl;
  390. this._successCallback = onSuccess;
  391. this._progressCallback = onProgress;
  392. this._errorCallback = onError;
  393. this.addPendingData(this);
  394. this._loadScene(nodeNames);
  395. this._loadAnimations();
  396. this.removePendingData(this);
  397. };
  398. GLTFLoader.prototype._onError = function (message) {
  399. this._errorCallback(message);
  400. this.dispose();
  401. };
  402. GLTFLoader.prototype._onProgress = function (event) {
  403. this._progressCallback(event);
  404. };
  405. GLTFLoader.prototype._onRenderReady = function () {
  406. switch (this._parent.coordinateSystemMode) {
  407. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO:
  408. if (!this._babylonScene.useRightHandedSystem) {
  409. this._addRightHandToLeftHandRootTransform();
  410. }
  411. break;
  412. case BABYLON.GLTFLoaderCoordinateSystemMode.PASS_THROUGH:
  413. // do nothing
  414. break;
  415. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED:
  416. this._babylonScene.useRightHandedSystem = true;
  417. break;
  418. default:
  419. BABYLON.Tools.Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  420. break;
  421. }
  422. this._showMeshes();
  423. this._startAnimations();
  424. this._successCallback();
  425. this._renderReadyObservable.notifyObservers(this);
  426. };
  427. GLTFLoader.prototype._onLoaderComplete = function () {
  428. if (this._parent.onComplete) {
  429. this._parent.onComplete();
  430. }
  431. };
  432. GLTFLoader.prototype._onLoaderFirstLODComplete = function () {
  433. if (this._parent.onFirstLODComplete) {
  434. this._parent.onFirstLODComplete();
  435. }
  436. };
  437. GLTFLoader.prototype._loadData = function (data) {
  438. this._gltf = data.json;
  439. var binaryBuffer;
  440. var buffers = this._gltf.buffers;
  441. if (buffers.length > 0 && buffers[0].uri === undefined) {
  442. binaryBuffer = buffers[0];
  443. }
  444. if (data.bin) {
  445. if (binaryBuffer) {
  446. if (binaryBuffer.byteLength != data.bin.byteLength) {
  447. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  448. }
  449. }
  450. else {
  451. BABYLON.Tools.Warn("Unexpected BIN chunk");
  452. }
  453. binaryBuffer.loadedData = data.bin;
  454. }
  455. };
  456. GLTFLoader.prototype._addRightHandToLeftHandRootTransform = function () {
  457. var rootMesh = new BABYLON.Mesh("root", this._babylonScene);
  458. rootMesh.scaling = new BABYLON.Vector3(1, 1, -1);
  459. rootMesh.rotation.y = Math.PI;
  460. var nodes = this._gltf.nodes;
  461. for (var i = 0; i < nodes.length; i++) {
  462. var mesh = nodes[i].babylonMesh;
  463. if (mesh && !mesh.parent) {
  464. mesh.parent = rootMesh;
  465. }
  466. }
  467. };
  468. GLTFLoader.prototype._getMeshes = function () {
  469. var meshes = [];
  470. var nodes = this._gltf.nodes;
  471. if (nodes) {
  472. nodes.forEach(function (node) {
  473. if (node.babylonMesh) {
  474. meshes.push(node.babylonMesh);
  475. }
  476. });
  477. }
  478. return meshes;
  479. };
  480. GLTFLoader.prototype._getSkeletons = function () {
  481. var skeletons = [];
  482. var skins = this._gltf.skins;
  483. if (skins) {
  484. skins.forEach(function (skin) {
  485. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  486. skeletons.push(skin.babylonSkeleton);
  487. }
  488. });
  489. }
  490. return skeletons;
  491. };
  492. GLTFLoader.prototype._getAnimationTargets = function () {
  493. var targets = [];
  494. var animations = this._gltf.animations;
  495. if (animations) {
  496. animations.forEach(function (animation) {
  497. targets.push.apply(targets, animation.targets);
  498. });
  499. }
  500. return targets;
  501. };
  502. GLTFLoader.prototype._showMeshes = function () {
  503. this._getMeshes().forEach(function (mesh) { return mesh.isVisible = true; });
  504. };
  505. GLTFLoader.prototype._startAnimations = function () {
  506. var _this = this;
  507. this._getAnimationTargets().forEach(function (target) { return _this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true); });
  508. };
  509. GLTFLoader.prototype._loadScene = function (nodeNames) {
  510. var _this = this;
  511. var scene = this._gltf.scenes[this._gltf.scene || 0];
  512. var nodeIndices = scene.nodes;
  513. this._traverseNodes(nodeIndices, function (node, index, parentNode) {
  514. node.index = index;
  515. node.parent = parentNode;
  516. return true;
  517. });
  518. var materials = this._gltf.materials;
  519. if (materials) {
  520. materials.forEach(function (material, index) { return material.index = index; });
  521. }
  522. if (nodeNames) {
  523. if (!(nodeNames instanceof Array)) {
  524. nodeNames = [nodeNames];
  525. }
  526. var filteredNodeIndices = new Array();
  527. this._traverseNodes(nodeIndices, function (node) {
  528. if (nodeNames.indexOf(node.name) === -1) {
  529. return true;
  530. }
  531. filteredNodeIndices.push(node.index);
  532. return false;
  533. });
  534. nodeIndices = filteredNodeIndices;
  535. }
  536. this._traverseNodes(nodeIndices, function (node) { return _this._loadSkin(node); });
  537. this._traverseNodes(nodeIndices, function (node) { return _this._loadMesh(node); });
  538. };
  539. GLTFLoader.prototype._loadSkin = function (node) {
  540. var _this = this;
  541. if (node.skin !== undefined) {
  542. var skin = this._gltf.skins[node.skin];
  543. var skeletonId = "skeleton" + node.skin;
  544. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  545. skin.index = node.skin;
  546. for (var i = 0; i < skin.joints.length; i++) {
  547. this._createBone(this._gltf.nodes[skin.joints[i]], skin);
  548. }
  549. if (skin.skeleton === undefined) {
  550. // TODO: handle when skeleton is not defined
  551. throw new Error("Not implemented");
  552. }
  553. if (skin.inverseBindMatrices === undefined) {
  554. // TODO: handle when inverse bind matrices are not defined
  555. throw new Error("Not implemented");
  556. }
  557. var accessor = this._gltf.accessors[skin.inverseBindMatrices];
  558. this._loadAccessorAsync(accessor, function (data) {
  559. _this._traverseNode(skin.skeleton, function (node, index, parent) { return _this._updateBone(node, parent, skin, data); });
  560. });
  561. }
  562. return true;
  563. };
  564. GLTFLoader.prototype._updateBone = function (node, parentNode, skin, inverseBindMatrixData) {
  565. var jointIndex = skin.joints.indexOf(node.index);
  566. if (jointIndex === -1) {
  567. this._createBone(node, skin);
  568. }
  569. var babylonBone = node.babylonSkinToBones[skin.index];
  570. // TODO: explain the math
  571. var matrix = jointIndex === -1 ? BABYLON.Matrix.Identity() : BABYLON.Matrix.FromArray(inverseBindMatrixData, jointIndex * 16);
  572. matrix.invertToRef(matrix);
  573. if (parentNode) {
  574. babylonBone.setParent(parentNode.babylonSkinToBones[skin.index], false);
  575. matrix.multiplyToRef(babylonBone.getParent().getInvertedAbsoluteTransform(), matrix);
  576. }
  577. babylonBone.updateMatrix(matrix);
  578. return true;
  579. };
  580. GLTFLoader.prototype._createBone = function (node, skin) {
  581. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton);
  582. node.babylonSkinToBones = node.babylonSkinToBones || {};
  583. node.babylonSkinToBones[skin.index] = babylonBone;
  584. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  585. node.babylonAnimationTargets.push(babylonBone);
  586. return babylonBone;
  587. };
  588. GLTFLoader.prototype._loadMesh = function (node) {
  589. var babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  590. babylonMesh.isVisible = false;
  591. this._loadTransform(node, babylonMesh);
  592. if (node.mesh !== undefined) {
  593. var mesh = this._gltf.meshes[node.mesh];
  594. this._loadMeshData(node, mesh, babylonMesh);
  595. }
  596. babylonMesh.parent = node.parent ? node.parent.babylonMesh : null;
  597. node.babylonMesh = babylonMesh;
  598. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  599. node.babylonAnimationTargets.push(node.babylonMesh);
  600. if (node.skin !== undefined) {
  601. var skin = this._gltf.skins[node.skin];
  602. babylonMesh.skeleton = skin.babylonSkeleton;
  603. }
  604. if (node.camera !== undefined) {
  605. // TODO: handle cameras
  606. }
  607. return true;
  608. };
  609. GLTFLoader.prototype._loadMeshData = function (node, mesh, babylonMesh) {
  610. var _this = this;
  611. babylonMesh.name = mesh.name || babylonMesh.name;
  612. var babylonMultiMaterial = new BABYLON.MultiMaterial(babylonMesh.name, this._babylonScene);
  613. babylonMesh.material = babylonMultiMaterial;
  614. var geometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene, null, false, babylonMesh);
  615. var vertexData = new BABYLON.VertexData();
  616. vertexData.positions = [];
  617. vertexData.indices = [];
  618. var subMeshInfos = [];
  619. var loadedPrimitives = 0;
  620. var totalPrimitives = mesh.primitives.length;
  621. var _loop_1 = function (i) {
  622. var primitive = mesh.primitives[i];
  623. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  624. // TODO: handle other primitive modes
  625. throw new Error("Not implemented");
  626. }
  627. this_1._createMorphTargets(node, mesh, primitive, babylonMesh);
  628. this_1._loadVertexDataAsync(primitive, function (subVertexData) {
  629. _this._loadMorphTargetsData(mesh, primitive, subVertexData, babylonMesh);
  630. subMeshInfos.push({
  631. materialIndex: i,
  632. verticesStart: vertexData.positions.length,
  633. verticesCount: subVertexData.positions.length,
  634. indicesStart: vertexData.indices.length,
  635. indicesCount: subVertexData.indices.length,
  636. loadMaterial: function () {
  637. if (primitive.material === undefined) {
  638. babylonMultiMaterial.subMaterials[i] = _this._getDefaultMaterial();
  639. }
  640. else {
  641. var material = _this._gltf.materials[primitive.material];
  642. _this.loadMaterial(material, function (babylonMaterial, isNew) {
  643. if (isNew && _this._parent.onMaterialLoaded) {
  644. _this._parent.onMaterialLoaded(babylonMaterial);
  645. }
  646. if (_this._parent.onBeforeMaterialReadyAsync) {
  647. _this.addLoaderPendingData(material);
  648. _this._parent.onBeforeMaterialReadyAsync(babylonMaterial, babylonMesh, babylonMultiMaterial.subMaterials[i] != null, function () {
  649. babylonMultiMaterial.subMaterials[i] = babylonMaterial;
  650. _this.removeLoaderPendingData(material);
  651. });
  652. }
  653. else {
  654. babylonMultiMaterial.subMaterials[i] = babylonMaterial;
  655. }
  656. });
  657. }
  658. }
  659. });
  660. vertexData.merge(subVertexData);
  661. if (++loadedPrimitives === totalPrimitives) {
  662. geometry.setAllVerticesData(vertexData, false);
  663. subMeshInfos.forEach(function (info) { return info.loadMaterial(); });
  664. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  665. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  666. babylonMesh.subMeshes = [];
  667. subMeshInfos.forEach(function (info) { return new BABYLON.SubMesh(info.materialIndex, info.verticesStart, info.verticesCount, info.indicesStart, info.indicesCount, babylonMesh); });
  668. }
  669. });
  670. };
  671. var this_1 = this;
  672. for (var i = 0; i < totalPrimitives; i++) {
  673. _loop_1(i);
  674. }
  675. };
  676. GLTFLoader.prototype._loadVertexDataAsync = function (primitive, onSuccess) {
  677. var _this = this;
  678. var attributes = primitive.attributes;
  679. if (!attributes) {
  680. this._onError("Primitive has no attributes");
  681. return;
  682. }
  683. var vertexData = new BABYLON.VertexData();
  684. var loadedAttributes = 0;
  685. var totalAttributes = Object.keys(attributes).length;
  686. var _loop_2 = function (semantic) {
  687. accessor = this_2._gltf.accessors[attributes[semantic]];
  688. this_2._loadAccessorAsync(accessor, function (data) {
  689. switch (semantic) {
  690. case "NORMAL":
  691. vertexData.normals = data;
  692. break;
  693. case "POSITION":
  694. vertexData.positions = data;
  695. break;
  696. case "TANGENT":
  697. vertexData.tangents = data;
  698. break;
  699. case "TEXCOORD_0":
  700. vertexData.uvs = data;
  701. break;
  702. case "TEXCOORD_1":
  703. vertexData.uvs2 = data;
  704. break;
  705. case "JOINTS_0":
  706. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  707. break;
  708. case "WEIGHTS_0":
  709. vertexData.matricesWeights = data;
  710. break;
  711. case "COLOR_0":
  712. vertexData.colors = data;
  713. break;
  714. default:
  715. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  716. break;
  717. }
  718. if (++loadedAttributes === totalAttributes) {
  719. var indicesAccessor = _this._gltf.accessors[primitive.indices];
  720. if (indicesAccessor) {
  721. _this._loadAccessorAsync(indicesAccessor, function (data) {
  722. vertexData.indices = data;
  723. onSuccess(vertexData);
  724. });
  725. }
  726. else {
  727. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  728. vertexData.indices.forEach(function (v, i) { return vertexData.indices[i] = i; });
  729. onSuccess(vertexData);
  730. }
  731. }
  732. });
  733. };
  734. var this_2 = this, accessor;
  735. for (var semantic in attributes) {
  736. _loop_2(semantic);
  737. }
  738. };
  739. GLTFLoader.prototype._createMorphTargets = function (node, mesh, primitive, babylonMesh) {
  740. var targets = primitive.targets;
  741. if (!targets) {
  742. return;
  743. }
  744. if (!babylonMesh.morphTargetManager) {
  745. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  746. }
  747. for (var index = 0; index < targets.length; index++) {
  748. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  749. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  750. }
  751. };
  752. GLTFLoader.prototype._loadMorphTargetsData = function (mesh, primitive, vertexData, babylonMesh) {
  753. var targets = primitive.targets;
  754. if (!targets) {
  755. return;
  756. }
  757. var _loop_3 = function () {
  758. var babylonMorphTarget = babylonMesh.morphTargetManager.getTarget(index);
  759. attributes = targets[index];
  760. var _loop_4 = function (semantic) {
  761. accessor = this_3._gltf.accessors[attributes[semantic]];
  762. this_3._loadAccessorAsync(accessor, function (data) {
  763. if (accessor.name) {
  764. babylonMorphTarget.name = accessor.name;
  765. }
  766. // glTF stores morph target information as deltas while babylon.js expects the final data.
  767. // As a result we have to add the original data to the delta to calculate the final data.
  768. var values = data;
  769. switch (semantic) {
  770. case "NORMAL":
  771. GLTF2.GLTFUtils.ForEach(values, function (v, i) { return values[i] += vertexData.normals[i]; });
  772. babylonMorphTarget.setNormals(values);
  773. break;
  774. case "POSITION":
  775. GLTF2.GLTFUtils.ForEach(values, function (v, i) { return values[i] += vertexData.positions[i]; });
  776. babylonMorphTarget.setPositions(values);
  777. break;
  778. case "TANGENT":
  779. // Tangent data for morph targets is stored as xyz delta.
  780. // The vertexData.tangent is stored as xyzw.
  781. // So we need to skip every fourth vertexData.tangent.
  782. for (var i = 0, j = 0; i < values.length; i++, j++) {
  783. values[i] += vertexData.tangents[j];
  784. if ((i + 1) % 3 == 0) {
  785. j++;
  786. }
  787. }
  788. babylonMorphTarget.setTangents(values);
  789. break;
  790. default:
  791. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  792. break;
  793. }
  794. });
  795. };
  796. for (var semantic in attributes) {
  797. _loop_4(semantic);
  798. }
  799. };
  800. var this_3 = this, attributes, accessor;
  801. for (var index = 0; index < targets.length; index++) {
  802. _loop_3();
  803. }
  804. };
  805. GLTFLoader.prototype._loadTransform = function (node, babylonMesh) {
  806. var position = BABYLON.Vector3.Zero();
  807. var rotation = BABYLON.Quaternion.Identity();
  808. var scaling = BABYLON.Vector3.One();
  809. if (node.matrix) {
  810. var mat = BABYLON.Matrix.FromArray(node.matrix);
  811. mat.decompose(scaling, rotation, position);
  812. }
  813. else {
  814. if (node.translation)
  815. position = BABYLON.Vector3.FromArray(node.translation);
  816. if (node.rotation)
  817. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  818. if (node.scale)
  819. scaling = BABYLON.Vector3.FromArray(node.scale);
  820. }
  821. babylonMesh.position = position;
  822. babylonMesh.rotationQuaternion = rotation;
  823. babylonMesh.scaling = scaling;
  824. };
  825. GLTFLoader.prototype._traverseNodes = function (indices, action, parentNode) {
  826. if (parentNode === void 0) { parentNode = null; }
  827. for (var i = 0; i < indices.length; i++) {
  828. this._traverseNode(indices[i], action, parentNode);
  829. }
  830. };
  831. GLTFLoader.prototype._traverseNode = function (index, action, parentNode) {
  832. if (parentNode === void 0) { parentNode = null; }
  833. var node = this._gltf.nodes[index];
  834. if (!action(node, index, parentNode)) {
  835. return;
  836. }
  837. if (node.children) {
  838. for (var i = 0; i < node.children.length; i++) {
  839. this._traverseNode(node.children[i], action, node);
  840. }
  841. }
  842. };
  843. GLTFLoader.prototype._loadAnimations = function () {
  844. var animations = this._gltf.animations;
  845. if (!animations || animations.length === 0) {
  846. return;
  847. }
  848. for (var animationIndex = 0; animationIndex < animations.length; animationIndex++) {
  849. var animation = animations[animationIndex];
  850. for (var channelIndex = 0; channelIndex < animation.channels.length; channelIndex++) {
  851. this._loadAnimationChannel(animation, animationIndex, channelIndex);
  852. }
  853. }
  854. };
  855. GLTFLoader.prototype._loadAnimationChannel = function (animation, animationIndex, channelIndex) {
  856. var channel = animation.channels[channelIndex];
  857. var samplerIndex = channel.sampler;
  858. var sampler = animation.samplers[samplerIndex];
  859. var targetNode = this._gltf.nodes[channel.target.node];
  860. if (!targetNode) {
  861. BABYLON.Tools.Warn("Animation channel target node (" + channel.target.node + ") does not exist");
  862. return;
  863. }
  864. var targetPath = {
  865. "translation": "position",
  866. "rotation": "rotationQuaternion",
  867. "scale": "scaling",
  868. "weights": "influence"
  869. }[channel.target.path];
  870. if (!targetPath) {
  871. BABYLON.Tools.Warn("Animation channel target path '" + channel.target.path + "' is not valid");
  872. return;
  873. }
  874. var animationType = {
  875. "position": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  876. "rotationQuaternion": BABYLON.Animation.ANIMATIONTYPE_QUATERNION,
  877. "scaling": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  878. "influence": BABYLON.Animation.ANIMATIONTYPE_FLOAT,
  879. }[targetPath];
  880. var inputData;
  881. var outputData;
  882. var checkSuccess = function () {
  883. if (!inputData || !outputData) {
  884. return;
  885. }
  886. var outputBufferOffset = 0;
  887. var getNextOutputValue = {
  888. "position": function () {
  889. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  890. outputBufferOffset += 3;
  891. return value;
  892. },
  893. "rotationQuaternion": function () {
  894. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  895. outputBufferOffset += 4;
  896. return value;
  897. },
  898. "scaling": function () {
  899. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  900. outputBufferOffset += 3;
  901. return value;
  902. },
  903. "influence": function () {
  904. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  905. var value = new Array(numTargets);
  906. for (var i = 0; i < numTargets; i++) {
  907. value[i] = outputData[outputBufferOffset++];
  908. }
  909. return value;
  910. },
  911. }[targetPath];
  912. var getNextKey = {
  913. "LINEAR": function (frameIndex) { return ({
  914. frame: inputData[frameIndex],
  915. value: getNextOutputValue()
  916. }); },
  917. "CUBICSPLINE": function (frameIndex) { return ({
  918. frame: inputData[frameIndex],
  919. inTangent: getNextOutputValue(),
  920. value: getNextOutputValue(),
  921. outTangent: getNextOutputValue()
  922. }); },
  923. }[sampler.interpolation];
  924. var keys = new Array(inputData.length);
  925. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  926. keys[frameIndex] = getNextKey(frameIndex);
  927. }
  928. animation.targets = animation.targets || [];
  929. if (targetPath === "influence") {
  930. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  931. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  932. var morphTarget = morphTargetManager.getTarget(targetIndex);
  933. var animationName = (animation.name || "anim" + animationIndex) + "_" + targetIndex;
  934. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  935. babylonAnimation.setKeys(keys.map(function (key) { return ({
  936. frame: key.frame,
  937. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  938. value: key.value[targetIndex],
  939. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  940. }); }));
  941. morphTarget.animations.push(babylonAnimation);
  942. animation.targets.push(morphTarget);
  943. }
  944. }
  945. else {
  946. var animationName = animation.name || "anim" + animationIndex;
  947. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  948. babylonAnimation.setKeys(keys);
  949. for (var i = 0; i < targetNode.babylonAnimationTargets.length; i++) {
  950. var target = targetNode.babylonAnimationTargets[i];
  951. target.animations.push(babylonAnimation.clone());
  952. animation.targets.push(target);
  953. }
  954. }
  955. };
  956. this._loadAccessorAsync(this._gltf.accessors[sampler.input], function (data) {
  957. inputData = data;
  958. checkSuccess();
  959. });
  960. this._loadAccessorAsync(this._gltf.accessors[sampler.output], function (data) {
  961. outputData = data;
  962. checkSuccess();
  963. });
  964. };
  965. GLTFLoader.prototype._loadBufferAsync = function (index, onSuccess) {
  966. var _this = this;
  967. var buffer = this._gltf.buffers[index];
  968. this.addPendingData(buffer);
  969. if (buffer.loadedData) {
  970. setTimeout(function () {
  971. onSuccess(buffer.loadedData);
  972. _this.removePendingData(buffer);
  973. });
  974. }
  975. else if (GLTF2.GLTFUtils.IsBase64(buffer.uri)) {
  976. var data = GLTF2.GLTFUtils.DecodeBase64(buffer.uri);
  977. buffer.loadedData = new Uint8Array(data);
  978. setTimeout(function () {
  979. onSuccess(buffer.loadedData);
  980. _this.removePendingData(buffer);
  981. });
  982. }
  983. else if (buffer.loadedObservable) {
  984. buffer.loadedObservable.add(function (buffer) {
  985. onSuccess(buffer.loadedData);
  986. _this.removePendingData(buffer);
  987. });
  988. }
  989. else {
  990. buffer.loadedObservable = new BABYLON.Observable();
  991. buffer.loadedObservable.add(function (buffer) {
  992. onSuccess(buffer.loadedData);
  993. _this.removePendingData(buffer);
  994. });
  995. BABYLON.Tools.LoadFile(this._rootUrl + buffer.uri, function (data) {
  996. buffer.loadedData = new Uint8Array(data);
  997. buffer.loadedObservable.notifyObservers(buffer);
  998. buffer.loadedObservable = null;
  999. }, function (event) {
  1000. if (!_this._disposed) {
  1001. _this._onProgress(event);
  1002. }
  1003. }, this._babylonScene.database, true, function (request) {
  1004. if (!_this._disposed) {
  1005. _this._onError("Failed to load file '" + buffer.uri + "': " + request.status + " " + request.statusText);
  1006. _this.removePendingData(buffer);
  1007. }
  1008. });
  1009. }
  1010. };
  1011. GLTFLoader.prototype._buildInt8ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  1012. if (!byteStride) {
  1013. return new Int8Array(buffer, byteOffset, byteLength);
  1014. }
  1015. var sourceBuffer = new Int8Array(buffer, byteOffset);
  1016. var targetBuffer = new Int8Array(byteLength);
  1017. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride, targetBuffer.length);
  1018. return targetBuffer;
  1019. };
  1020. GLTFLoader.prototype._buildInt16ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  1021. if (!byteStride) {
  1022. return new Int16Array(buffer, byteOffset, byteLength);
  1023. }
  1024. var sourceBuffer = new Int16Array(buffer, byteOffset);
  1025. var targetBuffer = new Int16Array(byteLength);
  1026. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride / 2, targetBuffer.length);
  1027. return targetBuffer;
  1028. };
  1029. GLTFLoader.prototype._buildUint32ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  1030. if (!byteStride) {
  1031. return new Uint32Array(buffer, byteOffset, byteLength);
  1032. }
  1033. var sourceBuffer = new Uint32Array(buffer, byteOffset);
  1034. var targetBuffer = new Uint32Array(byteLength);
  1035. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride / 4, targetBuffer.length);
  1036. return targetBuffer;
  1037. };
  1038. GLTFLoader.prototype._buildFloat32ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  1039. if (!byteStride) {
  1040. return new Float32Array(buffer, byteOffset, byteLength);
  1041. }
  1042. var sourceBuffer = new Float32Array(buffer, byteOffset);
  1043. var targetBuffer = new Float32Array(byteLength);
  1044. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride / 4, targetBuffer.length);
  1045. return targetBuffer;
  1046. };
  1047. GLTFLoader.prototype._extractInterleavedData = function (sourceBuffer, targetBuffer, bytePerComponent, stride, length) {
  1048. var tempIndex = 0;
  1049. var sourceIndex = 0;
  1050. var storageSize = bytePerComponent;
  1051. while (tempIndex < length) {
  1052. for (var cursor = 0; cursor < storageSize; cursor++) {
  1053. targetBuffer[tempIndex] = sourceBuffer[sourceIndex + cursor];
  1054. tempIndex++;
  1055. }
  1056. sourceIndex += stride;
  1057. }
  1058. };
  1059. GLTFLoader.prototype._loadBufferViewAsync = function (bufferView, byteOffset, byteLength, bytePerComponent, componentType, onSuccess) {
  1060. var _this = this;
  1061. byteOffset += (bufferView.byteOffset || 0);
  1062. this._loadBufferAsync(bufferView.buffer, function (bufferData) {
  1063. if (byteOffset + byteLength > bufferData.byteLength) {
  1064. _this._onError("Buffer access is out of range");
  1065. return;
  1066. }
  1067. var buffer = bufferData.buffer;
  1068. byteOffset += bufferData.byteOffset;
  1069. var bufferViewData;
  1070. switch (componentType) {
  1071. case GLTF2.EComponentType.BYTE:
  1072. case GLTF2.EComponentType.UNSIGNED_BYTE:
  1073. bufferViewData = _this._buildInt8ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  1074. break;
  1075. case GLTF2.EComponentType.UNSIGNED_SHORT:
  1076. case GLTF2.EComponentType.SHORT:
  1077. bufferViewData = _this._buildInt16ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  1078. break;
  1079. case GLTF2.EComponentType.UNSIGNED_INT:
  1080. bufferViewData = _this._buildUint32ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  1081. break;
  1082. case GLTF2.EComponentType.FLOAT:
  1083. bufferViewData = _this._buildFloat32ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  1084. break;
  1085. default:
  1086. _this._onError("Invalid component type (" + componentType + ")");
  1087. return;
  1088. }
  1089. onSuccess(bufferViewData);
  1090. });
  1091. };
  1092. GLTFLoader.prototype._loadAccessorAsync = function (accessor, onSuccess) {
  1093. var bufferView = this._gltf.bufferViews[accessor.bufferView];
  1094. var byteOffset = accessor.byteOffset || 0;
  1095. var bytePerComponent = this._getByteStrideFromType(accessor);
  1096. var byteLength = accessor.count * bytePerComponent;
  1097. this._loadBufferViewAsync(bufferView, byteOffset, byteLength, bytePerComponent, accessor.componentType, onSuccess);
  1098. };
  1099. GLTFLoader.prototype._getByteStrideFromType = function (accessor) {
  1100. switch (accessor.type) {
  1101. case "SCALAR": return 1;
  1102. case "VEC2": return 2;
  1103. case "VEC3": return 3;
  1104. case "VEC4": return 4;
  1105. case "MAT2": return 4;
  1106. case "MAT3": return 9;
  1107. case "MAT4": return 16;
  1108. default:
  1109. this._onError("Invalid accessor type (" + accessor.type + ")");
  1110. return 0;
  1111. }
  1112. };
  1113. Object.defineProperty(GLTFLoader.prototype, "blockPendingTracking", {
  1114. set: function (value) {
  1115. this._blockPendingTracking = value;
  1116. },
  1117. enumerable: true,
  1118. configurable: true
  1119. });
  1120. GLTFLoader.prototype.addPendingData = function (data) {
  1121. if (!this._renderReady) {
  1122. this._renderPendingCount++;
  1123. }
  1124. this.addLoaderPendingData(data);
  1125. };
  1126. GLTFLoader.prototype.removePendingData = function (data) {
  1127. if (!this._renderReady) {
  1128. if (--this._renderPendingCount === 0) {
  1129. this._renderReady = true;
  1130. this._onRenderReady();
  1131. }
  1132. }
  1133. this.removeLoaderPendingData(data);
  1134. };
  1135. GLTFLoader.prototype.addLoaderNonBlockingPendingData = function (data) {
  1136. if (!this._nonBlockingData) {
  1137. this._nonBlockingData = new Array();
  1138. }
  1139. this._nonBlockingData.push(data);
  1140. };
  1141. GLTFLoader.prototype.addLoaderPendingData = function (data) {
  1142. if (this._blockPendingTracking) {
  1143. this.addLoaderNonBlockingPendingData(data);
  1144. return;
  1145. }
  1146. this._loaderPendingCount++;
  1147. };
  1148. GLTFLoader.prototype.removeLoaderPendingData = function (data) {
  1149. var indexInPending = this._nonBlockingData ? this._nonBlockingData.indexOf(data) : -1;
  1150. if (indexInPending !== -1) {
  1151. this._nonBlockingData.splice(indexInPending, 1);
  1152. }
  1153. else if (--this._loaderPendingCount === 0) {
  1154. this._onLoaderFirstLODComplete();
  1155. }
  1156. if ((!this._nonBlockingData || this._nonBlockingData.length === 0) && this._loaderPendingCount === 0) {
  1157. this._onLoaderComplete();
  1158. this.dispose();
  1159. }
  1160. };
  1161. GLTFLoader.prototype._getDefaultMaterial = function () {
  1162. if (!this._defaultMaterial) {
  1163. var id = "__gltf_default";
  1164. var material = this._babylonScene.getMaterialByName(id);
  1165. if (!material) {
  1166. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  1167. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1168. material.metallic = 1;
  1169. material.roughness = 1;
  1170. }
  1171. this._defaultMaterial = material;
  1172. }
  1173. return this._defaultMaterial;
  1174. };
  1175. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (material) {
  1176. var babylonMaterial = material.babylonMaterial;
  1177. // Ensure metallic workflow
  1178. babylonMaterial.metallic = 1;
  1179. babylonMaterial.roughness = 1;
  1180. var properties = material.pbrMetallicRoughness;
  1181. if (!properties) {
  1182. return;
  1183. }
  1184. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  1185. babylonMaterial.metallic = properties.metallicFactor === undefined ? 1 : properties.metallicFactor;
  1186. babylonMaterial.roughness = properties.roughnessFactor === undefined ? 1 : properties.roughnessFactor;
  1187. if (properties.baseColorTexture) {
  1188. babylonMaterial.albedoTexture = this.loadTexture(properties.baseColorTexture);
  1189. }
  1190. if (properties.metallicRoughnessTexture) {
  1191. babylonMaterial.metallicTexture = this.loadTexture(properties.metallicRoughnessTexture);
  1192. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  1193. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  1194. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  1195. }
  1196. this.loadMaterialAlphaProperties(material, properties.baseColorFactor);
  1197. };
  1198. GLTFLoader.prototype.loadMaterial = function (material, assign) {
  1199. if (material.babylonMaterial) {
  1200. assign(material.babylonMaterial, false);
  1201. return;
  1202. }
  1203. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, material, assign)) {
  1204. return;
  1205. }
  1206. this.createPbrMaterial(material);
  1207. this.loadMaterialBaseProperties(material);
  1208. this._loadMaterialMetallicRoughnessProperties(material);
  1209. assign(material.babylonMaterial, true);
  1210. };
  1211. GLTFLoader.prototype.createPbrMaterial = function (material) {
  1212. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  1213. babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1214. material.babylonMaterial = babylonMaterial;
  1215. };
  1216. GLTFLoader.prototype.loadMaterialBaseProperties = function (material) {
  1217. var babylonMaterial = material.babylonMaterial;
  1218. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  1219. if (material.doubleSided) {
  1220. babylonMaterial.backFaceCulling = false;
  1221. babylonMaterial.twoSidedLighting = true;
  1222. }
  1223. if (material.normalTexture) {
  1224. babylonMaterial.bumpTexture = this.loadTexture(material.normalTexture);
  1225. babylonMaterial.invertNormalMapX = true;
  1226. babylonMaterial.invertNormalMapY = false;
  1227. if (material.normalTexture.scale !== undefined) {
  1228. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  1229. }
  1230. }
  1231. if (material.occlusionTexture) {
  1232. babylonMaterial.ambientTexture = this.loadTexture(material.occlusionTexture);
  1233. babylonMaterial.useAmbientInGrayScale = true;
  1234. if (material.occlusionTexture.strength !== undefined) {
  1235. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  1236. }
  1237. }
  1238. if (material.emissiveTexture) {
  1239. babylonMaterial.emissiveTexture = this.loadTexture(material.emissiveTexture);
  1240. }
  1241. };
  1242. GLTFLoader.prototype.loadMaterialAlphaProperties = function (material, colorFactor) {
  1243. var babylonMaterial = material.babylonMaterial;
  1244. var alphaMode = material.alphaMode || "OPAQUE";
  1245. switch (alphaMode) {
  1246. case "OPAQUE":
  1247. // default is opaque
  1248. break;
  1249. case "MASK":
  1250. case "BLEND":
  1251. if (colorFactor) {
  1252. babylonMaterial.alpha = colorFactor[3];
  1253. }
  1254. if (babylonMaterial.albedoTexture) {
  1255. babylonMaterial.albedoTexture.hasAlpha = true;
  1256. babylonMaterial.useAlphaFromAlbedoTexture = (alphaMode === "BLEND");
  1257. }
  1258. break;
  1259. default:
  1260. BABYLON.Tools.Warn("Invalid alpha mode '" + material.alphaMode + "'");
  1261. break;
  1262. }
  1263. };
  1264. GLTFLoader.prototype.loadTexture = function (textureInfo) {
  1265. var _this = this;
  1266. var texture = this._gltf.textures[textureInfo.index];
  1267. var texCoord = textureInfo.texCoord || 0;
  1268. if (!texture || texture.source === undefined) {
  1269. return null;
  1270. }
  1271. // check the cache first
  1272. var babylonTexture;
  1273. if (texture.babylonTextures) {
  1274. babylonTexture = texture.babylonTextures[texCoord];
  1275. if (!babylonTexture) {
  1276. for (var i = 0; i < texture.babylonTextures.length; i++) {
  1277. babylonTexture = texture.babylonTextures[i];
  1278. if (babylonTexture) {
  1279. babylonTexture = babylonTexture.clone();
  1280. babylonTexture.coordinatesIndex = texCoord;
  1281. break;
  1282. }
  1283. }
  1284. }
  1285. return babylonTexture;
  1286. }
  1287. var source = this._gltf.images[texture.source];
  1288. var sampler = (texture.sampler === undefined ? {} : this._gltf.samplers[texture.sampler]);
  1289. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  1290. var samplingMode = GLTF2.GLTFUtils.GetTextureSamplingMode(sampler.magFilter, sampler.minFilter);
  1291. this.addPendingData(texture);
  1292. babylonTexture = new BABYLON.Texture(null, this._babylonScene, noMipMaps, false, samplingMode, function () {
  1293. if (!_this._disposed) {
  1294. _this.removePendingData(texture);
  1295. }
  1296. }, function () {
  1297. if (!_this._disposed) {
  1298. _this._onError("Failed to load texture '" + source.uri + "'");
  1299. _this.removePendingData(texture);
  1300. }
  1301. });
  1302. var setTextureData = function (data) {
  1303. var url = URL.createObjectURL(new Blob([data], { type: source.mimeType }));
  1304. _this._objectURLs.push(url);
  1305. babylonTexture.updateURL(url);
  1306. };
  1307. if (!source.uri) {
  1308. var bufferView = this._gltf.bufferViews[source.bufferView];
  1309. this._loadBufferViewAsync(bufferView, 0, bufferView.byteLength, 1, GLTF2.EComponentType.UNSIGNED_BYTE, setTextureData);
  1310. }
  1311. else if (GLTF2.GLTFUtils.IsBase64(source.uri)) {
  1312. setTextureData(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(source.uri)));
  1313. }
  1314. else {
  1315. BABYLON.Tools.LoadFile(this._rootUrl + source.uri, setTextureData, function (event) {
  1316. if (!_this._disposed) {
  1317. _this._onProgress(event);
  1318. }
  1319. }, this._babylonScene.database, true, function (request) {
  1320. _this._onError("Failed to load file '" + source.uri + "': " + request.status + " " + request.statusText);
  1321. });
  1322. }
  1323. babylonTexture.coordinatesIndex = texCoord;
  1324. babylonTexture.wrapU = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapS);
  1325. babylonTexture.wrapV = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapT);
  1326. babylonTexture.name = texture.name || "texture" + textureInfo.index;
  1327. // Cache the texture
  1328. texture.babylonTextures = texture.babylonTextures || [];
  1329. texture.babylonTextures[texCoord] = babylonTexture;
  1330. if (this._parent.onTextureLoaded) {
  1331. this._parent.onTextureLoaded(babylonTexture);
  1332. }
  1333. return babylonTexture;
  1334. };
  1335. GLTFLoader.Extensions = {};
  1336. return GLTFLoader;
  1337. }());
  1338. GLTF2.GLTFLoader = GLTFLoader;
  1339. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  1340. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1341. })(BABYLON || (BABYLON = {}));
  1342. //# sourceMappingURL=babylon.glTFLoader.js.map
  1343. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  1344. var BABYLON;
  1345. (function (BABYLON) {
  1346. var GLTF2;
  1347. (function (GLTF2) {
  1348. /**
  1349. * Utils functions for GLTF
  1350. */
  1351. var GLTFUtils = (function () {
  1352. function GLTFUtils() {
  1353. }
  1354. /**
  1355. * If the uri is a base64 string
  1356. * @param uri: the uri to test
  1357. */
  1358. GLTFUtils.IsBase64 = function (uri) {
  1359. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  1360. };
  1361. /**
  1362. * Decode the base64 uri
  1363. * @param uri: the uri to decode
  1364. */
  1365. GLTFUtils.DecodeBase64 = function (uri) {
  1366. var decodedString = atob(uri.split(",")[1]);
  1367. var bufferLength = decodedString.length;
  1368. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  1369. for (var i = 0; i < bufferLength; i++) {
  1370. bufferView[i] = decodedString.charCodeAt(i);
  1371. }
  1372. return bufferView.buffer;
  1373. };
  1374. GLTFUtils.ForEach = function (view, func) {
  1375. for (var index = 0; index < view.length; index++) {
  1376. func(view[index], index);
  1377. }
  1378. };
  1379. GLTFUtils.GetTextureWrapMode = function (mode) {
  1380. // Set defaults if undefined
  1381. mode = mode === undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  1382. switch (mode) {
  1383. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  1384. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  1385. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1386. default:
  1387. BABYLON.Tools.Warn("Invalid texture wrap mode (" + mode + ")");
  1388. return BABYLON.Texture.WRAP_ADDRESSMODE;
  1389. }
  1390. };
  1391. GLTFUtils.GetTextureSamplingMode = function (magFilter, minFilter) {
  1392. // Set defaults if undefined
  1393. magFilter = magFilter === undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  1394. minFilter = minFilter === undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST : minFilter;
  1395. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  1396. switch (minFilter) {
  1397. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  1398. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  1399. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  1400. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  1401. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  1402. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  1403. default:
  1404. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  1405. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  1406. }
  1407. }
  1408. else {
  1409. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  1410. BABYLON.Tools.Warn("Invalid texture magnification filter (" + magFilter + ")");
  1411. }
  1412. switch (minFilter) {
  1413. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  1414. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  1415. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  1416. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  1417. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  1418. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  1419. default:
  1420. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  1421. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  1422. }
  1423. }
  1424. };
  1425. /**
  1426. * Decodes a buffer view into a string
  1427. * @param view: the buffer view
  1428. */
  1429. GLTFUtils.DecodeBufferToText = function (view) {
  1430. var result = "";
  1431. var length = view.byteLength;
  1432. for (var i = 0; i < length; ++i) {
  1433. result += String.fromCharCode(view[i]);
  1434. }
  1435. return result;
  1436. };
  1437. return GLTFUtils;
  1438. }());
  1439. GLTF2.GLTFUtils = GLTFUtils;
  1440. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1441. })(BABYLON || (BABYLON = {}));
  1442. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  1443. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  1444. var BABYLON;
  1445. (function (BABYLON) {
  1446. var GLTF2;
  1447. (function (GLTF2) {
  1448. var GLTFLoaderExtension = (function () {
  1449. function GLTFLoaderExtension() {
  1450. this.enabled = true;
  1451. }
  1452. GLTFLoaderExtension.prototype.loadMaterial = function (loader, material, assign) { return false; };
  1453. GLTFLoaderExtension.LoadMaterial = function (loader, material, assign) {
  1454. return this._ApplyExtensions(function (extension) { return extension.loadMaterial(loader, material, assign); });
  1455. };
  1456. GLTFLoaderExtension._ApplyExtensions = function (action) {
  1457. var extensions = GLTFLoaderExtension._Extensions;
  1458. if (!extensions) {
  1459. return;
  1460. }
  1461. for (var i = 0; i < extensions.length; i++) {
  1462. var extension = extensions[i];
  1463. if (extension.enabled && action(extension)) {
  1464. return true;
  1465. }
  1466. }
  1467. return false;
  1468. };
  1469. //
  1470. // Utilities
  1471. //
  1472. GLTFLoaderExtension._Extensions = [];
  1473. return GLTFLoaderExtension;
  1474. }());
  1475. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  1476. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1477. })(BABYLON || (BABYLON = {}));
  1478. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  1479. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  1480. var __extends = (this && this.__extends) || (function () {
  1481. var extendStatics = Object.setPrototypeOf ||
  1482. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  1483. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  1484. return function (d, b) {
  1485. extendStatics(d, b);
  1486. function __() { this.constructor = d; }
  1487. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1488. };
  1489. })();
  1490. var BABYLON;
  1491. (function (BABYLON) {
  1492. var GLTF2;
  1493. (function (GLTF2) {
  1494. var Extensions;
  1495. (function (Extensions) {
  1496. var MSFTLOD = (function (_super) {
  1497. __extends(MSFTLOD, _super);
  1498. function MSFTLOD() {
  1499. return _super !== null && _super.apply(this, arguments) || this;
  1500. }
  1501. Object.defineProperty(MSFTLOD.prototype, "name", {
  1502. get: function () {
  1503. return "MSFT_lod";
  1504. },
  1505. enumerable: true,
  1506. configurable: true
  1507. });
  1508. MSFTLOD.prototype.loadMaterial = function (loader, material, assign) {
  1509. if (!material.extensions) {
  1510. return false;
  1511. }
  1512. var properties = material.extensions[this.name];
  1513. if (!properties) {
  1514. return false;
  1515. }
  1516. // Clear out the extension so that it won't get loaded again.
  1517. material.extensions[this.name] = undefined;
  1518. // Tell the loader not to clear its state until the highest LOD is loaded.
  1519. var materialLODs = [material.index].concat(properties.ids);
  1520. loader.addLoaderPendingData(material);
  1521. for (var index = 0; index < materialLODs.length; index++) {
  1522. loader.addLoaderNonBlockingPendingData(index);
  1523. }
  1524. // Start with the lowest quality LOD.
  1525. this.loadMaterialLOD(loader, material, materialLODs, materialLODs.length - 1, assign);
  1526. return true;
  1527. };
  1528. MSFTLOD.prototype.loadMaterialLOD = function (loader, material, materialLODs, lod, assign) {
  1529. var _this = this;
  1530. var materialLOD = loader.gltf.materials[materialLODs[lod]];
  1531. if (lod !== materialLODs.length - 1) {
  1532. loader.blockPendingTracking = true;
  1533. }
  1534. loader.loadMaterial(materialLOD, function (babylonMaterial, isNew) {
  1535. assign(babylonMaterial, isNew);
  1536. loader.removeLoaderPendingData(lod);
  1537. // Loading is considered complete if this is the lowest quality LOD.
  1538. if (lod === materialLODs.length - 1) {
  1539. loader.removeLoaderPendingData(material);
  1540. }
  1541. if (lod === 0) {
  1542. loader.blockPendingTracking = false;
  1543. return;
  1544. }
  1545. // Load the next LOD when the loader is ready to render and
  1546. // all active material textures of the current LOD are loaded.
  1547. loader.executeWhenRenderReady(function () {
  1548. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  1549. setTimeout(function () {
  1550. _this.loadMaterialLOD(loader, material, materialLODs, lod - 1, assign);
  1551. }, MSFTLOD.MinimalLODDelay);
  1552. });
  1553. });
  1554. });
  1555. };
  1556. /**
  1557. * Specify the minimal delay between LODs in ms (default = 250)
  1558. */
  1559. MSFTLOD.MinimalLODDelay = 250;
  1560. return MSFTLOD;
  1561. }(GLTF2.GLTFLoaderExtension));
  1562. Extensions.MSFTLOD = MSFTLOD;
  1563. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  1564. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  1565. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1566. })(BABYLON || (BABYLON = {}));
  1567. //# sourceMappingURL=MSFT_lod.js.map
  1568. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  1569. var __extends = (this && this.__extends) || (function () {
  1570. var extendStatics = Object.setPrototypeOf ||
  1571. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  1572. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  1573. return function (d, b) {
  1574. extendStatics(d, b);
  1575. function __() { this.constructor = d; }
  1576. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1577. };
  1578. })();
  1579. var BABYLON;
  1580. (function (BABYLON) {
  1581. var GLTF2;
  1582. (function (GLTF2) {
  1583. var Extensions;
  1584. (function (Extensions) {
  1585. var KHRMaterialsPbrSpecularGlossiness = (function (_super) {
  1586. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  1587. function KHRMaterialsPbrSpecularGlossiness() {
  1588. return _super !== null && _super.apply(this, arguments) || this;
  1589. }
  1590. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  1591. get: function () {
  1592. return "KHR_materials_pbrSpecularGlossiness";
  1593. },
  1594. enumerable: true,
  1595. configurable: true
  1596. });
  1597. KHRMaterialsPbrSpecularGlossiness.prototype.loadMaterial = function (loader, material, assign) {
  1598. if (!material.extensions) {
  1599. return false;
  1600. }
  1601. var properties = material.extensions[this.name];
  1602. if (!properties) {
  1603. return false;
  1604. }
  1605. loader.createPbrMaterial(material);
  1606. loader.loadMaterialBaseProperties(material);
  1607. this._loadSpecularGlossinessProperties(loader, material, properties);
  1608. assign(material.babylonMaterial, true);
  1609. return true;
  1610. };
  1611. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, material, properties) {
  1612. var babylonMaterial = material.babylonMaterial;
  1613. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  1614. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  1615. babylonMaterial.microSurface = properties.glossinessFactor === undefined ? 1 : properties.glossinessFactor;
  1616. if (properties.diffuseTexture) {
  1617. babylonMaterial.albedoTexture = loader.loadTexture(properties.diffuseTexture);
  1618. loader.loadMaterialAlphaProperties(material);
  1619. }
  1620. if (properties.specularGlossinessTexture) {
  1621. babylonMaterial.reflectivityTexture = loader.loadTexture(properties.specularGlossinessTexture);
  1622. babylonMaterial.reflectivityTexture.hasAlpha = true;
  1623. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  1624. }
  1625. loader.loadMaterialAlphaProperties(material, properties.diffuseFactor);
  1626. };
  1627. return KHRMaterialsPbrSpecularGlossiness;
  1628. }(GLTF2.GLTFLoaderExtension));
  1629. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  1630. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  1631. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  1632. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1633. })(BABYLON || (BABYLON = {}));
  1634. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map