babylon.glTF2FileLoader.js 116 KB

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