babylonjs.serializers.js 100 KB

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