babylon.glTF2FileLoader.js 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297
  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. if (_this._gltf.nodes) {
  316. for (var i = 0; i < _this._gltf.nodes.length; i++) {
  317. var node = _this._gltf.nodes[i];
  318. if (node.babylonMesh) {
  319. meshes.push(node.babylonMesh);
  320. }
  321. }
  322. }
  323. var skeletons = [];
  324. if (_this._gltf.skins) {
  325. for (var i = 0; i < _this._gltf.skins.length; i++) {
  326. var skin = _this._gltf.skins[i];
  327. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  328. skeletons.push(skin.babylonSkeleton);
  329. }
  330. }
  331. }
  332. onSuccess(meshes, null, skeletons);
  333. }, onError);
  334. };
  335. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onError) {
  336. this._loadAsync(null, scene, data, rootUrl, onSuccess, onError);
  337. };
  338. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onError) {
  339. var _this = this;
  340. scene.useRightHandedSystem = true;
  341. this._clear();
  342. this._loadData(data);
  343. this._babylonScene = scene;
  344. this._rootUrl = rootUrl;
  345. this._onLoaded = function () {
  346. _this._showMeshes();
  347. _this._startAnimations();
  348. if (_this._errors.length === 0) {
  349. onSuccess();
  350. }
  351. else {
  352. _this._errors.forEach(function (error) { return BABYLON.Tools.Error(error); });
  353. onError();
  354. }
  355. _this._clear();
  356. };
  357. this._addPendingData(this);
  358. this._loadScene(nodeNames);
  359. this._loadAnimations();
  360. this._removePendingData(this);
  361. };
  362. GLTFLoader.prototype._loadData = function (data) {
  363. this._gltf = data.json;
  364. var binaryBuffer;
  365. var buffers = this._gltf.buffers;
  366. if (buffers.length > 0 && buffers[0].uri === undefined) {
  367. binaryBuffer = buffers[0];
  368. }
  369. if (data.bin) {
  370. if (binaryBuffer) {
  371. if (binaryBuffer.byteLength != data.bin.byteLength) {
  372. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  373. }
  374. }
  375. else {
  376. BABYLON.Tools.Warn("Unexpected BIN chunk");
  377. }
  378. binaryBuffer.loadedData = data.bin;
  379. }
  380. };
  381. GLTFLoader.prototype._showMeshes = function () {
  382. var nodes = this._gltf.nodes;
  383. for (var i = 0; i < nodes.length; i++) {
  384. var node = nodes[i];
  385. if (node.babylonMesh) {
  386. node.babylonMesh.isVisible = true;
  387. }
  388. }
  389. };
  390. GLTFLoader.prototype._startAnimations = function () {
  391. var animations = this._gltf.animations;
  392. if (!animations) {
  393. return;
  394. }
  395. for (var i = 0; i < animations.length; i++) {
  396. var animation = animations[i];
  397. for (var j = 0; j < animation.targets.length; j++) {
  398. this._babylonScene.beginAnimation(animation.targets[j], 0, Number.MAX_VALUE, true);
  399. }
  400. }
  401. };
  402. GLTFLoader.prototype._clear = function () {
  403. this._gltf = undefined;
  404. this._pendingCount = 0;
  405. this._onLoaded = undefined;
  406. this._errors = [];
  407. this._babylonScene = undefined;
  408. this._rootUrl = undefined;
  409. this._defaultMaterial = undefined;
  410. // Revoke object urls created during load
  411. if (this._gltf && this._gltf.textures) {
  412. for (var i = 0; i < this._gltf.textures.length; i++) {
  413. var texture = this._gltf.textures[i];
  414. if (texture.blobURL) {
  415. URL.revokeObjectURL(texture.blobURL);
  416. }
  417. }
  418. }
  419. };
  420. GLTFLoader.prototype._loadScene = function (nodeNames) {
  421. var _this = this;
  422. nodeNames = (nodeNames === "") ? null : nodeNames;
  423. nodeNames = (nodeNames instanceof Array) ? nodeNames : [nodeNames];
  424. var scene = this._gltf.scenes[this._gltf.scene || 0];
  425. this._traverseScene(nodeNames, scene, function (node) { return _this._loadSkin(node); });
  426. this._traverseScene(nodeNames, scene, function (node, parentNode) { return _this._loadMesh(node, parentNode); });
  427. };
  428. GLTFLoader.prototype._loadSkin = function (node) {
  429. var _this = this;
  430. if (node.skin !== undefined) {
  431. var skin = this._gltf.skins[node.skin];
  432. var skeletonId = "skeleton" + node.skin;
  433. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  434. skin.index = node.skin;
  435. for (var i = 0; i < skin.joints.length; i++) {
  436. this._createBone(this._gltf.nodes[skin.joints[i]], skin);
  437. }
  438. if (skin.skeleton === undefined) {
  439. // TODO: handle when skeleton is not defined
  440. throw new Error("Not implemented");
  441. }
  442. if (skin.inverseBindMatrices === undefined) {
  443. // TODO: handle when inverse bind matrices are not defined
  444. throw new Error("Not implemented");
  445. }
  446. var accessor = this._gltf.accessors[skin.inverseBindMatrices];
  447. this._loadAccessorAsync(accessor, function (data) {
  448. _this._traverseNode(null, skin.skeleton, function (node, parent) { return _this._updateBone(node, parent, skin, data); });
  449. });
  450. }
  451. return true;
  452. };
  453. GLTFLoader.prototype._updateBone = function (node, parentNode, skin, inverseBindMatrixData) {
  454. var jointIndex = skin.joints.indexOf(node.index);
  455. if (jointIndex === -1) {
  456. this._createBone(node, skin);
  457. }
  458. var babylonBone = node.babylonSkinToBones[skin.index];
  459. // TODO: explain the math
  460. var matrix = jointIndex === -1 ? BABYLON.Matrix.Identity() : BABYLON.Matrix.FromArray(inverseBindMatrixData, jointIndex * 16);
  461. matrix.invertToRef(matrix);
  462. if (parentNode) {
  463. babylonBone.setParent(parentNode.babylonSkinToBones[skin.index], false);
  464. matrix.multiplyToRef(babylonBone.getParent().getInvertedAbsoluteTransform(), matrix);
  465. }
  466. babylonBone.updateMatrix(matrix);
  467. return true;
  468. };
  469. GLTFLoader.prototype._createBone = function (node, skin) {
  470. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton);
  471. node.babylonSkinToBones = node.babylonSkinToBones || {};
  472. node.babylonSkinToBones[skin.index] = babylonBone;
  473. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  474. node.babylonAnimationTargets.push(babylonBone);
  475. return babylonBone;
  476. };
  477. GLTFLoader.prototype._loadMesh = function (node, parentNode) {
  478. var babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  479. babylonMesh.isVisible = false;
  480. this._loadTransform(node, babylonMesh);
  481. if (node.mesh !== undefined) {
  482. var mesh = this._gltf.meshes[node.mesh];
  483. this._loadMeshData(node, mesh, babylonMesh);
  484. }
  485. babylonMesh.parent = parentNode ? parentNode.babylonMesh : null;
  486. node.babylonMesh = babylonMesh;
  487. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  488. node.babylonAnimationTargets.push(node.babylonMesh);
  489. if (node.skin !== undefined) {
  490. var skin = this._gltf.skins[node.skin];
  491. babylonMesh.skeleton = skin.babylonSkeleton;
  492. }
  493. if (node.camera !== undefined) {
  494. // TODO: handle cameras
  495. }
  496. return true;
  497. };
  498. GLTFLoader.prototype._loadMeshData = function (node, mesh, babylonMesh) {
  499. var _this = this;
  500. babylonMesh.name = mesh.name || babylonMesh.name;
  501. babylonMesh.subMeshes = [];
  502. var multiMaterial = new BABYLON.MultiMaterial(babylonMesh.name, this._babylonScene);
  503. babylonMesh.material = multiMaterial;
  504. var geometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene, null, false, babylonMesh);
  505. var vertexData = new BABYLON.VertexData();
  506. vertexData.positions = [];
  507. vertexData.indices = [];
  508. var subMeshInfos = [];
  509. var primitivesLoaded = 0;
  510. var numPrimitives = mesh.primitives.length;
  511. var _loop_1 = function () {
  512. var primitive = mesh.primitives[i];
  513. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  514. // TODO: handle other primitive modes
  515. throw new Error("Not implemented");
  516. }
  517. this_1._createMorphTargets(node, mesh, primitive, babylonMesh);
  518. this_1._loadVertexDataAsync(primitive, function (subVertexData) {
  519. _this._loadMorphTargetsData(mesh, primitive, subVertexData, babylonMesh);
  520. subMeshInfos.push({
  521. materialIndex: multiMaterial.subMaterials.length,
  522. verticesStart: vertexData.positions.length,
  523. verticesCount: subVertexData.positions.length,
  524. indicesStart: vertexData.indices.length,
  525. indicesCount: subVertexData.indices.length
  526. });
  527. var subMaterial = primitive.material === undefined ? _this._getDefaultMaterial() : GLTF2.GLTFLoaderExtension.LoadMaterial(primitive.material);
  528. multiMaterial.subMaterials.push(subMaterial);
  529. vertexData.merge(subVertexData);
  530. if (++primitivesLoaded === numPrimitives) {
  531. geometry.setAllVerticesData(vertexData, false);
  532. // Sub meshes must be created after setting vertex data because of mesh._createGlobalSubMesh.
  533. for (var i = 0; i < subMeshInfos.length; i++) {
  534. var info = subMeshInfos[i];
  535. new BABYLON.SubMesh(info.materialIndex, info.verticesStart, info.verticesCount, info.indicesStart, info.indicesCount, babylonMesh);
  536. }
  537. }
  538. });
  539. };
  540. var this_1 = this;
  541. for (var i = 0; i < numPrimitives; i++) {
  542. _loop_1();
  543. }
  544. };
  545. GLTFLoader.prototype._loadVertexDataAsync = function (primitive, onSuccess) {
  546. var _this = this;
  547. var attributes = primitive.attributes;
  548. if (!attributes) {
  549. this._errors.push("Primitive has no attributes");
  550. return;
  551. }
  552. var vertexData = new BABYLON.VertexData();
  553. var loadedAttributes = 0;
  554. var numAttributes = Object.keys(attributes).length;
  555. var _loop_2 = function (semantic) {
  556. accessor = this_2._gltf.accessors[attributes[semantic]];
  557. this_2._loadAccessorAsync(accessor, function (data) {
  558. switch (semantic) {
  559. case "NORMAL":
  560. vertexData.normals = data;
  561. break;
  562. case "POSITION":
  563. vertexData.positions = data;
  564. break;
  565. case "TANGENT":
  566. vertexData.tangents = data;
  567. break;
  568. case "TEXCOORD_0":
  569. vertexData.uvs = data;
  570. break;
  571. case "TEXCOORD_1":
  572. vertexData.uvs2 = data;
  573. break;
  574. case "JOINTS_0":
  575. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  576. break;
  577. case "WEIGHTS_0":
  578. vertexData.matricesWeights = data;
  579. break;
  580. case "COLOR_0":
  581. vertexData.colors = data;
  582. break;
  583. default:
  584. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  585. break;
  586. }
  587. if (++loadedAttributes === numAttributes) {
  588. var indicesAccessor = _this._gltf.accessors[primitive.indices];
  589. if (indicesAccessor) {
  590. _this._loadAccessorAsync(indicesAccessor, function (data) {
  591. vertexData.indices = data;
  592. onSuccess(vertexData);
  593. });
  594. }
  595. else {
  596. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  597. vertexData.indices.forEach(function (v, i) { return vertexData.indices[i] = i; });
  598. onSuccess(vertexData);
  599. }
  600. }
  601. });
  602. };
  603. var this_2 = this, accessor;
  604. for (var semantic in attributes) {
  605. _loop_2(semantic);
  606. }
  607. };
  608. GLTFLoader.prototype._createMorphTargets = function (node, mesh, primitive, babylonMesh) {
  609. var targets = primitive.targets;
  610. if (!targets) {
  611. return;
  612. }
  613. if (!babylonMesh.morphTargetManager) {
  614. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  615. }
  616. for (var index = 0; index < targets.length; index++) {
  617. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  618. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  619. }
  620. };
  621. GLTFLoader.prototype._loadMorphTargetsData = function (mesh, primitive, vertexData, babylonMesh) {
  622. var targets = primitive.targets;
  623. if (!targets) {
  624. return;
  625. }
  626. var _loop_3 = function () {
  627. var babylonMorphTarget = babylonMesh.morphTargetManager.getTarget(index);
  628. attributes = targets[index];
  629. var _loop_4 = function (semantic) {
  630. accessor = this_3._gltf.accessors[attributes[semantic]];
  631. this_3._loadAccessorAsync(accessor, function (data) {
  632. if (accessor.name) {
  633. babylonMorphTarget.name = accessor.name;
  634. }
  635. // glTF stores morph target information as deltas while babylon.js expects the final data.
  636. // As a result we have to add the original data to the delta to calculate the final data.
  637. var values = data;
  638. switch (semantic) {
  639. case "NORMAL":
  640. values.forEach(function (v, i) { return values[i] += vertexData.normals[i]; });
  641. babylonMorphTarget.setNormals(values);
  642. break;
  643. case "POSITION":
  644. values.forEach(function (v, i) { return values[i] += vertexData.positions[i]; });
  645. babylonMorphTarget.setPositions(values);
  646. break;
  647. case "TANGENT":
  648. // Tangent data for morph targets is stored as xyz delta.
  649. // The vertexData.tangent is stored as xyzw.
  650. // So we need to skip every fourth vertexData.tangent.
  651. for (var i = 0, j = 0; i < values.length; i++, j++) {
  652. values[i] += vertexData.tangents[j];
  653. if ((i + 1) % 3 == 0) {
  654. j++;
  655. }
  656. }
  657. babylonMorphTarget.setTangents(values);
  658. break;
  659. default:
  660. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  661. break;
  662. }
  663. });
  664. };
  665. for (var semantic in attributes) {
  666. _loop_4(semantic);
  667. }
  668. };
  669. var this_3 = this, attributes, accessor;
  670. for (var index = 0; index < targets.length; index++) {
  671. _loop_3();
  672. }
  673. };
  674. GLTFLoader.prototype._loadTransform = function (node, babylonMesh) {
  675. var position = BABYLON.Vector3.Zero();
  676. var rotation = BABYLON.Quaternion.Identity();
  677. var scaling = BABYLON.Vector3.One();
  678. if (node.matrix) {
  679. var mat = BABYLON.Matrix.FromArray(node.matrix);
  680. mat.decompose(scaling, rotation, position);
  681. }
  682. else {
  683. if (node.translation)
  684. position = BABYLON.Vector3.FromArray(node.translation);
  685. if (node.rotation)
  686. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  687. if (node.scale)
  688. scaling = BABYLON.Vector3.FromArray(node.scale);
  689. }
  690. babylonMesh.position = position;
  691. babylonMesh.rotationQuaternion = rotation;
  692. babylonMesh.scaling = scaling;
  693. };
  694. GLTFLoader.prototype._traverseScene = function (nodeNames, scene, action) {
  695. var nodes = scene.nodes;
  696. if (nodes) {
  697. for (var i = 0; i < nodes.length; i++) {
  698. this._traverseNode(nodeNames, nodes[i], action);
  699. }
  700. }
  701. };
  702. GLTFLoader.prototype._traverseNode = function (nodeNames, index, action, parentNode) {
  703. if (parentNode === void 0) { parentNode = null; }
  704. var node = this._gltf.nodes[index];
  705. if (nodeNames) {
  706. if (nodeNames.indexOf(node.name)) {
  707. // load all children
  708. nodeNames = null;
  709. }
  710. else {
  711. // skip this node tree
  712. return;
  713. }
  714. }
  715. node.index = index;
  716. if (!action(node, parentNode)) {
  717. return;
  718. }
  719. if (node.children) {
  720. for (var i = 0; i < node.children.length; i++) {
  721. this._traverseNode(nodeNames, node.children[i], action, node);
  722. }
  723. }
  724. };
  725. GLTFLoader.prototype._loadAnimations = function () {
  726. var animations = this._gltf.animations;
  727. if (!animations || animations.length === 0) {
  728. return;
  729. }
  730. for (var animationIndex = 0; animationIndex < animations.length; animationIndex++) {
  731. var animation = animations[animationIndex];
  732. for (var channelIndex = 0; channelIndex < animation.channels.length; channelIndex++) {
  733. this._loadAnimationChannel(animation, animationIndex, channelIndex);
  734. }
  735. }
  736. };
  737. GLTFLoader.prototype._loadAnimationChannel = function (animation, animationIndex, channelIndex) {
  738. var channel = animation.channels[channelIndex];
  739. var samplerIndex = channel.sampler;
  740. var sampler = animation.samplers[samplerIndex];
  741. var targetNode = this._gltf.nodes[channel.target.node];
  742. if (!targetNode) {
  743. BABYLON.Tools.Warn("Animation channel target node (" + channel.target.node + ") does not exist");
  744. return;
  745. }
  746. var targetPath = {
  747. "translation": "position",
  748. "rotation": "rotationQuaternion",
  749. "scale": "scaling",
  750. "weights": "influence"
  751. }[channel.target.path];
  752. if (!targetPath) {
  753. BABYLON.Tools.Warn("Animation channel target path '" + channel.target.path + "' is not valid");
  754. return;
  755. }
  756. var animationType = {
  757. "position": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  758. "rotationQuaternion": BABYLON.Animation.ANIMATIONTYPE_QUATERNION,
  759. "scaling": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  760. "influence": BABYLON.Animation.ANIMATIONTYPE_FLOAT,
  761. }[targetPath];
  762. var inputData;
  763. var outputData;
  764. var checkSuccess = function () {
  765. if (!inputData || !outputData) {
  766. return;
  767. }
  768. var outputBufferOffset = 0;
  769. var getNextOutputValue = {
  770. "position": function () {
  771. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  772. outputBufferOffset += 3;
  773. return value;
  774. },
  775. "rotationQuaternion": function () {
  776. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  777. outputBufferOffset += 4;
  778. return value;
  779. },
  780. "scaling": function () {
  781. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  782. outputBufferOffset += 3;
  783. return value;
  784. },
  785. "influence": function () {
  786. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  787. var value = new Array(numTargets);
  788. for (var i = 0; i < numTargets; i++) {
  789. value[i] = outputData[outputBufferOffset++];
  790. }
  791. return value;
  792. },
  793. }[targetPath];
  794. var getNextKey = {
  795. "LINEAR": function (frameIndex) { return ({
  796. frame: inputData[frameIndex],
  797. value: getNextOutputValue()
  798. }); },
  799. "CUBICSPLINE": function (frameIndex) { return ({
  800. frame: inputData[frameIndex],
  801. inTangent: getNextOutputValue(),
  802. value: getNextOutputValue(),
  803. outTangent: getNextOutputValue()
  804. }); },
  805. }[sampler.interpolation];
  806. var keys = new Array(inputData.length);
  807. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  808. keys[frameIndex] = getNextKey(frameIndex);
  809. }
  810. animation.targets = animation.targets || [];
  811. if (targetPath === "influence") {
  812. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  813. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  814. var morphTarget = morphTargetManager.getTarget(targetIndex);
  815. var animationName = (animation.name || "anim" + animationIndex) + "_" + targetIndex;
  816. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  817. babylonAnimation.setKeys(keys.map(function (key) { return ({
  818. frame: key.frame,
  819. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  820. value: key.value[targetIndex],
  821. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  822. }); }));
  823. morphTarget.animations.push(babylonAnimation);
  824. animation.targets.push(morphTarget);
  825. }
  826. }
  827. else {
  828. var animationName = animation.name || "anim" + animationIndex;
  829. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  830. babylonAnimation.setKeys(keys);
  831. for (var i = 0; i < targetNode.babylonAnimationTargets.length; i++) {
  832. var target = targetNode.babylonAnimationTargets[i];
  833. target.animations.push(babylonAnimation.clone());
  834. animation.targets.push(target);
  835. }
  836. }
  837. };
  838. this._loadAccessorAsync(this._gltf.accessors[sampler.input], function (data) {
  839. inputData = data;
  840. checkSuccess();
  841. });
  842. this._loadAccessorAsync(this._gltf.accessors[sampler.output], function (data) {
  843. outputData = data;
  844. checkSuccess();
  845. });
  846. };
  847. GLTFLoader.prototype._loadBufferAsync = function (index, onSuccess) {
  848. var _this = this;
  849. var buffer = this._gltf.buffers[index];
  850. this._addPendingData(buffer);
  851. if (buffer.loadedData) {
  852. setTimeout(function () {
  853. onSuccess(buffer.loadedData);
  854. _this._removePendingData(buffer);
  855. });
  856. }
  857. else if (GLTF2.GLTFUtils.IsBase64(buffer.uri)) {
  858. var data = GLTF2.GLTFUtils.DecodeBase64(buffer.uri);
  859. buffer.loadedData = new Uint8Array(data);
  860. setTimeout(function () {
  861. onSuccess(buffer.loadedData);
  862. _this._removePendingData(buffer);
  863. });
  864. }
  865. else if (buffer.loadedObservable) {
  866. buffer.loadedObservable.add(function (buffer) {
  867. onSuccess(buffer.loadedData);
  868. _this._removePendingData(buffer);
  869. });
  870. }
  871. else {
  872. buffer.loadedObservable = new BABYLON.Observable();
  873. buffer.loadedObservable.add(function (buffer) {
  874. onSuccess(buffer.loadedData);
  875. _this._removePendingData(buffer);
  876. });
  877. BABYLON.Tools.LoadFile(this._rootUrl + buffer.uri, function (data) {
  878. buffer.loadedData = new Uint8Array(data);
  879. buffer.loadedObservable.notifyObservers(buffer);
  880. buffer.loadedObservable = null;
  881. }, null, null, true, function (request) {
  882. _this._errors.push("Failed to load file '" + buffer.uri + "': " + request.statusText + "(" + request.status + ")");
  883. _this._removePendingData(buffer);
  884. });
  885. }
  886. };
  887. GLTFLoader.prototype._loadBufferViewAsync = function (bufferView, byteOffset, byteLength, componentType, onSuccess) {
  888. var _this = this;
  889. byteOffset += (bufferView.byteOffset || 0);
  890. this._loadBufferAsync(bufferView.buffer, function (bufferData) {
  891. if (byteOffset + byteLength > bufferData.byteLength) {
  892. _this._errors.push("Buffer access is out of range");
  893. return;
  894. }
  895. var buffer = bufferData.buffer;
  896. byteOffset += bufferData.byteOffset;
  897. var bufferViewData;
  898. switch (componentType) {
  899. case GLTF2.EComponentType.BYTE:
  900. bufferViewData = new Int8Array(buffer, byteOffset, byteLength);
  901. break;
  902. case GLTF2.EComponentType.UNSIGNED_BYTE:
  903. bufferViewData = new Uint8Array(buffer, byteOffset, byteLength);
  904. break;
  905. case GLTF2.EComponentType.SHORT:
  906. bufferViewData = new Int16Array(buffer, byteOffset, byteLength);
  907. break;
  908. case GLTF2.EComponentType.UNSIGNED_SHORT:
  909. bufferViewData = new Uint16Array(buffer, byteOffset, byteLength);
  910. break;
  911. case GLTF2.EComponentType.UNSIGNED_INT:
  912. bufferViewData = new Uint32Array(buffer, byteOffset, byteLength);
  913. break;
  914. case GLTF2.EComponentType.FLOAT:
  915. bufferViewData = new Float32Array(buffer, byteOffset, byteLength);
  916. break;
  917. default:
  918. _this._errors.push("Invalid component type (" + componentType + ")");
  919. return;
  920. }
  921. onSuccess(bufferViewData);
  922. });
  923. };
  924. GLTFLoader.prototype._loadAccessorAsync = function (accessor, onSuccess) {
  925. var bufferView = this._gltf.bufferViews[accessor.bufferView];
  926. var byteOffset = accessor.byteOffset || 0;
  927. var byteLength = accessor.count * GLTF2.GLTFUtils.GetByteStrideFromType(accessor);
  928. this._loadBufferViewAsync(bufferView, byteOffset, byteLength, accessor.componentType, onSuccess);
  929. };
  930. GLTFLoader.prototype._addPendingData = function (data) {
  931. this._pendingCount++;
  932. };
  933. GLTFLoader.prototype._removePendingData = function (data) {
  934. if (--this._pendingCount === 0) {
  935. this._onLoaded();
  936. }
  937. };
  938. GLTFLoader.prototype._getDefaultMaterial = function () {
  939. if (!this._defaultMaterial) {
  940. var id = "__gltf_default";
  941. var material = this._babylonScene.getMaterialByName(id);
  942. if (!material) {
  943. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  944. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  945. material.metallic = 1;
  946. material.roughness = 1;
  947. }
  948. this._defaultMaterial = material;
  949. }
  950. return this._defaultMaterial;
  951. };
  952. GLTFLoader.prototype._loadMaterial = function (index) {
  953. var materials = this._gltf.materials;
  954. var material = materials ? materials[index] : null;
  955. if (!material) {
  956. BABYLON.Tools.Warn("Material index (" + index + ") does not exist");
  957. return null;
  958. }
  959. material.babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + index, this._babylonScene);
  960. material.babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  961. material.babylonMaterial.useScalarInLinearSpace = true;
  962. return material;
  963. };
  964. GLTFLoader.prototype._loadCoreMaterial = function (index) {
  965. var material = this._loadMaterial(index);
  966. if (!material) {
  967. return null;
  968. }
  969. this._loadCommonMaterialProperties(material);
  970. // Ensure metallic workflow
  971. material.babylonMaterial.metallic = 1;
  972. material.babylonMaterial.roughness = 1;
  973. var properties = material.pbrMetallicRoughness;
  974. if (properties) {
  975. material.babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  976. material.babylonMaterial.metallic = properties.metallicFactor === undefined ? 1 : properties.metallicFactor;
  977. material.babylonMaterial.roughness = properties.roughnessFactor === undefined ? 1 : properties.roughnessFactor;
  978. if (properties.baseColorTexture) {
  979. material.babylonMaterial.albedoTexture = this._loadTexture(properties.baseColorTexture);
  980. this._loadAlphaProperties(material);
  981. }
  982. if (properties.metallicRoughnessTexture) {
  983. material.babylonMaterial.metallicTexture = this._loadTexture(properties.metallicRoughnessTexture);
  984. material.babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  985. material.babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  986. material.babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  987. }
  988. }
  989. return material.babylonMaterial;
  990. };
  991. GLTFLoader.prototype._loadCommonMaterialProperties = function (material) {
  992. material.babylonMaterial.useEmissiveAsIllumination = (material.emissiveFactor || material.emissiveTexture) ? true : false;
  993. material.babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  994. if (material.doubleSided) {
  995. material.babylonMaterial.backFaceCulling = false;
  996. material.babylonMaterial.twoSidedLighting = true;
  997. }
  998. if (material.normalTexture) {
  999. material.babylonMaterial.bumpTexture = this._loadTexture(material.normalTexture);
  1000. if (material.normalTexture.scale !== undefined) {
  1001. material.babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  1002. }
  1003. }
  1004. if (material.occlusionTexture) {
  1005. material.babylonMaterial.ambientTexture = this._loadTexture(material.occlusionTexture);
  1006. material.babylonMaterial.useAmbientInGrayScale = true;
  1007. if (material.occlusionTexture.strength !== undefined) {
  1008. material.babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  1009. }
  1010. }
  1011. if (material.emissiveTexture) {
  1012. material.babylonMaterial.emissiveTexture = this._loadTexture(material.emissiveTexture);
  1013. }
  1014. };
  1015. GLTFLoader.prototype._loadAlphaProperties = function (material) {
  1016. var alphaMode = material.alphaMode || "OPAQUE";
  1017. switch (alphaMode) {
  1018. case "OPAQUE":
  1019. // default is opaque
  1020. break;
  1021. case "MASK":
  1022. material.babylonMaterial.albedoTexture.hasAlpha = true;
  1023. material.babylonMaterial.useAlphaFromAlbedoTexture = false;
  1024. material.babylonMaterial.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  1025. break;
  1026. case "BLEND":
  1027. material.babylonMaterial.albedoTexture.hasAlpha = true;
  1028. material.babylonMaterial.useAlphaFromAlbedoTexture = true;
  1029. material.babylonMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  1030. break;
  1031. default:
  1032. BABYLON.Tools.Error("Invalid alpha mode '" + material.alphaMode + "'");
  1033. }
  1034. };
  1035. GLTFLoader.prototype._loadTexture = function (textureInfo) {
  1036. var _this = this;
  1037. var texture = this._gltf.textures[textureInfo.index];
  1038. var texCoord = textureInfo.texCoord || 0;
  1039. if (!texture || texture.source === undefined) {
  1040. return null;
  1041. }
  1042. // check the cache first
  1043. var babylonTexture;
  1044. if (texture.babylonTextures) {
  1045. babylonTexture = texture.babylonTextures[texCoord];
  1046. if (!babylonTexture) {
  1047. for (var i = 0; i < texture.babylonTextures.length; i++) {
  1048. babylonTexture = texture.babylonTextures[i];
  1049. if (babylonTexture) {
  1050. babylonTexture = babylonTexture.clone();
  1051. babylonTexture.coordinatesIndex = texCoord;
  1052. break;
  1053. }
  1054. }
  1055. }
  1056. return babylonTexture;
  1057. }
  1058. var source = this._gltf.images[texture.source];
  1059. var url;
  1060. if (!source.uri) {
  1061. var bufferView = this._gltf.bufferViews[source.bufferView];
  1062. this._loadBufferViewAsync(bufferView, 0, bufferView.byteLength, GLTF2.EComponentType.UNSIGNED_BYTE, function (data) {
  1063. texture.blobURL = URL.createObjectURL(new Blob([data], { type: source.mimeType }));
  1064. texture.babylonTextures[texCoord].updateURL(texture.blobURL);
  1065. });
  1066. }
  1067. else if (GLTF2.GLTFUtils.IsBase64(source.uri)) {
  1068. var data = new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(source.uri));
  1069. texture.blobURL = URL.createObjectURL(new Blob([data], { type: source.mimeType }));
  1070. url = texture.blobURL;
  1071. }
  1072. else {
  1073. url = this._rootUrl + source.uri;
  1074. }
  1075. var sampler = (texture.sampler === undefined ? {} : this._gltf.samplers[texture.sampler]);
  1076. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  1077. var samplingMode = GLTF2.GLTFUtils.GetTextureFilterMode(sampler.minFilter);
  1078. this._addPendingData(texture);
  1079. var babylonTexture = new BABYLON.Texture(url, this._babylonScene, noMipMaps, false, samplingMode, function () {
  1080. _this._removePendingData(texture);
  1081. }, function () {
  1082. _this._errors.push("Failed to load texture '" + source.uri + "'");
  1083. _this._removePendingData(texture);
  1084. });
  1085. babylonTexture.coordinatesIndex = texCoord;
  1086. babylonTexture.wrapU = GLTF2.GLTFUtils.GetWrapMode(sampler.wrapS);
  1087. babylonTexture.wrapV = GLTF2.GLTFUtils.GetWrapMode(sampler.wrapT);
  1088. babylonTexture.name = texture.name;
  1089. // Cache the texture
  1090. texture.babylonTextures = texture.babylonTextures || [];
  1091. texture.babylonTextures[texCoord] = babylonTexture;
  1092. return babylonTexture;
  1093. };
  1094. return GLTFLoader;
  1095. }());
  1096. GLTFLoader.Extensions = {};
  1097. GLTF2.GLTFLoader = GLTFLoader;
  1098. BABYLON.GLTFFileLoader.GLTFLoaderV2 = new GLTFLoader();
  1099. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1100. })(BABYLON || (BABYLON = {}));
  1101. //# sourceMappingURL=babylon.glTFLoader.js.map
  1102. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  1103. var BABYLON;
  1104. (function (BABYLON) {
  1105. var GLTF2;
  1106. (function (GLTF2) {
  1107. /**
  1108. * Utils functions for GLTF
  1109. */
  1110. var GLTFUtils = (function () {
  1111. function GLTFUtils() {
  1112. }
  1113. /**
  1114. * If the uri is a base64 string
  1115. * @param uri: the uri to test
  1116. */
  1117. GLTFUtils.IsBase64 = function (uri) {
  1118. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  1119. };
  1120. /**
  1121. * Decode the base64 uri
  1122. * @param uri: the uri to decode
  1123. */
  1124. GLTFUtils.DecodeBase64 = function (uri) {
  1125. var decodedString = atob(uri.split(",")[1]);
  1126. var bufferLength = decodedString.length;
  1127. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  1128. for (var i = 0; i < bufferLength; i++) {
  1129. bufferView[i] = decodedString.charCodeAt(i);
  1130. }
  1131. return bufferView.buffer;
  1132. };
  1133. /**
  1134. * Returns the wrap mode of the texture
  1135. * @param mode: the mode value
  1136. */
  1137. GLTFUtils.GetWrapMode = function (mode) {
  1138. switch (mode) {
  1139. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  1140. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  1141. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1142. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1143. }
  1144. };
  1145. /**
  1146. * Returns the byte stride giving an accessor
  1147. * @param accessor: the GLTF accessor objet
  1148. */
  1149. GLTFUtils.GetByteStrideFromType = function (accessor) {
  1150. // Needs this function since "byteStride" isn't requiered in glTF format
  1151. var type = accessor.type;
  1152. switch (type) {
  1153. case "VEC2": return 2;
  1154. case "VEC3": return 3;
  1155. case "VEC4": return 4;
  1156. case "MAT2": return 4;
  1157. case "MAT3": return 9;
  1158. case "MAT4": return 16;
  1159. default: return 1;
  1160. }
  1161. };
  1162. /**
  1163. * Returns the texture filter mode giving a mode value
  1164. * @param mode: the filter mode value
  1165. */
  1166. GLTFUtils.GetTextureFilterMode = function (mode) {
  1167. switch (mode) {
  1168. case GLTF2.ETextureMinFilter.LINEAR:
  1169. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST:
  1170. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  1171. case GLTF2.ETextureMinFilter.NEAREST:
  1172. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  1173. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1174. }
  1175. };
  1176. /**
  1177. * Decodes a buffer view into a string
  1178. * @param view: the buffer view
  1179. */
  1180. GLTFUtils.DecodeBufferToText = function (view) {
  1181. var result = "";
  1182. var length = view.byteLength;
  1183. for (var i = 0; i < length; ++i) {
  1184. result += String.fromCharCode(view[i]);
  1185. }
  1186. return result;
  1187. };
  1188. return GLTFUtils;
  1189. }());
  1190. GLTF2.GLTFUtils = GLTFUtils;
  1191. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1192. })(BABYLON || (BABYLON = {}));
  1193. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  1194. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  1195. var BABYLON;
  1196. (function (BABYLON) {
  1197. var GLTF2;
  1198. (function (GLTF2) {
  1199. var GLTFLoaderExtension = (function () {
  1200. function GLTFLoaderExtension(name) {
  1201. this.enabled = true;
  1202. this._name = name;
  1203. }
  1204. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  1205. get: function () {
  1206. return this._name;
  1207. },
  1208. enumerable: true,
  1209. configurable: true
  1210. });
  1211. GLTFLoaderExtension.prototype.loadMaterial = function (index) { return null; };
  1212. // ---------
  1213. // Utilities
  1214. // ---------
  1215. GLTFLoaderExtension.LoadMaterial = function (index) {
  1216. for (var extensionName in GLTF2.GLTFLoader.Extensions) {
  1217. var extension = GLTF2.GLTFLoader.Extensions[extensionName];
  1218. if (extension.enabled) {
  1219. var babylonMaterial = extension.loadMaterial(index);
  1220. if (babylonMaterial) {
  1221. return babylonMaterial;
  1222. }
  1223. }
  1224. }
  1225. return GLTF2.GLTFLoader.LoadCoreMaterial(index);
  1226. };
  1227. return GLTFLoaderExtension;
  1228. }());
  1229. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  1230. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1231. })(BABYLON || (BABYLON = {}));
  1232. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  1233. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  1234. var __extends = (this && this.__extends) || (function () {
  1235. var extendStatics = Object.setPrototypeOf ||
  1236. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  1237. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  1238. return function (d, b) {
  1239. extendStatics(d, b);
  1240. function __() { this.constructor = d; }
  1241. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1242. };
  1243. })();
  1244. var BABYLON;
  1245. (function (BABYLON) {
  1246. var GLTF2;
  1247. (function (GLTF2) {
  1248. var GLTFMaterialsPbrSpecularGlossinessExtension = (function (_super) {
  1249. __extends(GLTFMaterialsPbrSpecularGlossinessExtension, _super);
  1250. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  1251. return _super.call(this, "KHR_materials_pbrSpecularGlossiness") || this;
  1252. }
  1253. GLTFMaterialsPbrSpecularGlossinessExtension.prototype.loadMaterial = function (index) {
  1254. var material = GLTF2.GLTFLoader.LoadMaterial(index);
  1255. if (!material || !material.extensions)
  1256. return null;
  1257. var properties = material.extensions[this.name];
  1258. if (!properties)
  1259. return null;
  1260. GLTF2.GLTFLoader.LoadCommonMaterialProperties(material);
  1261. //
  1262. // Load Factors
  1263. //
  1264. material.babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  1265. material.babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  1266. material.babylonMaterial.microSurface = properties.glossinessFactor === undefined ? 1 : properties.glossinessFactor;
  1267. //
  1268. // Load Textures
  1269. //
  1270. if (properties.diffuseTexture) {
  1271. material.babylonMaterial.albedoTexture = GLTF2.GLTFLoader.LoadTexture(properties.diffuseTexture);
  1272. GLTF2.GLTFLoader.LoadAlphaProperties(material);
  1273. }
  1274. if (properties.specularGlossinessTexture) {
  1275. material.babylonMaterial.reflectivityTexture = GLTF2.GLTFLoader.LoadTexture(properties.specularGlossinessTexture);
  1276. material.babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  1277. }
  1278. return material.babylonMaterial;
  1279. };
  1280. return GLTFMaterialsPbrSpecularGlossinessExtension;
  1281. }(GLTF2.GLTFLoaderExtension));
  1282. GLTF2.GLTFMaterialsPbrSpecularGlossinessExtension = GLTFMaterialsPbrSpecularGlossinessExtension;
  1283. GLTF2.GLTFLoader.RegisterExtension(new GLTFMaterialsPbrSpecularGlossinessExtension());
  1284. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1285. })(BABYLON || (BABYLON = {}));
  1286. //# sourceMappingURL=babylon.glTFMaterialsPbrSpecularGlossinessExtension.js.map