babylon.glTF2FileLoader.js 92 KB

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