babylon.glTF2FileLoader.js 78 KB

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