babylonjs.serializers.js 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345
  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.textures = new Array();
  219. this.imageData = {};
  220. if (options !== undefined) {
  221. this.options = options;
  222. }
  223. var totalByteLength = 0;
  224. totalByteLength = this.createScene(this.babylonScene, totalByteLength, null);
  225. this.totalByteLength = totalByteLength;
  226. }
  227. /**
  228. * Creates a buffer view based on teh supplied arguments
  229. * @param bufferIndex - index value of the specified buffer
  230. * @param byteOffset - byte offset value
  231. * @param byteLength - byte length of the bufferView
  232. * @param byteStride - byte distance between conequential elements.
  233. * @param name - name of the buffer view
  234. * @returns - bufferView for glTF
  235. */
  236. _Exporter.prototype.createBufferView = function (bufferIndex, byteOffset, byteLength, byteStride, name) {
  237. var bufferview = { buffer: bufferIndex, byteLength: byteLength };
  238. if (byteOffset > 0) {
  239. bufferview.byteOffset = byteOffset;
  240. }
  241. if (name) {
  242. bufferview.name = name;
  243. }
  244. if (byteStride) {
  245. bufferview.byteStride = byteStride;
  246. }
  247. return bufferview;
  248. };
  249. /**
  250. * Creates an accessor based on the supplied arguments
  251. * @param bufferviewIndex
  252. * @param name
  253. * @param type
  254. * @param componentType
  255. * @param count
  256. * @param min
  257. * @param max
  258. * @returns - accessor for glTF
  259. */
  260. _Exporter.prototype.createAccessor = function (bufferviewIndex, name, type, componentType, count, byteOffset, min, max) {
  261. var accessor = { name: name, bufferView: bufferviewIndex, componentType: componentType, count: count, type: type };
  262. if (min) {
  263. accessor.min = min;
  264. }
  265. if (max) {
  266. accessor.max = max;
  267. }
  268. if (byteOffset) {
  269. accessor.byteOffset = byteOffset;
  270. }
  271. return accessor;
  272. };
  273. /**
  274. * Calculates the minimum and maximum values of an array of floats, based on stride
  275. * @param buff - Data to check for min and max values.
  276. * @param vertexStart - Start offset to calculate min and max values.
  277. * @param vertexCount - Number of vertices to check for min and max values.
  278. * @param stride - Offset between consecutive attributes.
  279. * @param useRightHandedSystem - Indicates whether the data should be modified for a right or left handed coordinate system.
  280. * @returns - min number array and max number array.
  281. */
  282. _Exporter.prototype.calculateMinMax = function (buff, vertexStart, vertexCount, stride, useRightHandedSystem) {
  283. var min = [Infinity, Infinity, Infinity];
  284. var max = [-Infinity, -Infinity, -Infinity];
  285. var end = vertexStart + vertexCount;
  286. if (vertexCount > 0) {
  287. for (var i = vertexStart; i < end; ++i) {
  288. var index = stride * i;
  289. var scale = 1;
  290. for (var j = 0; j < stride; ++j) {
  291. if (j === (stride - 1) && !useRightHandedSystem) {
  292. scale = -1;
  293. }
  294. var num = scale * buff[index];
  295. if (num < min[j]) {
  296. min[j] = num;
  297. }
  298. if (num > max[j]) {
  299. max[j] = num;
  300. }
  301. ++index;
  302. }
  303. }
  304. }
  305. return { min: min, max: max };
  306. };
  307. /**
  308. * Writes mesh attribute data to a data buffer.
  309. * Returns the bytelength of the data.
  310. * @param vertexBufferKind - Indicates what kind of vertex data is being passed in.
  311. * @param meshAttributeArray - Array containing the attribute data.
  312. * @param strideSize - Represents the offset between consecutive attributes
  313. * @param byteOffset - The offset to start counting bytes from.
  314. * @param dataBuffer - The buffer to write the binary data to.
  315. * @param useRightHandedSystem - Indicates whether the data should be modified for a right or left handed coordinate system.
  316. * @returns - Byte length of the attribute data.
  317. */
  318. _Exporter.prototype.writeAttributeData = function (vertexBufferKind, meshAttributeArray, strideSize, vertexBufferOffset, byteOffset, dataBuffer, useRightHandedSystem) {
  319. var byteOff = byteOffset;
  320. var start = 0;
  321. var end = meshAttributeArray.length / strideSize;
  322. var byteLength = 0;
  323. switch (vertexBufferKind) {
  324. case BABYLON.VertexBuffer.PositionKind: {
  325. for (var k = start; k < end; ++k) {
  326. var index = k * strideSize;
  327. dataBuffer.setFloat32(byteOff, meshAttributeArray[index], true);
  328. byteOff += 4;
  329. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 1], true);
  330. byteOff += 4;
  331. if (useRightHandedSystem) {
  332. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 2], true);
  333. }
  334. else {
  335. dataBuffer.setFloat32(byteOff, -meshAttributeArray[index + 2], true);
  336. }
  337. byteOff += 4;
  338. }
  339. byteLength = meshAttributeArray.length * 4;
  340. break;
  341. }
  342. case BABYLON.VertexBuffer.NormalKind: {
  343. for (var k = start; k < end; ++k) {
  344. var index = k * strideSize;
  345. dataBuffer.setFloat32(byteOff, meshAttributeArray[index], true);
  346. byteOff += 4;
  347. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 1], true);
  348. byteOff += 4;
  349. if (useRightHandedSystem) {
  350. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 2], true);
  351. }
  352. else {
  353. dataBuffer.setFloat32(byteOff, -meshAttributeArray[index + 2], true);
  354. }
  355. byteOff += 4;
  356. }
  357. byteLength = meshAttributeArray.length * 4;
  358. break;
  359. }
  360. case BABYLON.VertexBuffer.TangentKind: {
  361. for (var k = start; k < end; ++k) {
  362. var index = k * strideSize;
  363. dataBuffer.setFloat32(byteOff, meshAttributeArray[index], true);
  364. byteOff += 4;
  365. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 1], true);
  366. byteOff += 4;
  367. if (useRightHandedSystem) {
  368. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 2], true);
  369. }
  370. else {
  371. dataBuffer.setFloat32(byteOff, -meshAttributeArray[index + 2], true);
  372. }
  373. byteOff += 4;
  374. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 3], true);
  375. byteOff += 4;
  376. }
  377. byteLength = meshAttributeArray.length * 4;
  378. break;
  379. }
  380. case BABYLON.VertexBuffer.ColorKind: {
  381. for (var k = start; k < end; ++k) {
  382. var index = k * strideSize;
  383. dataBuffer.setFloat32(byteOff, meshAttributeArray[index], true);
  384. byteOff += 4;
  385. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 1], true);
  386. byteOff += 4;
  387. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 2], true);
  388. byteOff += 4;
  389. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 3], true);
  390. byteOff += 4;
  391. }
  392. byteLength = meshAttributeArray.length * 4;
  393. break;
  394. }
  395. case BABYLON.VertexBuffer.UVKind: {
  396. for (var k = start; k < end; ++k) {
  397. var index = k * strideSize;
  398. dataBuffer.setFloat32(byteOff, meshAttributeArray[index], true);
  399. byteOff += 4;
  400. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 1], true);
  401. byteOff += 4;
  402. }
  403. byteLength = meshAttributeArray.length * 4;
  404. break;
  405. }
  406. case BABYLON.VertexBuffer.UV2Kind: {
  407. for (var k = start; k < end; ++k) {
  408. var index = k * strideSize;
  409. dataBuffer.setFloat32(byteOff, meshAttributeArray[index], true);
  410. byteOff += 4;
  411. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 1], true);
  412. byteOff += 4;
  413. }
  414. byteLength = meshAttributeArray.length * 4;
  415. break;
  416. }
  417. default: {
  418. throw new Error("Unsupported vertex buffer type: " + vertexBufferKind);
  419. }
  420. }
  421. return byteLength;
  422. };
  423. /**
  424. * Generates glTF json data
  425. * @param shouldUseGlb - Indicates whether the json should be written for a glb file.
  426. * @param glTFPrefix - Text to use when prefixing a glTF file.
  427. * @param prettyPrint - Indicates whether the json file should be pretty printed (true) or not (false).
  428. * @returns - json data as string
  429. */
  430. _Exporter.prototype.generateJSON = function (shouldUseGlb, glTFPrefix, prettyPrint) {
  431. var buffer = { byteLength: this.totalByteLength };
  432. var glTF = {
  433. asset: this.asset
  434. };
  435. if (buffer.byteLength > 0) {
  436. glTF.buffers = [buffer];
  437. }
  438. if (this.nodes && this.nodes.length !== 0) {
  439. glTF.nodes = this.nodes;
  440. }
  441. if (this.meshes && this.meshes.length !== 0) {
  442. glTF.meshes = this.meshes;
  443. }
  444. if (this.scenes && this.scenes.length !== 0) {
  445. glTF.scenes = this.scenes;
  446. glTF.scene = 0;
  447. }
  448. if (this.bufferViews && this.bufferViews.length !== 0) {
  449. glTF.bufferViews = this.bufferViews;
  450. }
  451. if (this.accessors && this.accessors.length !== 0) {
  452. glTF.accessors = this.accessors;
  453. }
  454. if (this.materials && this.materials.length !== 0) {
  455. glTF.materials = this.materials;
  456. }
  457. if (this.textures && this.textures.length !== 0) {
  458. glTF.textures = this.textures;
  459. }
  460. if (this.images && this.images.length !== 0) {
  461. if (!shouldUseGlb) {
  462. glTF.images = this.images;
  463. }
  464. else {
  465. glTF.images = [];
  466. // Replace uri with bufferview and mime type for glb
  467. var imageLength = this.images.length;
  468. var byteOffset = this.totalByteLength;
  469. for (var i = 0; i < imageLength; ++i) {
  470. var image = this.images[i];
  471. if (image.uri !== undefined) {
  472. var imageData = this.imageData[image.uri];
  473. var imageName = image.uri.split('.')[0] + " image";
  474. var bufferView = this.createBufferView(0, byteOffset, imageData.data.length, undefined, imageName);
  475. byteOffset += imageData.data.buffer.byteLength;
  476. this.bufferViews.push(bufferView);
  477. image.bufferView = this.bufferViews.length - 1;
  478. image.name = imageName;
  479. image.mimeType = imageData.mimeType;
  480. image.uri = undefined;
  481. glTF.images.push(image);
  482. }
  483. }
  484. buffer.byteLength = byteOffset;
  485. }
  486. }
  487. if (!shouldUseGlb) {
  488. buffer.uri = glTFPrefix + ".bin";
  489. }
  490. var jsonText = prettyPrint ? JSON.stringify(glTF, null, 2) : JSON.stringify(glTF);
  491. return jsonText;
  492. };
  493. /**
  494. * Generates data for .gltf and .bin files based on the glTF prefix string
  495. * @param glTFPrefix - Text to use when prefixing a glTF file.
  496. * @returns - GLTFData with glTF file data.
  497. */
  498. _Exporter.prototype._generateGLTF = function (glTFPrefix) {
  499. var jsonText = this.generateJSON(false, glTFPrefix, true);
  500. var binaryBuffer = this.generateBinary();
  501. var bin = new Blob([binaryBuffer], { type: 'application/octet-stream' });
  502. var glTFFileName = glTFPrefix + '.gltf';
  503. var glTFBinFile = glTFPrefix + '.bin';
  504. var container = new BABYLON._GLTFData();
  505. container.glTFFiles[glTFFileName] = jsonText;
  506. container.glTFFiles[glTFBinFile] = bin;
  507. if (this.imageData !== null) {
  508. for (var image in this.imageData) {
  509. container.glTFFiles[image] = new Blob([this.imageData[image].data], { type: this.imageData[image].mimeType });
  510. }
  511. }
  512. return container;
  513. };
  514. /**
  515. * Creates a binary buffer for glTF
  516. * @returns - array buffer for binary data
  517. */
  518. _Exporter.prototype.generateBinary = function () {
  519. var byteOffset = 0;
  520. var binaryBuffer = new ArrayBuffer(this.totalByteLength);
  521. var dataBuffer = new DataView(binaryBuffer);
  522. byteOffset = this.createScene(this.babylonScene, byteOffset, dataBuffer);
  523. return binaryBuffer;
  524. };
  525. /**
  526. * Pads the number to a multiple of 4
  527. * @param num - number to pad
  528. * @returns - padded number
  529. */
  530. _Exporter.prototype._getPadding = function (num) {
  531. var remainder = num % 4;
  532. var padding = remainder === 0 ? remainder : 4 - remainder;
  533. return padding;
  534. };
  535. /**
  536. * Generates a glb file from the json and binary data.
  537. * Returns an object with the glb file name as the key and data as the value.
  538. * @param glTFPrefix
  539. * @returns - object with glb filename as key and data as value
  540. */
  541. _Exporter.prototype._generateGLB = function (glTFPrefix) {
  542. var jsonText = this.generateJSON(true);
  543. var binaryBuffer = this.generateBinary();
  544. var glbFileName = glTFPrefix + '.glb';
  545. var headerLength = 12;
  546. var chunkLengthPrefix = 8;
  547. var jsonLength = jsonText.length;
  548. var imageByteLength = 0;
  549. for (var key in this.imageData) {
  550. imageByteLength += this.imageData[key].data.byteLength;
  551. }
  552. var jsonPadding = this._getPadding(jsonLength);
  553. var binPadding = this._getPadding(binaryBuffer.byteLength);
  554. var imagePadding = this._getPadding(imageByteLength);
  555. var byteLength = headerLength + (2 * chunkLengthPrefix) + jsonLength + jsonPadding + binaryBuffer.byteLength + binPadding + imageByteLength + imagePadding;
  556. //header
  557. var headerBuffer = new ArrayBuffer(headerLength);
  558. var headerBufferView = new DataView(headerBuffer);
  559. headerBufferView.setUint32(0, 0x46546C67, true); //glTF
  560. headerBufferView.setUint32(4, 2, true); // version
  561. headerBufferView.setUint32(8, byteLength, true); // total bytes in file
  562. //json chunk
  563. var jsonChunkBuffer = new ArrayBuffer(chunkLengthPrefix + jsonLength + jsonPadding);
  564. var jsonChunkBufferView = new DataView(jsonChunkBuffer);
  565. jsonChunkBufferView.setUint32(0, jsonLength + jsonPadding, true);
  566. jsonChunkBufferView.setUint32(4, 0x4E4F534A, true);
  567. //json chunk bytes
  568. var jsonData = new Uint8Array(jsonChunkBuffer, chunkLengthPrefix);
  569. for (var i = 0; i < jsonLength; ++i) {
  570. jsonData[i] = jsonText.charCodeAt(i);
  571. }
  572. //json padding
  573. var jsonPaddingView = new Uint8Array(jsonChunkBuffer, chunkLengthPrefix + jsonLength);
  574. for (var i = 0; i < jsonPadding; ++i) {
  575. jsonPaddingView[i] = 0x20;
  576. }
  577. //binary chunk
  578. var binaryChunkBuffer = new ArrayBuffer(chunkLengthPrefix);
  579. var binaryChunkBufferView = new DataView(binaryChunkBuffer);
  580. binaryChunkBufferView.setUint32(0, binaryBuffer.byteLength + imageByteLength + imagePadding, true);
  581. binaryChunkBufferView.setUint32(4, 0x004E4942, true);
  582. // binary padding
  583. var binPaddingBuffer = new ArrayBuffer(binPadding);
  584. var binPaddingView = new Uint8Array(binPaddingBuffer);
  585. for (var i = 0; i < binPadding; ++i) {
  586. binPaddingView[i] = 0;
  587. }
  588. var imagePaddingBuffer = new ArrayBuffer(imagePadding);
  589. var imagePaddingView = new Uint8Array(imagePaddingBuffer);
  590. for (var i = 0; i < imagePadding; ++i) {
  591. imagePaddingView[i] = 0;
  592. }
  593. var glbData = [headerBuffer, jsonChunkBuffer, binaryChunkBuffer, binaryBuffer];
  594. // binary data
  595. for (var key in this.imageData) {
  596. glbData.push(this.imageData[key].data.buffer);
  597. }
  598. glbData.push(binPaddingBuffer);
  599. glbData.push(imagePaddingBuffer);
  600. var glbFile = new Blob(glbData, { type: 'application/octet-stream' });
  601. var container = new BABYLON._GLTFData();
  602. container.glTFFiles[glbFileName] = glbFile;
  603. return container;
  604. };
  605. /**
  606. * Sets the TRS for each node
  607. * @param node - glTF Node for storing the transformation data.
  608. * @param babylonMesh - Babylon mesh used as the source for the transformation data.
  609. * @param useRightHandedSystem - Indicates whether the data should be modified for a right or left handed coordinate system.
  610. */
  611. _Exporter.prototype.setNodeTransformation = function (node, babylonMesh, useRightHandedSystem) {
  612. if (!(babylonMesh.position.x === 0 && babylonMesh.position.y === 0 && babylonMesh.position.z === 0)) {
  613. if (useRightHandedSystem) {
  614. node.translation = babylonMesh.position.asArray();
  615. }
  616. else {
  617. node.translation = [babylonMesh.position.x, babylonMesh.position.y, -babylonMesh.position.z];
  618. }
  619. }
  620. if (!(babylonMesh.scaling.x === 1 && babylonMesh.scaling.y === 1 && babylonMesh.scaling.z === 1)) {
  621. if (useRightHandedSystem) {
  622. node.scale = babylonMesh.scaling.asArray();
  623. }
  624. else {
  625. node.scale = [babylonMesh.scaling.x, babylonMesh.scaling.y, -babylonMesh.scaling.z];
  626. }
  627. }
  628. var rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(babylonMesh.rotation.y, babylonMesh.rotation.x, babylonMesh.rotation.z);
  629. if (babylonMesh.rotationQuaternion) {
  630. rotationQuaternion = rotationQuaternion.multiply(babylonMesh.rotationQuaternion);
  631. }
  632. if (!(rotationQuaternion.x === 0 && rotationQuaternion.y === 0 && rotationQuaternion.z === 0 && rotationQuaternion.w === 1)) {
  633. if (useRightHandedSystem) {
  634. node.rotation = rotationQuaternion.asArray();
  635. }
  636. else {
  637. node.rotation = [-rotationQuaternion.x, -rotationQuaternion.y, rotationQuaternion.z, rotationQuaternion.w];
  638. }
  639. }
  640. };
  641. /**
  642. *
  643. * @param babylonTexture - Babylon texture to extract.
  644. * @param mimeType - Mime Type of the babylonTexture.
  645. * @return - glTF texture, or null if the texture format is not supported.
  646. */
  647. _Exporter.prototype.exportTexture = function (babylonTexture, mimeType) {
  648. if (mimeType === void 0) { mimeType = "image/jpeg" /* JPEG */; }
  649. var textureInfo = null;
  650. var glTFTexture;
  651. glTFTexture = {
  652. source: this.images.length
  653. };
  654. var textureName = babylonTexture.getInternalTexture().url;
  655. if (textureName.search('/') !== -1) {
  656. var splitFilename = textureName.split('/');
  657. textureName = splitFilename[splitFilename.length - 1];
  658. var basefile = textureName.split('.')[0];
  659. var extension = textureName.split('.')[1];
  660. if (mimeType === "image/jpeg" /* JPEG */) {
  661. extension = ".jpg";
  662. }
  663. else if (mimeType === "image/png" /* PNG */) {
  664. extension = ".png";
  665. }
  666. else {
  667. throw new Error("Unsupported mime type " + mimeType);
  668. }
  669. textureName = basefile + extension;
  670. }
  671. var pixels = babylonTexture.readPixels();
  672. var imageCanvas = document.createElement('canvas');
  673. imageCanvas.id = "ImageCanvas";
  674. var ctx = imageCanvas.getContext('2d');
  675. var size = babylonTexture.getSize();
  676. imageCanvas.width = size.width;
  677. imageCanvas.height = size.height;
  678. var imgData = ctx.createImageData(size.width, size.height);
  679. imgData.data.set(pixels);
  680. ctx.putImageData(imgData, 0, 0);
  681. var base64Data = imageCanvas.toDataURL(mimeType);
  682. var binStr = atob(base64Data.split(',')[1]);
  683. var arr = new Uint8Array(binStr.length);
  684. for (var i = 0; i < binStr.length; ++i) {
  685. arr[i] = binStr.charCodeAt(i);
  686. }
  687. var imageValues = { data: arr, mimeType: mimeType };
  688. this.imageData[textureName] = imageValues;
  689. if (mimeType === "image/jpeg" /* JPEG */) {
  690. var glTFImage = {
  691. uri: textureName
  692. };
  693. var foundIndex = -1;
  694. for (var i = 0; i < this.images.length; ++i) {
  695. if (this.images[i].uri === textureName) {
  696. foundIndex = i;
  697. break;
  698. }
  699. }
  700. if (foundIndex === -1) {
  701. this.images.push(glTFImage);
  702. glTFTexture.source = this.images.length - 1;
  703. this.textures.push({
  704. source: this.images.length - 1
  705. });
  706. textureInfo = {
  707. index: this.images.length - 1
  708. };
  709. }
  710. else {
  711. glTFTexture.source = foundIndex;
  712. textureInfo = {
  713. index: foundIndex
  714. };
  715. }
  716. }
  717. return textureInfo;
  718. };
  719. /**
  720. * Creates a bufferview based on the vertices type for the Babylon mesh
  721. * @param kind - Indicates the type of vertices data.
  722. * @param babylonMesh - The Babylon mesh to get the vertices data from.
  723. * @param byteOffset - The offset from the buffer to start indexing from.
  724. * @param useRightHandedSystem - Indicates whether the data should be modified for a right or left handed coordinate system.
  725. * @param dataBuffer - The buffer to write the bufferview data to.
  726. * @returns bytelength of the bufferview data.
  727. */
  728. _Exporter.prototype.createBufferViewKind = function (kind, babylonMesh, byteOffset, useRightHandedSystem, dataBuffer) {
  729. var bufferMesh = null;
  730. var byteLength = 0;
  731. if (babylonMesh instanceof BABYLON.Mesh) {
  732. bufferMesh = babylonMesh;
  733. }
  734. else if (babylonMesh instanceof BABYLON.InstancedMesh) {
  735. bufferMesh = babylonMesh.sourceMesh;
  736. }
  737. if (bufferMesh !== null) {
  738. var vertexBuffer = null;
  739. var vertexBufferOffset = null;
  740. var vertexData = null;
  741. var vertexStrideSize = null;
  742. if (bufferMesh.getVerticesDataKinds().indexOf(kind) > -1) {
  743. vertexBuffer = bufferMesh.getVertexBuffer(kind);
  744. vertexBufferOffset = vertexBuffer.getOffset();
  745. vertexData = vertexBuffer.getData();
  746. vertexStrideSize = vertexBuffer.getStrideSize();
  747. if (dataBuffer && vertexData) {
  748. byteLength = this.writeAttributeData(kind, vertexData, vertexStrideSize, vertexBufferOffset, byteOffset, dataBuffer, useRightHandedSystem);
  749. byteOffset += byteLength;
  750. }
  751. else {
  752. var bufferViewName = null;
  753. switch (kind) {
  754. case BABYLON.VertexBuffer.PositionKind: {
  755. byteLength = vertexData.length * 4;
  756. bufferViewName = "Position - " + bufferMesh.name;
  757. break;
  758. }
  759. case BABYLON.VertexBuffer.NormalKind: {
  760. byteLength = vertexData.length * 4;
  761. bufferViewName = "Normal - " + bufferMesh.name;
  762. break;
  763. }
  764. case BABYLON.VertexBuffer.TangentKind: {
  765. byteLength = vertexData.length * 4;
  766. bufferViewName = "Tangent - " + bufferMesh.name;
  767. break;
  768. }
  769. case BABYLON.VertexBuffer.ColorKind: {
  770. byteLength = vertexData.length * 4;
  771. bufferViewName = "Color - " + bufferMesh.name;
  772. break;
  773. }
  774. case BABYLON.VertexBuffer.UVKind: {
  775. byteLength = vertexData.length * 4;
  776. bufferViewName = "TexCoord 0 - " + bufferMesh.name;
  777. break;
  778. }
  779. case BABYLON.VertexBuffer.UV2Kind: {
  780. byteLength = vertexData.length * 4;
  781. bufferViewName = "TexCoord 1 - " + bufferMesh.name;
  782. break;
  783. }
  784. default: {
  785. console.warn("Unsupported VertexBuffer kind: " + kind);
  786. }
  787. }
  788. if (bufferViewName !== null) {
  789. var bufferView = this.createBufferView(0, byteOffset, byteLength, vertexStrideSize * 4, bufferViewName);
  790. byteOffset += byteLength;
  791. this.bufferViews.push(bufferView);
  792. }
  793. }
  794. }
  795. }
  796. return byteLength;
  797. };
  798. /**
  799. * Sets data for the primitive attributes of each submesh
  800. * @param mesh - glTF Mesh object to store the primitive attribute information.
  801. * @param babylonMesh - Babylon mesh to get the primitive attribute data from.
  802. * @param byteOffset - The offset in bytes of the buffer data.
  803. * @param useRightHandedSystem - Indicates whether the data should be modified for a right or left handed coordinate system.
  804. * @param dataBuffer - Buffer to write the attribute data to.
  805. * @returns - bytelength of the primitive attributes plus the passed in byteOffset.
  806. */
  807. _Exporter.prototype.setPrimitiveAttributes = function (mesh, babylonMesh, byteOffset, useRightHandedSystem, dataBuffer) {
  808. var bufferMesh = null;
  809. if (babylonMesh instanceof BABYLON.Mesh) {
  810. bufferMesh = babylonMesh;
  811. }
  812. else if (babylonMesh instanceof BABYLON.InstancedMesh) {
  813. bufferMesh = babylonMesh.sourceMesh;
  814. }
  815. var positionBufferViewIndex = null;
  816. var normalBufferViewIndex = null;
  817. var colorBufferViewIndex = null;
  818. var tangentBufferViewIndex = null;
  819. var texCoord0BufferViewIndex = null;
  820. var texCoord1BufferViewIndex = null;
  821. var indexBufferViewIndex = null;
  822. if (bufferMesh !== null) {
  823. // For each BabylonMesh, create bufferviews for each 'kind'
  824. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  825. byteOffset += this.createBufferViewKind(BABYLON.VertexBuffer.PositionKind, babylonMesh, byteOffset, useRightHandedSystem, dataBuffer);
  826. positionBufferViewIndex = this.bufferViews.length - 1;
  827. }
  828. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  829. byteOffset += this.createBufferViewKind(BABYLON.VertexBuffer.NormalKind, babylonMesh, byteOffset, useRightHandedSystem, dataBuffer);
  830. normalBufferViewIndex = this.bufferViews.length - 1;
  831. }
  832. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  833. byteOffset += this.createBufferViewKind(BABYLON.VertexBuffer.ColorKind, babylonMesh, byteOffset, useRightHandedSystem, dataBuffer);
  834. colorBufferViewIndex = this.bufferViews.length - 1;
  835. }
  836. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  837. byteOffset += this.createBufferViewKind(BABYLON.VertexBuffer.TangentKind, babylonMesh, byteOffset, useRightHandedSystem, dataBuffer);
  838. colorBufferViewIndex = this.bufferViews.length - 1;
  839. }
  840. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  841. byteOffset += this.createBufferViewKind(BABYLON.VertexBuffer.UVKind, babylonMesh, byteOffset, useRightHandedSystem, dataBuffer);
  842. texCoord0BufferViewIndex = this.bufferViews.length - 1;
  843. }
  844. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  845. byteOffset += this.createBufferViewKind(BABYLON.VertexBuffer.UV2Kind, babylonMesh, byteOffset, useRightHandedSystem, dataBuffer);
  846. texCoord1BufferViewIndex = this.bufferViews.length - 1;
  847. }
  848. if (bufferMesh.getTotalIndices() > 0) {
  849. var indices = bufferMesh.getIndices();
  850. if (dataBuffer) {
  851. var end = indices.length;
  852. var byteOff = byteOffset;
  853. for (var k = 0; k < end; ++k) {
  854. dataBuffer.setUint32(byteOff, indices[k], true);
  855. byteOff += 4;
  856. }
  857. byteOffset = byteOff;
  858. }
  859. else {
  860. var byteLength = indices.length * 4;
  861. var bufferView = this.createBufferView(0, byteOffset, byteLength, undefined, "Indices - " + bufferMesh.name);
  862. byteOffset += byteLength;
  863. this.bufferViews.push(bufferView);
  864. indexBufferViewIndex = this.bufferViews.length - 1;
  865. }
  866. }
  867. }
  868. // go through all mesh primitives (submeshes)
  869. for (var j = 0; j < babylonMesh.subMeshes.length; ++j) {
  870. var submesh = babylonMesh.subMeshes[j];
  871. var meshPrimitive = { attributes: {} };
  872. if (bufferMesh !== null) {
  873. // Create a bufferview storing all the positions
  874. if (!dataBuffer) {
  875. // Loop through each attribute of the submesh (mesh primitive)
  876. if (positionBufferViewIndex !== null) {
  877. var positionVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  878. var positions = positionVertexBuffer.getData();
  879. var positionStrideSize = positionVertexBuffer.getStrideSize();
  880. // Create accessor
  881. var result = this.calculateMinMax(positions, 0, positions.length / positionStrideSize, positionStrideSize, useRightHandedSystem);
  882. var accessor = this.createAccessor(positionBufferViewIndex, "Position", "VEC3" /* VEC3 */, 5126 /* FLOAT */, positions.length / positionStrideSize, 0, result.min, result.max);
  883. this.accessors.push(accessor);
  884. meshPrimitive.attributes.POSITION = this.accessors.length - 1;
  885. }
  886. if (normalBufferViewIndex !== null) {
  887. var normalVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.NormalKind);
  888. var normals = normalVertexBuffer.getData();
  889. var normalStrideSize = normalVertexBuffer.getStrideSize();
  890. // Create accessor
  891. var accessor = this.createAccessor(normalBufferViewIndex, "Normal", "VEC3" /* VEC3 */, 5126 /* FLOAT */, normals.length / normalStrideSize);
  892. this.accessors.push(accessor);
  893. meshPrimitive.attributes.NORMAL = this.accessors.length - 1;
  894. }
  895. if (tangentBufferViewIndex !== null) {
  896. var tangentVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.TangentKind);
  897. var tangents = tangentVertexBuffer.getData();
  898. var tangentStrideSize = tangentVertexBuffer.getStrideSize();
  899. // Create accessor
  900. var accessor = this.createAccessor(tangentBufferViewIndex, "Tangent", "VEC4" /* VEC4 */, 5126 /* FLOAT */, tangents.length / tangentStrideSize);
  901. this.accessors.push(accessor);
  902. meshPrimitive.attributes.TANGENT = this.accessors.length - 1;
  903. }
  904. if (colorBufferViewIndex !== null) {
  905. var colorVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.ColorKind);
  906. var colors = colorVertexBuffer.getData();
  907. var colorStrideSize = colorVertexBuffer.getStrideSize();
  908. // Create accessor
  909. var accessor = this.createAccessor(colorBufferViewIndex, "Color", "VEC4" /* VEC4 */, 5126 /* FLOAT */, colors.length / colorStrideSize);
  910. this.accessors.push(accessor);
  911. meshPrimitive.attributes.COLOR_0 = this.accessors.length - 1;
  912. }
  913. if (texCoord0BufferViewIndex !== null) {
  914. // Create accessor
  915. var texCoord0VertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.UVKind);
  916. var texCoord0s = texCoord0VertexBuffer.getData();
  917. var texCoord0StrideSize = texCoord0VertexBuffer.getStrideSize();
  918. var accessor = this.createAccessor(texCoord0BufferViewIndex, "Texture Coords 0", "VEC2" /* VEC2 */, 5126 /* FLOAT */, texCoord0s.length / texCoord0StrideSize);
  919. this.accessors.push(accessor);
  920. meshPrimitive.attributes.TEXCOORD_0 = this.accessors.length - 1;
  921. }
  922. if (texCoord1BufferViewIndex !== null) {
  923. // Create accessor
  924. var texCoord1VertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind);
  925. var texCoord1s = texCoord1VertexBuffer.getData();
  926. var texCoord1StrideSize = texCoord1VertexBuffer.getStrideSize();
  927. var accessor = this.createAccessor(texCoord1BufferViewIndex, "Texture Coords 1", "VEC2" /* VEC2 */, 5126 /* FLOAT */, texCoord1s.length / texCoord1StrideSize);
  928. this.accessors.push(accessor);
  929. meshPrimitive.attributes.TEXCOORD_1 = this.accessors.length - 1;
  930. }
  931. if (indexBufferViewIndex) {
  932. // Create accessor
  933. var accessor = this.createAccessor(indexBufferViewIndex, "Indices", "SCALAR" /* SCALAR */, 5125 /* UNSIGNED_INT */, submesh.indexCount, submesh.indexStart * 4);
  934. this.accessors.push(accessor);
  935. meshPrimitive.indices = this.accessors.length - 1;
  936. }
  937. }
  938. if (bufferMesh.material) {
  939. if (bufferMesh.material instanceof BABYLON.StandardMaterial) {
  940. console.warn("Standard Material is currently not fully supported/implemented in glTF serializer");
  941. var babylonStandardMaterial = bufferMesh.material;
  942. var glTFPbrMetallicRoughness = GLTF2._GLTFMaterial.ConvertToGLTFPBRMetallicRoughness(babylonStandardMaterial);
  943. var glTFMaterial = { name: babylonStandardMaterial.name };
  944. if (!babylonStandardMaterial.backFaceCulling) {
  945. glTFMaterial.doubleSided = true;
  946. }
  947. if (babylonStandardMaterial.diffuseTexture && bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  948. var glTFTexture = this.exportTexture(babylonStandardMaterial.diffuseTexture);
  949. if (glTFTexture !== null) {
  950. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  951. }
  952. }
  953. if (babylonStandardMaterial.bumpTexture && bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  954. var glTFTexture = this.exportTexture(babylonStandardMaterial.bumpTexture);
  955. if (glTFTexture) {
  956. glTFMaterial.normalTexture = glTFTexture;
  957. }
  958. }
  959. if (babylonStandardMaterial.emissiveTexture && bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  960. var glTFEmissiveTexture = this.exportTexture(babylonStandardMaterial.emissiveTexture);
  961. if (glTFEmissiveTexture) {
  962. glTFMaterial.emissiveTexture = glTFEmissiveTexture;
  963. }
  964. glTFMaterial.emissiveFactor = [1.0, 1.0, 1.0];
  965. }
  966. if (babylonStandardMaterial.ambientTexture && bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  967. var glTFOcclusionTexture = this.exportTexture(babylonStandardMaterial.ambientTexture);
  968. if (glTFOcclusionTexture) {
  969. glTFMaterial.occlusionTexture = glTFOcclusionTexture;
  970. }
  971. }
  972. if (babylonStandardMaterial.alpha < 1.0 || babylonStandardMaterial.opacityTexture) {
  973. if (babylonStandardMaterial.alphaMode === BABYLON.Engine.ALPHA_COMBINE) {
  974. glTFMaterial.alphaMode = "BLEND" /* BLEND */;
  975. }
  976. else {
  977. console.warn("glTF 2.0 does not support alpha mode: " + babylonStandardMaterial.alphaMode.toString());
  978. }
  979. }
  980. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  981. this.materials.push(glTFMaterial);
  982. meshPrimitive.material = this.materials.length - 1;
  983. }
  984. else if (bufferMesh.material instanceof BABYLON.PBRMetallicRoughnessMaterial) {
  985. var babylonPBRMaterial = bufferMesh.material;
  986. var glTFPbrMetallicRoughness = {};
  987. if (babylonPBRMaterial.baseColor) {
  988. glTFPbrMetallicRoughness.baseColorFactor = [
  989. babylonPBRMaterial.baseColor.r,
  990. babylonPBRMaterial.baseColor.g,
  991. babylonPBRMaterial.baseColor.b,
  992. babylonPBRMaterial.alpha
  993. ];
  994. }
  995. if (babylonPBRMaterial.baseTexture !== undefined) {
  996. var glTFTexture = this.exportTexture(babylonPBRMaterial.baseTexture);
  997. if (glTFTexture !== null) {
  998. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  999. }
  1000. glTFPbrMetallicRoughness.baseColorTexture;
  1001. }
  1002. if (babylonPBRMaterial.metallic !== undefined) {
  1003. glTFPbrMetallicRoughness.metallicFactor = babylonPBRMaterial.metallic;
  1004. }
  1005. if (babylonPBRMaterial.roughness !== undefined) {
  1006. glTFPbrMetallicRoughness.roughnessFactor = babylonPBRMaterial.roughness;
  1007. }
  1008. var glTFMaterial = {
  1009. name: babylonPBRMaterial.name
  1010. };
  1011. if (babylonPBRMaterial.doubleSided) {
  1012. glTFMaterial.doubleSided = babylonPBRMaterial.doubleSided;
  1013. }
  1014. if (babylonPBRMaterial.normalTexture) {
  1015. var glTFTexture = this.exportTexture(babylonPBRMaterial.normalTexture);
  1016. if (glTFTexture) {
  1017. glTFMaterial.normalTexture = glTFTexture;
  1018. }
  1019. }
  1020. if (babylonPBRMaterial.occlusionTexture) {
  1021. var glTFTexture = this.exportTexture(babylonPBRMaterial.occlusionTexture);
  1022. if (glTFTexture) {
  1023. glTFMaterial.occlusionTexture = glTFTexture;
  1024. if (babylonPBRMaterial.occlusionStrength !== undefined) {
  1025. glTFMaterial.occlusionTexture.strength = babylonPBRMaterial.occlusionStrength;
  1026. }
  1027. }
  1028. }
  1029. if (babylonPBRMaterial.emissiveTexture) {
  1030. var glTFTexture = this.exportTexture(babylonPBRMaterial.emissiveTexture);
  1031. if (glTFTexture !== null) {
  1032. glTFMaterial.emissiveTexture = glTFTexture;
  1033. }
  1034. }
  1035. if (!babylonPBRMaterial.emissiveColor.equals(new BABYLON.Color3(0.0, 0.0, 0.0))) {
  1036. glTFMaterial.emissiveFactor = babylonPBRMaterial.emissiveColor.asArray();
  1037. }
  1038. if (babylonPBRMaterial.transparencyMode) {
  1039. var alphaMode = GLTF2._GLTFMaterial.GetAlphaMode(babylonPBRMaterial);
  1040. if (alphaMode !== "OPAQUE" /* OPAQUE */) {
  1041. glTFMaterial.alphaMode = alphaMode;
  1042. if (alphaMode === "BLEND" /* BLEND */) {
  1043. glTFMaterial.alphaCutoff = babylonPBRMaterial.alphaCutOff;
  1044. }
  1045. }
  1046. }
  1047. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  1048. this.materials.push(glTFMaterial);
  1049. meshPrimitive.material = this.materials.length - 1;
  1050. }
  1051. else {
  1052. console.warn("Material type is not yet implemented in glTF serializer: " + bufferMesh.material.name);
  1053. }
  1054. }
  1055. mesh.primitives.push(meshPrimitive);
  1056. }
  1057. }
  1058. return byteOffset;
  1059. };
  1060. /**
  1061. * Creates a glTF scene based on the array of meshes.
  1062. * Returns the the total byte offset.
  1063. * @param babylonScene - Babylon scene to get the mesh data from.
  1064. * @param byteOffset - Offset to start from in bytes.
  1065. * @param dataBuffer - Buffer to write geometry data to.
  1066. * @returns bytelength + byteoffset
  1067. */
  1068. _Exporter.prototype.createScene = function (babylonScene, byteOffset, dataBuffer) {
  1069. if (babylonScene.meshes.length > 0) {
  1070. var babylonMeshes = babylonScene.meshes;
  1071. var scene = { nodes: new Array() };
  1072. for (var i = 0; i < babylonMeshes.length; ++i) {
  1073. if (this.options &&
  1074. this.options.shouldExportMesh !== undefined &&
  1075. !this.options.shouldExportMesh(babylonMeshes[i])) {
  1076. continue;
  1077. }
  1078. else {
  1079. // create node to hold translation/rotation/scale and the mesh
  1080. var node = { mesh: -1 };
  1081. var babylonMesh = babylonMeshes[i];
  1082. var useRightHandedSystem = babylonMesh.getScene().useRightHandedSystem;
  1083. // Set transformation
  1084. this.setNodeTransformation(node, babylonMesh, useRightHandedSystem);
  1085. // create mesh
  1086. var mesh = { primitives: new Array() };
  1087. mesh.primitives = [];
  1088. byteOffset = this.setPrimitiveAttributes(mesh, babylonMesh, byteOffset, useRightHandedSystem, dataBuffer);
  1089. // go through all mesh primitives (submeshes)
  1090. this.meshes.push(mesh);
  1091. node.mesh = this.meshes.length - 1;
  1092. if (babylonMesh.name) {
  1093. node.name = babylonMesh.name;
  1094. }
  1095. this.nodes.push(node);
  1096. scene.nodes.push(this.nodes.length - 1);
  1097. }
  1098. }
  1099. this.scenes.push(scene);
  1100. }
  1101. return byteOffset;
  1102. };
  1103. return _Exporter;
  1104. }());
  1105. GLTF2._Exporter = _Exporter;
  1106. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1107. })(BABYLON || (BABYLON = {}));
  1108. //# sourceMappingURL=babylon.glTFExporter.js.map
  1109. var BABYLON;
  1110. (function (BABYLON) {
  1111. /**
  1112. * Class for holding and downloading glTF file data
  1113. */
  1114. var _GLTFData = /** @class */ (function () {
  1115. /**
  1116. * Initializes the glTF file object.
  1117. */
  1118. function _GLTFData() {
  1119. this.glTFFiles = {};
  1120. }
  1121. /**
  1122. * Downloads the glTF data as files based on their names and data.
  1123. */
  1124. _GLTFData.prototype.downloadFiles = function () {
  1125. /**
  1126. * Checks for a matching suffix at the end of a string (for ES5 and lower).
  1127. * @param str - Source string.
  1128. * @param suffix - Suffix to search for in the source string.
  1129. * @returns - Boolean indicating whether the suffix was found (true) or not (false).
  1130. */
  1131. function endsWith(str, suffix) {
  1132. return str.indexOf(suffix, str.length - suffix.length) !== -1;
  1133. }
  1134. for (var key in this.glTFFiles) {
  1135. var link = document.createElement('a');
  1136. document.body.appendChild(link);
  1137. link.setAttribute("type", "hidden");
  1138. link.download = key;
  1139. var blob = this.glTFFiles[key];
  1140. var mimeType = void 0;
  1141. if (endsWith(key, ".glb")) {
  1142. mimeType = { type: "model/gltf-binary" };
  1143. }
  1144. else if (endsWith(key, ".bin")) {
  1145. mimeType = { type: "application/octet-stream" };
  1146. }
  1147. else if (endsWith(key, ".gltf")) {
  1148. mimeType = { type: "model/gltf+json" };
  1149. }
  1150. else if (endsWith(key, ".jpeg" || ".jpg")) {
  1151. mimeType = { type: "image/jpeg" /* JPEG */ };
  1152. }
  1153. else if (endsWith(key, ".png")) {
  1154. mimeType = { type: "image/png" /* PNG */ };
  1155. }
  1156. link.href = window.URL.createObjectURL(new Blob([blob], mimeType));
  1157. link.click();
  1158. }
  1159. };
  1160. return _GLTFData;
  1161. }());
  1162. BABYLON._GLTFData = _GLTFData;
  1163. })(BABYLON || (BABYLON = {}));
  1164. //# sourceMappingURL=babylon.glTFData.js.map
  1165. var BABYLON;
  1166. (function (BABYLON) {
  1167. var GLTF2;
  1168. (function (GLTF2) {
  1169. /**
  1170. * Utility methods for working with glTF material conversion properties. This class should only be used internally.
  1171. */
  1172. var _GLTFMaterial = /** @class */ (function () {
  1173. function _GLTFMaterial() {
  1174. }
  1175. /**
  1176. * Converts a Babylon StandardMaterial to a glTF Metallic Roughness Material.
  1177. * @param babylonStandardMaterial
  1178. * @returns - glTF Metallic Roughness Material representation
  1179. */
  1180. _GLTFMaterial.ConvertToGLTFPBRMetallicRoughness = function (babylonStandardMaterial) {
  1181. var babylonSpecularGlossiness = {
  1182. diffuse: babylonStandardMaterial.diffuseColor,
  1183. opacity: babylonStandardMaterial.alpha,
  1184. specular: babylonStandardMaterial.specularColor || BABYLON.Color3.Black(),
  1185. glossiness: babylonStandardMaterial.specularPower / 256
  1186. };
  1187. if (babylonStandardMaterial.specularTexture) {
  1188. }
  1189. var babylonMetallicRoughness = _GLTFMaterial._ConvertToMetallicRoughness(babylonSpecularGlossiness);
  1190. var glTFPbrMetallicRoughness = {
  1191. baseColorFactor: [
  1192. babylonMetallicRoughness.baseColor.r,
  1193. babylonMetallicRoughness.baseColor.g,
  1194. babylonMetallicRoughness.baseColor.b,
  1195. babylonMetallicRoughness.opacity
  1196. ],
  1197. metallicFactor: babylonMetallicRoughness.metallic,
  1198. roughnessFactor: babylonMetallicRoughness.roughness
  1199. };
  1200. return glTFPbrMetallicRoughness;
  1201. };
  1202. /**
  1203. * Converts Specular Glossiness to Metallic Roughness. This is based on the algorithm used in the Babylon glTF 3ds Max Exporter.
  1204. * {@link https://github.com/BabylonJS/Exporters/blob/master/3ds%20Max/Max2Babylon/Exporter/BabylonExporter.GLTFExporter.Material.cs}
  1205. * @param babylonSpecularGlossiness - Babylon specular glossiness parameters
  1206. * @returns - Babylon metallic roughness values
  1207. */
  1208. _GLTFMaterial._ConvertToMetallicRoughness = function (babylonSpecularGlossiness) {
  1209. var diffuse = babylonSpecularGlossiness.diffuse;
  1210. var opacity = babylonSpecularGlossiness.opacity;
  1211. var specular = babylonSpecularGlossiness.specular;
  1212. var glossiness = BABYLON.Scalar.Clamp(babylonSpecularGlossiness.glossiness);
  1213. var oneMinusSpecularStrength = 1 - Math.max(specular.r, Math.max(specular.g, specular.b));
  1214. var diffusePerceivedBrightness = _GLTFMaterial.PerceivedBrightness(diffuse);
  1215. var specularPerceivedBrightness = _GLTFMaterial.PerceivedBrightness(specular);
  1216. var metallic = _GLTFMaterial.SolveMetallic(diffusePerceivedBrightness, specularPerceivedBrightness, oneMinusSpecularStrength);
  1217. var diffuseScaleFactor = oneMinusSpecularStrength / (1 - this.dielectricSpecular.r) / Math.max(1 - metallic, this.epsilon);
  1218. var baseColorFromDiffuse = diffuse.scale(diffuseScaleFactor);
  1219. var baseColorFromSpecular = specular.subtract(this.dielectricSpecular.scale(1 - metallic)).scale(1 / Math.max(metallic, this.epsilon));
  1220. var lerpColor = BABYLON.Color3.Lerp(baseColorFromDiffuse, baseColorFromSpecular, metallic * metallic);
  1221. var baseColor = new BABYLON.Color3();
  1222. lerpColor.clampToRef(0, 1, baseColor);
  1223. var babylonMetallicRoughness = {
  1224. baseColor: baseColor,
  1225. opacity: opacity,
  1226. metallic: metallic,
  1227. roughness: 1.0 - glossiness
  1228. };
  1229. return babylonMetallicRoughness;
  1230. };
  1231. /**
  1232. * Returns the perceived brightness value based on the provided color
  1233. * @param color - color used in calculating the perceived brightness
  1234. * @returns - perceived brightness value
  1235. */
  1236. _GLTFMaterial.PerceivedBrightness = function (color) {
  1237. return Math.sqrt(0.299 * color.r * color.r + 0.587 * color.g * color.g + 0.114 * color.b * color.b);
  1238. };
  1239. /**
  1240. * Computes the metallic factor
  1241. * @param diffuse - diffused value
  1242. * @param specular - specular value
  1243. * @param oneMinusSpecularStrength - one minus the specular strength
  1244. * @returns - metallic value
  1245. */
  1246. _GLTFMaterial.SolveMetallic = function (diffuse, specular, oneMinusSpecularStrength) {
  1247. if (specular < this.dielectricSpecular.r) {
  1248. return 0;
  1249. }
  1250. var a = this.dielectricSpecular.r;
  1251. var b = diffuse * oneMinusSpecularStrength / (1.0 - this.dielectricSpecular.r) + specular - 2.0 * this.dielectricSpecular.r;
  1252. var c = this.dielectricSpecular.r - specular;
  1253. var D = b * b - 4.0 * a * c;
  1254. return BABYLON.Scalar.Clamp((-b + Math.sqrt(D)) / (2.0 * a));
  1255. };
  1256. /**
  1257. * Gets the glTF alpha mode from the Babylon Material
  1258. * @param babylonMaterial - Babylon Material
  1259. * @returns - The Babylon alpha mode value
  1260. */
  1261. _GLTFMaterial.GetAlphaMode = function (babylonMaterial) {
  1262. if (babylonMaterial instanceof BABYLON.StandardMaterial) {
  1263. var babylonStandardMaterial = babylonMaterial;
  1264. if ((babylonStandardMaterial.alpha != 1.0) ||
  1265. (babylonStandardMaterial.diffuseTexture != null && babylonStandardMaterial.diffuseTexture.hasAlpha) ||
  1266. (babylonStandardMaterial.opacityTexture != null)) {
  1267. return "BLEND" /* BLEND */;
  1268. }
  1269. else {
  1270. return "OPAQUE" /* OPAQUE */;
  1271. }
  1272. }
  1273. else if (babylonMaterial instanceof BABYLON.PBRMetallicRoughnessMaterial) {
  1274. var babylonPBRMetallicRoughness = babylonMaterial;
  1275. switch (babylonPBRMetallicRoughness.transparencyMode) {
  1276. case BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE: {
  1277. return "OPAQUE" /* OPAQUE */;
  1278. }
  1279. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND: {
  1280. return "BLEND" /* BLEND */;
  1281. }
  1282. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST: {
  1283. return "MASK" /* MASK */;
  1284. }
  1285. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND: {
  1286. console.warn("GLTF Exporter | Alpha test and blend mode not supported in glTF. Alpha blend used instead.");
  1287. return "BLEND" /* BLEND */;
  1288. }
  1289. default: {
  1290. throw new Error("Unsupported alpha mode " + babylonPBRMetallicRoughness.transparencyMode);
  1291. }
  1292. }
  1293. }
  1294. else {
  1295. throw new Error("Unsupported Babylon material type");
  1296. }
  1297. };
  1298. /**
  1299. * Represents the dielectric specular values for R, G and B.
  1300. */
  1301. _GLTFMaterial.dielectricSpecular = new BABYLON.Color3(0.04, 0.04, 0.04);
  1302. /**
  1303. * Epsilon value, used as a small tolerance value for a numeric value.
  1304. */
  1305. _GLTFMaterial.epsilon = 1e-6;
  1306. return _GLTFMaterial;
  1307. }());
  1308. GLTF2._GLTFMaterial = _GLTFMaterial;
  1309. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1310. })(BABYLON || (BABYLON = {}));
  1311. //# sourceMappingURL=babylon.glTFMaterial.js.map
  1312. (function universalModuleDefinition(root, factory) {
  1313. var f = factory();
  1314. if (root && root["BABYLON"]) {
  1315. return;
  1316. }
  1317. if(typeof exports === 'object' && typeof module === 'object')
  1318. module.exports = f;
  1319. else if(typeof define === 'function' && define.amd)
  1320. define(["BJSSerializers"], factory);
  1321. else if(typeof exports === 'object')
  1322. exports["BJSSerializers"] = f;
  1323. else {
  1324. root["BABYLON"] = f;
  1325. }
  1326. })(this, function() {
  1327. return BABYLON;
  1328. });