babylonjs.serializers.js 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263
  1. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  2. var babylonDependency = (globalObject && globalObject.BABYLON) || BABYLON || (typeof require !== 'undefined' && require("babylonjs"));
  3. var BABYLON = babylonDependency;
  4. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  5. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  6. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  7. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  8. return c > 3 && r && Object.defineProperty(target, key, r), r;
  9. };
  10. var __extends = (this && this.__extends) || (function () {
  11. var extendStatics = Object.setPrototypeOf ||
  12. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  13. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  14. return function (d, b) {
  15. extendStatics(d, b);
  16. function __() { this.constructor = d; }
  17. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  18. };
  19. })();
  20. var BABYLON;
  21. (function (BABYLON) {
  22. var OBJExport = /** @class */ (function () {
  23. function OBJExport() {
  24. }
  25. //Exports the geometrys of a Mesh array in .OBJ file format (text)
  26. OBJExport.OBJ = function (mesh, materials, matlibname, globalposition) {
  27. var output = [];
  28. var v = 1;
  29. if (materials) {
  30. if (!matlibname) {
  31. matlibname = 'mat';
  32. }
  33. output.push("mtllib " + matlibname + ".mtl");
  34. }
  35. for (var j = 0; j < mesh.length; j++) {
  36. output.push("g object" + j);
  37. output.push("o object_" + j);
  38. //Uses the position of the item in the scene, to the file (this back to normal in the end)
  39. var lastMatrix = null;
  40. if (globalposition) {
  41. var newMatrix = BABYLON.Matrix.Translation(mesh[j].position.x, mesh[j].position.y, mesh[j].position.z);
  42. lastMatrix = BABYLON.Matrix.Translation(-(mesh[j].position.x), -(mesh[j].position.y), -(mesh[j].position.z));
  43. mesh[j].bakeTransformIntoVertices(newMatrix);
  44. }
  45. //TODO: submeshes (groups)
  46. //TODO: smoothing groups (s 1, s off);
  47. if (materials) {
  48. var mat = mesh[j].material;
  49. if (mat) {
  50. output.push("usemtl " + mat.id);
  51. }
  52. }
  53. var g = mesh[j].geometry;
  54. if (!g) {
  55. continue;
  56. }
  57. var trunkVerts = g.getVerticesData('position');
  58. var trunkNormals = g.getVerticesData('normal');
  59. var trunkUV = g.getVerticesData('uv');
  60. var trunkFaces = g.getIndices();
  61. var curV = 0;
  62. if (!trunkVerts || !trunkNormals || !trunkUV || !trunkFaces) {
  63. continue;
  64. }
  65. for (var i = 0; i < trunkVerts.length; i += 3) {
  66. output.push("v " + trunkVerts[i] + " " + trunkVerts[i + 1] + " " + trunkVerts[i + 2]);
  67. curV++;
  68. }
  69. for (i = 0; i < trunkNormals.length; i += 3) {
  70. output.push("vn " + trunkNormals[i] + " " + trunkNormals[i + 1] + " " + trunkNormals[i + 2]);
  71. }
  72. for (i = 0; i < trunkUV.length; i += 2) {
  73. output.push("vt " + trunkUV[i] + " " + trunkUV[i + 1]);
  74. }
  75. for (i = 0; i < trunkFaces.length; i += 3) {
  76. output.push("f " + (trunkFaces[i + 2] + v) + "/" + (trunkFaces[i + 2] + v) + "/" + (trunkFaces[i + 2] + v) +
  77. " " + (trunkFaces[i + 1] + v) + "/" + (trunkFaces[i + 1] + v) + "/" + (trunkFaces[i + 1] + v) +
  78. " " + (trunkFaces[i] + v) + "/" + (trunkFaces[i] + v) + "/" + (trunkFaces[i] + v));
  79. }
  80. //back de previous matrix, to not change the original mesh in the scene
  81. if (globalposition && lastMatrix) {
  82. mesh[j].bakeTransformIntoVertices(lastMatrix);
  83. }
  84. v += curV;
  85. }
  86. var text = output.join("\n");
  87. return (text);
  88. };
  89. //Exports the material(s) of a mesh in .MTL file format (text)
  90. //TODO: Export the materials of mesh array
  91. OBJExport.MTL = function (mesh) {
  92. var output = [];
  93. var m = mesh.material;
  94. output.push("newmtl mat1");
  95. output.push(" Ns " + m.specularPower.toFixed(4));
  96. output.push(" Ni 1.5000");
  97. output.push(" d " + m.alpha.toFixed(4));
  98. output.push(" Tr 0.0000");
  99. output.push(" Tf 1.0000 1.0000 1.0000");
  100. output.push(" illum 2");
  101. output.push(" Ka " + m.ambientColor.r.toFixed(4) + " " + m.ambientColor.g.toFixed(4) + " " + m.ambientColor.b.toFixed(4));
  102. output.push(" Kd " + m.diffuseColor.r.toFixed(4) + " " + m.diffuseColor.g.toFixed(4) + " " + m.diffuseColor.b.toFixed(4));
  103. output.push(" Ks " + m.specularColor.r.toFixed(4) + " " + m.specularColor.g.toFixed(4) + " " + m.specularColor.b.toFixed(4));
  104. output.push(" Ke " + m.emissiveColor.r.toFixed(4) + " " + m.emissiveColor.g.toFixed(4) + " " + m.emissiveColor.b.toFixed(4));
  105. //TODO: uv scale, offset, wrap
  106. //TODO: UV mirrored in Blender? second UV channel? lightMap? reflection textures?
  107. var uvscale = "";
  108. if (m.ambientTexture) {
  109. output.push(" map_Ka " + uvscale + m.ambientTexture.name);
  110. }
  111. if (m.diffuseTexture) {
  112. output.push(" map_Kd " + uvscale + m.diffuseTexture.name);
  113. //TODO: alpha testing, opacity in diffuse texture alpha channel (diffuseTexture.hasAlpha -> map_d)
  114. }
  115. if (m.specularTexture) {
  116. output.push(" map_Ks " + uvscale + m.specularTexture.name);
  117. /* TODO: glossiness = specular highlight component is in alpha channel of specularTexture. (???)
  118. if (m.useGlossinessFromSpecularMapAlpha) {
  119. output.push(" map_Ns "+uvscale + m.specularTexture.name);
  120. }
  121. */
  122. }
  123. /* TODO: emissive texture not in .MAT format (???)
  124. if (m.emissiveTexture) {
  125. output.push(" map_d "+uvscale+m.emissiveTexture.name);
  126. }
  127. */
  128. if (m.bumpTexture) {
  129. output.push(" map_bump -imfchan z " + uvscale + m.bumpTexture.name);
  130. }
  131. if (m.opacityTexture) {
  132. output.push(" map_d " + uvscale + m.opacityTexture.name);
  133. }
  134. var text = output.join("\n");
  135. return (text);
  136. };
  137. return OBJExport;
  138. }());
  139. BABYLON.OBJExport = OBJExport;
  140. })(BABYLON || (BABYLON = {}));
  141. //# sourceMappingURL=babylon.objSerializer.js.map
  142. var BABYLON;
  143. (function (BABYLON) {
  144. ;
  145. /**
  146. * Class for generating glTF data from a Babylon scene.
  147. */
  148. var GLTF2Export = /** @class */ (function () {
  149. function GLTF2Export() {
  150. }
  151. /**
  152. * Exports the geometry of the scene to .gltf file format.
  153. * @param scene - Babylon scene with scene hierarchy information.
  154. * @param filePrefix - File prefix to use when generating the glTF file.
  155. * @param options - Exporter options.
  156. * @returns - Returns an object with a .gltf file and associates texture names
  157. * as keys and their data and paths as values.
  158. */
  159. GLTF2Export.GLTF = function (scene, filePrefix, options) {
  160. var glTFPrefix = filePrefix.replace(/\.[^/.]+$/, "");
  161. var gltfGenerator = new BABYLON.GLTF2._Exporter(scene, options);
  162. if (scene.isReady) {
  163. return gltfGenerator._generateGLTF(glTFPrefix);
  164. }
  165. else {
  166. throw new Error("glTF Serializer: Scene is not ready!");
  167. }
  168. };
  169. /**
  170. * Exports the geometry of the scene to .glb file format.
  171. * @param scene - Babylon scene with scene hierarchy information.
  172. * @param filePrefix - File prefix to use when generating glb file.
  173. * @param options - Exporter options.
  174. * @returns - Returns an object with a .glb filename as key and data as value
  175. */
  176. GLTF2Export.GLB = function (scene, filePrefix, options) {
  177. var glTFPrefix = filePrefix.replace(/\.[^/.]+$/, "");
  178. var gltfGenerator = new BABYLON.GLTF2._Exporter(scene, options);
  179. if (scene.isReady) {
  180. return gltfGenerator._generateGLB(glTFPrefix);
  181. }
  182. else {
  183. throw new Error("glTF Serializer: Scene is not ready!");
  184. }
  185. };
  186. return GLTF2Export;
  187. }());
  188. BABYLON.GLTF2Export = GLTF2Export;
  189. })(BABYLON || (BABYLON = {}));
  190. //# sourceMappingURL=babylon.glTFSerializer.js.map
  191. /**
  192. * Module for the Babylon glTF 2.0 exporter. Should ONLY be used internally.
  193. * @ignore - capitalization of GLTF2 module.
  194. */
  195. var BABYLON;
  196. (function (BABYLON) {
  197. var GLTF2;
  198. (function (GLTF2) {
  199. /**
  200. * Converts Babylon Scene into glTF 2.0.
  201. */
  202. var _Exporter = /** @class */ (function () {
  203. /**
  204. * Creates a glTF Exporter instance, which can accept optional exporter options.
  205. * @param babylonScene - Babylon scene object
  206. * @param options - Options to modify the behavior of the exporter.
  207. */
  208. function _Exporter(babylonScene, options) {
  209. this.asset = { generator: "BabylonJS", version: "2.0" };
  210. this.babylonScene = babylonScene;
  211. this.bufferViews = new Array();
  212. this.accessors = new Array();
  213. this.meshes = new Array();
  214. this.scenes = new Array();
  215. this.nodes = new Array();
  216. this.images = new Array();
  217. this.materials = new Array();
  218. this.imageData = {};
  219. if (options !== undefined) {
  220. this.options = options;
  221. }
  222. var totalByteLength = 0;
  223. totalByteLength = this.createScene(this.babylonScene, totalByteLength);
  224. this.totalByteLength = totalByteLength;
  225. }
  226. /**
  227. * Creates a buffer view based on teh supplied arguments
  228. * @param {number} bufferIndex - index value of the specified buffer
  229. * @param {number} byteOffset - byte offset value
  230. * @param {number} byteLength - byte length of the bufferView
  231. * @returns - bufferView for glTF
  232. */
  233. _Exporter.prototype.createBufferView = function (bufferIndex, byteOffset, byteLength, name) {
  234. var bufferview = { buffer: bufferIndex, byteLength: byteLength };
  235. if (byteOffset > 0) {
  236. bufferview.byteOffset = byteOffset;
  237. }
  238. if (name) {
  239. bufferview.name = name;
  240. }
  241. return bufferview;
  242. };
  243. /**
  244. * Creates an accessor based on the supplied arguments
  245. * @param bufferviewIndex
  246. * @param name
  247. * @param type
  248. * @param componentType
  249. * @param count
  250. * @param min
  251. * @param max
  252. * @returns - accessor for glTF
  253. */
  254. _Exporter.prototype.createAccessor = function (bufferviewIndex, name, type, componentType, count, min, max) {
  255. var accessor = { name: name, bufferView: bufferviewIndex, componentType: componentType, count: count, type: type };
  256. if (min) {
  257. accessor.min = min;
  258. }
  259. if (max) {
  260. accessor.max = max;
  261. }
  262. return accessor;
  263. };
  264. /**
  265. * Calculates the minimum and maximum values of an array of floats, based on stride
  266. * @param buff
  267. * @param vertexStart
  268. * @param vertexCount
  269. * @param arrayOffset
  270. * @param stride
  271. * @returns - min number array and max number array
  272. */
  273. _Exporter.prototype.calculateMinMax = function (buff, vertexStart, vertexCount, arrayOffset, stride) {
  274. var min = [Infinity, Infinity, Infinity];
  275. var max = [-Infinity, -Infinity, -Infinity];
  276. var end = vertexStart + vertexCount;
  277. if (vertexCount > 0) {
  278. for (var i = vertexStart; i < end; ++i) {
  279. var index = stride * i;
  280. for (var j = 0; j < stride; ++j) {
  281. if (buff[index] < min[j]) {
  282. min[j] = buff[index];
  283. }
  284. if (buff[index] > max[j]) {
  285. max[j] = buff[index];
  286. }
  287. ++index;
  288. }
  289. }
  290. }
  291. return { min: min, max: max };
  292. };
  293. /**
  294. * Write mesh attribute data to buffer.
  295. * Returns the bytelength of the data.
  296. * @param vertexBufferType
  297. * @param submesh
  298. * @param meshAttributeArray
  299. * @param strideSize
  300. * @param byteOffset
  301. * @param dataBuffer
  302. * @param useRightHandedSystem
  303. * @returns - byte length
  304. */
  305. _Exporter.prototype.writeAttributeData = function (vertexBufferType, submesh, meshAttributeArray, strideSize, byteOffset, dataBuffer, useRightHandedSystem) {
  306. var byteOff = byteOffset;
  307. var end = submesh.verticesStart + submesh.verticesCount;
  308. var byteLength = 0;
  309. switch (vertexBufferType) {
  310. case BABYLON.VertexBuffer.PositionKind: {
  311. for (var k = submesh.verticesStart; k < end; ++k) {
  312. var index = k * strideSize;
  313. dataBuffer.setFloat32(byteOff, meshAttributeArray[index], true);
  314. byteOff += 4;
  315. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 1], true);
  316. byteOff += 4;
  317. if (useRightHandedSystem) {
  318. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 2], true);
  319. }
  320. else {
  321. dataBuffer.setFloat32(byteOff, -meshAttributeArray[index + 2], true);
  322. }
  323. byteOff += 4;
  324. }
  325. byteLength = submesh.verticesCount * 12;
  326. break;
  327. }
  328. case BABYLON.VertexBuffer.NormalKind: {
  329. for (var k = submesh.verticesStart; k < end; ++k) {
  330. var index = k * strideSize;
  331. dataBuffer.setFloat32(byteOff, meshAttributeArray[index], true);
  332. byteOff += 4;
  333. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 1], true);
  334. byteOff += 4;
  335. if (useRightHandedSystem) {
  336. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 2], true);
  337. }
  338. else {
  339. dataBuffer.setFloat32(byteOff, -meshAttributeArray[index + 2], true);
  340. }
  341. byteOff += 4;
  342. }
  343. byteLength = submesh.verticesCount * 12;
  344. break;
  345. }
  346. case BABYLON.VertexBuffer.TangentKind: {
  347. for (var k = submesh.indexStart; k < end; ++k) {
  348. var index = k * strideSize;
  349. dataBuffer.setFloat32(byteOff, meshAttributeArray[index], true);
  350. byteOff += 4;
  351. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 1], true);
  352. byteOff += 4;
  353. if (useRightHandedSystem) {
  354. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 2], true);
  355. }
  356. else {
  357. dataBuffer.setFloat32(byteOff, -meshAttributeArray[index + 2], true);
  358. }
  359. byteOff += 4;
  360. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 3], true);
  361. byteOff += 4;
  362. }
  363. byteLength = submesh.verticesCount * 16;
  364. break;
  365. }
  366. case BABYLON.VertexBuffer.ColorKind: {
  367. for (var k = submesh.verticesStart; k < end; ++k) {
  368. var index = k * strideSize;
  369. dataBuffer.setFloat32(byteOff, meshAttributeArray[index], true);
  370. byteOff += 4;
  371. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 1], true);
  372. byteOff += 4;
  373. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 2], true);
  374. byteOff += 4;
  375. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 3], true);
  376. byteOff += 4;
  377. }
  378. byteLength = submesh.verticesCount * 16;
  379. break;
  380. }
  381. case BABYLON.VertexBuffer.UVKind: {
  382. for (var k = submesh.verticesStart; k < end; ++k) {
  383. var index = k * strideSize;
  384. dataBuffer.setFloat32(byteOff, meshAttributeArray[index], true);
  385. byteOff += 4;
  386. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 1], true);
  387. byteOff += 4;
  388. }
  389. byteLength = submesh.verticesCount * 8;
  390. break;
  391. }
  392. case BABYLON.VertexBuffer.UV2Kind: {
  393. for (var k = submesh.verticesStart; k < end; ++k) {
  394. var index = k * strideSize;
  395. dataBuffer.setFloat32(byteOff, meshAttributeArray[index], true);
  396. byteOff += 4;
  397. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 1], true);
  398. byteOff += 4;
  399. }
  400. byteLength = submesh.verticesCount * 8;
  401. break;
  402. }
  403. default: {
  404. throw new Error("Unsupported vertex buffer type: " + vertexBufferType);
  405. }
  406. }
  407. return byteLength;
  408. };
  409. /**
  410. * Generates glTF json data
  411. * @param glb
  412. * @param glTFPrefix
  413. * @param prettyPrint
  414. * @returns - json data as string
  415. */
  416. _Exporter.prototype.generateJSON = function (glb, glTFPrefix, prettyPrint) {
  417. var buffer = { byteLength: this.totalByteLength };
  418. var glTF = {
  419. asset: this.asset
  420. };
  421. if (buffer.byteLength > 0) {
  422. glTF.buffers = [buffer];
  423. }
  424. if (this.nodes && this.nodes.length !== 0) {
  425. glTF.nodes = this.nodes;
  426. }
  427. if (this.meshes && this.meshes.length !== 0) {
  428. glTF.meshes = this.meshes;
  429. }
  430. if (this.scenes && this.scenes.length !== 0) {
  431. glTF.scenes = this.scenes;
  432. glTF.scene = 0;
  433. }
  434. if (this.bufferViews && this.bufferViews.length !== 0) {
  435. glTF.bufferViews = this.bufferViews;
  436. }
  437. if (this.accessors && this.accessors.length !== 0) {
  438. glTF.accessors = this.accessors;
  439. }
  440. if (this.materials && this.materials.length !== 0) {
  441. glTF.materials = this.materials;
  442. }
  443. if (this.textures && this.textures.length !== 0) {
  444. glTF.textures = this.textures;
  445. }
  446. if (this.images && this.images.length !== 0) {
  447. if (!glb) {
  448. glTF.images = this.images;
  449. }
  450. else {
  451. glTF.images = [];
  452. // Replace uri with bufferview and mime type for glb
  453. var imageLength = this.images.length;
  454. var byteOffset = this.totalByteLength;
  455. for (var i = 0; i < imageLength; ++i) {
  456. var image = this.images[i];
  457. if (image.uri !== undefined) {
  458. var imageData = this.imageData[image.uri];
  459. var imageName = image.uri.split('.')[0] + " image";
  460. var bufferView = this.createBufferView(0, byteOffset, imageData.data.length, imageName);
  461. byteOffset += imageData.data.buffer.byteLength;
  462. this.bufferViews.push(bufferView);
  463. image.bufferView = this.bufferViews.length - 1;
  464. image.name = imageName;
  465. image.mimeType = imageData.mimeType;
  466. image.uri = undefined;
  467. glTF.images.push(image);
  468. }
  469. }
  470. buffer.byteLength = byteOffset;
  471. }
  472. }
  473. if (!glb) {
  474. buffer.uri = glTFPrefix + ".bin";
  475. }
  476. var jsonText = prettyPrint ? JSON.stringify(glTF, null, 2) : JSON.stringify(glTF);
  477. return jsonText;
  478. };
  479. /**
  480. * Generates data for .gltf and .bin files based on the glTF prefix string
  481. * @param glTFPrefix
  482. * @returns - object with glTF json tex filename
  483. * and binary file name as keys and their data as values
  484. */
  485. _Exporter.prototype._generateGLTF = function (glTFPrefix) {
  486. var jsonText = this.generateJSON(false, glTFPrefix, true);
  487. var binaryBuffer = this.generateBinary();
  488. var bin = new Blob([binaryBuffer], { type: 'application/octet-stream' });
  489. var glTFFileName = glTFPrefix + '.gltf';
  490. var glTFBinFile = glTFPrefix + '.bin';
  491. var container = new BABYLON._GLTFData();
  492. container.glTFFiles[glTFFileName] = jsonText;
  493. container.glTFFiles[glTFBinFile] = bin;
  494. if (this.imageData !== null) {
  495. for (var image in this.imageData) {
  496. container.glTFFiles[image] = new Blob([this.imageData[image].data], { type: this.imageData[image].mimeType });
  497. }
  498. }
  499. return container;
  500. };
  501. /**
  502. * Creates a binary buffer for glTF
  503. * @returns - array buffer for binary data
  504. */
  505. _Exporter.prototype.generateBinary = function () {
  506. var byteOffset = 0;
  507. var binaryBuffer = new ArrayBuffer(this.totalByteLength);
  508. var dataBuffer = new DataView(binaryBuffer);
  509. byteOffset = this.createScene(this.babylonScene, byteOffset, dataBuffer);
  510. return binaryBuffer;
  511. };
  512. /**
  513. * Pads the number to a power of 4
  514. * @param num - number to pad
  515. * @returns - padded number
  516. */
  517. _Exporter.prototype._getPadding = function (num) {
  518. var remainder = num % 4;
  519. var padding = remainder === 0 ? remainder : 4 - remainder;
  520. return padding;
  521. };
  522. /**
  523. * Generates a glb file from the json and binary data.
  524. * Returns an object with the glb file name as the key and data as the value.
  525. * @param jsonText
  526. * @param binaryBuffer
  527. * @param glTFPrefix
  528. * @returns - object with glb filename as key and data as value
  529. */
  530. _Exporter.prototype._generateGLB = function (glTFPrefix) {
  531. var jsonText = this.generateJSON(true);
  532. var binaryBuffer = this.generateBinary();
  533. var glbFileName = glTFPrefix + '.glb';
  534. var headerLength = 12;
  535. var chunkLengthPrefix = 8;
  536. var jsonLength = jsonText.length;
  537. var imageByteLength = 0;
  538. for (var key in this.imageData) {
  539. imageByteLength += this.imageData[key].data.byteLength;
  540. }
  541. var jsonPadding = this._getPadding(jsonLength);
  542. var binPadding = this._getPadding(binaryBuffer.byteLength);
  543. var byteLength = headerLength + (2 * chunkLengthPrefix) + jsonLength + jsonPadding + binaryBuffer.byteLength + binPadding + imageByteLength;
  544. //header
  545. var headerBuffer = new ArrayBuffer(headerLength);
  546. var headerBufferView = new DataView(headerBuffer);
  547. headerBufferView.setUint32(0, 0x46546C67, true); //glTF
  548. headerBufferView.setUint32(4, 2, true); // version
  549. headerBufferView.setUint32(8, byteLength, true); // total bytes in file
  550. //json chunk
  551. var jsonChunkBuffer = new ArrayBuffer(chunkLengthPrefix + jsonLength + jsonPadding);
  552. var jsonChunkBufferView = new DataView(jsonChunkBuffer);
  553. jsonChunkBufferView.setUint32(0, jsonLength + jsonPadding, true);
  554. jsonChunkBufferView.setUint32(4, 0x4E4F534A, true);
  555. //json chunk bytes
  556. var jsonData = new Uint8Array(jsonChunkBuffer, chunkLengthPrefix);
  557. for (var i = 0; i < jsonLength; ++i) {
  558. jsonData[i] = jsonText.charCodeAt(i);
  559. }
  560. //json padding
  561. var jsonPaddingView = new Uint8Array(jsonChunkBuffer, chunkLengthPrefix + jsonLength);
  562. for (var i = 0; i < jsonPadding; ++i) {
  563. jsonPaddingView[i] = 0x20;
  564. }
  565. //binary chunk
  566. var binaryChunkBuffer = new ArrayBuffer(chunkLengthPrefix);
  567. var binaryChunkBufferView = new DataView(binaryChunkBuffer);
  568. binaryChunkBufferView.setUint32(0, binaryBuffer.byteLength + imageByteLength, true);
  569. binaryChunkBufferView.setUint32(4, 0x004E4942, true);
  570. // binary padding
  571. var binPaddingBuffer = new ArrayBuffer(binPadding);
  572. var binPaddingView = new Uint8Array(binPaddingBuffer);
  573. for (var i = 0; i < binPadding; ++i) {
  574. binPaddingView[i] = 0;
  575. }
  576. var glbData = [headerBuffer, jsonChunkBuffer, binaryChunkBuffer, binaryBuffer];
  577. // binary data
  578. for (var key in this.imageData) {
  579. glbData.push(this.imageData[key].data.buffer);
  580. }
  581. glbData.push(binPaddingBuffer);
  582. var glbFile = new Blob(glbData, { type: 'application/octet-stream' });
  583. var container = new BABYLON._GLTFData();
  584. container.glTFFiles[glbFileName] = glbFile;
  585. return container;
  586. };
  587. /**
  588. * Sets the TRS for each node
  589. * @param node
  590. * @param babylonMesh
  591. * @param useRightHandedSystem
  592. */
  593. _Exporter.prototype.setNodeTransformation = function (node, babylonMesh, useRightHandedSystem) {
  594. if (!(babylonMesh.position.x === 0 && babylonMesh.position.y === 0 && babylonMesh.position.z === 0)) {
  595. if (useRightHandedSystem) {
  596. node.translation = babylonMesh.position.asArray();
  597. }
  598. else {
  599. node.translation = [babylonMesh.position.x, babylonMesh.position.y, -babylonMesh.position.z];
  600. }
  601. }
  602. if (!(babylonMesh.scaling.x === 1 && babylonMesh.scaling.y === 1 && babylonMesh.scaling.z === 1)) {
  603. if (useRightHandedSystem) {
  604. node.scale = babylonMesh.scaling.asArray();
  605. }
  606. else {
  607. node.scale = [babylonMesh.scaling.x, babylonMesh.scaling.y, -babylonMesh.scaling.z];
  608. }
  609. }
  610. var rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(babylonMesh.rotation.y, babylonMesh.rotation.x, babylonMesh.rotation.z);
  611. if (babylonMesh.rotationQuaternion) {
  612. rotationQuaternion = rotationQuaternion.multiply(babylonMesh.rotationQuaternion);
  613. }
  614. if (!(rotationQuaternion.x === 0 && rotationQuaternion.y === 0 && rotationQuaternion.z === 0 && rotationQuaternion.w === 1)) {
  615. if (useRightHandedSystem) {
  616. node.rotation = rotationQuaternion.asArray();
  617. }
  618. else {
  619. node.rotation = [-rotationQuaternion.x, -rotationQuaternion.y, rotationQuaternion.z, rotationQuaternion.w];
  620. }
  621. }
  622. };
  623. /**
  624. *
  625. * @param babylonTexture
  626. * @return - glTF texture, or null if the texture format is not supported
  627. */
  628. _Exporter.prototype.exportTexture = function (babylonTexture, mimeType) {
  629. if (mimeType === void 0) { mimeType = "image/jpeg" /* JPEG */; }
  630. var textureInfo = null;
  631. var glTFTexture;
  632. glTFTexture = {
  633. source: this.images.length
  634. };
  635. var textureName = babylonTexture.getInternalTexture().url;
  636. if (textureName.search('/') !== -1) {
  637. var splitFilename = textureName.split('/');
  638. textureName = splitFilename[splitFilename.length - 1];
  639. var basefile = textureName.split('.')[0];
  640. var extension = textureName.split('.')[1];
  641. if (mimeType === "image/jpeg" /* JPEG */) {
  642. extension = ".jpg";
  643. }
  644. else if (mimeType === "image/png" /* PNG */) {
  645. extension = ".png";
  646. }
  647. else {
  648. throw new Error("Unsupported mime type " + mimeType);
  649. }
  650. textureName = basefile + extension;
  651. }
  652. var pixels = babylonTexture.readPixels();
  653. var imageCanvas = document.createElement('canvas');
  654. imageCanvas.id = "ImageCanvas";
  655. var ctx = imageCanvas.getContext('2d');
  656. var size = babylonTexture.getSize();
  657. imageCanvas.width = size.width;
  658. imageCanvas.height = size.height;
  659. var imgData = ctx.createImageData(size.width, size.height);
  660. imgData.data.set(pixels);
  661. ctx.putImageData(imgData, 0, 0);
  662. var base64Data = imageCanvas.toDataURL(mimeType);
  663. var binStr = atob(base64Data.split(',')[1]);
  664. var arr = new Uint8Array(binStr.length);
  665. for (var i = 0; i < binStr.length; ++i) {
  666. arr[i] = binStr.charCodeAt(i);
  667. }
  668. var imageValues = { data: arr, mimeType: mimeType };
  669. this.imageData[textureName] = imageValues;
  670. if (mimeType === "image/jpeg" /* JPEG */) {
  671. var glTFImage = {
  672. uri: textureName
  673. };
  674. var foundIndex = -1;
  675. for (var i = 0; i < this.images.length; ++i) {
  676. if (this.images[i].uri === textureName) {
  677. foundIndex = i;
  678. break;
  679. }
  680. }
  681. if (foundIndex === -1) {
  682. this.images.push(glTFImage);
  683. glTFTexture.source = this.images.length - 1;
  684. this.textures.push({
  685. source: this.images.length - 1
  686. });
  687. textureInfo = {
  688. index: this.images.length - 1
  689. };
  690. }
  691. else {
  692. glTFTexture.source = foundIndex;
  693. textureInfo = {
  694. index: foundIndex
  695. };
  696. }
  697. }
  698. return textureInfo;
  699. };
  700. /**
  701. * Sets data for the primitive attributes of each submesh
  702. * @param mesh
  703. * @param babylonMesh
  704. * @param byteOffset
  705. * @param useRightHandedSystem
  706. * @param dataBuffer
  707. * @returns - bytelength of the primitive attributes plus the passed in byteOffset
  708. */
  709. _Exporter.prototype.setPrimitiveAttributes = function (mesh, babylonMesh, byteOffset, useRightHandedSystem, dataBuffer) {
  710. // go through all mesh primitives (submeshes)
  711. for (var j = 0; j < babylonMesh.subMeshes.length; ++j) {
  712. var bufferMesh = null;
  713. var submesh = babylonMesh.subMeshes[j];
  714. var meshPrimitive = { attributes: {} };
  715. if (babylonMesh instanceof BABYLON.Mesh) {
  716. bufferMesh = babylonMesh;
  717. }
  718. else if (babylonMesh instanceof BABYLON.InstancedMesh) {
  719. bufferMesh = babylonMesh.sourceMesh;
  720. }
  721. // Loop through each attribute of the submesh (mesh primitive)
  722. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  723. var positionVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  724. var positionVertexBufferOffset = positionVertexBuffer.getOffset();
  725. var positions = positionVertexBuffer.getData();
  726. var positionStrideSize = positionVertexBuffer.getStrideSize();
  727. if (dataBuffer) {
  728. byteOffset += this.writeAttributeData(BABYLON.VertexBuffer.PositionKind, submesh, positions, positionStrideSize, byteOffset, dataBuffer, useRightHandedSystem);
  729. }
  730. else {
  731. // Create bufferview
  732. var byteLength = submesh.verticesCount * 12;
  733. var bufferview = this.createBufferView(0, byteOffset, byteLength, "Positions");
  734. byteOffset += byteLength;
  735. this.bufferViews.push(bufferview);
  736. // Create accessor
  737. var result = this.calculateMinMax(positions, submesh.verticesStart, submesh.verticesCount, positionVertexBufferOffset, positionStrideSize);
  738. var accessor = this.createAccessor(this.bufferViews.length - 1, "Position", "VEC3" /* VEC3 */, 5126 /* FLOAT */, submesh.verticesCount, result.min, result.max);
  739. this.accessors.push(accessor);
  740. meshPrimitive.attributes.POSITION = this.accessors.length - 1;
  741. }
  742. }
  743. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  744. var normalVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.NormalKind);
  745. var normals = normalVertexBuffer.getData();
  746. var normalStrideSize = normalVertexBuffer.getStrideSize();
  747. if (dataBuffer) {
  748. byteOffset += this.writeAttributeData(BABYLON.VertexBuffer.NormalKind, submesh, normals, normalStrideSize, byteOffset, dataBuffer, useRightHandedSystem);
  749. }
  750. else {
  751. // Create bufferview
  752. var byteLength = submesh.verticesCount * 12;
  753. var bufferview = this.createBufferView(0, byteOffset, byteLength, "Normals");
  754. byteOffset += byteLength;
  755. this.bufferViews.push(bufferview);
  756. // Create accessor
  757. var accessor = this.createAccessor(this.bufferViews.length - 1, "Normal", "VEC3" /* VEC3 */, 5126 /* FLOAT */, submesh.verticesCount);
  758. this.accessors.push(accessor);
  759. meshPrimitive.attributes.NORMAL = this.accessors.length - 1;
  760. }
  761. }
  762. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  763. var tangentVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.TangentKind);
  764. var tangents = tangentVertexBuffer.getData();
  765. var tangentStrideSize = tangentVertexBuffer.getStrideSize();
  766. if (dataBuffer) {
  767. byteOffset += this.writeAttributeData(BABYLON.VertexBuffer.TangentKind, submesh, tangents, tangentStrideSize, byteOffset, dataBuffer, useRightHandedSystem);
  768. }
  769. else {
  770. // Create bufferview
  771. var byteLength = submesh.verticesCount * 16;
  772. var bufferview = this.createBufferView(0, byteOffset, byteLength, "Tangents");
  773. byteOffset += byteLength;
  774. this.bufferViews.push(bufferview);
  775. // Create accessor
  776. var accessor = this.createAccessor(this.bufferViews.length - 1, "Tangent", "VEC4" /* VEC4 */, 5126 /* FLOAT */, submesh.verticesCount);
  777. this.accessors.push(accessor);
  778. meshPrimitive.attributes.TANGENT = this.accessors.length - 1;
  779. }
  780. }
  781. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  782. var colorVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.ColorKind);
  783. var colors = colorVertexBuffer.getData();
  784. var colorStrideSize = colorVertexBuffer.getStrideSize();
  785. if (dataBuffer) {
  786. byteOffset += this.writeAttributeData(BABYLON.VertexBuffer.ColorKind, submesh, colors, colorStrideSize, byteOffset, dataBuffer, useRightHandedSystem);
  787. }
  788. else {
  789. // Create bufferview
  790. var byteLength = submesh.verticesCount * 16;
  791. var bufferview = this.createBufferView(0, byteOffset, byteLength, "Colors");
  792. byteOffset += byteLength;
  793. this.bufferViews.push(bufferview);
  794. // Create accessor
  795. var accessor = this.createAccessor(this.bufferViews.length - 1, "Color", "VEC4" /* VEC4 */, 5126 /* FLOAT */, submesh.verticesCount);
  796. this.accessors.push(accessor);
  797. meshPrimitive.attributes.COLOR_0 = this.accessors.length - 1;
  798. }
  799. }
  800. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  801. var texCoord0VertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.UVKind);
  802. var texCoords0 = texCoord0VertexBuffer.getData();
  803. var texCoord0StrideSize = texCoord0VertexBuffer.getStrideSize();
  804. if (dataBuffer) {
  805. byteOffset += this.writeAttributeData(BABYLON.VertexBuffer.UVKind, submesh, texCoords0, texCoord0StrideSize, byteOffset, dataBuffer, useRightHandedSystem);
  806. }
  807. else {
  808. // Create bufferview
  809. var byteLength = submesh.verticesCount * 8;
  810. var bufferview = this.createBufferView(0, byteOffset, byteLength, "Texture Coords0");
  811. byteOffset += byteLength;
  812. this.bufferViews.push(bufferview);
  813. // Create accessor
  814. var accessor = this.createAccessor(this.bufferViews.length - 1, "Texture Coords", "VEC2" /* VEC2 */, 5126 /* FLOAT */, submesh.verticesCount);
  815. this.accessors.push(accessor);
  816. meshPrimitive.attributes.TEXCOORD_0 = this.accessors.length - 1;
  817. }
  818. }
  819. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  820. var texCoord1VertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind);
  821. var texCoords1 = texCoord1VertexBuffer.getData();
  822. var texCoord1StrideSize = texCoord1VertexBuffer.getStrideSize();
  823. if (dataBuffer) {
  824. byteOffset += this.writeAttributeData(BABYLON.VertexBuffer.UV2Kind, submesh, texCoords1, texCoord1StrideSize, byteOffset, dataBuffer, useRightHandedSystem);
  825. }
  826. else {
  827. // Create bufferview
  828. var byteLength = submesh.verticesCount * 8;
  829. var bufferview = this.createBufferView(0, byteOffset, byteLength, "Texture Coords 1");
  830. byteOffset += byteLength;
  831. this.bufferViews.push(bufferview);
  832. // Create accessor
  833. var accessor = this.createAccessor(this.bufferViews.length - 1, "Texture Coords", "VEC2" /* VEC2 */, 5126 /* FLOAT */, submesh.verticesCount);
  834. this.accessors.push(accessor);
  835. meshPrimitive.attributes.TEXCOORD_1 = this.accessors.length - 1;
  836. }
  837. }
  838. if (bufferMesh.getTotalIndices() > 0) {
  839. if (dataBuffer) {
  840. var indices = bufferMesh.getIndices();
  841. var start = submesh.indexStart;
  842. var end = submesh.indexCount + start;
  843. var byteOff = byteOffset;
  844. for (var k = start; k < end; k = k + 3) {
  845. dataBuffer.setUint32(byteOff, indices[k], true);
  846. byteOff += 4;
  847. dataBuffer.setUint32(byteOff, indices[k + 1], true);
  848. byteOff += 4;
  849. dataBuffer.setUint32(byteOff, indices[k + 2], true);
  850. byteOff += 4;
  851. }
  852. var byteLength = submesh.indexCount * 4;
  853. byteOffset += byteLength;
  854. }
  855. else {
  856. // Create bufferview
  857. var indicesCount = submesh.indexCount;
  858. var byteLength = indicesCount * 4;
  859. var bufferview = this.createBufferView(0, byteOffset, byteLength, "Indices");
  860. byteOffset += byteLength;
  861. this.bufferViews.push(bufferview);
  862. // Create accessor
  863. var accessor = this.createAccessor(this.bufferViews.length - 1, "Indices", "SCALAR" /* SCALAR */, 5125 /* UNSIGNED_INT */, indicesCount);
  864. this.accessors.push(accessor);
  865. meshPrimitive.indices = this.accessors.length - 1;
  866. }
  867. }
  868. if (bufferMesh.material) {
  869. if (bufferMesh.material instanceof BABYLON.StandardMaterial) {
  870. var babylonStandardMaterial = bufferMesh.material;
  871. var glTFMaterial = { name: babylonStandardMaterial.name };
  872. if (!babylonStandardMaterial.backFaceCulling) {
  873. glTFMaterial.doubleSided = true;
  874. }
  875. if (babylonStandardMaterial.bumpTexture) {
  876. var glTFTexture = this.exportTexture(babylonStandardMaterial.bumpTexture);
  877. if (glTFTexture) {
  878. glTFMaterial.normalTexture = glTFTexture;
  879. }
  880. }
  881. if (babylonStandardMaterial.emissiveTexture) {
  882. var glTFEmissiveTexture = this.exportTexture(babylonStandardMaterial.emissiveTexture);
  883. if (glTFEmissiveTexture) {
  884. glTFMaterial.emissiveTexture = glTFEmissiveTexture;
  885. }
  886. glTFMaterial.emissiveFactor = [1.0, 1.0, 1.0];
  887. }
  888. if (babylonStandardMaterial.ambientTexture) {
  889. var glTFOcclusionTexture = this.exportTexture(babylonStandardMaterial.ambientTexture);
  890. if (glTFOcclusionTexture) {
  891. glTFMaterial.occlusionTexture = glTFOcclusionTexture;
  892. }
  893. }
  894. // Spec Gloss
  895. var glTFPbrMetallicRoughness = GLTF2._GLTFMaterial.ConvertToGLTFPBRMetallicRoughness(babylonStandardMaterial);
  896. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  897. // TODO: Handle Textures
  898. this.materials.push(glTFMaterial);
  899. meshPrimitive.material = this.materials.length - 1;
  900. }
  901. else if (bufferMesh.material instanceof BABYLON.PBRMetallicRoughnessMaterial) {
  902. if (!this.textures) {
  903. this.textures = new Array();
  904. }
  905. var babylonPBRMaterial = bufferMesh.material;
  906. var glTFPbrMetallicRoughness = {};
  907. if (babylonPBRMaterial.baseColor) {
  908. glTFPbrMetallicRoughness.baseColorFactor = [
  909. babylonPBRMaterial.baseColor.r,
  910. babylonPBRMaterial.baseColor.g,
  911. babylonPBRMaterial.baseColor.b,
  912. babylonPBRMaterial.alpha
  913. ];
  914. }
  915. if (babylonPBRMaterial.baseTexture !== undefined) {
  916. var glTFTexture = this.exportTexture(babylonPBRMaterial.baseTexture);
  917. if (glTFTexture !== null) {
  918. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  919. }
  920. glTFPbrMetallicRoughness.baseColorTexture;
  921. }
  922. if (babylonPBRMaterial.metallic !== undefined) {
  923. glTFPbrMetallicRoughness.metallicFactor = babylonPBRMaterial.metallic;
  924. }
  925. if (babylonPBRMaterial.roughness !== undefined) {
  926. glTFPbrMetallicRoughness.roughnessFactor = babylonPBRMaterial.roughness;
  927. }
  928. var glTFMaterial = {
  929. name: babylonPBRMaterial.name
  930. };
  931. if (babylonPBRMaterial.doubleSided) {
  932. glTFMaterial.doubleSided = babylonPBRMaterial.doubleSided;
  933. }
  934. if (babylonPBRMaterial.normalTexture) {
  935. var glTFTexture = this.exportTexture(babylonPBRMaterial.normalTexture);
  936. if (glTFTexture) {
  937. glTFMaterial.normalTexture = glTFTexture;
  938. }
  939. }
  940. if (babylonPBRMaterial.occlusionTexture) {
  941. var glTFTexture = this.exportTexture(babylonPBRMaterial.occlusionTexture);
  942. if (glTFTexture) {
  943. glTFMaterial.occlusionTexture = glTFTexture;
  944. if (babylonPBRMaterial.occlusionStrength !== undefined) {
  945. glTFMaterial.occlusionTexture.strength = babylonPBRMaterial.occlusionStrength;
  946. }
  947. }
  948. }
  949. if (babylonPBRMaterial.emissiveTexture) {
  950. var glTFTexture = this.exportTexture(babylonPBRMaterial.emissiveTexture);
  951. if (glTFTexture !== null) {
  952. glTFMaterial.emissiveTexture = glTFTexture;
  953. }
  954. }
  955. if (!babylonPBRMaterial.emissiveColor.equals(new BABYLON.Color3(0.0, 0.0, 0.0))) {
  956. glTFMaterial.emissiveFactor = babylonPBRMaterial.emissiveColor.asArray();
  957. }
  958. if (babylonPBRMaterial.transparencyMode) {
  959. var alphaMode = GLTF2._GLTFMaterial.GetAlphaMode(babylonPBRMaterial);
  960. if (alphaMode !== "OPAQUE" /* OPAQUE */) {
  961. glTFMaterial.alphaMode = alphaMode;
  962. if (alphaMode === "BLEND" /* BLEND */) {
  963. glTFMaterial.alphaCutoff = babylonPBRMaterial.alphaCutOff;
  964. }
  965. }
  966. }
  967. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  968. // TODO: Handle Textures
  969. this.materials.push(glTFMaterial);
  970. meshPrimitive.material = this.materials.length - 1;
  971. }
  972. }
  973. mesh.primitives.push(meshPrimitive);
  974. }
  975. return byteOffset;
  976. };
  977. /**
  978. * Creates a glTF scene based on the array of meshes.
  979. * Returns the the total byte offset.
  980. * @param gltf
  981. * @param byteOffset
  982. * @param buffer
  983. * @param dataBuffer
  984. * @returns bytelength + byteoffset
  985. */
  986. _Exporter.prototype.createScene = function (babylonScene, byteOffset, dataBuffer) {
  987. if (babylonScene.meshes.length > 0) {
  988. var babylonMeshes = babylonScene.meshes;
  989. var scene = { nodes: new Array() };
  990. for (var i = 0; i < babylonMeshes.length; ++i) {
  991. if (this.options &&
  992. this.options.shouldExportMesh !== undefined &&
  993. !this.options.shouldExportMesh(babylonMeshes[i])) {
  994. continue;
  995. }
  996. else {
  997. // create node to hold translation/rotation/scale and the mesh
  998. var node = { mesh: -1 };
  999. var babylonMesh = babylonMeshes[i];
  1000. var useRightHandedSystem = babylonMesh.getScene().useRightHandedSystem;
  1001. // Set transformation
  1002. this.setNodeTransformation(node, babylonMesh, useRightHandedSystem);
  1003. // create mesh
  1004. var mesh = { primitives: new Array() };
  1005. mesh.primitives = [];
  1006. byteOffset = this.setPrimitiveAttributes(mesh, babylonMesh, byteOffset, useRightHandedSystem, dataBuffer);
  1007. // go through all mesh primitives (submeshes)
  1008. this.meshes.push(mesh);
  1009. node.mesh = this.meshes.length - 1;
  1010. if (babylonMesh.name) {
  1011. node.name = babylonMesh.name;
  1012. }
  1013. this.nodes.push(node);
  1014. scene.nodes.push(this.nodes.length - 1);
  1015. }
  1016. }
  1017. this.scenes.push(scene);
  1018. }
  1019. return byteOffset;
  1020. };
  1021. return _Exporter;
  1022. }());
  1023. GLTF2._Exporter = _Exporter;
  1024. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1025. })(BABYLON || (BABYLON = {}));
  1026. //# sourceMappingURL=babylon.glTFExporter.js.map
  1027. var BABYLON;
  1028. (function (BABYLON) {
  1029. /**
  1030. * Class for holding and downloading glTF file data
  1031. */
  1032. var _GLTFData = /** @class */ (function () {
  1033. /**
  1034. * Initializes the glTF file object.
  1035. */
  1036. function _GLTFData() {
  1037. this.glTFFiles = {};
  1038. }
  1039. /**
  1040. * Downloads the glTF data as files based on their names and data.
  1041. */
  1042. _GLTFData.prototype.downloadFiles = function () {
  1043. /**
  1044. * Checks for a matching suffix at the end of a string (for ES5 and lower).
  1045. * @param str - Source string.
  1046. * @param suffix - Suffix to search for in the source string.
  1047. * @returns - Boolean indicating whether the suffix was found (true) or not (false).
  1048. */
  1049. function endsWith(str, suffix) {
  1050. return str.indexOf(suffix, str.length - suffix.length) !== -1;
  1051. }
  1052. for (var key in this.glTFFiles) {
  1053. var link = document.createElement('a');
  1054. document.body.appendChild(link);
  1055. link.setAttribute("type", "hidden");
  1056. link.download = key;
  1057. var blob = this.glTFFiles[key];
  1058. var mimeType = void 0;
  1059. if (endsWith(key, ".glb")) {
  1060. mimeType = { type: "model/gltf-binary" };
  1061. }
  1062. else if (endsWith(key, ".bin")) {
  1063. mimeType = { type: "application/octet-stream" };
  1064. }
  1065. else if (endsWith(key, ".gltf")) {
  1066. mimeType = { type: "model/gltf+json" };
  1067. }
  1068. else if (endsWith(key, ".jpeg" || ".jpg")) {
  1069. mimeType = { type: "image/jpeg" /* JPEG */ };
  1070. }
  1071. else if (endsWith(key, ".png")) {
  1072. mimeType = { type: "image/png" /* PNG */ };
  1073. }
  1074. link.href = window.URL.createObjectURL(new Blob([blob], mimeType));
  1075. link.click();
  1076. }
  1077. };
  1078. return _GLTFData;
  1079. }());
  1080. BABYLON._GLTFData = _GLTFData;
  1081. })(BABYLON || (BABYLON = {}));
  1082. //# sourceMappingURL=babylon.glTFData.js.map
  1083. var BABYLON;
  1084. (function (BABYLON) {
  1085. var GLTF2;
  1086. (function (GLTF2) {
  1087. /**
  1088. * Utility methods for working with glTF material conversion properties. This class should only be used internally.
  1089. */
  1090. var _GLTFMaterial = /** @class */ (function () {
  1091. function _GLTFMaterial() {
  1092. }
  1093. /**
  1094. * Converts a Babylon StandardMaterial to a glTF Metallic Roughness Material.
  1095. * @param babylonStandardMaterial
  1096. * @returns - glTF Metallic Roughness Material representation
  1097. */
  1098. _GLTFMaterial.ConvertToGLTFPBRMetallicRoughness = function (babylonStandardMaterial) {
  1099. var babylonSpecularGlossiness = {
  1100. diffuse: babylonStandardMaterial.diffuseColor,
  1101. opacity: babylonStandardMaterial.alpha,
  1102. specular: babylonStandardMaterial.specularColor || BABYLON.Color3.Black(),
  1103. glossiness: babylonStandardMaterial.specularPower / 256
  1104. };
  1105. if (babylonStandardMaterial.specularTexture) {
  1106. }
  1107. var babylonMetallicRoughness = _GLTFMaterial._ConvertToMetallicRoughness(babylonSpecularGlossiness);
  1108. var glTFPbrMetallicRoughness = {
  1109. baseColorFactor: [
  1110. babylonMetallicRoughness.baseColor.r,
  1111. babylonMetallicRoughness.baseColor.g,
  1112. babylonMetallicRoughness.baseColor.b,
  1113. babylonMetallicRoughness.opacity
  1114. ],
  1115. metallicFactor: babylonMetallicRoughness.metallic,
  1116. roughnessFactor: babylonMetallicRoughness.roughness
  1117. };
  1118. return glTFPbrMetallicRoughness;
  1119. };
  1120. /**
  1121. * Converts Specular Glossiness to Metallic Roughness. This is based on the algorithm used in the Babylon glTF 3ds Max Exporter.
  1122. * {@link https://github.com/BabylonJS/Exporters/blob/master/3ds%20Max/Max2Babylon/Exporter/BabylonExporter.GLTFExporter.Material.cs}
  1123. * @param babylonSpecularGlossiness - Babylon specular glossiness parameters
  1124. * @returns - Babylon metallic roughness values
  1125. */
  1126. _GLTFMaterial._ConvertToMetallicRoughness = function (babylonSpecularGlossiness) {
  1127. var diffuse = babylonSpecularGlossiness.diffuse;
  1128. var opacity = babylonSpecularGlossiness.opacity;
  1129. var specular = babylonSpecularGlossiness.specular;
  1130. var glossiness = babylonSpecularGlossiness.glossiness;
  1131. var oneMinusSpecularStrength = 1 - Math.max(specular.r, Math.max(specular.g, specular.b));
  1132. var diffusePerceivedBrightness = _GLTFMaterial.PerceivedBrightness(diffuse);
  1133. var specularPerceivedBrightness = _GLTFMaterial.PerceivedBrightness(specular);
  1134. var metallic = _GLTFMaterial.SolveMetallic(diffusePerceivedBrightness, specularPerceivedBrightness, oneMinusSpecularStrength);
  1135. var diffuseScaleFactor = oneMinusSpecularStrength / (1 - this.dielectricSpecular.r) / Math.max(1 - metallic, this.epsilon);
  1136. var baseColorFromDiffuse = diffuse.scale(diffuseScaleFactor);
  1137. var baseColorFromSpecular = specular.subtract(this.dielectricSpecular.scale(1 - metallic)).scale(1 / Math.max(metallic, this.epsilon));
  1138. var lerpColor = BABYLON.Color3.Lerp(baseColorFromDiffuse, baseColorFromSpecular, metallic * metallic);
  1139. var baseColor = new BABYLON.Color3();
  1140. lerpColor.clampToRef(0, 1, baseColor);
  1141. var babylonMetallicRoughness = {
  1142. baseColor: baseColor,
  1143. opacity: opacity,
  1144. metallic: metallic,
  1145. roughness: 1.0 - glossiness
  1146. };
  1147. return babylonMetallicRoughness;
  1148. };
  1149. /**
  1150. * Returns the perceived brightness value based on the provided color
  1151. * @param color - color used in calculating the perceived brightness
  1152. * @returns - perceived brightness value
  1153. */
  1154. _GLTFMaterial.PerceivedBrightness = function (color) {
  1155. return Math.sqrt(0.299 * color.r * color.r + 0.587 * color.g * color.g + 0.114 * color.b * color.b);
  1156. };
  1157. /**
  1158. * Computes the metallic factor
  1159. * @param diffuse - diffused value
  1160. * @param specular - specular value
  1161. * @param oneMinusSpecularStrength - one minus the specular strength
  1162. * @returns - metallic value
  1163. */
  1164. _GLTFMaterial.SolveMetallic = function (diffuse, specular, oneMinusSpecularStrength) {
  1165. if (specular < this.dielectricSpecular.r) {
  1166. return 0;
  1167. }
  1168. var a = this.dielectricSpecular.r;
  1169. var b = diffuse * oneMinusSpecularStrength / (1.0 - this.dielectricSpecular.r) + specular - 2.0 * this.dielectricSpecular.r;
  1170. var c = this.dielectricSpecular.r - specular;
  1171. var D = b * b - 4.0 * a * c;
  1172. return BABYLON.Scalar.Clamp((-b + Math.sqrt(D)) / (2.0 * a));
  1173. };
  1174. /**
  1175. * Gets the glTF alpha mode from the Babylon Material
  1176. * @param babylonMaterial - Babylon Material
  1177. * @returns - The Babylon alpha mode value
  1178. */
  1179. _GLTFMaterial.GetAlphaMode = function (babylonMaterial) {
  1180. if (babylonMaterial instanceof BABYLON.StandardMaterial) {
  1181. var babylonStandardMaterial = babylonMaterial;
  1182. if ((babylonStandardMaterial.alpha != 1.0) ||
  1183. (babylonStandardMaterial.diffuseTexture != null && babylonStandardMaterial.diffuseTexture.hasAlpha) ||
  1184. (babylonStandardMaterial.opacityTexture != null)) {
  1185. return "BLEND" /* BLEND */;
  1186. }
  1187. else {
  1188. return "OPAQUE" /* OPAQUE */;
  1189. }
  1190. }
  1191. else if (babylonMaterial instanceof BABYLON.PBRMetallicRoughnessMaterial) {
  1192. var babylonPBRMetallicRoughness = babylonMaterial;
  1193. switch (babylonPBRMetallicRoughness.transparencyMode) {
  1194. case BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE: {
  1195. return "OPAQUE" /* OPAQUE */;
  1196. }
  1197. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND: {
  1198. return "BLEND" /* BLEND */;
  1199. }
  1200. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST: {
  1201. return "MASK" /* MASK */;
  1202. }
  1203. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND: {
  1204. console.warn("GLTF Exporter | Alpha test and blend mode not supported in glTF. Alpha blend used instead.");
  1205. return "BLEND" /* BLEND */;
  1206. }
  1207. default: {
  1208. throw new Error("Unsupported alpha mode " + babylonPBRMetallicRoughness.transparencyMode);
  1209. }
  1210. }
  1211. }
  1212. else {
  1213. throw new Error("Unsupported Babylon material type");
  1214. }
  1215. };
  1216. /**
  1217. * Represents the dielectric specular values for R, G and B.
  1218. */
  1219. _GLTFMaterial.dielectricSpecular = new BABYLON.Color3(0.04, 0.04, 0.04);
  1220. /**
  1221. * Epsilon value, used as a small tolerance value for a numeric value.
  1222. */
  1223. _GLTFMaterial.epsilon = 1e-6;
  1224. return _GLTFMaterial;
  1225. }());
  1226. GLTF2._GLTFMaterial = _GLTFMaterial;
  1227. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1228. })(BABYLON || (BABYLON = {}));
  1229. //# sourceMappingURL=babylon.glTFMaterial.js.map
  1230. (function universalModuleDefinition(root, factory) {
  1231. var f = factory();
  1232. if (root && root["BABYLON"]) {
  1233. return;
  1234. }
  1235. if(typeof exports === 'object' && typeof module === 'object')
  1236. module.exports = f;
  1237. else if(typeof define === 'function' && define.amd)
  1238. define(["BJSSerializers"], factory);
  1239. else if(typeof exports === 'object')
  1240. exports["BJSSerializers"] = f;
  1241. else {
  1242. root["BABYLON"] = f;
  1243. }
  1244. })(this, function() {
  1245. return BABYLON;
  1246. });