babylon.glTF2FileLoader.js 105 KB

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