babylonjs.serializers.js 70 KB

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