babylonjs.serializers.js 100 KB

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