babylon.glTF2FileLoader.js 99 KB

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