babylonjs.serializers.js 83 KB

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