babylonjs.serializers.js 98 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. 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;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. (function universalModuleDefinition(root, factory) {
  18. if(typeof exports === 'object' && typeof module === 'object')
  19. module.exports = factory(require("babylonjs"));
  20. else if(typeof define === 'function' && define.amd)
  21. define("babylonjs-serializers", ["babylonjs"], factory);
  22. else if(typeof exports === 'object')
  23. exports["babylonjs-serializers"] = factory(require("babylonjs"));
  24. else {
  25. root["BABYLON"] = factory(root["BABYLON"]);
  26. }
  27. })(this, function(BABYLON) {
  28. var BABYLON;
  29. (function (BABYLON) {
  30. var OBJExport = /** @class */ (function () {
  31. function OBJExport() {
  32. }
  33. //Exports the geometrys of a Mesh array in .OBJ file format (text)
  34. OBJExport.OBJ = function (mesh, materials, matlibname, globalposition) {
  35. var output = [];
  36. var v = 1;
  37. if (materials) {
  38. if (!matlibname) {
  39. matlibname = 'mat';
  40. }
  41. output.push("mtllib " + matlibname + ".mtl");
  42. }
  43. for (var j = 0; j < mesh.length; j++) {
  44. output.push("g object" + j);
  45. output.push("o object_" + j);
  46. //Uses the position of the item in the scene, to the file (this back to normal in the end)
  47. var lastMatrix = null;
  48. if (globalposition) {
  49. var newMatrix = BABYLON.Matrix.Translation(mesh[j].position.x, mesh[j].position.y, mesh[j].position.z);
  50. lastMatrix = BABYLON.Matrix.Translation(-(mesh[j].position.x), -(mesh[j].position.y), -(mesh[j].position.z));
  51. mesh[j].bakeTransformIntoVertices(newMatrix);
  52. }
  53. //TODO: submeshes (groups)
  54. //TODO: smoothing groups (s 1, s off);
  55. if (materials) {
  56. var mat = mesh[j].material;
  57. if (mat) {
  58. output.push("usemtl " + mat.id);
  59. }
  60. }
  61. var g = mesh[j].geometry;
  62. if (!g) {
  63. continue;
  64. }
  65. var trunkVerts = g.getVerticesData('position');
  66. var trunkNormals = g.getVerticesData('normal');
  67. var trunkUV = g.getVerticesData('uv');
  68. var trunkFaces = g.getIndices();
  69. var curV = 0;
  70. if (!trunkVerts || !trunkNormals || !trunkUV || !trunkFaces) {
  71. continue;
  72. }
  73. for (var i = 0; i < trunkVerts.length; i += 3) {
  74. output.push("v " + trunkVerts[i] + " " + trunkVerts[i + 1] + " " + trunkVerts[i + 2]);
  75. curV++;
  76. }
  77. for (i = 0; i < trunkNormals.length; i += 3) {
  78. output.push("vn " + trunkNormals[i] + " " + trunkNormals[i + 1] + " " + trunkNormals[i + 2]);
  79. }
  80. for (i = 0; i < trunkUV.length; i += 2) {
  81. output.push("vt " + trunkUV[i] + " " + trunkUV[i + 1]);
  82. }
  83. for (i = 0; i < trunkFaces.length; i += 3) {
  84. output.push("f " + (trunkFaces[i + 2] + v) + "/" + (trunkFaces[i + 2] + v) + "/" + (trunkFaces[i + 2] + v) +
  85. " " + (trunkFaces[i + 1] + v) + "/" + (trunkFaces[i + 1] + v) + "/" + (trunkFaces[i + 1] + v) +
  86. " " + (trunkFaces[i] + v) + "/" + (trunkFaces[i] + v) + "/" + (trunkFaces[i] + v));
  87. }
  88. //back de previous matrix, to not change the original mesh in the scene
  89. if (globalposition && lastMatrix) {
  90. mesh[j].bakeTransformIntoVertices(lastMatrix);
  91. }
  92. v += curV;
  93. }
  94. var text = output.join("\n");
  95. return (text);
  96. };
  97. //Exports the material(s) of a mesh in .MTL file format (text)
  98. //TODO: Export the materials of mesh array
  99. OBJExport.MTL = function (mesh) {
  100. var output = [];
  101. var m = mesh.material;
  102. output.push("newmtl mat1");
  103. output.push(" Ns " + m.specularPower.toFixed(4));
  104. output.push(" Ni 1.5000");
  105. output.push(" d " + m.alpha.toFixed(4));
  106. output.push(" Tr 0.0000");
  107. output.push(" Tf 1.0000 1.0000 1.0000");
  108. output.push(" illum 2");
  109. output.push(" Ka " + m.ambientColor.r.toFixed(4) + " " + m.ambientColor.g.toFixed(4) + " " + m.ambientColor.b.toFixed(4));
  110. output.push(" Kd " + m.diffuseColor.r.toFixed(4) + " " + m.diffuseColor.g.toFixed(4) + " " + m.diffuseColor.b.toFixed(4));
  111. output.push(" Ks " + m.specularColor.r.toFixed(4) + " " + m.specularColor.g.toFixed(4) + " " + m.specularColor.b.toFixed(4));
  112. output.push(" Ke " + m.emissiveColor.r.toFixed(4) + " " + m.emissiveColor.g.toFixed(4) + " " + m.emissiveColor.b.toFixed(4));
  113. //TODO: uv scale, offset, wrap
  114. //TODO: UV mirrored in Blender? second UV channel? lightMap? reflection textures?
  115. var uvscale = "";
  116. if (m.ambientTexture) {
  117. output.push(" map_Ka " + uvscale + m.ambientTexture.name);
  118. }
  119. if (m.diffuseTexture) {
  120. output.push(" map_Kd " + uvscale + m.diffuseTexture.name);
  121. //TODO: alpha testing, opacity in diffuse texture alpha channel (diffuseTexture.hasAlpha -> map_d)
  122. }
  123. if (m.specularTexture) {
  124. output.push(" map_Ks " + uvscale + m.specularTexture.name);
  125. /* TODO: glossiness = specular highlight component is in alpha channel of specularTexture. (???)
  126. if (m.useGlossinessFromSpecularMapAlpha) {
  127. output.push(" map_Ns "+uvscale + m.specularTexture.name);
  128. }
  129. */
  130. }
  131. /* TODO: emissive texture not in .MAT format (???)
  132. if (m.emissiveTexture) {
  133. output.push(" map_d "+uvscale+m.emissiveTexture.name);
  134. }
  135. */
  136. if (m.bumpTexture) {
  137. output.push(" map_bump -imfchan z " + uvscale + m.bumpTexture.name);
  138. }
  139. if (m.opacityTexture) {
  140. output.push(" map_d " + uvscale + m.opacityTexture.name);
  141. }
  142. var text = output.join("\n");
  143. return (text);
  144. };
  145. return OBJExport;
  146. }());
  147. BABYLON.OBJExport = OBJExport;
  148. })(BABYLON || (BABYLON = {}));
  149. //# sourceMappingURL=babylon.objSerializer.js.map
  150. var BABYLON;
  151. (function (BABYLON) {
  152. ;
  153. /**
  154. * Class for generating glTF data from a Babylon scene.
  155. */
  156. var GLTF2Export = /** @class */ (function () {
  157. function GLTF2Export() {
  158. }
  159. /**
  160. * Exports the geometry of the scene to .gltf file format.
  161. * @param scene - Babylon scene with scene hierarchy information.
  162. * @param filePrefix - File prefix to use when generating the glTF file.
  163. * @param options - Exporter options.
  164. * @returns - Returns an object with a .gltf file and associates texture names
  165. * as keys and their data and paths as values.
  166. */
  167. GLTF2Export.GLTF = function (scene, filePrefix, options) {
  168. var glTFPrefix = filePrefix.replace(/\.[^/.]+$/, "");
  169. var gltfGenerator = new BABYLON.GLTF2._Exporter(scene, options);
  170. if (scene.isReady) {
  171. return gltfGenerator._generateGLTF(glTFPrefix);
  172. }
  173. else {
  174. throw new Error("glTF Serializer: Scene is not ready!");
  175. }
  176. };
  177. /**
  178. * Exports the geometry of the scene to .glb file format.
  179. * @param scene - Babylon scene with scene hierarchy information.
  180. * @param filePrefix - File prefix to use when generating glb file.
  181. * @param options - Exporter options.
  182. * @returns - Returns an object with a .glb filename as key and data as value
  183. */
  184. GLTF2Export.GLB = function (scene, filePrefix, options) {
  185. var glTFPrefix = filePrefix.replace(/\.[^/.]+$/, "");
  186. var gltfGenerator = new BABYLON.GLTF2._Exporter(scene, options);
  187. if (scene.isReady) {
  188. return gltfGenerator._generateGLB(glTFPrefix);
  189. }
  190. else {
  191. throw new Error("glTF Serializer: Scene is not ready!");
  192. }
  193. };
  194. return GLTF2Export;
  195. }());
  196. BABYLON.GLTF2Export = GLTF2Export;
  197. })(BABYLON || (BABYLON = {}));
  198. //# sourceMappingURL=babylon.glTFSerializer.js.map
  199. /**
  200. * Module for the Babylon glTF 2.0 exporter. Should ONLY be used internally.
  201. * @ignore - capitalization of GLTF2 module.
  202. */
  203. var BABYLON;
  204. (function (BABYLON) {
  205. var GLTF2;
  206. (function (GLTF2) {
  207. /**
  208. * Converts Babylon Scene into glTF 2.0.
  209. */
  210. var _Exporter = /** @class */ (function () {
  211. /**
  212. * Creates a glTF Exporter instance, which can accept optional exporter options.
  213. * @param babylonScene - Babylon scene object
  214. * @param options - Options to modify the behavior of the exporter.
  215. */
  216. function _Exporter(babylonScene, options) {
  217. this.asset = { generator: "BabylonJS", version: "2.0" };
  218. this.babylonScene = babylonScene;
  219. this.bufferViews = new Array();
  220. this.accessors = new Array();
  221. this.meshes = new Array();
  222. this.scenes = new Array();
  223. this.nodes = new Array();
  224. this.images = new Array();
  225. this.materials = new Array();
  226. this.textures = new Array();
  227. this.imageData = {};
  228. this.convertToRightHandedSystem = this.babylonScene.useRightHandedSystem ? false : true;
  229. if (options) {
  230. this.options = options;
  231. }
  232. }
  233. /**
  234. * Creates a buffer view based on teh supplied arguments
  235. * @param bufferIndex - index value of the specified buffer
  236. * @param byteOffset - byte offset value
  237. * @param byteLength - byte length of the bufferView
  238. * @param byteStride - byte distance between conequential elements.
  239. * @param name - name of the buffer view
  240. * @returns - bufferView for glTF
  241. */
  242. _Exporter.prototype.createBufferView = function (bufferIndex, byteOffset, byteLength, byteStride, name) {
  243. var bufferview = { buffer: bufferIndex, byteLength: byteLength };
  244. if (byteOffset) {
  245. bufferview.byteOffset = byteOffset;
  246. }
  247. if (name) {
  248. bufferview.name = name;
  249. }
  250. if (byteStride) {
  251. bufferview.byteStride = byteStride;
  252. }
  253. return bufferview;
  254. };
  255. /**
  256. * Creates an accessor based on the supplied arguments
  257. * @param bufferviewIndex - The index of the bufferview referenced by this accessor.
  258. * @param name - The name of the accessor.
  259. * @param type - The type of the accessor.
  260. * @param componentType - The datatype of components in the attribute.
  261. * @param count - The number of attributes referenced by this accessor.
  262. * @param byteOffset - The offset relative to the start of the bufferView in bytes.
  263. * @param min - Minimum value of each component in this attribute.
  264. * @param max - Maximum value of each component in this attribute.
  265. * @returns - accessor for glTF
  266. */
  267. _Exporter.prototype.createAccessor = function (bufferviewIndex, name, type, componentType, count, byteOffset, min, max) {
  268. var accessor = { name: name, bufferView: bufferviewIndex, componentType: componentType, count: count, type: type };
  269. if (min) {
  270. accessor.min = min;
  271. }
  272. if (max) {
  273. accessor.max = max;
  274. }
  275. if (byteOffset) {
  276. accessor.byteOffset = byteOffset;
  277. }
  278. return accessor;
  279. };
  280. /**
  281. * Calculates the minimum and maximum values of an array of position floats.
  282. * @param positions - Positions array of a mesh.
  283. * @param vertexStart - Starting vertex offset to calculate min and max values.
  284. * @param vertexCount - Number of vertices to check for min and max values.
  285. * @returns - min number array and max number array.
  286. */
  287. _Exporter.prototype.calculateMinMaxPositions = function (positions, vertexStart, vertexCount) {
  288. var min = [Infinity, Infinity, Infinity];
  289. var max = [-Infinity, -Infinity, -Infinity];
  290. var positionStrideSize = 3;
  291. var end = vertexStart + vertexCount;
  292. if (vertexCount) {
  293. for (var i = vertexStart; i < end; ++i) {
  294. var indexOffset = positionStrideSize * i;
  295. var position = BABYLON.Vector3.FromArray(positions, indexOffset);
  296. var vector = this.convertToRightHandedSystem ? _Exporter.GetRightHandedVector3(position).asArray() : position.asArray();
  297. for (var j = 0; j < positionStrideSize; ++j) {
  298. var num = vector[j];
  299. if (num < min[j]) {
  300. min[j] = num;
  301. }
  302. if (num > max[j]) {
  303. max[j] = num;
  304. }
  305. ++indexOffset;
  306. }
  307. }
  308. }
  309. return { min: min, max: max };
  310. };
  311. /**
  312. * Converts a vector3 array to right-handed.
  313. * @param vector - vector3 Array to convert to right-handed.
  314. * @returns - right-handed Vector3 array.
  315. */
  316. _Exporter.GetRightHandedVector3 = function (vector) {
  317. return new BABYLON.Vector3(vector.x, vector.y, -vector.z);
  318. };
  319. /**
  320. * Converts a vector4 array to right-handed.
  321. * @param vector - vector4 Array to convert to right-handed.
  322. * @returns - right-handed vector4 array.
  323. */
  324. _Exporter.GetRightHandedVector4 = function (vector) {
  325. return new BABYLON.Vector4(vector.x, vector.y, -vector.z, -vector.w);
  326. };
  327. /**
  328. * Converts a quaternion to right-handed.
  329. * @param quaternion - Source quaternion to convert to right-handed.
  330. */
  331. _Exporter.GetRightHandedQuaternion = function (quaternion) {
  332. return new BABYLON.Quaternion(-quaternion.x, -quaternion.y, quaternion.z, quaternion.w);
  333. };
  334. /**
  335. * Writes mesh attribute data to a data buffer.
  336. * Returns the bytelength of the data.
  337. * @param vertexBufferKind - Indicates what kind of vertex data is being passed in.
  338. * @param meshAttributeArray - Array containing the attribute data.
  339. * @param strideSize - Represents the offset between consecutive attributes
  340. * @param byteOffset - The offset to start counting bytes from.
  341. * @param dataBuffer - The buffer to write the binary data to.
  342. * @returns - Byte length of the attribute data.
  343. */
  344. _Exporter.prototype.writeAttributeData = function (vertexBufferKind, meshAttributeArray, strideSize, vertexBufferOffset, byteOffset, dataBuffer) {
  345. var byteOff = byteOffset;
  346. var end = meshAttributeArray.length / strideSize;
  347. var byteLength = 0;
  348. for (var k = 0; k < end; ++k) {
  349. var index = k * strideSize;
  350. var vector = [];
  351. if (vertexBufferKind === BABYLON.VertexBuffer.PositionKind || vertexBufferKind === BABYLON.VertexBuffer.NormalKind) {
  352. var vertexData = BABYLON.Vector3.FromArray(meshAttributeArray, index);
  353. vector = this.convertToRightHandedSystem ? _Exporter.GetRightHandedVector3(vertexData).asArray() : vertexData.asArray();
  354. }
  355. else if (vertexBufferKind === BABYLON.VertexBuffer.TangentKind || vertexBufferKind === BABYLON.VertexBuffer.ColorKind) {
  356. var vertexData = BABYLON.Vector4.FromArray(meshAttributeArray, index);
  357. vector = (this.convertToRightHandedSystem && !(vertexBufferKind === BABYLON.VertexBuffer.ColorKind)) ? _Exporter.GetRightHandedVector4(vertexData).asArray() : vertexData.asArray();
  358. }
  359. else if (vertexBufferKind === BABYLON.VertexBuffer.UVKind || vertexBufferKind === BABYLON.VertexBuffer.UV2Kind) {
  360. vector = [meshAttributeArray[index], meshAttributeArray[index + 1]];
  361. }
  362. else {
  363. BABYLON.Tools.Warn("Unsupported Vertex Buffer Type: " + vertexBufferKind);
  364. }
  365. for (var i = 0; i < vector.length; ++i) {
  366. dataBuffer.setFloat32(byteOff, vector[i], true);
  367. byteOff += 4;
  368. }
  369. }
  370. byteLength = meshAttributeArray.length * 4;
  371. return byteLength;
  372. };
  373. /**
  374. * Generates glTF json data
  375. * @param shouldUseGlb - Indicates whether the json should be written for a glb file.
  376. * @param glTFPrefix - Text to use when prefixing a glTF file.
  377. * @param prettyPrint - Indicates whether the json file should be pretty printed (true) or not (false).
  378. * @returns - json data as string
  379. */
  380. _Exporter.prototype.generateJSON = function (shouldUseGlb, glTFPrefix, prettyPrint) {
  381. var buffer = { byteLength: this.totalByteLength };
  382. var glTF = {
  383. asset: this.asset
  384. };
  385. if (buffer.byteLength) {
  386. glTF.buffers = [buffer];
  387. }
  388. if (this.nodes && this.nodes.length) {
  389. glTF.nodes = this.nodes;
  390. }
  391. if (this.meshes && this.meshes.length) {
  392. glTF.meshes = this.meshes;
  393. }
  394. if (this.scenes && this.scenes.length) {
  395. glTF.scenes = this.scenes;
  396. glTF.scene = 0;
  397. }
  398. if (this.bufferViews && this.bufferViews.length) {
  399. glTF.bufferViews = this.bufferViews;
  400. }
  401. if (this.accessors && this.accessors.length) {
  402. glTF.accessors = this.accessors;
  403. }
  404. if (this.materials && this.materials.length) {
  405. glTF.materials = this.materials;
  406. }
  407. if (this.textures && this.textures.length) {
  408. glTF.textures = this.textures;
  409. }
  410. if (this.images && this.images.length) {
  411. if (!shouldUseGlb) {
  412. glTF.images = this.images;
  413. }
  414. else {
  415. glTF.images = [];
  416. // Replace uri with bufferview and mime type for glb
  417. var imageLength = this.images.length;
  418. var byteOffset = this.totalByteLength;
  419. for (var i = 0; i < imageLength; ++i) {
  420. var image = this.images[i];
  421. if (image.uri) {
  422. var imageData = this.imageData[image.uri];
  423. var imageName = image.uri.split('.')[0] + " image";
  424. var bufferView = this.createBufferView(0, byteOffset, imageData.data.length, undefined, imageName);
  425. byteOffset += imageData.data.buffer.byteLength;
  426. this.bufferViews.push(bufferView);
  427. image.bufferView = this.bufferViews.length - 1;
  428. image.name = imageName;
  429. image.mimeType = imageData.mimeType;
  430. image.uri = undefined;
  431. glTF.images.push(image);
  432. }
  433. }
  434. buffer.byteLength = byteOffset;
  435. }
  436. }
  437. if (!shouldUseGlb) {
  438. buffer.uri = glTFPrefix + ".bin";
  439. }
  440. var jsonText = prettyPrint ? JSON.stringify(glTF, null, 2) : JSON.stringify(glTF);
  441. return jsonText;
  442. };
  443. /**
  444. * Generates data for .gltf and .bin files based on the glTF prefix string
  445. * @param glTFPrefix - Text to use when prefixing a glTF file.
  446. * @returns - GLTFData with glTF file data.
  447. */
  448. _Exporter.prototype._generateGLTF = function (glTFPrefix) {
  449. var binaryBuffer = this.generateBinary();
  450. var jsonText = this.generateJSON(false, glTFPrefix, true);
  451. var bin = new Blob([binaryBuffer], { type: 'application/octet-stream' });
  452. var glTFFileName = glTFPrefix + '.gltf';
  453. var glTFBinFile = glTFPrefix + '.bin';
  454. var container = new BABYLON._GLTFData();
  455. container.glTFFiles[glTFFileName] = jsonText;
  456. container.glTFFiles[glTFBinFile] = bin;
  457. if (this.imageData) {
  458. for (var image in this.imageData) {
  459. container.glTFFiles[image] = new Blob([this.imageData[image].data], { type: this.imageData[image].mimeType });
  460. }
  461. }
  462. return container;
  463. };
  464. /**
  465. * Creates a binary buffer for glTF
  466. * @returns - array buffer for binary data
  467. */
  468. _Exporter.prototype.generateBinary = function () {
  469. var byteOffset = 0;
  470. byteOffset = this.createScene(this.babylonScene, byteOffset);
  471. return this.binaryBuffer;
  472. };
  473. /**
  474. * Pads the number to a multiple of 4
  475. * @param num - number to pad
  476. * @returns - padded number
  477. */
  478. _Exporter.prototype._getPadding = function (num) {
  479. var remainder = num % 4;
  480. var padding = remainder === 0 ? remainder : 4 - remainder;
  481. return padding;
  482. };
  483. /**
  484. * Generates a glb file from the json and binary data.
  485. * Returns an object with the glb file name as the key and data as the value.
  486. * @param glTFPrefix
  487. * @returns - object with glb filename as key and data as value
  488. */
  489. _Exporter.prototype._generateGLB = function (glTFPrefix) {
  490. var binaryBuffer = this.generateBinary();
  491. var jsonText = this.generateJSON(true);
  492. var glbFileName = glTFPrefix + '.glb';
  493. var headerLength = 12;
  494. var chunkLengthPrefix = 8;
  495. var jsonLength = jsonText.length;
  496. var imageByteLength = 0;
  497. for (var key in this.imageData) {
  498. imageByteLength += this.imageData[key].data.byteLength;
  499. }
  500. var jsonPadding = this._getPadding(jsonLength);
  501. var binPadding = this._getPadding(binaryBuffer.byteLength);
  502. var imagePadding = this._getPadding(imageByteLength);
  503. var byteLength = headerLength + (2 * chunkLengthPrefix) + jsonLength + jsonPadding + binaryBuffer.byteLength + binPadding + imageByteLength + imagePadding;
  504. //header
  505. var headerBuffer = new ArrayBuffer(headerLength);
  506. var headerBufferView = new DataView(headerBuffer);
  507. headerBufferView.setUint32(0, 0x46546C67, true); //glTF
  508. headerBufferView.setUint32(4, 2, true); // version
  509. headerBufferView.setUint32(8, byteLength, true); // total bytes in file
  510. //json chunk
  511. var jsonChunkBuffer = new ArrayBuffer(chunkLengthPrefix + jsonLength + jsonPadding);
  512. var jsonChunkBufferView = new DataView(jsonChunkBuffer);
  513. jsonChunkBufferView.setUint32(0, jsonLength + jsonPadding, true);
  514. jsonChunkBufferView.setUint32(4, 0x4E4F534A, true);
  515. //json chunk bytes
  516. var jsonData = new Uint8Array(jsonChunkBuffer, chunkLengthPrefix);
  517. for (var i = 0; i < jsonLength; ++i) {
  518. jsonData[i] = jsonText.charCodeAt(i);
  519. }
  520. //json padding
  521. var jsonPaddingView = new Uint8Array(jsonChunkBuffer, chunkLengthPrefix + jsonLength);
  522. for (var i = 0; i < jsonPadding; ++i) {
  523. jsonPaddingView[i] = 0x20;
  524. }
  525. //binary chunk
  526. var binaryChunkBuffer = new ArrayBuffer(chunkLengthPrefix);
  527. var binaryChunkBufferView = new DataView(binaryChunkBuffer);
  528. binaryChunkBufferView.setUint32(0, binaryBuffer.byteLength + imageByteLength + imagePadding, true);
  529. binaryChunkBufferView.setUint32(4, 0x004E4942, true);
  530. // binary padding
  531. var binPaddingBuffer = new ArrayBuffer(binPadding);
  532. var binPaddingView = new Uint8Array(binPaddingBuffer);
  533. for (var i = 0; i < binPadding; ++i) {
  534. binPaddingView[i] = 0;
  535. }
  536. var imagePaddingBuffer = new ArrayBuffer(imagePadding);
  537. var imagePaddingView = new Uint8Array(imagePaddingBuffer);
  538. for (var i = 0; i < imagePadding; ++i) {
  539. imagePaddingView[i] = 0;
  540. }
  541. var glbData = [headerBuffer, jsonChunkBuffer, binaryChunkBuffer, binaryBuffer];
  542. // binary data
  543. for (var key in this.imageData) {
  544. glbData.push(this.imageData[key].data.buffer);
  545. }
  546. glbData.push(binPaddingBuffer);
  547. glbData.push(imagePaddingBuffer);
  548. var glbFile = new Blob(glbData, { type: 'application/octet-stream' });
  549. var container = new BABYLON._GLTFData();
  550. container.glTFFiles[glbFileName] = glbFile;
  551. return container;
  552. };
  553. /**
  554. * Sets the TRS for each node
  555. * @param node - glTF Node for storing the transformation data.
  556. * @param babylonMesh - Babylon mesh used as the source for the transformation data.
  557. */
  558. _Exporter.prototype.setNodeTransformation = function (node, babylonMesh) {
  559. if (!babylonMesh.position.equalsToFloats(0, 0, 0)) {
  560. node.translation = this.convertToRightHandedSystem ? _Exporter.GetRightHandedVector3(babylonMesh.position).asArray() : babylonMesh.position.asArray();
  561. }
  562. if (!babylonMesh.scaling.equalsToFloats(1, 1, 1)) {
  563. node.scale = babylonMesh.scaling.asArray();
  564. }
  565. var rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(babylonMesh.rotation.y, babylonMesh.rotation.x, babylonMesh.rotation.z);
  566. if (babylonMesh.rotationQuaternion) {
  567. rotationQuaternion = rotationQuaternion.multiply(babylonMesh.rotationQuaternion);
  568. }
  569. if (!(rotationQuaternion.x === 0 && rotationQuaternion.y === 0 && rotationQuaternion.z === 0 && rotationQuaternion.w === 1)) {
  570. node.rotation = this.convertToRightHandedSystem ? _Exporter.GetRightHandedQuaternion(rotationQuaternion).asArray() : rotationQuaternion.asArray();
  571. }
  572. };
  573. /**
  574. * Creates a bufferview based on the vertices type for the Babylon mesh
  575. * @param kind - Indicates the type of vertices data.
  576. * @param babylonMesh - The Babylon mesh to get the vertices data from.
  577. * @param byteOffset - The offset from the buffer to start indexing from.
  578. * @param dataBuffer - The buffer to write the bufferview data to.
  579. * @returns bytelength of the bufferview data.
  580. */
  581. _Exporter.prototype.createBufferViewKind = function (kind, babylonMesh, byteOffset, dataBuffer) {
  582. var bufferMesh = null;
  583. var byteLength = 0;
  584. if (babylonMesh instanceof BABYLON.Mesh) {
  585. bufferMesh = babylonMesh;
  586. }
  587. else if (babylonMesh instanceof BABYLON.InstancedMesh) {
  588. bufferMesh = babylonMesh.sourceMesh;
  589. }
  590. if (bufferMesh) {
  591. var vertexBuffer = null;
  592. var vertexBufferOffset = null;
  593. var vertexData = null;
  594. var vertexStrideSize = null;
  595. if (bufferMesh.isVerticesDataPresent(kind)) {
  596. vertexBuffer = bufferMesh.getVertexBuffer(kind);
  597. if (vertexBuffer) {
  598. vertexBufferOffset = vertexBuffer.getOffset();
  599. vertexData = vertexBuffer.getData();
  600. if (vertexData) {
  601. vertexStrideSize = vertexBuffer.getStrideSize();
  602. if (dataBuffer && vertexData) {
  603. byteLength = this.writeAttributeData(kind, vertexData, vertexStrideSize, vertexBufferOffset, byteOffset, dataBuffer);
  604. byteOffset += byteLength;
  605. }
  606. else {
  607. byteLength = vertexData.length * 4;
  608. var bufferView = this.createBufferView(0, byteOffset, byteLength, vertexStrideSize * 4, kind + " - " + bufferMesh.name);
  609. byteOffset += byteLength;
  610. this.bufferViews.push(bufferView);
  611. }
  612. }
  613. }
  614. }
  615. }
  616. return byteLength;
  617. };
  618. /**
  619. * Sets data for the primitive attributes of each submesh
  620. * @param mesh - glTF Mesh object to store the primitive attribute information.
  621. * @param babylonMesh - Babylon mesh to get the primitive attribute data from.
  622. * @param byteOffset - The offset in bytes of the buffer data.
  623. * @param dataBuffer - Buffer to write the attribute data to.
  624. * @returns - bytelength of the primitive attributes plus the passed in byteOffset.
  625. */
  626. _Exporter.prototype.setPrimitiveAttributes = function (mesh, babylonMesh, byteOffset, dataBuffer) {
  627. var bufferMesh = null;
  628. if (babylonMesh instanceof BABYLON.Mesh) {
  629. bufferMesh = babylonMesh;
  630. }
  631. else if (babylonMesh instanceof BABYLON.InstancedMesh) {
  632. bufferMesh = babylonMesh.sourceMesh;
  633. }
  634. var attributeData = [
  635. { kind: BABYLON.VertexBuffer.PositionKind, accessorType: "VEC3" /* VEC3 */ },
  636. { kind: BABYLON.VertexBuffer.NormalKind, accessorType: "VEC3" /* VEC3 */ },
  637. { kind: BABYLON.VertexBuffer.ColorKind, accessorType: "VEC4" /* VEC4 */ },
  638. { kind: BABYLON.VertexBuffer.TangentKind, accessorType: "VEC4" /* VEC4 */ },
  639. { kind: BABYLON.VertexBuffer.UVKind, accessorType: "VEC2" /* VEC2 */ },
  640. { kind: BABYLON.VertexBuffer.UV2Kind, accessorType: "VEC2" /* VEC2 */ },
  641. ];
  642. var indexBufferViewIndex = null;
  643. if (bufferMesh) {
  644. // For each BabylonMesh, create bufferviews for each 'kind'
  645. for (var _i = 0, attributeData_1 = attributeData; _i < attributeData_1.length; _i++) {
  646. var attribute = attributeData_1[_i];
  647. var attributeKind = attribute.kind;
  648. if (bufferMesh.isVerticesDataPresent(attributeKind)) {
  649. byteOffset += this.createBufferViewKind(attributeKind, babylonMesh, byteOffset, dataBuffer);
  650. attribute.bufferViewIndex = this.bufferViews.length - 1;
  651. }
  652. }
  653. if (bufferMesh.getTotalIndices()) {
  654. var indices = bufferMesh.getIndices();
  655. if (indices) {
  656. if (dataBuffer) {
  657. var end = indices.length;
  658. var byteOff = byteOffset;
  659. for (var k = 0; k < end; ++k) {
  660. dataBuffer.setUint32(byteOff, indices[k], true);
  661. byteOff += 4;
  662. }
  663. byteOffset = byteOff;
  664. }
  665. else {
  666. var byteLength = indices.length * 4;
  667. var bufferView = this.createBufferView(0, byteOffset, byteLength, undefined, "Indices - " + bufferMesh.name);
  668. byteOffset += byteLength;
  669. this.bufferViews.push(bufferView);
  670. indexBufferViewIndex = this.bufferViews.length - 1;
  671. }
  672. }
  673. }
  674. if (babylonMesh.subMeshes) {
  675. var uvCoordsPresent = false;
  676. // go through all mesh primitives (submeshes)
  677. for (var _a = 0, _b = babylonMesh.subMeshes; _a < _b.length; _a++) {
  678. var submesh = _b[_a];
  679. var meshPrimitive = { attributes: {} };
  680. // Create a bufferview storing all the positions
  681. if (!dataBuffer) {
  682. for (var _c = 0, attributeData_2 = attributeData; _c < attributeData_2.length; _c++) {
  683. var attribute = attributeData_2[_c];
  684. var attributeKind = attribute.kind;
  685. if (bufferMesh.isVerticesDataPresent(attributeKind)) {
  686. var vertexBuffer = bufferMesh.getVertexBuffer(attributeKind);
  687. if (vertexBuffer) {
  688. var bufferData = vertexBuffer.getData();
  689. if (bufferData) {
  690. var strideSize = vertexBuffer.getStrideSize();
  691. var minMax = void 0;
  692. var min = null;
  693. var max = null;
  694. var bufferViewIndex = attribute.bufferViewIndex;
  695. if (bufferViewIndex != undefined) {
  696. if (attributeKind == BABYLON.VertexBuffer.PositionKind) {
  697. minMax = this.calculateMinMaxPositions(bufferData, 0, bufferData.length / strideSize);
  698. min = minMax.min;
  699. max = minMax.max;
  700. }
  701. var accessor = this.createAccessor(bufferViewIndex, attributeKind + " - " + babylonMesh.name, attribute.accessorType, 5126 /* FLOAT */, bufferData.length / strideSize, 0, min, max);
  702. this.accessors.push(accessor);
  703. switch (attributeKind) {
  704. case BABYLON.VertexBuffer.PositionKind: {
  705. meshPrimitive.attributes.POSITION = this.accessors.length - 1;
  706. break;
  707. }
  708. case BABYLON.VertexBuffer.NormalKind: {
  709. meshPrimitive.attributes.NORMAL = this.accessors.length - 1;
  710. break;
  711. }
  712. case BABYLON.VertexBuffer.ColorKind: {
  713. meshPrimitive.attributes.COLOR_0 = this.accessors.length - 1;
  714. break;
  715. }
  716. case BABYLON.VertexBuffer.TangentKind: {
  717. meshPrimitive.attributes.TANGENT = this.accessors.length - 1;
  718. break;
  719. }
  720. case BABYLON.VertexBuffer.UVKind: {
  721. meshPrimitive.attributes.TEXCOORD_0 = this.accessors.length - 1;
  722. uvCoordsPresent = true;
  723. break;
  724. }
  725. case BABYLON.VertexBuffer.UV2Kind: {
  726. meshPrimitive.attributes.TEXCOORD_1 = this.accessors.length - 1;
  727. uvCoordsPresent = true;
  728. break;
  729. }
  730. default: {
  731. BABYLON.Tools.Warn("Unsupported Vertex Buffer Type: " + attributeKind);
  732. }
  733. }
  734. }
  735. }
  736. }
  737. }
  738. }
  739. if (indexBufferViewIndex) {
  740. // Create accessor
  741. var accessor = this.createAccessor(indexBufferViewIndex, "indices - " + babylonMesh.name, "SCALAR" /* SCALAR */, 5125 /* UNSIGNED_INT */, submesh.indexCount, submesh.indexStart * 4, null, null);
  742. this.accessors.push(accessor);
  743. meshPrimitive.indices = this.accessors.length - 1;
  744. }
  745. }
  746. if (bufferMesh.material) {
  747. var materialIndex = null;
  748. if (bufferMesh.material instanceof BABYLON.StandardMaterial || bufferMesh.material instanceof BABYLON.PBRMetallicRoughnessMaterial || bufferMesh.material instanceof BABYLON.PBRMaterial) {
  749. materialIndex = babylonMesh.getScene().materials.indexOf(bufferMesh.material);
  750. }
  751. else if (bufferMesh.material instanceof BABYLON.MultiMaterial) {
  752. var babylonMultiMaterial = bufferMesh.material;
  753. var material = babylonMultiMaterial.subMaterials[submesh.materialIndex];
  754. if (material) {
  755. materialIndex = babylonMesh.getScene().materials.indexOf(material);
  756. }
  757. }
  758. else {
  759. BABYLON.Tools.Warn("Material type " + bufferMesh.material.getClassName() + " for material " + bufferMesh.material.name + " is not yet implemented in glTF serializer.");
  760. }
  761. if (materialIndex != null && Object.keys(meshPrimitive.attributes).length > 0) {
  762. if (uvCoordsPresent || !GLTF2._GLTFMaterial._HasTexturesPresent(this.materials[materialIndex])) {
  763. meshPrimitive.material = materialIndex;
  764. }
  765. else {
  766. // If no texture coordinate information is present, make a copy of the material without the textures to be glTF compliant.
  767. var newMat = GLTF2._GLTFMaterial._StripTexturesFromMaterial(this.materials[materialIndex]);
  768. this.materials.push(newMat);
  769. meshPrimitive.material = this.materials.length - 1;
  770. }
  771. }
  772. }
  773. mesh.primitives.push(meshPrimitive);
  774. }
  775. }
  776. }
  777. return byteOffset;
  778. };
  779. /**
  780. * Creates a glTF scene based on the array of meshes.
  781. * Returns the the total byte offset.
  782. * @param babylonScene - Babylon scene to get the mesh data from.
  783. * @param byteOffset - Offset to start from in bytes.
  784. * @returns bytelength + byteoffset
  785. */
  786. _Exporter.prototype.createScene = function (babylonScene, byteOffset) {
  787. if (babylonScene.meshes.length) {
  788. var babylonMeshes = babylonScene.meshes;
  789. var scene = { nodes: new Array() };
  790. GLTF2._GLTFMaterial._ConvertMaterialsToGLTF(babylonScene.materials, "image/png" /* PNG */, this.images, this.textures, this.materials, this.imageData, true);
  791. var result = this.createNodeMap(babylonScene, byteOffset);
  792. this.nodeMap = result.nodeMap;
  793. this.totalByteLength = result.byteOffset;
  794. this.binaryBuffer = new ArrayBuffer(this.totalByteLength);
  795. var dataBuffer = new DataView(this.binaryBuffer);
  796. for (var i = 0; i < babylonMeshes.length; ++i) {
  797. var babylonMesh = babylonMeshes[i];
  798. // Build Hierarchy with the node map.
  799. var glTFNodeIndex = this.nodeMap[babylonMesh.uniqueId];
  800. var glTFNode = this.nodes[glTFNodeIndex];
  801. if (!babylonMesh.parent) {
  802. if (this.options &&
  803. this.options.shouldExportMesh != undefined &&
  804. !this.options.shouldExportMesh(babylonMesh)) {
  805. BABYLON.Tools.Log("Omitting " + babylonMesh.name + " from scene.");
  806. }
  807. else {
  808. scene.nodes.push(glTFNodeIndex);
  809. }
  810. }
  811. var directDescendents = babylonMesh.getDescendants(true);
  812. if (!glTFNode.children && directDescendents && directDescendents.length) {
  813. glTFNode.children = [];
  814. for (var _i = 0, directDescendents_1 = directDescendents; _i < directDescendents_1.length; _i++) {
  815. var descendent = directDescendents_1[_i];
  816. glTFNode.children.push(this.nodeMap[descendent.uniqueId]);
  817. }
  818. }
  819. var mesh = { primitives: new Array() };
  820. byteOffset = this.setPrimitiveAttributes(mesh, babylonMesh, byteOffset, dataBuffer);
  821. }
  822. this.scenes.push(scene);
  823. }
  824. return byteOffset;
  825. };
  826. /**
  827. * Creates a mapping of Node unique id to node index
  828. * @param scene - Babylon Scene.
  829. * @param byteOffset - The initial byte offset.
  830. * @returns - Node mapping of unique id to index.
  831. */
  832. _Exporter.prototype.createNodeMap = function (scene, byteOffset) {
  833. var nodeMap = {};
  834. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  835. var babylonMesh = _a[_i];
  836. var result = this.createNode(babylonMesh, byteOffset, null);
  837. this.nodes.push(result.node);
  838. nodeMap[babylonMesh.uniqueId] = this.nodes.length - 1;
  839. byteOffset = result.byteOffset;
  840. }
  841. return { nodeMap: nodeMap, byteOffset: byteOffset };
  842. };
  843. /**
  844. * Creates a glTF node from a Babylon mesh.
  845. * @param babylonMesh - Source Babylon mesh.
  846. * @param byteOffset - The initial byte offset.
  847. * @param dataBuffer - Buffer for storing geometry data.
  848. * @returns - Object containing an INode and byteoffset.
  849. */
  850. _Exporter.prototype.createNode = function (babylonMesh, byteOffset, dataBuffer) {
  851. // create node to hold translation/rotation/scale and the mesh
  852. var node = {};
  853. if (babylonMesh.name) {
  854. node.name = babylonMesh.name;
  855. }
  856. // Set transformation
  857. this.setNodeTransformation(node, babylonMesh);
  858. // create mesh
  859. var mesh = { primitives: new Array() };
  860. mesh.primitives = [];
  861. byteOffset = this.setPrimitiveAttributes(mesh, babylonMesh, byteOffset, dataBuffer);
  862. if (mesh.primitives.length) {
  863. this.meshes.push(mesh);
  864. node.mesh = this.meshes.length - 1;
  865. }
  866. return { node: node, byteOffset: byteOffset };
  867. };
  868. return _Exporter;
  869. }());
  870. GLTF2._Exporter = _Exporter;
  871. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  872. })(BABYLON || (BABYLON = {}));
  873. //# sourceMappingURL=babylon.glTFExporter.js.map
  874. var BABYLON;
  875. (function (BABYLON) {
  876. /**
  877. * Class for holding and downloading glTF file data
  878. */
  879. var _GLTFData = /** @class */ (function () {
  880. /**
  881. * Initializes the glTF file object.
  882. */
  883. function _GLTFData() {
  884. this.glTFFiles = {};
  885. }
  886. /**
  887. * Downloads the glTF data as files based on their names and data.
  888. */
  889. _GLTFData.prototype.downloadFiles = function () {
  890. /**
  891. * Checks for a matching suffix at the end of a string (for ES5 and lower).
  892. * @param str - Source string.
  893. * @param suffix - Suffix to search for in the source string.
  894. * @returns - Boolean indicating whether the suffix was found (true) or not (false).
  895. */
  896. function endsWith(str, suffix) {
  897. return str.indexOf(suffix, str.length - suffix.length) !== -1;
  898. }
  899. for (var key in this.glTFFiles) {
  900. var link = document.createElement('a');
  901. document.body.appendChild(link);
  902. link.setAttribute("type", "hidden");
  903. link.download = key;
  904. var blob = this.glTFFiles[key];
  905. var mimeType = void 0;
  906. if (endsWith(key, ".glb")) {
  907. mimeType = { type: "model/gltf-binary" };
  908. }
  909. else if (endsWith(key, ".bin")) {
  910. mimeType = { type: "application/octet-stream" };
  911. }
  912. else if (endsWith(key, ".gltf")) {
  913. mimeType = { type: "model/gltf+json" };
  914. }
  915. else if (endsWith(key, ".jpeg" || ".jpg")) {
  916. mimeType = { type: "image/jpeg" /* JPEG */ };
  917. }
  918. else if (endsWith(key, ".png")) {
  919. mimeType = { type: "image/png" /* PNG */ };
  920. }
  921. link.href = window.URL.createObjectURL(new Blob([blob], mimeType));
  922. link.click();
  923. }
  924. };
  925. return _GLTFData;
  926. }());
  927. BABYLON._GLTFData = _GLTFData;
  928. })(BABYLON || (BABYLON = {}));
  929. //# sourceMappingURL=babylon.glTFData.js.map
  930. var BABYLON;
  931. (function (BABYLON) {
  932. var GLTF2;
  933. (function (GLTF2) {
  934. /**
  935. * Utility methods for working with glTF material conversion properties. This class should only be used internally.
  936. */
  937. var _GLTFMaterial = /** @class */ (function () {
  938. function _GLTFMaterial() {
  939. }
  940. /**
  941. * Specifies if two colors are approximately equal in value.
  942. * @param color1 - first color to compare to.
  943. * @param color2 - second color to compare to.
  944. * @param epsilon - threshold value
  945. */
  946. _GLTFMaterial.FuzzyEquals = function (color1, color2, epsilon) {
  947. return BABYLON.Scalar.WithinEpsilon(color1.r, color2.r, epsilon) &&
  948. BABYLON.Scalar.WithinEpsilon(color1.g, color2.g, epsilon) &&
  949. BABYLON.Scalar.WithinEpsilon(color1.b, color2.b, epsilon);
  950. };
  951. /**
  952. * Gets the materials from a Babylon scene and converts them to glTF materials.
  953. * @param scene - babylonjs scene.
  954. * @param mimeType - texture mime type.
  955. * @param images - array of images.
  956. * @param textures - array of textures.
  957. * @param materials - array of materials.
  958. * @param imageData - mapping of texture names to base64 textures
  959. * @param hasTextureCoords - specifies if texture coordinates are present on the material.
  960. */
  961. _GLTFMaterial._ConvertMaterialsToGLTF = function (babylonMaterials, mimeType, images, textures, materials, imageData, hasTextureCoords) {
  962. for (var i = 0; i < babylonMaterials.length; ++i) {
  963. var babylonMaterial = babylonMaterials[i];
  964. if (babylonMaterial instanceof BABYLON.StandardMaterial) {
  965. _GLTFMaterial._ConvertStandardMaterial(babylonMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords);
  966. }
  967. else if (babylonMaterial instanceof BABYLON.PBRMetallicRoughnessMaterial) {
  968. _GLTFMaterial._ConvertPBRMetallicRoughnessMaterial(babylonMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords);
  969. }
  970. else if (babylonMaterial instanceof BABYLON.PBRMaterial) {
  971. _GLTFMaterial._ConvertPBRMaterial(babylonMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords);
  972. }
  973. else {
  974. throw new Error("Unsupported material type: " + babylonMaterial.name);
  975. }
  976. }
  977. };
  978. /**
  979. * Makes a copy of the glTF material without the texture parameters.
  980. * @param originalMaterial - original glTF material.
  981. * @returns glTF material without texture parameters
  982. */
  983. _GLTFMaterial._StripTexturesFromMaterial = function (originalMaterial) {
  984. var newMaterial = {};
  985. if (originalMaterial) {
  986. newMaterial.name = originalMaterial.name;
  987. newMaterial.doubleSided = originalMaterial.doubleSided;
  988. newMaterial.alphaMode = originalMaterial.alphaMode;
  989. newMaterial.alphaCutoff = originalMaterial.alphaCutoff;
  990. newMaterial.emissiveFactor = originalMaterial.emissiveFactor;
  991. var originalPBRMetallicRoughness = originalMaterial.pbrMetallicRoughness;
  992. if (originalPBRMetallicRoughness) {
  993. newMaterial.pbrMetallicRoughness = {};
  994. newMaterial.pbrMetallicRoughness.baseColorFactor = originalPBRMetallicRoughness.baseColorFactor;
  995. newMaterial.pbrMetallicRoughness.metallicFactor = originalPBRMetallicRoughness.metallicFactor;
  996. newMaterial.pbrMetallicRoughness.roughnessFactor = originalPBRMetallicRoughness.roughnessFactor;
  997. }
  998. }
  999. return newMaterial;
  1000. };
  1001. /**
  1002. * Specifies if the material has any texture parameters present.
  1003. * @param material - glTF Material.
  1004. * @returns boolean specifying if texture parameters are present
  1005. */
  1006. _GLTFMaterial._HasTexturesPresent = function (material) {
  1007. if (material.emissiveTexture || material.normalTexture || material.occlusionTexture) {
  1008. return true;
  1009. }
  1010. var pbrMat = material.pbrMetallicRoughness;
  1011. if (pbrMat) {
  1012. if (pbrMat.baseColorTexture || pbrMat.metallicRoughnessTexture) {
  1013. return true;
  1014. }
  1015. }
  1016. return false;
  1017. };
  1018. /**
  1019. * Converts a Babylon StandardMaterial to a glTF Metallic Roughness Material.
  1020. * @param babylonStandardMaterial
  1021. * @returns - glTF Metallic Roughness Material representation
  1022. */
  1023. _GLTFMaterial._ConvertToGLTFPBRMetallicRoughness = function (babylonStandardMaterial) {
  1024. var P0 = new BABYLON.Vector2(0, 1);
  1025. var P1 = new BABYLON.Vector2(0, 0.1);
  1026. var P2 = new BABYLON.Vector2(0, 0.1);
  1027. var P3 = new BABYLON.Vector2(1300, 0.1);
  1028. /**
  1029. * Given the control points, solve for x based on a given t for a cubic bezier curve.
  1030. * @param t - a value between 0 and 1.
  1031. * @param p0 - first control point.
  1032. * @param p1 - second control point.
  1033. * @param p2 - third control point.
  1034. * @param p3 - fourth control point.
  1035. * @returns - number result of cubic bezier curve at the specified t.
  1036. */
  1037. function _cubicBezierCurve(t, p0, p1, p2, p3) {
  1038. return ((1 - t) * (1 - t) * (1 - t) * p0 +
  1039. 3 * (1 - t) * (1 - t) * t * p1 +
  1040. 3 * (1 - t) * t * t * p2 +
  1041. t * t * t * p3);
  1042. }
  1043. /**
  1044. * Evaluates a specified specular power value to determine the appropriate roughness value,
  1045. * based on a pre-defined cubic bezier curve with specular on the abscissa axis (x-axis)
  1046. * and roughness on the ordinant axis (y-axis).
  1047. * @param specularPower - specular power of standard material.
  1048. * @returns - Number representing the roughness value.
  1049. */
  1050. function _solveForRoughness(specularPower) {
  1051. var t = Math.pow(specularPower / P3.x, 0.333333);
  1052. return _cubicBezierCurve(t, P0.y, P1.y, P2.y, P3.y);
  1053. }
  1054. var diffuse = babylonStandardMaterial.diffuseColor.toLinearSpace().scale(0.5);
  1055. var opacity = babylonStandardMaterial.alpha;
  1056. var specularPower = BABYLON.Scalar.Clamp(babylonStandardMaterial.specularPower, 0, this._maxSpecularPower);
  1057. var roughness = _solveForRoughness(specularPower);
  1058. var glTFPbrMetallicRoughness = {
  1059. baseColorFactor: [
  1060. diffuse.r,
  1061. diffuse.g,
  1062. diffuse.b,
  1063. opacity
  1064. ],
  1065. metallicFactor: 0,
  1066. roughnessFactor: roughness,
  1067. };
  1068. return glTFPbrMetallicRoughness;
  1069. };
  1070. /**
  1071. * Computes the metallic factor
  1072. * @param diffuse - diffused value
  1073. * @param specular - specular value
  1074. * @param oneMinusSpecularStrength - one minus the specular strength
  1075. * @returns - metallic value
  1076. */
  1077. _GLTFMaterial._SolveMetallic = function (diffuse, specular, oneMinusSpecularStrength) {
  1078. if (specular < _GLTFMaterial._dielectricSpecular.r) {
  1079. _GLTFMaterial._dielectricSpecular;
  1080. return 0;
  1081. }
  1082. var a = _GLTFMaterial._dielectricSpecular.r;
  1083. var b = diffuse * oneMinusSpecularStrength / (1.0 - _GLTFMaterial._dielectricSpecular.r) + specular - 2.0 * _GLTFMaterial._dielectricSpecular.r;
  1084. var c = _GLTFMaterial._dielectricSpecular.r - specular;
  1085. var D = b * b - 4.0 * a * c;
  1086. return BABYLON.Scalar.Clamp((-b + Math.sqrt(D)) / (2.0 * a), 0, 1);
  1087. };
  1088. /**
  1089. * Gets the glTF alpha mode from the Babylon Material
  1090. * @param babylonMaterial - Babylon Material
  1091. * @returns - The Babylon alpha mode value
  1092. */
  1093. _GLTFMaterial._GetAlphaMode = function (babylonMaterial) {
  1094. if (babylonMaterial instanceof BABYLON.StandardMaterial) {
  1095. var babylonStandardMaterial = babylonMaterial;
  1096. if ((babylonStandardMaterial.alpha != 1.0) ||
  1097. (babylonStandardMaterial.diffuseTexture != null && babylonStandardMaterial.diffuseTexture.hasAlpha) ||
  1098. (babylonStandardMaterial.opacityTexture != null)) {
  1099. return "BLEND" /* BLEND */;
  1100. }
  1101. else {
  1102. return "OPAQUE" /* OPAQUE */;
  1103. }
  1104. }
  1105. else if (babylonMaterial instanceof BABYLON.PBRMetallicRoughnessMaterial) {
  1106. var babylonPBRMetallicRoughness = babylonMaterial;
  1107. switch (babylonPBRMetallicRoughness.transparencyMode) {
  1108. case BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE: {
  1109. return "OPAQUE" /* OPAQUE */;
  1110. }
  1111. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND: {
  1112. return "BLEND" /* BLEND */;
  1113. }
  1114. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST: {
  1115. return "MASK" /* MASK */;
  1116. }
  1117. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND: {
  1118. BABYLON.Tools.Warn(babylonMaterial.name + ": GLTF Exporter | Alpha test and blend mode not supported in glTF. Alpha blend used instead.");
  1119. return "BLEND" /* BLEND */;
  1120. }
  1121. default: {
  1122. throw new Error("Unsupported alpha mode " + babylonPBRMetallicRoughness.transparencyMode);
  1123. }
  1124. }
  1125. }
  1126. else if (babylonMaterial instanceof BABYLON.PBRMaterial) {
  1127. var babylonPBRMaterial = babylonMaterial;
  1128. switch (babylonPBRMaterial.transparencyMode) {
  1129. case BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE: {
  1130. return "OPAQUE" /* OPAQUE */;
  1131. }
  1132. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND: {
  1133. return "BLEND" /* BLEND */;
  1134. }
  1135. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST: {
  1136. return "MASK" /* MASK */;
  1137. }
  1138. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND: {
  1139. BABYLON.Tools.Warn(babylonMaterial.name + ": GLTF Exporter | Alpha test and blend mode not supported in glTF. Alpha blend used instead.");
  1140. return "BLEND" /* BLEND */;
  1141. }
  1142. default: {
  1143. throw new Error("Unsupported alpha mode " + babylonPBRMaterial.transparencyMode);
  1144. }
  1145. }
  1146. }
  1147. else {
  1148. throw new Error("Unsupported Babylon material type");
  1149. }
  1150. };
  1151. /**
  1152. * Converts a Babylon Standard Material to a glTF Material.
  1153. * @param babylonStandardMaterial - BJS Standard Material.
  1154. * @param mimeType - mime type to use for the textures.
  1155. * @param images - array of glTF image interfaces.
  1156. * @param textures - array of glTF texture interfaces.
  1157. * @param materials - array of glTF material interfaces.
  1158. * @param imageData - map of image file name to data.
  1159. * @param hasTextureCoords - specifies if texture coordinates are present on the submesh to determine if textures should be applied.
  1160. */
  1161. _GLTFMaterial._ConvertStandardMaterial = function (babylonStandardMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords) {
  1162. BABYLON.Tools.Warn(babylonStandardMaterial.name + ": Standard Material is currently not fully supported/implemented in glTF serializer");
  1163. var glTFPbrMetallicRoughness = _GLTFMaterial._ConvertToGLTFPBRMetallicRoughness(babylonStandardMaterial);
  1164. var glTFMaterial = { name: babylonStandardMaterial.name };
  1165. if (babylonStandardMaterial.backFaceCulling != null && !babylonStandardMaterial.backFaceCulling) {
  1166. if (!babylonStandardMaterial.twoSidedLighting) {
  1167. BABYLON.Tools.Warn(babylonStandardMaterial.name + ": Back-face culling enabled and two-sided lighting disabled is not supported in glTF.");
  1168. }
  1169. glTFMaterial.doubleSided = true;
  1170. }
  1171. if (hasTextureCoords) {
  1172. if (babylonStandardMaterial.diffuseTexture) {
  1173. var glTFTexture = _GLTFMaterial._ExportTexture(babylonStandardMaterial.diffuseTexture, mimeType, images, textures, imageData);
  1174. if (glTFTexture != null) {
  1175. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  1176. }
  1177. }
  1178. if (babylonStandardMaterial.bumpTexture) {
  1179. var glTFTexture = _GLTFMaterial._ExportTexture(babylonStandardMaterial.bumpTexture, mimeType, images, textures, imageData);
  1180. if (glTFTexture) {
  1181. glTFMaterial.normalTexture = glTFTexture;
  1182. }
  1183. }
  1184. if (babylonStandardMaterial.emissiveTexture) {
  1185. var glTFEmissiveTexture = _GLTFMaterial._ExportTexture(babylonStandardMaterial.emissiveTexture, mimeType, images, textures, imageData);
  1186. if (glTFEmissiveTexture) {
  1187. glTFMaterial.emissiveTexture = glTFEmissiveTexture;
  1188. }
  1189. glTFMaterial.emissiveFactor = [1.0, 1.0, 1.0];
  1190. }
  1191. if (babylonStandardMaterial.ambientTexture) {
  1192. var glTFTexture = _GLTFMaterial._ExportTexture(babylonStandardMaterial.ambientTexture, mimeType, images, textures, imageData);
  1193. if (glTFTexture) {
  1194. var occlusionTexture = {
  1195. index: glTFTexture.index
  1196. };
  1197. glTFMaterial.occlusionTexture = occlusionTexture;
  1198. occlusionTexture.strength = 1.0;
  1199. }
  1200. }
  1201. }
  1202. if (babylonStandardMaterial.alpha < 1.0 || babylonStandardMaterial.opacityTexture) {
  1203. if (babylonStandardMaterial.alphaMode === BABYLON.Engine.ALPHA_COMBINE) {
  1204. glTFMaterial.alphaMode = "BLEND" /* BLEND */;
  1205. }
  1206. else {
  1207. BABYLON.Tools.Warn(babylonStandardMaterial.name + ": glTF 2.0 does not support alpha mode: " + babylonStandardMaterial.alphaMode.toString());
  1208. }
  1209. }
  1210. if (babylonStandardMaterial.emissiveColor && !this.FuzzyEquals(babylonStandardMaterial.emissiveColor, BABYLON.Color3.Black(), this._epsilon)) {
  1211. glTFMaterial.emissiveFactor = babylonStandardMaterial.emissiveColor.asArray();
  1212. }
  1213. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  1214. materials.push(glTFMaterial);
  1215. };
  1216. /**
  1217. * Converts a Babylon PBR Metallic Roughness Material to a glTF Material.
  1218. * @param babylonPBRMetalRoughMaterial - BJS PBR Metallic Roughness Material.
  1219. * @param mimeType - mime type to use for the textures.
  1220. * @param images - array of glTF image interfaces.
  1221. * @param textures - array of glTF texture interfaces.
  1222. * @param materials - array of glTF material interfaces.
  1223. * @param imageData - map of image file name to data.
  1224. * @param hasTextureCoords - specifies if texture coordinates are present on the submesh to determine if textures should be applied.
  1225. */
  1226. _GLTFMaterial._ConvertPBRMetallicRoughnessMaterial = function (babylonPBRMetalRoughMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords) {
  1227. var glTFPbrMetallicRoughness = {};
  1228. if (babylonPBRMetalRoughMaterial.baseColor) {
  1229. glTFPbrMetallicRoughness.baseColorFactor = [
  1230. babylonPBRMetalRoughMaterial.baseColor.r,
  1231. babylonPBRMetalRoughMaterial.baseColor.g,
  1232. babylonPBRMetalRoughMaterial.baseColor.b,
  1233. babylonPBRMetalRoughMaterial.alpha
  1234. ];
  1235. }
  1236. if (babylonPBRMetalRoughMaterial.metallic != null && babylonPBRMetalRoughMaterial.metallic !== 1) {
  1237. glTFPbrMetallicRoughness.metallicFactor = babylonPBRMetalRoughMaterial.metallic;
  1238. }
  1239. if (babylonPBRMetalRoughMaterial.roughness != null && babylonPBRMetalRoughMaterial.roughness !== 1) {
  1240. glTFPbrMetallicRoughness.roughnessFactor = babylonPBRMetalRoughMaterial.roughness;
  1241. }
  1242. var glTFMaterial = {
  1243. name: babylonPBRMetalRoughMaterial.name
  1244. };
  1245. if (babylonPBRMetalRoughMaterial.doubleSided) {
  1246. glTFMaterial.doubleSided = babylonPBRMetalRoughMaterial.doubleSided;
  1247. }
  1248. if (hasTextureCoords) {
  1249. if (babylonPBRMetalRoughMaterial.baseTexture != null) {
  1250. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMetalRoughMaterial.baseTexture, mimeType, images, textures, imageData);
  1251. if (glTFTexture != null) {
  1252. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  1253. }
  1254. }
  1255. if (babylonPBRMetalRoughMaterial.normalTexture) {
  1256. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMetalRoughMaterial.normalTexture, mimeType, images, textures, imageData);
  1257. if (glTFTexture) {
  1258. glTFMaterial.normalTexture = glTFTexture;
  1259. }
  1260. }
  1261. if (babylonPBRMetalRoughMaterial.occlusionTexture) {
  1262. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMetalRoughMaterial.occlusionTexture, mimeType, images, textures, imageData);
  1263. if (glTFTexture) {
  1264. glTFMaterial.occlusionTexture = glTFTexture;
  1265. if (babylonPBRMetalRoughMaterial.occlusionStrength != null) {
  1266. glTFMaterial.occlusionTexture.strength = babylonPBRMetalRoughMaterial.occlusionStrength;
  1267. }
  1268. }
  1269. }
  1270. if (babylonPBRMetalRoughMaterial.emissiveTexture) {
  1271. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMetalRoughMaterial.emissiveTexture, mimeType, images, textures, imageData);
  1272. if (glTFTexture != null) {
  1273. glTFMaterial.emissiveTexture = glTFTexture;
  1274. }
  1275. }
  1276. }
  1277. if (this.FuzzyEquals(babylonPBRMetalRoughMaterial.emissiveColor, BABYLON.Color3.Black(), this._epsilon)) {
  1278. glTFMaterial.emissiveFactor = babylonPBRMetalRoughMaterial.emissiveColor.asArray();
  1279. }
  1280. if (babylonPBRMetalRoughMaterial.transparencyMode != null) {
  1281. var alphaMode = _GLTFMaterial._GetAlphaMode(babylonPBRMetalRoughMaterial);
  1282. if (alphaMode !== "OPAQUE" /* OPAQUE */) {
  1283. glTFMaterial.alphaMode = alphaMode;
  1284. if (alphaMode === "BLEND" /* BLEND */) {
  1285. glTFMaterial.alphaCutoff = babylonPBRMetalRoughMaterial.alphaCutOff;
  1286. }
  1287. }
  1288. }
  1289. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  1290. materials.push(glTFMaterial);
  1291. };
  1292. /**
  1293. * Converts an image typed array buffer to a base64 image.
  1294. * @param buffer - typed array buffer.
  1295. * @param width - width of the image.
  1296. * @param height - height of the image.
  1297. * @param mimeType - mimetype of the image.
  1298. * @returns - base64 image string.
  1299. */
  1300. _GLTFMaterial._CreateBase64FromCanvas = function (buffer, width, height, mimeType) {
  1301. var imageCanvas = document.createElement('canvas');
  1302. imageCanvas.id = "WriteCanvas";
  1303. var ctx = imageCanvas.getContext('2d');
  1304. imageCanvas.width = width;
  1305. imageCanvas.height = height;
  1306. var imgData = ctx.createImageData(width, height);
  1307. imgData.data.set(buffer);
  1308. ctx.putImageData(imgData, 0, 0);
  1309. return imageCanvas.toDataURL(mimeType);
  1310. };
  1311. /**
  1312. * Generates a white texture based on the specified width and height.
  1313. * @param width - width of the texture in pixels.
  1314. * @param height - height of the texture in pixels.
  1315. * @param scene - babylonjs scene.
  1316. * @returns - white texture.
  1317. */
  1318. _GLTFMaterial._CreateWhiteTexture = function (width, height, scene) {
  1319. var data = new Uint8Array(width * height * 4);
  1320. for (var i = 0; i < data.length; ++i) {
  1321. data[i] = 255;
  1322. }
  1323. var rawTexture = BABYLON.RawTexture.CreateRGBATexture(data, width, height, scene);
  1324. return rawTexture;
  1325. };
  1326. /**
  1327. * Resizes the two source textures to the same dimensions. If a texture is null, a default white texture is generated. If both textures are null, returns null.
  1328. * @param texture1 - first texture to resize.
  1329. * @param texture2 - second texture to resize.
  1330. * @param scene - babylonjs scene.
  1331. * @returns resized textures or null.
  1332. */
  1333. _GLTFMaterial._ResizeTexturesToSameDimensions = function (texture1, texture2, scene) {
  1334. var texture1Size = texture1 ? texture1.getSize() : { width: 0, height: 0 };
  1335. var texture2Size = texture2 ? texture2.getSize() : { width: 0, height: 0 };
  1336. var resizedTexture1;
  1337. var resizedTexture2;
  1338. if (texture1Size.width < texture2Size.width) {
  1339. if (texture1) {
  1340. resizedTexture1 = BABYLON.TextureTools.CreateResizedCopy(texture1, texture2Size.width, texture2Size.height, true);
  1341. }
  1342. else {
  1343. resizedTexture1 = this._CreateWhiteTexture(texture2Size.width, texture2Size.height, scene);
  1344. }
  1345. resizedTexture2 = texture2;
  1346. }
  1347. else if (texture1Size.width > texture2Size.width) {
  1348. if (texture2) {
  1349. resizedTexture2 = BABYLON.TextureTools.CreateResizedCopy(texture2, texture1Size.width, texture1Size.height, true);
  1350. }
  1351. else {
  1352. resizedTexture2 = this._CreateWhiteTexture(texture1Size.width, texture1Size.height, scene);
  1353. }
  1354. resizedTexture1 = texture1;
  1355. }
  1356. else {
  1357. resizedTexture1 = texture1;
  1358. resizedTexture2 = texture2;
  1359. }
  1360. return {
  1361. "texture1": resizedTexture1,
  1362. "texture2": resizedTexture2
  1363. };
  1364. };
  1365. /**
  1366. * Convert Specular Glossiness Textures to Metallic Roughness.
  1367. * See link below for info on the material conversions from PBR Metallic/Roughness and Specular/Glossiness
  1368. * @link https://github.com/KhronosGroup/glTF/blob/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness/examples/convert-between-workflows-bjs/js/babylon.pbrUtilities.js
  1369. * @param diffuseTexture - texture used to store diffuse information.
  1370. * @param specularGlossinessTexture - texture used to store specular and glossiness information.
  1371. * @param factors - specular glossiness material factors.
  1372. * @param mimeType - the mime type to use for the texture.
  1373. * @returns pbr metallic roughness interface or null.
  1374. */
  1375. _GLTFMaterial._ConvertSpecularGlossinessTexturesToMetallicRoughness = function (diffuseTexture, specularGlossinessTexture, factors, mimeType) {
  1376. if (!(diffuseTexture || specularGlossinessTexture)) {
  1377. return null;
  1378. }
  1379. var scene = diffuseTexture ? diffuseTexture.getScene() : specularGlossinessTexture.getScene();
  1380. if (!scene) {
  1381. throw new Error("_ConvertSpecularGlossinessTexturesToMetallicRoughness: Scene from textures is missing!");
  1382. }
  1383. var resizedTextures = this._ResizeTexturesToSameDimensions(diffuseTexture, specularGlossinessTexture, scene);
  1384. var diffuseSize = resizedTextures.texture1.getSize();
  1385. var diffuseBuffer;
  1386. var specularGlossinessBuffer;
  1387. var width = diffuseSize.width;
  1388. var height = diffuseSize.height;
  1389. var pixels = (resizedTextures.texture1.readPixels());
  1390. if (pixels instanceof Uint8Array) {
  1391. diffuseBuffer = (resizedTextures.texture1.readPixels());
  1392. }
  1393. else {
  1394. throw new Error("_ConvertSpecularGlossinessTexturesToMetallicRoughness: Pixel array buffer type not supported for texture: " + resizedTextures.texture1.name);
  1395. }
  1396. pixels = resizedTextures.texture2.readPixels();
  1397. if (pixels instanceof Uint8Array) {
  1398. specularGlossinessBuffer = (resizedTextures.texture2.readPixels());
  1399. }
  1400. else {
  1401. throw new Error("_ConvertSpecularGlossinessTexturesToMetallicRoughness: Pixel array buffer type not supported for texture: " + resizedTextures.texture2.name);
  1402. }
  1403. var byteLength = specularGlossinessBuffer.byteLength;
  1404. var metallicRoughnessBuffer = new Uint8Array(byteLength);
  1405. var baseColorBuffer = new Uint8Array(byteLength);
  1406. var strideSize = 4;
  1407. var maxBaseColor = BABYLON.Color3.Black();
  1408. var maxMetallic = 0;
  1409. var maxRoughness = 0;
  1410. for (var h = 0; h < height; ++h) {
  1411. for (var w = 0; w < width; ++w) {
  1412. var offset = (width * h + w) * strideSize;
  1413. var diffuseColor = BABYLON.Color3.FromInts(diffuseBuffer[offset], diffuseBuffer[offset + 1], diffuseBuffer[offset + 2]).multiply(factors.diffuseColor);
  1414. var specularColor = BABYLON.Color3.FromInts(specularGlossinessBuffer[offset], specularGlossinessBuffer[offset + 1], specularGlossinessBuffer[offset + 2]).multiply(factors.specularColor);
  1415. var glossiness = (specularGlossinessBuffer[offset + 3] / 255) * factors.glossiness;
  1416. var specularGlossiness = {
  1417. diffuseColor: diffuseColor,
  1418. specularColor: specularColor,
  1419. glossiness: glossiness
  1420. };
  1421. var metallicRoughness = this._ConvertSpecularGlossinessToMetallicRoughness(specularGlossiness);
  1422. maxBaseColor.r = Math.max(maxBaseColor.r, metallicRoughness.baseColor.r);
  1423. maxBaseColor.g = Math.max(maxBaseColor.g, metallicRoughness.baseColor.g);
  1424. maxBaseColor.b = Math.max(maxBaseColor.b, metallicRoughness.baseColor.b);
  1425. maxMetallic = Math.max(maxMetallic, metallicRoughness.metallic);
  1426. maxRoughness = Math.max(maxRoughness, metallicRoughness.roughness);
  1427. baseColorBuffer[offset] = metallicRoughness.baseColor.r * 255;
  1428. baseColorBuffer[offset + 1] = metallicRoughness.baseColor.g * 255;
  1429. baseColorBuffer[offset + 2] = metallicRoughness.baseColor.b * 255;
  1430. baseColorBuffer[offset + 3] = resizedTextures.texture1.hasAlpha ? diffuseBuffer[offset + 3] : 255;
  1431. metallicRoughnessBuffer[offset] = 255;
  1432. metallicRoughnessBuffer[offset + 1] = metallicRoughness.roughness * 255;
  1433. metallicRoughnessBuffer[offset + 2] = metallicRoughness.metallic * 255;
  1434. metallicRoughnessBuffer[offset + 3] = 255;
  1435. }
  1436. }
  1437. // Retrieves the metallic roughness factors from the maximum texture values.
  1438. var metallicRoughnessFactors = {
  1439. baseColor: maxBaseColor,
  1440. metallic: maxMetallic,
  1441. roughness: maxRoughness
  1442. };
  1443. var writeOutMetallicRoughnessTexture = false;
  1444. var writeOutBaseColorTexture = false;
  1445. for (var h = 0; h < height; ++h) {
  1446. for (var w = 0; w < width; ++w) {
  1447. var destinationOffset = (width * h + w) * strideSize;
  1448. baseColorBuffer[destinationOffset] /= metallicRoughnessFactors.baseColor.r > this._epsilon ? metallicRoughnessFactors.baseColor.r : 1;
  1449. baseColorBuffer[destinationOffset + 1] /= metallicRoughnessFactors.baseColor.g > this._epsilon ? metallicRoughnessFactors.baseColor.g : 1;
  1450. baseColorBuffer[destinationOffset + 2] /= metallicRoughnessFactors.baseColor.b > this._epsilon ? metallicRoughnessFactors.baseColor.b : 1;
  1451. var baseColorPixel = new BABYLON.Color3(baseColorBuffer[destinationOffset], baseColorBuffer[destinationOffset + 1], baseColorBuffer[destinationOffset + 2]);
  1452. if (!this.FuzzyEquals(baseColorPixel, BABYLON.Color3.White(), this._epsilon)) {
  1453. writeOutBaseColorTexture = true;
  1454. }
  1455. metallicRoughnessBuffer[destinationOffset + 1] /= metallicRoughnessFactors.roughness > this._epsilon ? metallicRoughnessFactors.roughness : 1;
  1456. metallicRoughnessBuffer[destinationOffset + 2] /= metallicRoughnessFactors.metallic > this._epsilon ? metallicRoughnessFactors.metallic : 1;
  1457. var metallicRoughnessPixel = new BABYLON.Color3(metallicRoughnessBuffer[destinationOffset], metallicRoughnessBuffer[destinationOffset + 1], metallicRoughnessBuffer[destinationOffset + 2]);
  1458. if (!this.FuzzyEquals(metallicRoughnessPixel, BABYLON.Color3.White(), this._epsilon)) {
  1459. writeOutMetallicRoughnessTexture = true;
  1460. }
  1461. }
  1462. }
  1463. if (writeOutMetallicRoughnessTexture) {
  1464. var metallicRoughnessBase64 = this._CreateBase64FromCanvas(metallicRoughnessBuffer, width, height, mimeType);
  1465. metallicRoughnessFactors.metallicRoughnessTextureBase64 = metallicRoughnessBase64;
  1466. }
  1467. if (writeOutBaseColorTexture) {
  1468. var baseColorBase64 = this._CreateBase64FromCanvas(baseColorBuffer, width, height, mimeType);
  1469. metallicRoughnessFactors.baseColorTextureBase64 = baseColorBase64;
  1470. }
  1471. return metallicRoughnessFactors;
  1472. };
  1473. /**
  1474. * Converts specular glossiness material properties to metallic roughness.
  1475. * @param specularGlossiness - interface with specular glossiness material properties.
  1476. * @returns - interface with metallic roughness material properties.
  1477. */
  1478. _GLTFMaterial._ConvertSpecularGlossinessToMetallicRoughness = function (specularGlossiness) {
  1479. var diffusePerceivedBrightness = _GLTFMaterial._GetPerceivedBrightness(specularGlossiness.diffuseColor);
  1480. var specularPerceivedBrightness = _GLTFMaterial._GetPerceivedBrightness(specularGlossiness.specularColor);
  1481. var oneMinusSpecularStrength = 1 - _GLTFMaterial._GetMaxComponent(specularGlossiness.specularColor);
  1482. var metallic = _GLTFMaterial._SolveMetallic(diffusePerceivedBrightness, specularPerceivedBrightness, oneMinusSpecularStrength);
  1483. var baseColorFromDiffuse = specularGlossiness.diffuseColor.scale(oneMinusSpecularStrength / (1.0 - this._dielectricSpecular.r) / Math.max(1 - metallic, this._epsilon));
  1484. var baseColorFromSpecular = specularGlossiness.specularColor.subtract(this._dielectricSpecular.scale(1 - metallic)).scale(1 / Math.max(metallic, this._epsilon));
  1485. var baseColor = BABYLON.Color3.Lerp(baseColorFromDiffuse, baseColorFromSpecular, metallic * metallic);
  1486. baseColor = baseColor.clampToRef(0, 1, baseColor);
  1487. var metallicRoughness = {
  1488. baseColor: baseColor,
  1489. metallic: metallic,
  1490. roughness: 1 - specularGlossiness.glossiness
  1491. };
  1492. return metallicRoughness;
  1493. };
  1494. /**
  1495. * Calculates the surface reflectance, independent of lighting conditions.
  1496. * @param color - Color source to calculate brightness from.
  1497. * @returns number representing the perceived brightness, or zero if color is undefined.
  1498. */
  1499. _GLTFMaterial._GetPerceivedBrightness = function (color) {
  1500. if (color) {
  1501. return Math.sqrt(0.299 * color.r * color.r + 0.587 * color.g * color.g + 0.114 * color.b * color.b);
  1502. }
  1503. return 0;
  1504. };
  1505. /**
  1506. * Returns the maximum color component value.
  1507. * @param color
  1508. * @returns maximum color component value, or zero if color is null or undefined.
  1509. */
  1510. _GLTFMaterial._GetMaxComponent = function (color) {
  1511. if (color) {
  1512. return Math.max(color.r, Math.max(color.g, color.b));
  1513. }
  1514. return 0;
  1515. };
  1516. /**
  1517. * Converts a Babylon PBR Metallic Roughness Material to a glTF Material.
  1518. * @param babylonPBRMaterial - BJS PBR Metallic Roughness Material.
  1519. * @param mimeType - mime type to use for the textures.
  1520. * @param images - array of glTF image interfaces.
  1521. * @param textures - array of glTF texture interfaces.
  1522. * @param materials - array of glTF material interfaces.
  1523. * @param imageData - map of image file name to data.
  1524. * @param hasTextureCoords - specifies if texture coordinates are present on the submesh to determine if textures should be applied.
  1525. */
  1526. _GLTFMaterial._ConvertPBRMaterial = function (babylonPBRMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords) {
  1527. var glTFPbrMetallicRoughness = {};
  1528. var metallicRoughness;
  1529. var glTFMaterial = {
  1530. name: babylonPBRMaterial.name
  1531. };
  1532. var useMetallicRoughness = babylonPBRMaterial.isMetallicWorkflow();
  1533. if (!useMetallicRoughness) {
  1534. var specGloss = {
  1535. diffuseColor: babylonPBRMaterial.albedoColor || BABYLON.Color3.White(),
  1536. specularColor: babylonPBRMaterial.reflectivityColor || BABYLON.Color3.White(),
  1537. glossiness: babylonPBRMaterial.microSurface || 1,
  1538. };
  1539. if (babylonPBRMaterial.reflectivityTexture && !babylonPBRMaterial.useMicroSurfaceFromReflectivityMapAlpha) {
  1540. throw new Error("_ConvertPBRMaterial: Glossiness values not included in the reflectivity texture currently not supported");
  1541. }
  1542. metallicRoughness = this._ConvertSpecularGlossinessTexturesToMetallicRoughness(babylonPBRMaterial.albedoTexture, babylonPBRMaterial.reflectivityTexture, specGloss, mimeType);
  1543. if (!metallicRoughness) {
  1544. metallicRoughness = this._ConvertSpecularGlossinessToMetallicRoughness(specGloss);
  1545. }
  1546. else {
  1547. if (hasTextureCoords) {
  1548. if (metallicRoughness.baseColorTextureBase64) {
  1549. var glTFBaseColorTexture = _GLTFMaterial._GetTextureInfoFromBase64(metallicRoughness.baseColorTextureBase64, "bjsBaseColorTexture_" + (textures.length) + ".png", mimeType, images, textures, imageData);
  1550. if (glTFBaseColorTexture != null) {
  1551. glTFPbrMetallicRoughness.baseColorTexture = glTFBaseColorTexture;
  1552. }
  1553. }
  1554. if (metallicRoughness.metallicRoughnessTextureBase64) {
  1555. var glTFMRColorTexture = _GLTFMaterial._GetTextureInfoFromBase64(metallicRoughness.metallicRoughnessTextureBase64, "bjsMetallicRoughnessTexture_" + (textures.length) + ".png", mimeType, images, textures, imageData);
  1556. if (glTFMRColorTexture != null) {
  1557. glTFPbrMetallicRoughness.metallicRoughnessTexture = glTFMRColorTexture;
  1558. }
  1559. }
  1560. }
  1561. }
  1562. }
  1563. else {
  1564. metallicRoughness = {
  1565. baseColor: babylonPBRMaterial.albedoColor,
  1566. metallic: babylonPBRMaterial.metallic,
  1567. roughness: babylonPBRMaterial.roughness
  1568. };
  1569. }
  1570. if (!(this.FuzzyEquals(metallicRoughness.baseColor, BABYLON.Color3.White(), this._epsilon) && babylonPBRMaterial.alpha >= this._epsilon)) {
  1571. glTFPbrMetallicRoughness.baseColorFactor = [
  1572. metallicRoughness.baseColor.r,
  1573. metallicRoughness.baseColor.g,
  1574. metallicRoughness.baseColor.b,
  1575. babylonPBRMaterial.alpha
  1576. ];
  1577. }
  1578. if (metallicRoughness.metallic != null && metallicRoughness.metallic !== 1) {
  1579. glTFPbrMetallicRoughness.metallicFactor = metallicRoughness.metallic;
  1580. }
  1581. if (metallicRoughness.roughness != null && metallicRoughness.roughness !== 1) {
  1582. glTFPbrMetallicRoughness.roughnessFactor = metallicRoughness.roughness;
  1583. }
  1584. if (babylonPBRMaterial.backFaceCulling != null && !babylonPBRMaterial.backFaceCulling) {
  1585. if (!babylonPBRMaterial.twoSidedLighting) {
  1586. BABYLON.Tools.Warn(babylonPBRMaterial.name + ": Back-face culling enabled and two-sided lighting disabled is not supported in glTF.");
  1587. }
  1588. glTFMaterial.doubleSided = true;
  1589. }
  1590. if (hasTextureCoords) {
  1591. if (useMetallicRoughness && babylonPBRMaterial.albedoTexture) {
  1592. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMaterial.albedoTexture, mimeType, images, textures, imageData);
  1593. if (glTFTexture) {
  1594. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  1595. }
  1596. }
  1597. if (babylonPBRMaterial.bumpTexture) {
  1598. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMaterial.bumpTexture, mimeType, images, textures, imageData);
  1599. if (glTFTexture) {
  1600. glTFMaterial.normalTexture = glTFTexture;
  1601. }
  1602. }
  1603. if (babylonPBRMaterial.ambientTexture) {
  1604. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMaterial.ambientTexture, mimeType, images, textures, imageData);
  1605. if (glTFTexture) {
  1606. var occlusionTexture = {
  1607. index: glTFTexture.index
  1608. };
  1609. glTFMaterial.occlusionTexture = occlusionTexture;
  1610. if (babylonPBRMaterial.ambientTextureStrength) {
  1611. occlusionTexture.strength = babylonPBRMaterial.ambientTextureStrength;
  1612. }
  1613. }
  1614. }
  1615. if (babylonPBRMaterial.emissiveTexture) {
  1616. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMaterial.emissiveTexture, mimeType, images, textures, imageData);
  1617. if (glTFTexture != null) {
  1618. glTFMaterial.emissiveTexture = glTFTexture;
  1619. }
  1620. }
  1621. if (babylonPBRMaterial.metallicTexture) {
  1622. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMaterial.metallicTexture, mimeType, images, textures, imageData);
  1623. if (glTFTexture != null) {
  1624. glTFPbrMetallicRoughness.metallicRoughnessTexture = glTFTexture;
  1625. }
  1626. }
  1627. }
  1628. if (!this.FuzzyEquals(babylonPBRMaterial.emissiveColor, BABYLON.Color3.Black(), this._epsilon)) {
  1629. glTFMaterial.emissiveFactor = babylonPBRMaterial.emissiveColor.asArray();
  1630. }
  1631. if (babylonPBRMaterial.transparencyMode != null) {
  1632. var alphaMode = _GLTFMaterial._GetAlphaMode(babylonPBRMaterial);
  1633. if (alphaMode !== "OPAQUE" /* OPAQUE */) {
  1634. glTFMaterial.alphaMode = alphaMode;
  1635. if (alphaMode === "BLEND" /* BLEND */) {
  1636. glTFMaterial.alphaCutoff = babylonPBRMaterial.alphaCutOff;
  1637. }
  1638. }
  1639. }
  1640. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  1641. materials.push(glTFMaterial);
  1642. };
  1643. /**
  1644. * Extracts a texture from a Babylon texture into file data and glTF data.
  1645. * @param babylonTexture - Babylon texture to extract.
  1646. * @param mimeType - Mime Type of the babylonTexture.
  1647. * @param images - Array of glTF images.
  1648. * @param textures - Array of glTF textures.
  1649. * @param imageData - map of image file name and data.
  1650. * @return - glTF texture info, or null if the texture format is not supported.
  1651. */
  1652. _GLTFMaterial._ExportTexture = function (babylonTexture, mimeType, images, textures, imageData) {
  1653. var textureName = "texture_" + (textures.length - 1).toString();
  1654. var textureData = babylonTexture.getInternalTexture();
  1655. if (textureData != null) {
  1656. textureName = textureData.url || textureName;
  1657. }
  1658. textureName = BABYLON.Tools.GetFilename(textureName);
  1659. var baseFile = textureName.split('.')[0];
  1660. var extension = "";
  1661. if (mimeType === "image/jpeg" /* JPEG */) {
  1662. extension = ".jpg";
  1663. }
  1664. else if (mimeType === "image/png" /* PNG */) {
  1665. extension = ".png";
  1666. }
  1667. else {
  1668. throw new Error("Unsupported mime type " + mimeType);
  1669. }
  1670. textureName = baseFile + extension;
  1671. var pixels = babylonTexture.readPixels();
  1672. var size = babylonTexture.getSize();
  1673. var base64Data = this._CreateBase64FromCanvas(pixels, size.width, size.height, mimeType);
  1674. return this._GetTextureInfoFromBase64(base64Data, textureName, mimeType, images, textures, imageData);
  1675. };
  1676. /**
  1677. * Builds a texture from base64 string.
  1678. * @param base64Texture - base64 texture string.
  1679. * @param textureName - Name to use for the texture.
  1680. * @param mimeType - image mime type for the texture.
  1681. * @param images - array of images.
  1682. * @param textures - array of textures.
  1683. * @param imageData - map of image data.
  1684. * @returns - glTF texture info, or null if the texture format is not supported.
  1685. */
  1686. _GLTFMaterial._GetTextureInfoFromBase64 = function (base64Texture, textureName, mimeType, images, textures, imageData) {
  1687. var textureInfo = null;
  1688. var glTFTexture = {
  1689. source: images.length
  1690. };
  1691. var binStr = atob(base64Texture.split(',')[1]);
  1692. var arr = new Uint8Array(binStr.length);
  1693. for (var i = 0; i < binStr.length; ++i) {
  1694. arr[i] = binStr.charCodeAt(i);
  1695. }
  1696. var imageValues = { data: arr, mimeType: mimeType };
  1697. imageData[textureName] = imageValues;
  1698. if (mimeType === "image/jpeg" /* JPEG */ || mimeType === "image/png" /* PNG */) {
  1699. var glTFImage = {
  1700. uri: textureName
  1701. };
  1702. var foundIndex = -1;
  1703. for (var i = 0; i < images.length; ++i) {
  1704. if (images[i].uri === textureName) {
  1705. foundIndex = i;
  1706. break;
  1707. }
  1708. }
  1709. if (foundIndex === -1) {
  1710. images.push(glTFImage);
  1711. glTFTexture.source = images.length - 1;
  1712. textures.push({
  1713. source: images.length - 1
  1714. });
  1715. textureInfo = {
  1716. index: images.length - 1
  1717. };
  1718. }
  1719. else {
  1720. glTFTexture.source = foundIndex;
  1721. textureInfo = {
  1722. index: foundIndex
  1723. };
  1724. }
  1725. }
  1726. return textureInfo;
  1727. };
  1728. /**
  1729. * Represents the dielectric specular values for R, G and B.
  1730. */
  1731. _GLTFMaterial._dielectricSpecular = new BABYLON.Color3(0.04, 0.04, 0.04);
  1732. /**
  1733. * Allows the maximum specular power to be defined for material calculations.
  1734. */
  1735. _GLTFMaterial._maxSpecularPower = 1024;
  1736. /**
  1737. * Numeric tolerance value
  1738. */
  1739. _GLTFMaterial._epsilon = 1e-6;
  1740. return _GLTFMaterial;
  1741. }());
  1742. GLTF2._GLTFMaterial = _GLTFMaterial;
  1743. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1744. })(BABYLON || (BABYLON = {}));
  1745. //# sourceMappingURL=babylon.glTFMaterial.js.map
  1746. return BABYLON;
  1747. });