babylon.glTF2FileLoader.js 73 KB

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