babylon.glTF2FileLoader.js 85 KB

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