babylon.glTF2FileLoader.js 111 KB

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