babylon.glTF2Serializer.js 76 KB

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