babylon.glTF2Serializer.js 91 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598
  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 && Object.keys(meshPrimitive.attributes).length > 0) {
  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/png" /* PNG */, 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. * Specifies if two colors are approximately equal in value.
  797. * @param color1 - first color to compare to.
  798. * @param color2 - second color to compare to.
  799. * @param epsilon - threshold value
  800. */
  801. _GLTFMaterial.FuzzyEquals = function (color1, color2, epsilon) {
  802. return BABYLON.Scalar.WithinEpsilon(color1.r, color2.r, epsilon) &&
  803. BABYLON.Scalar.WithinEpsilon(color1.g, color2.g, epsilon) &&
  804. BABYLON.Scalar.WithinEpsilon(color1.b, color2.b, epsilon);
  805. };
  806. /**
  807. * Gets the materials from a Babylon scene and converts them to glTF materials.
  808. * @param scene - babylonjs scene.
  809. * @param mimeType - texture mime type.
  810. * @param images - array of images.
  811. * @param textures - array of textures.
  812. * @param materials - array of materials.
  813. * @param imageData - mapping of texture names to base64 textures
  814. * @param hasTextureCoords - specifies if texture coordinates are present on the material.
  815. */
  816. _GLTFMaterial._ConvertMaterialsToGLTF = function (babylonMaterials, mimeType, images, textures, materials, imageData, hasTextureCoords) {
  817. for (var i = 0; i < babylonMaterials.length; ++i) {
  818. var babylonMaterial = babylonMaterials[i];
  819. if (babylonMaterial instanceof BABYLON.StandardMaterial) {
  820. _GLTFMaterial._ConvertStandardMaterial(babylonMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords);
  821. }
  822. else if (babylonMaterial instanceof BABYLON.PBRMetallicRoughnessMaterial) {
  823. _GLTFMaterial._ConvertPBRMetallicRoughnessMaterial(babylonMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords);
  824. }
  825. else if (babylonMaterial instanceof BABYLON.PBRMaterial) {
  826. _GLTFMaterial._ConvertPBRMaterial(babylonMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords);
  827. }
  828. else {
  829. throw new Error("Unsupported material type: " + babylonMaterial.name);
  830. }
  831. }
  832. };
  833. /**
  834. * Makes a copy of the glTF material without the texture parameters.
  835. * @param originalMaterial - original glTF material.
  836. * @returns glTF material without texture parameters
  837. */
  838. _GLTFMaterial._StripTexturesFromMaterial = function (originalMaterial) {
  839. var newMaterial = {};
  840. if (originalMaterial) {
  841. newMaterial.name = originalMaterial.name;
  842. newMaterial.doubleSided = originalMaterial.doubleSided;
  843. newMaterial.alphaMode = originalMaterial.alphaMode;
  844. newMaterial.alphaCutoff = originalMaterial.alphaCutoff;
  845. newMaterial.emissiveFactor = originalMaterial.emissiveFactor;
  846. var originalPBRMetallicRoughness = originalMaterial.pbrMetallicRoughness;
  847. if (originalPBRMetallicRoughness) {
  848. newMaterial.pbrMetallicRoughness = {};
  849. newMaterial.pbrMetallicRoughness.baseColorFactor = originalPBRMetallicRoughness.baseColorFactor;
  850. newMaterial.pbrMetallicRoughness.metallicFactor = originalPBRMetallicRoughness.metallicFactor;
  851. newMaterial.pbrMetallicRoughness.roughnessFactor = originalPBRMetallicRoughness.roughnessFactor;
  852. }
  853. }
  854. return newMaterial;
  855. };
  856. /**
  857. * Specifies if the material has any texture parameters present.
  858. * @param material - glTF Material.
  859. * @returns boolean specifying if texture parameters are present
  860. */
  861. _GLTFMaterial._HasTexturesPresent = function (material) {
  862. if (material.emissiveTexture || material.normalTexture || material.occlusionTexture) {
  863. return true;
  864. }
  865. var pbrMat = material.pbrMetallicRoughness;
  866. if (pbrMat) {
  867. if (pbrMat.baseColorTexture || pbrMat.metallicRoughnessTexture) {
  868. return true;
  869. }
  870. }
  871. return false;
  872. };
  873. /**
  874. * Converts a Babylon StandardMaterial to a glTF Metallic Roughness Material.
  875. * @param babylonStandardMaterial
  876. * @returns - glTF Metallic Roughness Material representation
  877. */
  878. _GLTFMaterial._ConvertToGLTFPBRMetallicRoughness = function (babylonStandardMaterial) {
  879. var P0 = new BABYLON.Vector2(0, 1);
  880. var P1 = new BABYLON.Vector2(0, 0.1);
  881. var P2 = new BABYLON.Vector2(0, 0.1);
  882. var P3 = new BABYLON.Vector2(1300, 0.1);
  883. /**
  884. * Given the control points, solve for x based on a given t for a cubic bezier curve.
  885. * @param t - a value between 0 and 1.
  886. * @param p0 - first control point.
  887. * @param p1 - second control point.
  888. * @param p2 - third control point.
  889. * @param p3 - fourth control point.
  890. * @returns - number result of cubic bezier curve at the specified t.
  891. */
  892. function _cubicBezierCurve(t, p0, p1, p2, p3) {
  893. return ((1 - t) * (1 - t) * (1 - t) * p0 +
  894. 3 * (1 - t) * (1 - t) * t * p1 +
  895. 3 * (1 - t) * t * t * p2 +
  896. t * t * t * p3);
  897. }
  898. /**
  899. * Evaluates a specified specular power value to determine the appropriate roughness value,
  900. * based on a pre-defined cubic bezier curve with specular on the abscissa axis (x-axis)
  901. * and roughness on the ordinant axis (y-axis).
  902. * @param specularPower - specular power of standard material.
  903. * @returns - Number representing the roughness value.
  904. */
  905. function _solveForRoughness(specularPower) {
  906. var t = Math.pow(specularPower / P3.x, 0.333333);
  907. return _cubicBezierCurve(t, P0.y, P1.y, P2.y, P3.y);
  908. }
  909. var diffuse = babylonStandardMaterial.diffuseColor.toLinearSpace().scale(0.5);
  910. var opacity = babylonStandardMaterial.alpha;
  911. var specularPower = BABYLON.Scalar.Clamp(babylonStandardMaterial.specularPower, 0, this._maxSpecularPower);
  912. var roughness = _solveForRoughness(specularPower);
  913. var glTFPbrMetallicRoughness = {
  914. baseColorFactor: [
  915. diffuse.r,
  916. diffuse.g,
  917. diffuse.b,
  918. opacity
  919. ],
  920. metallicFactor: 0,
  921. roughnessFactor: roughness,
  922. };
  923. return glTFPbrMetallicRoughness;
  924. };
  925. /**
  926. * Computes the metallic factor
  927. * @param diffuse - diffused value
  928. * @param specular - specular value
  929. * @param oneMinusSpecularStrength - one minus the specular strength
  930. * @returns - metallic value
  931. */
  932. _GLTFMaterial._SolveMetallic = function (diffuse, specular, oneMinusSpecularStrength) {
  933. if (specular < _GLTFMaterial._dielectricSpecular.r) {
  934. _GLTFMaterial._dielectricSpecular;
  935. return 0;
  936. }
  937. var a = _GLTFMaterial._dielectricSpecular.r;
  938. var b = diffuse * oneMinusSpecularStrength / (1.0 - _GLTFMaterial._dielectricSpecular.r) + specular - 2.0 * _GLTFMaterial._dielectricSpecular.r;
  939. var c = _GLTFMaterial._dielectricSpecular.r - specular;
  940. var D = b * b - 4.0 * a * c;
  941. return BABYLON.Scalar.Clamp((-b + Math.sqrt(D)) / (2.0 * a), 0, 1);
  942. };
  943. /**
  944. * Gets the glTF alpha mode from the Babylon Material
  945. * @param babylonMaterial - Babylon Material
  946. * @returns - The Babylon alpha mode value
  947. */
  948. _GLTFMaterial._GetAlphaMode = function (babylonMaterial) {
  949. if (babylonMaterial instanceof BABYLON.StandardMaterial) {
  950. var babylonStandardMaterial = babylonMaterial;
  951. if ((babylonStandardMaterial.alpha != 1.0) ||
  952. (babylonStandardMaterial.diffuseTexture != null && babylonStandardMaterial.diffuseTexture.hasAlpha) ||
  953. (babylonStandardMaterial.opacityTexture != null)) {
  954. return "BLEND" /* BLEND */;
  955. }
  956. else {
  957. return "OPAQUE" /* OPAQUE */;
  958. }
  959. }
  960. else if (babylonMaterial instanceof BABYLON.PBRMetallicRoughnessMaterial) {
  961. var babylonPBRMetallicRoughness = babylonMaterial;
  962. switch (babylonPBRMetallicRoughness.transparencyMode) {
  963. case BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE: {
  964. return "OPAQUE" /* OPAQUE */;
  965. }
  966. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND: {
  967. return "BLEND" /* BLEND */;
  968. }
  969. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST: {
  970. return "MASK" /* MASK */;
  971. }
  972. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND: {
  973. BABYLON.Tools.Warn(babylonMaterial.name + ": GLTF Exporter | Alpha test and blend mode not supported in glTF. Alpha blend used instead.");
  974. return "BLEND" /* BLEND */;
  975. }
  976. default: {
  977. throw new Error("Unsupported alpha mode " + babylonPBRMetallicRoughness.transparencyMode);
  978. }
  979. }
  980. }
  981. else if (babylonMaterial instanceof BABYLON.PBRMaterial) {
  982. var babylonPBRMaterial = babylonMaterial;
  983. switch (babylonPBRMaterial.transparencyMode) {
  984. case BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE: {
  985. return "OPAQUE" /* OPAQUE */;
  986. }
  987. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND: {
  988. return "BLEND" /* BLEND */;
  989. }
  990. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST: {
  991. return "MASK" /* MASK */;
  992. }
  993. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND: {
  994. BABYLON.Tools.Warn(babylonMaterial.name + ": GLTF Exporter | Alpha test and blend mode not supported in glTF. Alpha blend used instead.");
  995. return "BLEND" /* BLEND */;
  996. }
  997. default: {
  998. throw new Error("Unsupported alpha mode " + babylonPBRMaterial.transparencyMode);
  999. }
  1000. }
  1001. }
  1002. else {
  1003. throw new Error("Unsupported Babylon material type");
  1004. }
  1005. };
  1006. /**
  1007. * Converts a Babylon Standard Material to a glTF Material.
  1008. * @param babylonStandardMaterial - BJS Standard Material.
  1009. * @param mimeType - mime type to use for the textures.
  1010. * @param images - array of glTF image interfaces.
  1011. * @param textures - array of glTF texture interfaces.
  1012. * @param materials - array of glTF material interfaces.
  1013. * @param imageData - map of image file name to data.
  1014. * @param hasTextureCoords - specifies if texture coordinates are present on the submesh to determine if textures should be applied.
  1015. */
  1016. _GLTFMaterial._ConvertStandardMaterial = function (babylonStandardMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords) {
  1017. BABYLON.Tools.Warn(babylonStandardMaterial.name + ": Standard Material is currently not fully supported/implemented in glTF serializer");
  1018. var glTFPbrMetallicRoughness = _GLTFMaterial._ConvertToGLTFPBRMetallicRoughness(babylonStandardMaterial);
  1019. var glTFMaterial = { name: babylonStandardMaterial.name };
  1020. if (babylonStandardMaterial.backFaceCulling != null && !babylonStandardMaterial.backFaceCulling) {
  1021. if (!babylonStandardMaterial.twoSidedLighting) {
  1022. BABYLON.Tools.Warn(babylonStandardMaterial.name + ": Back-face culling enabled and two-sided lighting disabled is not supported in glTF.");
  1023. }
  1024. glTFMaterial.doubleSided = true;
  1025. }
  1026. if (hasTextureCoords) {
  1027. if (babylonStandardMaterial.diffuseTexture) {
  1028. var glTFTexture = _GLTFMaterial._ExportTexture(babylonStandardMaterial.diffuseTexture, mimeType, images, textures, imageData);
  1029. if (glTFTexture != null) {
  1030. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  1031. }
  1032. }
  1033. if (babylonStandardMaterial.bumpTexture) {
  1034. var glTFTexture = _GLTFMaterial._ExportTexture(babylonStandardMaterial.bumpTexture, mimeType, images, textures, imageData);
  1035. if (glTFTexture) {
  1036. glTFMaterial.normalTexture = glTFTexture;
  1037. }
  1038. }
  1039. if (babylonStandardMaterial.emissiveTexture) {
  1040. var glTFEmissiveTexture = _GLTFMaterial._ExportTexture(babylonStandardMaterial.emissiveTexture, mimeType, images, textures, imageData);
  1041. if (glTFEmissiveTexture) {
  1042. glTFMaterial.emissiveTexture = glTFEmissiveTexture;
  1043. }
  1044. glTFMaterial.emissiveFactor = [1.0, 1.0, 1.0];
  1045. }
  1046. if (babylonStandardMaterial.ambientTexture) {
  1047. var glTFTexture = _GLTFMaterial._ExportTexture(babylonStandardMaterial.ambientTexture, mimeType, images, textures, imageData);
  1048. if (glTFTexture) {
  1049. var occlusionTexture = {
  1050. index: glTFTexture.index
  1051. };
  1052. glTFMaterial.occlusionTexture = occlusionTexture;
  1053. occlusionTexture.strength = 1.0;
  1054. }
  1055. }
  1056. }
  1057. if (babylonStandardMaterial.alpha < 1.0 || babylonStandardMaterial.opacityTexture) {
  1058. if (babylonStandardMaterial.alphaMode === BABYLON.Engine.ALPHA_COMBINE) {
  1059. glTFMaterial.alphaMode = "BLEND" /* BLEND */;
  1060. }
  1061. else {
  1062. BABYLON.Tools.Warn(babylonStandardMaterial.name + ": glTF 2.0 does not support alpha mode: " + babylonStandardMaterial.alphaMode.toString());
  1063. }
  1064. }
  1065. if (babylonStandardMaterial.emissiveColor && !this.FuzzyEquals(babylonStandardMaterial.emissiveColor, BABYLON.Color3.Black(), this._epsilon)) {
  1066. glTFMaterial.emissiveFactor = babylonStandardMaterial.emissiveColor.asArray();
  1067. }
  1068. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  1069. materials.push(glTFMaterial);
  1070. };
  1071. /**
  1072. * Converts a Babylon PBR Metallic Roughness Material to a glTF Material.
  1073. * @param babylonPBRMetalRoughMaterial - BJS PBR Metallic Roughness Material.
  1074. * @param mimeType - mime type to use for the textures.
  1075. * @param images - array of glTF image interfaces.
  1076. * @param textures - array of glTF texture interfaces.
  1077. * @param materials - array of glTF material interfaces.
  1078. * @param imageData - map of image file name to data.
  1079. * @param hasTextureCoords - specifies if texture coordinates are present on the submesh to determine if textures should be applied.
  1080. */
  1081. _GLTFMaterial._ConvertPBRMetallicRoughnessMaterial = function (babylonPBRMetalRoughMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords) {
  1082. var glTFPbrMetallicRoughness = {};
  1083. if (babylonPBRMetalRoughMaterial.baseColor) {
  1084. glTFPbrMetallicRoughness.baseColorFactor = [
  1085. babylonPBRMetalRoughMaterial.baseColor.r,
  1086. babylonPBRMetalRoughMaterial.baseColor.g,
  1087. babylonPBRMetalRoughMaterial.baseColor.b,
  1088. babylonPBRMetalRoughMaterial.alpha
  1089. ];
  1090. }
  1091. if (babylonPBRMetalRoughMaterial.metallic != null && babylonPBRMetalRoughMaterial.metallic !== 1) {
  1092. glTFPbrMetallicRoughness.metallicFactor = babylonPBRMetalRoughMaterial.metallic;
  1093. }
  1094. if (babylonPBRMetalRoughMaterial.roughness != null && babylonPBRMetalRoughMaterial.roughness !== 1) {
  1095. glTFPbrMetallicRoughness.roughnessFactor = babylonPBRMetalRoughMaterial.roughness;
  1096. }
  1097. var glTFMaterial = {
  1098. name: babylonPBRMetalRoughMaterial.name
  1099. };
  1100. if (babylonPBRMetalRoughMaterial.doubleSided) {
  1101. glTFMaterial.doubleSided = babylonPBRMetalRoughMaterial.doubleSided;
  1102. }
  1103. if (hasTextureCoords) {
  1104. if (babylonPBRMetalRoughMaterial.baseTexture != null) {
  1105. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMetalRoughMaterial.baseTexture, mimeType, images, textures, imageData);
  1106. if (glTFTexture != null) {
  1107. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  1108. }
  1109. }
  1110. if (babylonPBRMetalRoughMaterial.normalTexture) {
  1111. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMetalRoughMaterial.normalTexture, mimeType, images, textures, imageData);
  1112. if (glTFTexture) {
  1113. glTFMaterial.normalTexture = glTFTexture;
  1114. }
  1115. }
  1116. if (babylonPBRMetalRoughMaterial.occlusionTexture) {
  1117. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMetalRoughMaterial.occlusionTexture, mimeType, images, textures, imageData);
  1118. if (glTFTexture) {
  1119. glTFMaterial.occlusionTexture = glTFTexture;
  1120. if (babylonPBRMetalRoughMaterial.occlusionStrength != null) {
  1121. glTFMaterial.occlusionTexture.strength = babylonPBRMetalRoughMaterial.occlusionStrength;
  1122. }
  1123. }
  1124. }
  1125. if (babylonPBRMetalRoughMaterial.emissiveTexture) {
  1126. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMetalRoughMaterial.emissiveTexture, mimeType, images, textures, imageData);
  1127. if (glTFTexture != null) {
  1128. glTFMaterial.emissiveTexture = glTFTexture;
  1129. }
  1130. }
  1131. }
  1132. if (this.FuzzyEquals(babylonPBRMetalRoughMaterial.emissiveColor, BABYLON.Color3.Black(), this._epsilon)) {
  1133. glTFMaterial.emissiveFactor = babylonPBRMetalRoughMaterial.emissiveColor.asArray();
  1134. }
  1135. if (babylonPBRMetalRoughMaterial.transparencyMode != null) {
  1136. var alphaMode = _GLTFMaterial._GetAlphaMode(babylonPBRMetalRoughMaterial);
  1137. if (alphaMode !== "OPAQUE" /* OPAQUE */) {
  1138. glTFMaterial.alphaMode = alphaMode;
  1139. if (alphaMode === "BLEND" /* BLEND */) {
  1140. glTFMaterial.alphaCutoff = babylonPBRMetalRoughMaterial.alphaCutOff;
  1141. }
  1142. }
  1143. }
  1144. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  1145. materials.push(glTFMaterial);
  1146. };
  1147. /**
  1148. * Converts an image typed array buffer to a base64 image.
  1149. * @param buffer - typed array buffer.
  1150. * @param width - width of the image.
  1151. * @param height - height of the image.
  1152. * @param mimeType - mimetype of the image.
  1153. * @returns - base64 image string.
  1154. */
  1155. _GLTFMaterial._CreateBase64FromCanvas = function (buffer, width, height, mimeType) {
  1156. var imageCanvas = document.createElement('canvas');
  1157. imageCanvas.id = "WriteCanvas";
  1158. var ctx = imageCanvas.getContext('2d');
  1159. imageCanvas.width = width;
  1160. imageCanvas.height = height;
  1161. var imgData = ctx.createImageData(width, height);
  1162. imgData.data.set(buffer);
  1163. ctx.putImageData(imgData, 0, 0);
  1164. return imageCanvas.toDataURL(mimeType);
  1165. };
  1166. /**
  1167. * Generates a white texture based on the specified width and height.
  1168. * @param width - width of the texture in pixels.
  1169. * @param height - height of the texture in pixels.
  1170. * @param scene - babylonjs scene.
  1171. * @returns - white texture.
  1172. */
  1173. _GLTFMaterial._CreateWhiteTexture = function (width, height, scene) {
  1174. var data = new Uint8Array(width * height * 4);
  1175. for (var i = 0; i < data.length; ++i) {
  1176. data[i] = 255;
  1177. }
  1178. var rawTexture = BABYLON.RawTexture.CreateRGBATexture(data, width, height, scene);
  1179. return rawTexture;
  1180. };
  1181. /**
  1182. * 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.
  1183. * @param texture1 - first texture to resize.
  1184. * @param texture2 - second texture to resize.
  1185. * @param scene - babylonjs scene.
  1186. * @returns resized textures or null.
  1187. */
  1188. _GLTFMaterial._ResizeTexturesToSameDimensions = function (texture1, texture2, scene) {
  1189. var texture1Size = texture1 ? texture1.getSize() : { width: 0, height: 0 };
  1190. var texture2Size = texture2 ? texture2.getSize() : { width: 0, height: 0 };
  1191. var resizedTexture1;
  1192. var resizedTexture2;
  1193. if (texture1Size.width < texture2Size.width) {
  1194. if (texture1) {
  1195. resizedTexture1 = BABYLON.TextureTools.CreateResizedCopy(texture1, texture2Size.width, texture2Size.height, true);
  1196. }
  1197. else {
  1198. resizedTexture1 = this._CreateWhiteTexture(texture2Size.width, texture2Size.height, scene);
  1199. }
  1200. resizedTexture2 = texture2;
  1201. }
  1202. else if (texture1Size.width > texture2Size.width) {
  1203. if (texture2) {
  1204. resizedTexture2 = BABYLON.TextureTools.CreateResizedCopy(texture2, texture1Size.width, texture1Size.height, true);
  1205. }
  1206. else {
  1207. resizedTexture2 = this._CreateWhiteTexture(texture1Size.width, texture1Size.height, scene);
  1208. }
  1209. resizedTexture1 = texture1;
  1210. }
  1211. else {
  1212. resizedTexture1 = texture1;
  1213. resizedTexture2 = texture2;
  1214. }
  1215. return {
  1216. "texture1": resizedTexture1,
  1217. "texture2": resizedTexture2
  1218. };
  1219. };
  1220. /**
  1221. * Convert Specular Glossiness Textures to Metallic Roughness.
  1222. * See link below for info on the material conversions from PBR Metallic/Roughness and Specular/Glossiness
  1223. * @link https://github.com/KhronosGroup/glTF/blob/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness/examples/convert-between-workflows-bjs/js/babylon.pbrUtilities.js
  1224. * @param diffuseTexture - texture used to store diffuse information.
  1225. * @param specularGlossinessTexture - texture used to store specular and glossiness information.
  1226. * @param factors - specular glossiness material factors.
  1227. * @param mimeType - the mime type to use for the texture.
  1228. * @returns pbr metallic roughness interface or null.
  1229. */
  1230. _GLTFMaterial._ConvertSpecularGlossinessTexturesToMetallicRoughness = function (diffuseTexture, specularGlossinessTexture, factors, mimeType) {
  1231. if (!(diffuseTexture || specularGlossinessTexture)) {
  1232. return null;
  1233. }
  1234. var scene = diffuseTexture ? diffuseTexture.getScene() : specularGlossinessTexture.getScene();
  1235. if (!scene) {
  1236. throw new Error("_ConvertSpecularGlossinessTexturesToMetallicRoughness: Scene from textures is missing!");
  1237. }
  1238. var resizedTextures = this._ResizeTexturesToSameDimensions(diffuseTexture, specularGlossinessTexture, scene);
  1239. var diffuseSize = resizedTextures.texture1.getSize();
  1240. var diffuseBuffer;
  1241. var specularGlossinessBuffer;
  1242. var width = diffuseSize.width;
  1243. var height = diffuseSize.height;
  1244. var pixels = (resizedTextures.texture1.readPixels());
  1245. if (pixels instanceof Uint8Array) {
  1246. diffuseBuffer = (resizedTextures.texture1.readPixels());
  1247. }
  1248. else {
  1249. throw new Error("_ConvertSpecularGlossinessTexturesToMetallicRoughness: Pixel array buffer type not supported for texture: " + resizedTextures.texture1.name);
  1250. }
  1251. pixels = resizedTextures.texture2.readPixels();
  1252. if (pixels instanceof Uint8Array) {
  1253. specularGlossinessBuffer = (resizedTextures.texture2.readPixels());
  1254. }
  1255. else {
  1256. throw new Error("_ConvertSpecularGlossinessTexturesToMetallicRoughness: Pixel array buffer type not supported for texture: " + resizedTextures.texture2.name);
  1257. }
  1258. var byteLength = specularGlossinessBuffer.byteLength;
  1259. var metallicRoughnessBuffer = new Uint8Array(byteLength);
  1260. var baseColorBuffer = new Uint8Array(byteLength);
  1261. var strideSize = 4;
  1262. var maxBaseColor = BABYLON.Color3.Black();
  1263. var maxMetallic = 0;
  1264. var maxRoughness = 0;
  1265. for (var h = 0; h < height; ++h) {
  1266. for (var w = 0; w < width; ++w) {
  1267. var offset = (width * h + w) * strideSize;
  1268. var diffuseColor = BABYLON.Color3.FromInts(diffuseBuffer[offset], diffuseBuffer[offset + 1], diffuseBuffer[offset + 2]).multiply(factors.diffuseColor);
  1269. var specularColor = BABYLON.Color3.FromInts(specularGlossinessBuffer[offset], specularGlossinessBuffer[offset + 1], specularGlossinessBuffer[offset + 2]).multiply(factors.specularColor);
  1270. var glossiness = (specularGlossinessBuffer[offset + 3] / 255) * factors.glossiness;
  1271. var specularGlossiness = {
  1272. diffuseColor: diffuseColor,
  1273. specularColor: specularColor,
  1274. glossiness: glossiness
  1275. };
  1276. var metallicRoughness = this._ConvertSpecularGlossinessToMetallicRoughness(specularGlossiness);
  1277. maxBaseColor.r = Math.max(maxBaseColor.r, metallicRoughness.baseColor.r);
  1278. maxBaseColor.g = Math.max(maxBaseColor.g, metallicRoughness.baseColor.g);
  1279. maxBaseColor.b = Math.max(maxBaseColor.b, metallicRoughness.baseColor.b);
  1280. maxMetallic = Math.max(maxMetallic, metallicRoughness.metallic);
  1281. maxRoughness = Math.max(maxRoughness, metallicRoughness.roughness);
  1282. baseColorBuffer[offset] = metallicRoughness.baseColor.r * 255;
  1283. baseColorBuffer[offset + 1] = metallicRoughness.baseColor.g * 255;
  1284. baseColorBuffer[offset + 2] = metallicRoughness.baseColor.b * 255;
  1285. baseColorBuffer[offset + 3] = resizedTextures.texture1.hasAlpha ? diffuseBuffer[offset + 3] : 255;
  1286. metallicRoughnessBuffer[offset] = 255;
  1287. metallicRoughnessBuffer[offset + 1] = metallicRoughness.roughness * 255;
  1288. metallicRoughnessBuffer[offset + 2] = metallicRoughness.metallic * 255;
  1289. metallicRoughnessBuffer[offset + 3] = 255;
  1290. }
  1291. }
  1292. // Retrieves the metallic roughness factors from the maximum texture values.
  1293. var metallicRoughnessFactors = {
  1294. baseColor: maxBaseColor,
  1295. metallic: maxMetallic,
  1296. roughness: maxRoughness
  1297. };
  1298. var writeOutMetallicRoughnessTexture = false;
  1299. var writeOutBaseColorTexture = false;
  1300. for (var h = 0; h < height; ++h) {
  1301. for (var w = 0; w < width; ++w) {
  1302. var destinationOffset = (width * h + w) * strideSize;
  1303. baseColorBuffer[destinationOffset] /= metallicRoughnessFactors.baseColor.r > this._epsilon ? metallicRoughnessFactors.baseColor.r : 1;
  1304. baseColorBuffer[destinationOffset + 1] /= metallicRoughnessFactors.baseColor.g > this._epsilon ? metallicRoughnessFactors.baseColor.g : 1;
  1305. baseColorBuffer[destinationOffset + 2] /= metallicRoughnessFactors.baseColor.b > this._epsilon ? metallicRoughnessFactors.baseColor.b : 1;
  1306. var baseColorPixel = BABYLON.Color3.FromArray([baseColorBuffer[destinationOffset], baseColorBuffer[destinationOffset + 1], baseColorBuffer[destinationOffset + 2]]);
  1307. if (!this.FuzzyEquals(baseColorPixel, BABYLON.Color3.White(), this._epsilon)) {
  1308. writeOutBaseColorTexture = true;
  1309. }
  1310. metallicRoughnessBuffer[destinationOffset + 1] /= metallicRoughnessFactors.roughness > this._epsilon ? metallicRoughnessFactors.roughness : 1;
  1311. metallicRoughnessBuffer[destinationOffset + 2] /= metallicRoughnessFactors.metallic > this._epsilon ? metallicRoughnessFactors.metallic : 1;
  1312. var metallicRoughnessPixel = BABYLON.Color3.FromArray([metallicRoughnessBuffer[destinationOffset], metallicRoughnessBuffer[destinationOffset + 1], metallicRoughnessBuffer[destinationOffset + 2]]);
  1313. if (!this.FuzzyEquals(metallicRoughnessPixel, BABYLON.Color3.White(), this._epsilon)) {
  1314. writeOutMetallicRoughnessTexture = true;
  1315. }
  1316. }
  1317. }
  1318. if (writeOutMetallicRoughnessTexture) {
  1319. var metallicRoughnessBase64 = this._CreateBase64FromCanvas(metallicRoughnessBuffer, width, height, mimeType);
  1320. metallicRoughnessFactors.metallicRoughnessTextureBase64 = metallicRoughnessBase64;
  1321. }
  1322. if (writeOutBaseColorTexture) {
  1323. var baseColorBase64 = this._CreateBase64FromCanvas(baseColorBuffer, width, height, mimeType);
  1324. metallicRoughnessFactors.baseColorTextureBase64 = baseColorBase64;
  1325. }
  1326. return metallicRoughnessFactors;
  1327. };
  1328. /**
  1329. * Converts specular glossiness material properties to metallic roughness.
  1330. * @param specularGlossiness - interface with specular glossiness material properties.
  1331. * @returns - interface with metallic roughness material properties.
  1332. */
  1333. _GLTFMaterial._ConvertSpecularGlossinessToMetallicRoughness = function (specularGlossiness) {
  1334. var diffusePerceivedBrightness = _GLTFMaterial._GetPerceivedBrightness(specularGlossiness.diffuseColor);
  1335. var specularPerceivedBrightness = _GLTFMaterial._GetPerceivedBrightness(specularGlossiness.specularColor);
  1336. var oneMinusSpecularStrength = 1 - _GLTFMaterial._GetMaxComponent(specularGlossiness.specularColor);
  1337. var metallic = _GLTFMaterial._SolveMetallic(diffusePerceivedBrightness, specularPerceivedBrightness, oneMinusSpecularStrength);
  1338. var baseColorFromDiffuse = specularGlossiness.diffuseColor.scale(oneMinusSpecularStrength / (1.0 - this._dielectricSpecular.r) / Math.max(1 - metallic, this._epsilon));
  1339. var baseColorFromSpecular = specularGlossiness.specularColor.subtract(this._dielectricSpecular.scale(1 - metallic)).scale(1 / Math.max(metallic, this._epsilon));
  1340. var baseColor = BABYLON.Color3.Lerp(baseColorFromDiffuse, baseColorFromSpecular, metallic * metallic);
  1341. baseColor = baseColor.clampToRef(0, 1, baseColor);
  1342. var metallicRoughness = {
  1343. baseColor: baseColor,
  1344. metallic: metallic,
  1345. roughness: 1 - specularGlossiness.glossiness
  1346. };
  1347. return metallicRoughness;
  1348. };
  1349. /**
  1350. * Calculates the surface reflectance, independent of lighting conditions.
  1351. * @param color - Color source to calculate brightness from.
  1352. * @returns number representing the perceived brightness, or zero if color is undefined.
  1353. */
  1354. _GLTFMaterial._GetPerceivedBrightness = function (color) {
  1355. if (color) {
  1356. return Math.sqrt(0.299 * color.r * color.r + 0.587 * color.g * color.g + 0.114 * color.b * color.b);
  1357. }
  1358. return 0;
  1359. };
  1360. /**
  1361. * Returns the maximum color component value.
  1362. * @param color
  1363. * @returns maximum color component value, or zero if color is null or undefined.
  1364. */
  1365. _GLTFMaterial._GetMaxComponent = function (color) {
  1366. if (color) {
  1367. return Math.max(color.r, Math.max(color.g, color.b));
  1368. }
  1369. return 0;
  1370. };
  1371. /**
  1372. * Converts a Babylon PBR Metallic Roughness Material to a glTF Material.
  1373. * @param babylonPBRMaterial - BJS PBR Metallic Roughness Material.
  1374. * @param mimeType - mime type to use for the textures.
  1375. * @param images - array of glTF image interfaces.
  1376. * @param textures - array of glTF texture interfaces.
  1377. * @param materials - array of glTF material interfaces.
  1378. * @param imageData - map of image file name to data.
  1379. * @param hasTextureCoords - specifies if texture coordinates are present on the submesh to determine if textures should be applied.
  1380. */
  1381. _GLTFMaterial._ConvertPBRMaterial = function (babylonPBRMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords) {
  1382. var glTFPbrMetallicRoughness = {};
  1383. var metallicRoughness;
  1384. var glTFMaterial = {
  1385. name: babylonPBRMaterial.name
  1386. };
  1387. var useMetallicRoughness = babylonPBRMaterial.isMetallicWorkflow();
  1388. if (!useMetallicRoughness) {
  1389. var specGloss = {
  1390. diffuseColor: babylonPBRMaterial.albedoColor || BABYLON.Color3.White(),
  1391. specularColor: babylonPBRMaterial.reflectivityColor || BABYLON.Color3.White(),
  1392. glossiness: babylonPBRMaterial.microSurface || 1,
  1393. };
  1394. if (babylonPBRMaterial.reflectivityTexture && !babylonPBRMaterial.useMicroSurfaceFromReflectivityMapAlpha) {
  1395. throw new Error("_ConvertPBRMaterial: Glossiness values not included in the reflectivity texture currently not supported");
  1396. }
  1397. metallicRoughness = this._ConvertSpecularGlossinessTexturesToMetallicRoughness(babylonPBRMaterial.albedoTexture, babylonPBRMaterial.reflectivityTexture, specGloss, mimeType);
  1398. if (!metallicRoughness) {
  1399. metallicRoughness = this._ConvertSpecularGlossinessToMetallicRoughness(specGloss);
  1400. }
  1401. else {
  1402. if (metallicRoughness.baseColorTextureBase64) {
  1403. var glTFBaseColorTexture = _GLTFMaterial._GetTextureInfoFromBase64(metallicRoughness.baseColorTextureBase64, "bjsBaseColorTexture_" + (textures.length) + ".png", mimeType, images, textures, imageData);
  1404. if (glTFBaseColorTexture != null) {
  1405. glTFPbrMetallicRoughness.baseColorTexture = glTFBaseColorTexture;
  1406. }
  1407. }
  1408. if (metallicRoughness.metallicRoughnessTextureBase64) {
  1409. var glTFMRColorTexture = _GLTFMaterial._GetTextureInfoFromBase64(metallicRoughness.metallicRoughnessTextureBase64, "bjsMetallicRoughnessTexture_" + (textures.length) + ".png", mimeType, images, textures, imageData);
  1410. if (glTFMRColorTexture != null) {
  1411. glTFPbrMetallicRoughness.metallicRoughnessTexture = glTFMRColorTexture;
  1412. }
  1413. }
  1414. }
  1415. }
  1416. if (!(this.FuzzyEquals(babylonPBRMaterial.albedoColor, BABYLON.Color3.White(), this._epsilon) && babylonPBRMaterial.alpha >= this._epsilon)) {
  1417. glTFPbrMetallicRoughness.baseColorFactor = [
  1418. babylonPBRMaterial.albedoColor.r,
  1419. babylonPBRMaterial.albedoColor.g,
  1420. babylonPBRMaterial.albedoColor.b,
  1421. babylonPBRMaterial.alpha
  1422. ];
  1423. }
  1424. if (babylonPBRMaterial.metallic != null && babylonPBRMaterial.metallic !== 1) {
  1425. glTFPbrMetallicRoughness.metallicFactor = babylonPBRMaterial.metallic;
  1426. }
  1427. if (babylonPBRMaterial.roughness != null && babylonPBRMaterial.roughness !== 1) {
  1428. glTFPbrMetallicRoughness.roughnessFactor = babylonPBRMaterial.roughness;
  1429. }
  1430. if (babylonPBRMaterial.backFaceCulling != null && !babylonPBRMaterial.backFaceCulling) {
  1431. if (!babylonPBRMaterial.twoSidedLighting) {
  1432. BABYLON.Tools.Warn(babylonPBRMaterial.name + ": Back-face culling enabled and two-sided lighting disabled is not supported in glTF.");
  1433. }
  1434. glTFMaterial.doubleSided = true;
  1435. }
  1436. if (hasTextureCoords) {
  1437. if (useMetallicRoughness && babylonPBRMaterial.albedoTexture) {
  1438. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMaterial.albedoTexture, mimeType, images, textures, imageData);
  1439. if (glTFTexture) {
  1440. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  1441. }
  1442. }
  1443. if (babylonPBRMaterial.bumpTexture) {
  1444. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMaterial.bumpTexture, mimeType, images, textures, imageData);
  1445. if (glTFTexture) {
  1446. glTFMaterial.normalTexture = glTFTexture;
  1447. }
  1448. }
  1449. if (babylonPBRMaterial.ambientTexture) {
  1450. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMaterial.ambientTexture, mimeType, images, textures, imageData);
  1451. if (glTFTexture) {
  1452. var occlusionTexture = {
  1453. index: glTFTexture.index
  1454. };
  1455. glTFMaterial.occlusionTexture = occlusionTexture;
  1456. if (babylonPBRMaterial.ambientTextureStrength) {
  1457. occlusionTexture.strength = babylonPBRMaterial.ambientTextureStrength;
  1458. }
  1459. }
  1460. }
  1461. if (babylonPBRMaterial.emissiveTexture) {
  1462. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMaterial.emissiveTexture, mimeType, images, textures, imageData);
  1463. if (glTFTexture != null) {
  1464. glTFMaterial.emissiveTexture = glTFTexture;
  1465. }
  1466. }
  1467. if (babylonPBRMaterial.metallicTexture) {
  1468. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMaterial.metallicTexture, mimeType, images, textures, imageData);
  1469. if (glTFTexture != null) {
  1470. glTFPbrMetallicRoughness.metallicRoughnessTexture = glTFTexture;
  1471. }
  1472. }
  1473. }
  1474. if (!this.FuzzyEquals(babylonPBRMaterial.emissiveColor, BABYLON.Color3.Black(), this._epsilon)) {
  1475. glTFMaterial.emissiveFactor = babylonPBRMaterial.emissiveColor.asArray();
  1476. }
  1477. if (babylonPBRMaterial.transparencyMode != null) {
  1478. var alphaMode = _GLTFMaterial._GetAlphaMode(babylonPBRMaterial);
  1479. if (alphaMode !== "OPAQUE" /* OPAQUE */) {
  1480. glTFMaterial.alphaMode = alphaMode;
  1481. if (alphaMode === "BLEND" /* BLEND */) {
  1482. glTFMaterial.alphaCutoff = babylonPBRMaterial.alphaCutOff;
  1483. }
  1484. }
  1485. }
  1486. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  1487. materials.push(glTFMaterial);
  1488. };
  1489. /**
  1490. * Extracts a texture from a Babylon texture into file data and glTF data.
  1491. * @param babylonTexture - Babylon texture to extract.
  1492. * @param mimeType - Mime Type of the babylonTexture.
  1493. * @param images - Array of glTF images.
  1494. * @param textures - Array of glTF textures.
  1495. * @param imageData - map of image file name and data.
  1496. * @return - glTF texture info, or null if the texture format is not supported.
  1497. */
  1498. _GLTFMaterial._ExportTexture = function (babylonTexture, mimeType, images, textures, imageData) {
  1499. var textureName = "texture_" + (textures.length - 1).toString();
  1500. var textureData = babylonTexture.getInternalTexture();
  1501. if (textureData != null) {
  1502. textureName = textureData.url || textureName;
  1503. }
  1504. textureName = BABYLON.Tools.GetFilename(textureName);
  1505. var baseFile = textureName.split('.')[0];
  1506. var extension = "";
  1507. if (mimeType === "image/jpeg" /* JPEG */) {
  1508. extension = ".jpg";
  1509. }
  1510. else if (mimeType === "image/png" /* PNG */) {
  1511. extension = ".png";
  1512. }
  1513. else {
  1514. throw new Error("Unsupported mime type " + mimeType);
  1515. }
  1516. textureName = baseFile + extension;
  1517. var pixels = babylonTexture.readPixels();
  1518. var size = babylonTexture.getSize();
  1519. var base64Data = this._CreateBase64FromCanvas(pixels, size.width, size.height, mimeType);
  1520. return this._GetTextureInfoFromBase64(base64Data, textureName, mimeType, images, textures, imageData);
  1521. };
  1522. /**
  1523. * Builds a texture from base64 string.
  1524. * @param base64Texture - base64 texture string.
  1525. * @param textureName - Name to use for the texture.
  1526. * @param mimeType - image mime type for the texture.
  1527. * @param images - array of images.
  1528. * @param textures - array of textures.
  1529. * @param imageData - map of image data.
  1530. * @returns - glTF texture info, or null if the texture format is not supported.
  1531. */
  1532. _GLTFMaterial._GetTextureInfoFromBase64 = function (base64Texture, textureName, mimeType, images, textures, imageData) {
  1533. var textureInfo = null;
  1534. var glTFTexture = {
  1535. source: images.length
  1536. };
  1537. var binStr = atob(base64Texture.split(',')[1]);
  1538. var arr = new Uint8Array(binStr.length);
  1539. for (var i = 0; i < binStr.length; ++i) {
  1540. arr[i] = binStr.charCodeAt(i);
  1541. }
  1542. var imageValues = { data: arr, mimeType: mimeType };
  1543. imageData[textureName] = imageValues;
  1544. if (mimeType === "image/jpeg" /* JPEG */ || mimeType === "image/png" /* PNG */) {
  1545. var glTFImage = {
  1546. uri: textureName
  1547. };
  1548. var foundIndex = -1;
  1549. for (var i = 0; i < images.length; ++i) {
  1550. if (images[i].uri === textureName) {
  1551. foundIndex = i;
  1552. break;
  1553. }
  1554. }
  1555. if (foundIndex === -1) {
  1556. images.push(glTFImage);
  1557. glTFTexture.source = images.length - 1;
  1558. textures.push({
  1559. source: images.length - 1
  1560. });
  1561. textureInfo = {
  1562. index: images.length - 1
  1563. };
  1564. }
  1565. else {
  1566. glTFTexture.source = foundIndex;
  1567. textureInfo = {
  1568. index: foundIndex
  1569. };
  1570. }
  1571. }
  1572. return textureInfo;
  1573. };
  1574. /**
  1575. * Represents the dielectric specular values for R, G and B.
  1576. */
  1577. _GLTFMaterial._dielectricSpecular = new BABYLON.Color3(0.04, 0.04, 0.04);
  1578. /**
  1579. * Allows the maximum specular power to be defined for material calculations.
  1580. */
  1581. _GLTFMaterial._maxSpecularPower = 1024;
  1582. /**
  1583. * Numeric tolerance value
  1584. */
  1585. _GLTFMaterial._epsilon = 1e-6;
  1586. return _GLTFMaterial;
  1587. }());
  1588. GLTF2._GLTFMaterial = _GLTFMaterial;
  1589. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1590. })(BABYLON || (BABYLON = {}));
  1591. //# sourceMappingURL=babylon.glTFMaterial.js.map