babylon.glTF2FileLoader.js 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275
  1. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  2. var BABYLON;
  3. (function (BABYLON) {
  4. var GLTFFileLoader = (function () {
  5. function GLTFFileLoader() {
  6. this.extensions = {
  7. ".gltf": { isBinary: false },
  8. ".glb": { isBinary: true }
  9. };
  10. }
  11. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onError) {
  12. var loaderData = GLTFFileLoader._parse(data);
  13. var loader = this._getLoader(loaderData);
  14. if (!loader) {
  15. onError();
  16. return;
  17. }
  18. loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onError);
  19. };
  20. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onError) {
  21. var loaderData = GLTFFileLoader._parse(data);
  22. var loader = this._getLoader(loaderData);
  23. if (!loader) {
  24. onError();
  25. return;
  26. }
  27. return loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onError);
  28. };
  29. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  30. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  31. };
  32. GLTFFileLoader._parse = function (data) {
  33. if (data instanceof ArrayBuffer) {
  34. return GLTFFileLoader._parseBinary(data);
  35. }
  36. return {
  37. json: JSON.parse(data),
  38. bin: null
  39. };
  40. };
  41. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  42. var loaderVersion = { major: 2, minor: 0 };
  43. var asset = loaderData.json.asset || {};
  44. var version = GLTFFileLoader._parseVersion(asset.version);
  45. if (!version) {
  46. BABYLON.Tools.Error("Invalid version");
  47. return null;
  48. }
  49. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  50. if (minVersion) {
  51. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  52. BABYLON.Tools.Error("Incompatible version");
  53. return null;
  54. }
  55. }
  56. var loaders = {
  57. 1: GLTFFileLoader.GLTFLoaderV1,
  58. 2: GLTFFileLoader.GLTFLoaderV2
  59. };
  60. var loader = loaders[version.major];
  61. if (loader === undefined) {
  62. BABYLON.Tools.Error("Unsupported version");
  63. return null;
  64. }
  65. if (loader === null) {
  66. BABYLON.Tools.Error("v" + version.major + " loader is not available");
  67. return null;
  68. }
  69. return loader;
  70. };
  71. GLTFFileLoader._parseBinary = function (data) {
  72. var Binary = {
  73. Magic: 0x46546C67
  74. };
  75. var binaryReader = new BinaryReader(data);
  76. var magic = binaryReader.readUint32();
  77. if (magic !== Binary.Magic) {
  78. BABYLON.Tools.Error("Unexpected magic: " + magic);
  79. return null;
  80. }
  81. var version = binaryReader.readUint32();
  82. switch (version) {
  83. case 1: return GLTFFileLoader._parseV1(binaryReader);
  84. case 2: return GLTFFileLoader._parseV2(binaryReader);
  85. }
  86. BABYLON.Tools.Error("Unsupported version: " + version);
  87. return null;
  88. };
  89. GLTFFileLoader._parseV1 = function (binaryReader) {
  90. var ContentFormat = {
  91. JSON: 0
  92. };
  93. var length = binaryReader.readUint32();
  94. if (length != binaryReader.getLength()) {
  95. BABYLON.Tools.Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  96. return null;
  97. }
  98. var contentLength = binaryReader.readUint32();
  99. var contentFormat = binaryReader.readUint32();
  100. var content;
  101. switch (contentFormat) {
  102. case ContentFormat.JSON:
  103. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  104. break;
  105. default:
  106. BABYLON.Tools.Error("Unexpected content format: " + contentFormat);
  107. return null;
  108. }
  109. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  110. var body = binaryReader.readUint8Array(bytesRemaining);
  111. return {
  112. json: content,
  113. bin: body
  114. };
  115. };
  116. GLTFFileLoader._parseV2 = function (binaryReader) {
  117. var ChunkFormat = {
  118. JSON: 0x4E4F534A,
  119. BIN: 0x004E4942
  120. };
  121. var length = binaryReader.readUint32();
  122. if (length !== binaryReader.getLength()) {
  123. BABYLON.Tools.Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  124. return null;
  125. }
  126. // JSON chunk
  127. var chunkLength = binaryReader.readUint32();
  128. var chunkFormat = binaryReader.readUint32();
  129. if (chunkFormat !== ChunkFormat.JSON) {
  130. BABYLON.Tools.Error("First chunk format is not JSON");
  131. return null;
  132. }
  133. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  134. // Look for BIN chunk
  135. var bin = null;
  136. while (binaryReader.getPosition() < binaryReader.getLength()) {
  137. chunkLength = binaryReader.readUint32();
  138. chunkFormat = binaryReader.readUint32();
  139. switch (chunkFormat) {
  140. case ChunkFormat.JSON:
  141. BABYLON.Tools.Error("Unexpected JSON chunk");
  142. return null;
  143. case ChunkFormat.BIN:
  144. bin = binaryReader.readUint8Array(chunkLength);
  145. break;
  146. default:
  147. // ignore unrecognized chunkFormat
  148. binaryReader.skipBytes(chunkLength);
  149. break;
  150. }
  151. }
  152. return {
  153. json: json,
  154. bin: bin
  155. };
  156. };
  157. GLTFFileLoader._parseVersion = function (version) {
  158. if (!version) {
  159. return null;
  160. }
  161. var parts = version.split(".");
  162. if (parts.length === 0) {
  163. return null;
  164. }
  165. var major = parseInt(parts[0]);
  166. if (major > 1 && parts.length != 2) {
  167. return null;
  168. }
  169. var minor = parseInt(parts[1]);
  170. return {
  171. major: major,
  172. minor: parseInt(parts[0])
  173. };
  174. };
  175. GLTFFileLoader._compareVersion = function (a, b) {
  176. if (a.major > b.major)
  177. return 1;
  178. if (a.major < b.major)
  179. return -1;
  180. if (a.minor > b.minor)
  181. return 1;
  182. if (a.minor < b.minor)
  183. return -1;
  184. return 0;
  185. };
  186. GLTFFileLoader._decodeBufferToText = function (view) {
  187. var result = "";
  188. var length = view.byteLength;
  189. for (var i = 0; i < length; ++i) {
  190. result += String.fromCharCode(view[i]);
  191. }
  192. return result;
  193. };
  194. return GLTFFileLoader;
  195. }());
  196. GLTFFileLoader.GLTFLoaderV1 = null;
  197. GLTFFileLoader.GLTFLoaderV2 = null;
  198. GLTFFileLoader.HomogeneousCoordinates = false;
  199. GLTFFileLoader.IncrementalLoading = true;
  200. BABYLON.GLTFFileLoader = GLTFFileLoader;
  201. var BinaryReader = (function () {
  202. function BinaryReader(arrayBuffer) {
  203. this._arrayBuffer = arrayBuffer;
  204. this._dataView = new DataView(arrayBuffer);
  205. this._byteOffset = 0;
  206. }
  207. BinaryReader.prototype.getPosition = function () {
  208. return this._byteOffset;
  209. };
  210. BinaryReader.prototype.getLength = function () {
  211. return this._arrayBuffer.byteLength;
  212. };
  213. BinaryReader.prototype.readUint32 = function () {
  214. var value = this._dataView.getUint32(this._byteOffset, true);
  215. this._byteOffset += 4;
  216. return value;
  217. };
  218. BinaryReader.prototype.readUint8Array = function (length) {
  219. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  220. this._byteOffset += length;
  221. return value;
  222. };
  223. BinaryReader.prototype.skipBytes = function (length) {
  224. this._byteOffset += length;
  225. };
  226. return BinaryReader;
  227. }());
  228. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  229. })(BABYLON || (BABYLON = {}));
  230. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  231. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  232. var BABYLON;
  233. (function (BABYLON) {
  234. var GLTF2;
  235. (function (GLTF2) {
  236. /**
  237. * Enums
  238. */
  239. var EComponentType;
  240. (function (EComponentType) {
  241. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  242. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  243. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  244. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  245. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  246. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  247. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  248. var EMeshPrimitiveMode;
  249. (function (EMeshPrimitiveMode) {
  250. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  251. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  252. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  253. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  254. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  255. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  256. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  257. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  258. var ETextureMagFilter;
  259. (function (ETextureMagFilter) {
  260. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  261. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  262. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  263. var ETextureMinFilter;
  264. (function (ETextureMinFilter) {
  265. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  266. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  267. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  268. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  269. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  270. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  271. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  272. var ETextureWrapMode;
  273. (function (ETextureWrapMode) {
  274. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  275. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  276. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  277. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  278. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  279. })(BABYLON || (BABYLON = {}));
  280. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  281. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  282. var BABYLON;
  283. (function (BABYLON) {
  284. var GLTF2;
  285. (function (GLTF2) {
  286. var GLTFLoader = (function () {
  287. function GLTFLoader() {
  288. }
  289. GLTFLoader.RegisterExtension = function (extension) {
  290. if (GLTFLoader.Extensions[extension.name]) {
  291. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  292. return;
  293. }
  294. this.Extensions[extension.name] = extension;
  295. };
  296. GLTFLoader.LoadMaterial = function (index) {
  297. return BABYLON.GLTFFileLoader.GLTFLoaderV2._loadMaterial(index);
  298. };
  299. GLTFLoader.LoadCoreMaterial = function (index) {
  300. return BABYLON.GLTFFileLoader.GLTFLoaderV2._loadCoreMaterial(index);
  301. };
  302. GLTFLoader.LoadCommonMaterialProperties = function (material) {
  303. return BABYLON.GLTFFileLoader.GLTFLoaderV2._loadCommonMaterialProperties(material);
  304. };
  305. GLTFLoader.LoadAlphaProperties = function (material) {
  306. return BABYLON.GLTFFileLoader.GLTFLoaderV2._loadAlphaProperties(material);
  307. };
  308. GLTFLoader.LoadTexture = function (textureInfo) {
  309. return BABYLON.GLTFFileLoader.GLTFLoaderV2._loadTexture(textureInfo);
  310. };
  311. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onError) {
  312. var _this = this;
  313. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  314. var meshes = [];
  315. for (var i = 0; i < _this._gltf.nodes.length; i++) {
  316. var node = _this._gltf.nodes[i];
  317. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  318. meshes.push(node.babylonNode);
  319. }
  320. }
  321. var skeletons = [];
  322. for (var i = 0; i < _this._gltf.skins.length; i++) {
  323. var skin = _this._gltf.skins[i];
  324. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  325. skeletons.push(skin.babylonSkeleton);
  326. }
  327. }
  328. onSuccess(meshes, null, skeletons);
  329. }, onError);
  330. };
  331. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onError) {
  332. this._loadAsync(null, scene, data, rootUrl, onSuccess, onError);
  333. };
  334. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onError) {
  335. var _this = this;
  336. scene.useRightHandedSystem = true;
  337. this._clear();
  338. this._loadData(data);
  339. this._babylonScene = scene;
  340. this._rootUrl = rootUrl;
  341. this._onLoaded = function () {
  342. _this._showMeshes();
  343. _this._startFirstAnimation();
  344. if (_this._errors.length === 0) {
  345. onSuccess();
  346. }
  347. else {
  348. _this._errors.forEach(function (error) { return BABYLON.Tools.Error(error); });
  349. onError();
  350. }
  351. _this._clear();
  352. };
  353. this._addPendingData(this);
  354. this._loadScene(nodeNames);
  355. this._loadAnimations();
  356. this._removePendingData(this);
  357. };
  358. GLTFLoader.prototype._loadData = function (data) {
  359. this._gltf = data.json;
  360. var binaryBuffer;
  361. var buffers = this._gltf.buffers;
  362. if (buffers.length > 0 && buffers[0].uri === undefined) {
  363. binaryBuffer = buffers[0];
  364. }
  365. if (data.bin) {
  366. if (binaryBuffer) {
  367. if (binaryBuffer.byteLength != data.bin.byteLength) {
  368. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  369. }
  370. }
  371. else {
  372. BABYLON.Tools.Warn("Unexpected BIN chunk");
  373. }
  374. binaryBuffer.loadedData = data.bin;
  375. }
  376. };
  377. GLTFLoader.prototype._showMeshes = function () {
  378. var nodes = this._gltf.nodes;
  379. for (var i = 0; i < nodes.length; i++) {
  380. var node = nodes[i];
  381. if (node.babylonNode instanceof BABYLON.Mesh) {
  382. node.babylonNode.isVisible = true;
  383. }
  384. }
  385. };
  386. GLTFLoader.prototype._startFirstAnimation = function () {
  387. var animations = this._gltf.animations;
  388. if (!animations) {
  389. return;
  390. }
  391. var animation = animations[0];
  392. for (var i = 0; i < animation.targets.length; i++) {
  393. this._babylonScene.beginAnimation(animation.targets[i], 0, Number.MAX_VALUE, true);
  394. }
  395. };
  396. GLTFLoader.prototype._clear = function () {
  397. this._gltf = undefined;
  398. this._pendingCount = 0;
  399. this._onLoaded = undefined;
  400. this._errors = [];
  401. this._babylonScene = undefined;
  402. this._rootUrl = undefined;
  403. this._defaultMaterial = undefined;
  404. // Revoke object urls created during load
  405. if (this._gltf && this._gltf.textures) {
  406. for (var i = 0; i < this._gltf.textures.length; i++) {
  407. var texture = this._gltf.textures[i];
  408. if (texture.blobURL) {
  409. URL.revokeObjectURL(texture.blobURL);
  410. }
  411. }
  412. }
  413. };
  414. GLTFLoader.prototype._loadScene = function (nodeNames) {
  415. var _this = this;
  416. var scene = this._gltf.scenes[this._gltf.scene || 0];
  417. this._traverseScene(nodeNames, scene, function (node) { return _this._loadSkin(node); });
  418. this._traverseScene(nodeNames, scene, function (node, parentNode) { return _this._loadMesh(node, parentNode); });
  419. };
  420. GLTFLoader.prototype._loadSkin = function (node) {
  421. var _this = this;
  422. if (node.babylonNode) {
  423. return false;
  424. }
  425. if (node.skin !== undefined) {
  426. var skin = this._gltf.skins[node.skin];
  427. var skeletonId = "skeleton" + node.skin;
  428. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  429. for (var i = 0; i < skin.joints.length; i++) {
  430. var jointIndex = skin.joints[i];
  431. var jointNode = this._gltf.nodes[jointIndex];
  432. jointNode.babylonNode = new BABYLON.Bone(jointNode.name || "bone" + jointIndex, skin.babylonSkeleton);
  433. }
  434. if (skin.skeleton === undefined) {
  435. // TODO: handle when skeleton is not defined
  436. throw new Error("Not implemented");
  437. }
  438. if (skin.inverseBindMatrices === undefined) {
  439. // TODO: handle when inverse bind matrices are not defined
  440. throw new Error("Not implemented");
  441. }
  442. var accessor = this._gltf.accessors[skin.inverseBindMatrices];
  443. this._loadAccessorAsync(accessor, function (data) {
  444. _this._traverseNode(null, skin.skeleton, function (node, parent) { return _this._updateBone(node, parent, skin, data); });
  445. });
  446. }
  447. return true;
  448. };
  449. GLTFLoader.prototype._updateBone = function (node, parentNode, skin, inverseBindMatrixData) {
  450. var jointIndex = skin.joints.indexOf(node.index);
  451. if (jointIndex === -1) {
  452. // TODO: handle non-joint in between two joints
  453. throw new Error("Not implemented");
  454. }
  455. var babylonBone = node.babylonNode;
  456. // TODO: explain the math
  457. var matrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, jointIndex * 16);
  458. matrix.invertToRef(matrix);
  459. if (parentNode) {
  460. babylonBone.setParent(parentNode.babylonNode, false);
  461. matrix.multiplyToRef(babylonBone.getParent().getInvertedAbsoluteTransform(), matrix);
  462. }
  463. babylonBone.updateMatrix(matrix);
  464. return true;
  465. };
  466. GLTFLoader.prototype._loadMesh = function (node, parentNode) {
  467. if (node.babylonNode) {
  468. if (node.babylonNode instanceof BABYLON.Bone) {
  469. if (node.mesh !== undefined) {
  470. // TODO: handle mesh attached to bone
  471. throw new Error("Not implemented");
  472. }
  473. }
  474. return false;
  475. }
  476. var babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  477. babylonMesh.isVisible = false;
  478. this._loadTransform(node, babylonMesh);
  479. if (node.mesh !== undefined) {
  480. var mesh = this._gltf.meshes[node.mesh];
  481. this._loadMeshData(node, mesh, babylonMesh);
  482. }
  483. babylonMesh.parent = parentNode ? parentNode.babylonNode : null;
  484. node.babylonNode = babylonMesh;
  485. if (node.skin !== undefined) {
  486. var skin = this._gltf.skins[node.skin];
  487. babylonMesh.skeleton = skin.babylonSkeleton;
  488. }
  489. if (node.camera !== undefined) {
  490. // TODO: handle cameras
  491. }
  492. return true;
  493. };
  494. GLTFLoader.prototype._loadMeshData = function (node, mesh, babylonMesh) {
  495. var _this = this;
  496. babylonMesh.name = mesh.name || babylonMesh.name;
  497. babylonMesh.subMeshes = [];
  498. var multiMaterial = new BABYLON.MultiMaterial(babylonMesh.name, this._babylonScene);
  499. babylonMesh.material = multiMaterial;
  500. var geometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene, null, false, babylonMesh);
  501. var vertexData = new BABYLON.VertexData();
  502. vertexData.positions = [];
  503. vertexData.indices = [];
  504. var primitivesLoaded = 0;
  505. var numPrimitives = mesh.primitives.length;
  506. for (var i = 0; i < numPrimitives; i++) {
  507. var primitive = mesh.primitives[i];
  508. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  509. // TODO: handle other primitive modes
  510. throw new Error("Not implemented");
  511. }
  512. this._createMorphTargets(node, mesh, primitive, babylonMesh);
  513. this._loadVertexDataAsync(primitive, function (subVertexData) {
  514. _this._loadMorphTargetsData(mesh, primitive, subVertexData, babylonMesh);
  515. var subMesh = new BABYLON.SubMesh(multiMaterial.subMaterials.length, vertexData.positions.length, subVertexData.positions.length, vertexData.indices.length, subVertexData.indices.length, babylonMesh);
  516. var subMaterial = primitive.material === undefined ? _this._getDefaultMaterial() : GLTF2.GLTFLoaderExtension.LoadMaterial(primitive.material);
  517. multiMaterial.subMaterials.push(subMaterial);
  518. vertexData.merge(subVertexData);
  519. if (++primitivesLoaded === numPrimitives) {
  520. geometry.setAllVerticesData(vertexData, false);
  521. }
  522. });
  523. }
  524. };
  525. GLTFLoader.prototype._loadVertexDataAsync = function (primitive, onSuccess) {
  526. var _this = this;
  527. var attributes = primitive.attributes;
  528. if (!attributes) {
  529. this._errors.push("Primitive has no attributes");
  530. return;
  531. }
  532. var vertexData = new BABYLON.VertexData();
  533. var loadedAttributes = 0;
  534. var numAttributes = Object.keys(attributes).length;
  535. var _loop_1 = function (semantic) {
  536. accessor = this_1._gltf.accessors[attributes[semantic]];
  537. this_1._loadAccessorAsync(accessor, function (data) {
  538. switch (semantic) {
  539. case "NORMAL":
  540. vertexData.normals = data;
  541. break;
  542. case "POSITION":
  543. vertexData.positions = data;
  544. break;
  545. case "TANGENT":
  546. vertexData.tangents = data;
  547. break;
  548. case "TEXCOORD_0":
  549. vertexData.uvs = data;
  550. break;
  551. case "TEXCOORD_1":
  552. vertexData.uvs2 = data;
  553. break;
  554. case "JOINTS_0":
  555. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  556. break;
  557. case "WEIGHTS_0":
  558. vertexData.matricesWeights = data;
  559. break;
  560. case "COLOR_0":
  561. vertexData.colors = data;
  562. break;
  563. default:
  564. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  565. break;
  566. }
  567. if (++loadedAttributes === numAttributes) {
  568. var indicesAccessor = _this._gltf.accessors[primitive.indices];
  569. if (indicesAccessor) {
  570. _this._loadAccessorAsync(indicesAccessor, function (data) {
  571. vertexData.indices = data;
  572. onSuccess(vertexData);
  573. });
  574. }
  575. else {
  576. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  577. vertexData.indices.forEach(function (v, i) { return vertexData.indices[i] = i; });
  578. onSuccess(vertexData);
  579. }
  580. }
  581. });
  582. };
  583. var this_1 = this, accessor;
  584. for (var semantic in attributes) {
  585. _loop_1(semantic);
  586. }
  587. };
  588. GLTFLoader.prototype._createMorphTargets = function (node, mesh, primitive, babylonMesh) {
  589. var targets = primitive.targets;
  590. if (!targets) {
  591. return;
  592. }
  593. if (!babylonMesh.morphTargetManager) {
  594. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  595. }
  596. for (var index = 0; index < targets.length; index++) {
  597. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  598. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  599. }
  600. };
  601. GLTFLoader.prototype._loadMorphTargetsData = function (mesh, primitive, vertexData, babylonMesh) {
  602. var targets = primitive.targets;
  603. if (!targets) {
  604. return;
  605. }
  606. var _loop_2 = function () {
  607. var babylonMorphTarget = babylonMesh.morphTargetManager.getTarget(index);
  608. attributes = targets[index];
  609. var _loop_3 = function (semantic) {
  610. accessor = this_2._gltf.accessors[attributes[semantic]];
  611. this_2._loadAccessorAsync(accessor, function (data) {
  612. if (accessor.name) {
  613. babylonMorphTarget.name = accessor.name;
  614. }
  615. // glTF stores morph target information as deltas while babylon.js expects the final data.
  616. // As a result we have to add the original data to the delta to calculate the final data.
  617. var values = data;
  618. switch (semantic) {
  619. case "NORMAL":
  620. values.forEach(function (v, i) { return values[i] += vertexData.normals[i]; });
  621. babylonMorphTarget.setNormals(values);
  622. break;
  623. case "POSITION":
  624. values.forEach(function (v, i) { return values[i] += vertexData.positions[i]; });
  625. babylonMorphTarget.setPositions(values);
  626. break;
  627. case "TANGENT":
  628. // Tangent data for morph targets is stored as xyz delta.
  629. // The vertexData.tangent is stored as xyzw.
  630. // So we need to skip every fourth vertexData.tangent.
  631. for (var i = 0, j = 0; i < values.length; i++, j++) {
  632. values[i] += vertexData.tangents[j];
  633. if ((i + 1) % 3 == 0) {
  634. j++;
  635. }
  636. }
  637. babylonMorphTarget.setTangents(values);
  638. break;
  639. default:
  640. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  641. break;
  642. }
  643. });
  644. };
  645. for (var semantic in attributes) {
  646. _loop_3(semantic);
  647. }
  648. };
  649. var this_2 = this, attributes, accessor;
  650. for (var index = 0; index < targets.length; index++) {
  651. _loop_2();
  652. }
  653. };
  654. GLTFLoader.prototype._loadTransform = function (node, babylonMesh) {
  655. var position = BABYLON.Vector3.Zero();
  656. var rotation = BABYLON.Quaternion.Identity();
  657. var scaling = BABYLON.Vector3.One();
  658. if (node.matrix) {
  659. var mat = BABYLON.Matrix.FromArray(node.matrix);
  660. mat.decompose(scaling, rotation, position);
  661. }
  662. else {
  663. if (node.translation)
  664. position = BABYLON.Vector3.FromArray(node.translation);
  665. if (node.rotation)
  666. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  667. if (node.scale)
  668. scaling = BABYLON.Vector3.FromArray(node.scale);
  669. }
  670. babylonMesh.position = position;
  671. babylonMesh.rotationQuaternion = rotation;
  672. babylonMesh.scaling = scaling;
  673. };
  674. GLTFLoader.prototype._traverseScene = function (nodeNames, scene, action) {
  675. var nodes = scene.nodes;
  676. if (nodes) {
  677. for (var i = 0; i < nodes.length; i++) {
  678. this._traverseNode(nodeNames, nodes[i], action);
  679. }
  680. }
  681. };
  682. GLTFLoader.prototype._traverseNode = function (nodeNames, index, action, parentNode) {
  683. if (parentNode === void 0) { parentNode = null; }
  684. var node = this._gltf.nodes[index];
  685. if (nodeNames) {
  686. if (nodeNames.indexOf(node.name)) {
  687. // load all children
  688. nodeNames = null;
  689. }
  690. else {
  691. // skip this node tree
  692. return;
  693. }
  694. }
  695. node.index = index;
  696. if (!action(node, parentNode)) {
  697. return;
  698. }
  699. if (node.children) {
  700. for (var i = 0; i < node.children.length; i++) {
  701. this._traverseNode(nodeNames, node.children[i], action, node);
  702. }
  703. }
  704. };
  705. GLTFLoader.prototype._loadAnimations = function () {
  706. var animations = this._gltf.animations;
  707. if (!animations || animations.length === 0) {
  708. return;
  709. }
  710. for (var animationIndex = 0; animationIndex < animations.length; animationIndex++) {
  711. var animation = animations[animationIndex];
  712. for (var channelIndex = 0; channelIndex < animation.channels.length; channelIndex++) {
  713. this._loadAnimationChannel(animation, animationIndex, channelIndex);
  714. }
  715. }
  716. };
  717. GLTFLoader.prototype._loadAnimationChannel = function (animation, animationIndex, channelIndex) {
  718. var channel = animation.channels[channelIndex];
  719. var samplerIndex = channel.sampler;
  720. var sampler = animation.samplers[samplerIndex];
  721. var targetNode = this._gltf.nodes[channel.target.node].babylonNode;
  722. if (!targetNode) {
  723. BABYLON.Tools.Warn("Animation channel target node (" + channel.target.node + ") does not exist");
  724. return;
  725. }
  726. var targetPath = {
  727. "translation": "position",
  728. "rotation": "rotationQuaternion",
  729. "scale": "scaling",
  730. "weights": "influence"
  731. }[channel.target.path];
  732. if (!targetPath) {
  733. BABYLON.Tools.Warn("Animation channel target path '" + channel.target.path + "' is not valid");
  734. return;
  735. }
  736. var animationType = {
  737. "position": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  738. "rotationQuaternion": BABYLON.Animation.ANIMATIONTYPE_QUATERNION,
  739. "scaling": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  740. "influence": BABYLON.Animation.ANIMATIONTYPE_FLOAT,
  741. }[targetPath];
  742. var inputData;
  743. var outputData;
  744. var checkSuccess = function () {
  745. if (!inputData || !outputData) {
  746. return;
  747. }
  748. var outputBufferOffset = 0;
  749. var getNextOutputValue = {
  750. "position": function () {
  751. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  752. outputBufferOffset += 3;
  753. return value;
  754. },
  755. "rotationQuaternion": function () {
  756. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  757. outputBufferOffset += 4;
  758. return value;
  759. },
  760. "scaling": function () {
  761. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  762. outputBufferOffset += 3;
  763. return value;
  764. },
  765. "influence": function () {
  766. var numTargets = targetNode.morphTargetManager.numTargets;
  767. var value = new Array(numTargets);
  768. for (var i = 0; i < numTargets; i++) {
  769. value[i] = outputData[outputBufferOffset++];
  770. }
  771. return value;
  772. },
  773. }[targetPath];
  774. var getNextKey = {
  775. "LINEAR": function (frameIndex) { return ({
  776. frame: inputData[frameIndex],
  777. value: getNextOutputValue()
  778. }); },
  779. "CUBICSPLINE": function (frameIndex) { return ({
  780. frame: inputData[frameIndex],
  781. inTangent: getNextOutputValue(),
  782. value: getNextOutputValue(),
  783. outTangent: getNextOutputValue()
  784. }); },
  785. }[sampler.interpolation];
  786. var keys = new Array(inputData.length);
  787. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  788. keys[frameIndex] = getNextKey(frameIndex);
  789. }
  790. animation.targets = animation.targets || [];
  791. if (targetPath === "influence") {
  792. var targetMesh = targetNode;
  793. for (var targetIndex = 0; targetIndex < targetMesh.morphTargetManager.numTargets; targetIndex++) {
  794. var morphTarget = targetMesh.morphTargetManager.getTarget(targetIndex);
  795. var animationName = (animation.name || "anim" + animationIndex) + "_" + targetIndex;
  796. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  797. babylonAnimation.setKeys(keys.map(function (key) { return ({
  798. frame: key.frame,
  799. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  800. value: key.value[targetIndex],
  801. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  802. }); }));
  803. morphTarget.animations.push(babylonAnimation);
  804. animation.targets.push(morphTarget);
  805. }
  806. }
  807. else {
  808. var animationName = animation.name || "anim" + animationIndex;
  809. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  810. babylonAnimation.setKeys(keys);
  811. targetNode.animations.push(babylonAnimation);
  812. animation.targets.push(targetNode);
  813. }
  814. };
  815. this._loadAccessorAsync(this._gltf.accessors[sampler.input], function (data) {
  816. inputData = data;
  817. checkSuccess();
  818. });
  819. this._loadAccessorAsync(this._gltf.accessors[sampler.output], function (data) {
  820. outputData = data;
  821. checkSuccess();
  822. });
  823. };
  824. GLTFLoader.prototype._loadBufferAsync = function (index, onSuccess) {
  825. var _this = this;
  826. var buffer = this._gltf.buffers[index];
  827. this._addPendingData(buffer);
  828. if (buffer.loadedData) {
  829. setTimeout(function () {
  830. onSuccess(buffer.loadedData);
  831. _this._removePendingData(buffer);
  832. });
  833. }
  834. else if (GLTF2.GLTFUtils.IsBase64(buffer.uri)) {
  835. var data = GLTF2.GLTFUtils.DecodeBase64(buffer.uri);
  836. buffer.loadedData = new Uint8Array(data);
  837. setTimeout(function () {
  838. onSuccess(buffer.loadedData);
  839. _this._removePendingData(buffer);
  840. });
  841. }
  842. else if (buffer.loadedObservable) {
  843. buffer.loadedObservable.add(function (buffer) {
  844. onSuccess(buffer.loadedData);
  845. _this._removePendingData(buffer);
  846. });
  847. }
  848. else {
  849. buffer.loadedObservable = new BABYLON.Observable();
  850. buffer.loadedObservable.add(function (buffer) {
  851. onSuccess(buffer.loadedData);
  852. _this._removePendingData(buffer);
  853. });
  854. BABYLON.Tools.LoadFile(this._rootUrl + buffer.uri, function (data) {
  855. buffer.loadedData = new Uint8Array(data);
  856. buffer.loadedObservable.notifyObservers(buffer);
  857. buffer.loadedObservable = null;
  858. }, null, null, true, function (request) {
  859. _this._errors.push("Failed to load file '" + buffer.uri + "': " + request.statusText + "(" + request.status + ")");
  860. _this._removePendingData(buffer);
  861. });
  862. }
  863. };
  864. GLTFLoader.prototype._loadBufferViewAsync = function (bufferView, byteOffset, byteLength, componentType, onSuccess) {
  865. var _this = this;
  866. byteOffset += (bufferView.byteOffset || 0);
  867. this._loadBufferAsync(bufferView.buffer, function (bufferData) {
  868. if (byteOffset + byteLength > bufferData.byteLength) {
  869. _this._errors.push("Buffer access is out of range");
  870. return;
  871. }
  872. var buffer = bufferData.buffer;
  873. byteOffset += bufferData.byteOffset;
  874. var bufferViewData;
  875. switch (componentType) {
  876. case GLTF2.EComponentType.BYTE:
  877. bufferViewData = new Int8Array(buffer, byteOffset, byteLength);
  878. break;
  879. case GLTF2.EComponentType.UNSIGNED_BYTE:
  880. bufferViewData = new Uint8Array(buffer, byteOffset, byteLength);
  881. break;
  882. case GLTF2.EComponentType.SHORT:
  883. bufferViewData = new Int16Array(buffer, byteOffset, byteLength);
  884. break;
  885. case GLTF2.EComponentType.UNSIGNED_SHORT:
  886. bufferViewData = new Uint16Array(buffer, byteOffset, byteLength);
  887. break;
  888. case GLTF2.EComponentType.UNSIGNED_INT:
  889. bufferViewData = new Uint32Array(buffer, byteOffset, byteLength);
  890. break;
  891. case GLTF2.EComponentType.FLOAT:
  892. bufferViewData = new Float32Array(buffer, byteOffset, byteLength);
  893. break;
  894. default:
  895. _this._errors.push("Invalid component type (" + componentType + ")");
  896. return;
  897. }
  898. onSuccess(bufferViewData);
  899. });
  900. };
  901. GLTFLoader.prototype._loadAccessorAsync = function (accessor, onSuccess) {
  902. var bufferView = this._gltf.bufferViews[accessor.bufferView];
  903. var byteOffset = accessor.byteOffset || 0;
  904. var byteLength = accessor.count * GLTF2.GLTFUtils.GetByteStrideFromType(accessor);
  905. this._loadBufferViewAsync(bufferView, byteOffset, byteLength, accessor.componentType, onSuccess);
  906. };
  907. GLTFLoader.prototype._addPendingData = function (data) {
  908. this._pendingCount++;
  909. };
  910. GLTFLoader.prototype._removePendingData = function (data) {
  911. if (--this._pendingCount === 0) {
  912. this._onLoaded();
  913. }
  914. };
  915. GLTFLoader.prototype._getDefaultMaterial = function () {
  916. if (!this._defaultMaterial) {
  917. var id = "__gltf_default";
  918. var material = this._babylonScene.getMaterialByName(id);
  919. if (!material) {
  920. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  921. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  922. material.metallic = 1;
  923. material.roughness = 1;
  924. }
  925. this._defaultMaterial = material;
  926. }
  927. return this._defaultMaterial;
  928. };
  929. GLTFLoader.prototype._loadMaterial = function (index) {
  930. var materials = this._gltf.materials;
  931. var material = materials ? materials[index] : null;
  932. if (!material) {
  933. BABYLON.Tools.Warn("Material index (" + index + ") does not exist");
  934. return null;
  935. }
  936. material.babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + index, this._babylonScene);
  937. material.babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  938. material.babylonMaterial.useScalarInLinearSpace = true;
  939. return material;
  940. };
  941. GLTFLoader.prototype._loadCoreMaterial = function (index) {
  942. var material = this._loadMaterial(index);
  943. if (!material) {
  944. return null;
  945. }
  946. this._loadCommonMaterialProperties(material);
  947. // Ensure metallic workflow
  948. material.babylonMaterial.metallic = 1;
  949. material.babylonMaterial.roughness = 1;
  950. var properties = material.pbrMetallicRoughness;
  951. if (!properties) {
  952. return;
  953. }
  954. material.babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  955. material.babylonMaterial.metallic = properties.metallicFactor === undefined ? 1 : properties.metallicFactor;
  956. material.babylonMaterial.roughness = properties.roughnessFactor === undefined ? 1 : properties.roughnessFactor;
  957. if (properties.baseColorTexture) {
  958. material.babylonMaterial.albedoTexture = this._loadTexture(properties.baseColorTexture);
  959. this._loadAlphaProperties(material);
  960. }
  961. if (properties.metallicRoughnessTexture) {
  962. material.babylonMaterial.metallicTexture = this._loadTexture(properties.metallicRoughnessTexture);
  963. material.babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  964. material.babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  965. material.babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  966. }
  967. return material.babylonMaterial;
  968. };
  969. GLTFLoader.prototype._loadCommonMaterialProperties = function (material) {
  970. material.babylonMaterial.useEmissiveAsIllumination = (material.emissiveFactor || material.emissiveTexture) ? true : false;
  971. material.babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  972. if (material.doubleSided) {
  973. material.babylonMaterial.backFaceCulling = false;
  974. material.babylonMaterial.twoSidedLighting = true;
  975. }
  976. if (material.normalTexture) {
  977. material.babylonMaterial.bumpTexture = this._loadTexture(material.normalTexture);
  978. if (material.normalTexture.scale !== undefined) {
  979. material.babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  980. }
  981. }
  982. if (material.occlusionTexture) {
  983. material.babylonMaterial.ambientTexture = this._loadTexture(material.occlusionTexture);
  984. material.babylonMaterial.useAmbientInGrayScale = true;
  985. if (material.occlusionTexture.strength !== undefined) {
  986. material.babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  987. }
  988. }
  989. if (material.emissiveTexture) {
  990. material.babylonMaterial.emissiveTexture = this._loadTexture(material.emissiveTexture);
  991. }
  992. };
  993. GLTFLoader.prototype._loadAlphaProperties = function (material) {
  994. var alphaMode = material.alphaMode || "OPAQUE";
  995. switch (alphaMode) {
  996. case "OPAQUE":
  997. // default is opaque
  998. break;
  999. case "MASK":
  1000. material.babylonMaterial.albedoTexture.hasAlpha = true;
  1001. material.babylonMaterial.useAlphaFromAlbedoTexture = false;
  1002. material.babylonMaterial.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  1003. break;
  1004. case "BLEND":
  1005. material.babylonMaterial.albedoTexture.hasAlpha = true;
  1006. material.babylonMaterial.useAlphaFromAlbedoTexture = true;
  1007. material.babylonMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  1008. break;
  1009. default:
  1010. BABYLON.Tools.Error("Invalid alpha mode '" + material.alphaMode + "'");
  1011. }
  1012. };
  1013. GLTFLoader.prototype._loadTexture = function (textureInfo) {
  1014. var _this = this;
  1015. var texture = this._gltf.textures[textureInfo.index];
  1016. var texCoord = textureInfo.texCoord || 0;
  1017. if (!texture || texture.source === undefined) {
  1018. return null;
  1019. }
  1020. // check the cache first
  1021. var babylonTexture;
  1022. if (texture.babylonTextures) {
  1023. babylonTexture = texture.babylonTextures[texCoord];
  1024. if (!babylonTexture) {
  1025. for (var i = 0; i < texture.babylonTextures.length; i++) {
  1026. babylonTexture = texture.babylonTextures[i];
  1027. if (babylonTexture) {
  1028. babylonTexture = babylonTexture.clone();
  1029. babylonTexture.coordinatesIndex = texCoord;
  1030. break;
  1031. }
  1032. }
  1033. }
  1034. return babylonTexture;
  1035. }
  1036. var source = this._gltf.images[texture.source];
  1037. var url;
  1038. if (!source.uri) {
  1039. var bufferView = this._gltf.bufferViews[source.bufferView];
  1040. this._loadBufferViewAsync(bufferView, 0, bufferView.byteLength, GLTF2.EComponentType.UNSIGNED_BYTE, function (data) {
  1041. texture.blobURL = URL.createObjectURL(new Blob([data], { type: source.mimeType }));
  1042. texture.babylonTextures[texCoord].updateURL(texture.blobURL);
  1043. });
  1044. }
  1045. else if (GLTF2.GLTFUtils.IsBase64(source.uri)) {
  1046. var data = new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(source.uri));
  1047. texture.blobURL = URL.createObjectURL(new Blob([data], { type: source.mimeType }));
  1048. url = texture.blobURL;
  1049. }
  1050. else {
  1051. url = this._rootUrl + source.uri;
  1052. }
  1053. var sampler = (texture.sampler === undefined ? {} : this._gltf.samplers[texture.sampler]);
  1054. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  1055. var samplingMode = GLTF2.GLTFUtils.GetTextureFilterMode(sampler.minFilter);
  1056. this._addPendingData(texture);
  1057. var babylonTexture = new BABYLON.Texture(url, this._babylonScene, noMipMaps, false, samplingMode, function () {
  1058. _this._removePendingData(texture);
  1059. }, function () {
  1060. _this._errors.push("Failed to load texture '" + source.uri + "'");
  1061. _this._removePendingData(texture);
  1062. });
  1063. babylonTexture.coordinatesIndex = texCoord;
  1064. babylonTexture.wrapU = GLTF2.GLTFUtils.GetWrapMode(sampler.wrapS);
  1065. babylonTexture.wrapV = GLTF2.GLTFUtils.GetWrapMode(sampler.wrapT);
  1066. babylonTexture.name = texture.name;
  1067. // Cache the texture
  1068. texture.babylonTextures = texture.babylonTextures || [];
  1069. texture.babylonTextures[texCoord] = babylonTexture;
  1070. return babylonTexture;
  1071. };
  1072. return GLTFLoader;
  1073. }());
  1074. GLTFLoader.Extensions = {};
  1075. GLTF2.GLTFLoader = GLTFLoader;
  1076. BABYLON.GLTFFileLoader.GLTFLoaderV2 = new GLTFLoader();
  1077. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1078. })(BABYLON || (BABYLON = {}));
  1079. //# sourceMappingURL=babylon.glTFLoader.js.map
  1080. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  1081. var BABYLON;
  1082. (function (BABYLON) {
  1083. var GLTF2;
  1084. (function (GLTF2) {
  1085. /**
  1086. * Utils functions for GLTF
  1087. */
  1088. var GLTFUtils = (function () {
  1089. function GLTFUtils() {
  1090. }
  1091. /**
  1092. * If the uri is a base64 string
  1093. * @param uri: the uri to test
  1094. */
  1095. GLTFUtils.IsBase64 = function (uri) {
  1096. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  1097. };
  1098. /**
  1099. * Decode the base64 uri
  1100. * @param uri: the uri to decode
  1101. */
  1102. GLTFUtils.DecodeBase64 = function (uri) {
  1103. var decodedString = atob(uri.split(",")[1]);
  1104. var bufferLength = decodedString.length;
  1105. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  1106. for (var i = 0; i < bufferLength; i++) {
  1107. bufferView[i] = decodedString.charCodeAt(i);
  1108. }
  1109. return bufferView.buffer;
  1110. };
  1111. /**
  1112. * Returns the wrap mode of the texture
  1113. * @param mode: the mode value
  1114. */
  1115. GLTFUtils.GetWrapMode = function (mode) {
  1116. switch (mode) {
  1117. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  1118. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  1119. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1120. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1121. }
  1122. };
  1123. /**
  1124. * Returns the byte stride giving an accessor
  1125. * @param accessor: the GLTF accessor objet
  1126. */
  1127. GLTFUtils.GetByteStrideFromType = function (accessor) {
  1128. // Needs this function since "byteStride" isn't requiered in glTF format
  1129. var type = accessor.type;
  1130. switch (type) {
  1131. case "VEC2": return 2;
  1132. case "VEC3": return 3;
  1133. case "VEC4": return 4;
  1134. case "MAT2": return 4;
  1135. case "MAT3": return 9;
  1136. case "MAT4": return 16;
  1137. default: return 1;
  1138. }
  1139. };
  1140. /**
  1141. * Returns the texture filter mode giving a mode value
  1142. * @param mode: the filter mode value
  1143. */
  1144. GLTFUtils.GetTextureFilterMode = function (mode) {
  1145. switch (mode) {
  1146. case GLTF2.ETextureMinFilter.LINEAR:
  1147. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST:
  1148. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  1149. case GLTF2.ETextureMinFilter.NEAREST:
  1150. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  1151. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1152. }
  1153. };
  1154. /**
  1155. * Decodes a buffer view into a string
  1156. * @param view: the buffer view
  1157. */
  1158. GLTFUtils.DecodeBufferToText = function (view) {
  1159. var result = "";
  1160. var length = view.byteLength;
  1161. for (var i = 0; i < length; ++i) {
  1162. result += String.fromCharCode(view[i]);
  1163. }
  1164. return result;
  1165. };
  1166. return GLTFUtils;
  1167. }());
  1168. GLTF2.GLTFUtils = GLTFUtils;
  1169. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1170. })(BABYLON || (BABYLON = {}));
  1171. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  1172. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  1173. var BABYLON;
  1174. (function (BABYLON) {
  1175. var GLTF2;
  1176. (function (GLTF2) {
  1177. var GLTFLoaderExtension = (function () {
  1178. function GLTFLoaderExtension(name) {
  1179. this.enabled = true;
  1180. this._name = name;
  1181. }
  1182. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  1183. get: function () {
  1184. return this._name;
  1185. },
  1186. enumerable: true,
  1187. configurable: true
  1188. });
  1189. GLTFLoaderExtension.prototype.loadMaterial = function (index) { return null; };
  1190. // ---------
  1191. // Utilities
  1192. // ---------
  1193. GLTFLoaderExtension.LoadMaterial = function (index) {
  1194. for (var extensionName in GLTF2.GLTFLoader.Extensions) {
  1195. var extension = GLTF2.GLTFLoader.Extensions[extensionName];
  1196. if (extension.enabled) {
  1197. var babylonMaterial = extension.loadMaterial(index);
  1198. if (babylonMaterial) {
  1199. return babylonMaterial;
  1200. }
  1201. }
  1202. }
  1203. return GLTF2.GLTFLoader.LoadCoreMaterial(index);
  1204. };
  1205. return GLTFLoaderExtension;
  1206. }());
  1207. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  1208. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1209. })(BABYLON || (BABYLON = {}));
  1210. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  1211. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  1212. var __extends = (this && this.__extends) || (function () {
  1213. var extendStatics = Object.setPrototypeOf ||
  1214. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  1215. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  1216. return function (d, b) {
  1217. extendStatics(d, b);
  1218. function __() { this.constructor = d; }
  1219. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1220. };
  1221. })();
  1222. var BABYLON;
  1223. (function (BABYLON) {
  1224. var GLTF2;
  1225. (function (GLTF2) {
  1226. var GLTFMaterialsPbrSpecularGlossinessExtension = (function (_super) {
  1227. __extends(GLTFMaterialsPbrSpecularGlossinessExtension, _super);
  1228. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  1229. return _super.call(this, "KHR_materials_pbrSpecularGlossiness") || this;
  1230. }
  1231. GLTFMaterialsPbrSpecularGlossinessExtension.prototype.loadMaterial = function (index) {
  1232. var material = GLTF2.GLTFLoader.LoadMaterial(index);
  1233. if (!material || !material.extensions)
  1234. return null;
  1235. var properties = material.extensions[this.name];
  1236. if (!properties)
  1237. return null;
  1238. GLTF2.GLTFLoader.LoadCommonMaterialProperties(material);
  1239. //
  1240. // Load Factors
  1241. //
  1242. material.babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  1243. material.babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  1244. material.babylonMaterial.microSurface = properties.glossinessFactor === undefined ? 1 : properties.glossinessFactor;
  1245. //
  1246. // Load Textures
  1247. //
  1248. if (properties.diffuseTexture) {
  1249. material.babylonMaterial.albedoTexture = GLTF2.GLTFLoader.LoadTexture(properties.diffuseTexture);
  1250. GLTF2.GLTFLoader.LoadAlphaProperties(material);
  1251. }
  1252. if (properties.specularGlossinessTexture) {
  1253. material.babylonMaterial.reflectivityTexture = GLTF2.GLTFLoader.LoadTexture(properties.specularGlossinessTexture);
  1254. material.babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  1255. }
  1256. return material.babylonMaterial;
  1257. };
  1258. return GLTFMaterialsPbrSpecularGlossinessExtension;
  1259. }(GLTF2.GLTFLoaderExtension));
  1260. GLTF2.GLTFMaterialsPbrSpecularGlossinessExtension = GLTFMaterialsPbrSpecularGlossinessExtension;
  1261. GLTF2.GLTFLoader.RegisterExtension(new GLTFMaterialsPbrSpecularGlossinessExtension());
  1262. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1263. })(BABYLON || (BABYLON = {}));
  1264. //# sourceMappingURL=babylon.glTFMaterialsPbrSpecularGlossinessExtension.js.map