babylon.glTF2FileLoader.js 85 KB

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