babylon.glTF2FileLoader.js 78 KB

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