babylon.glTF2FileLoader.js 97 KB

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