babylon.glTF2FileLoader.js 78 KB

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