babylon.glTF2Serializer.js 94 KB

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