babylon.glTF2FileLoader.js 116 KB

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