babylon.glTF2FileLoader.js 78 KB

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