babylon.glTF2FileLoader.js 88 KB

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