babylon.glTF2Serializer.js 131 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380
  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. BABYLON.Tools.Error("glTF Serializer: Scene is not ready!");
  27. return null;
  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. BABYLON.Tools.Error("glTF Serializer: Scene is not ready!");
  45. return null;
  46. }
  47. };
  48. return GLTF2Export;
  49. }());
  50. BABYLON.GLTF2Export = GLTF2Export;
  51. })(BABYLON || (BABYLON = {}));
  52. //# sourceMappingURL=babylon.glTFSerializer.js.map
  53. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  54. /**
  55. * Module for the Babylon glTF 2.0 exporter. Should ONLY be used internally
  56. * @hidden
  57. */
  58. var BABYLON;
  59. (function (BABYLON) {
  60. var GLTF2;
  61. (function (GLTF2) {
  62. /**
  63. * Utility interface for storing vertex attribute data
  64. * @hidden
  65. */
  66. /**
  67. * Converts Babylon Scene into glTF 2.0.
  68. * @hidden
  69. */
  70. var _Exporter = /** @class */ (function () {
  71. /**
  72. * Creates a glTF Exporter instance, which can accept optional exporter options
  73. * @param babylonScene Babylon scene object
  74. * @param options Options to modify the behavior of the exporter
  75. */
  76. function _Exporter(babylonScene, options) {
  77. this.asset = { generator: "BabylonJS", version: "2.0" };
  78. this.babylonScene = babylonScene;
  79. this.bufferViews = [];
  80. this.accessors = [];
  81. this.meshes = [];
  82. this.scenes = [];
  83. this.nodes = [];
  84. this.images = [];
  85. this.materials = [];
  86. this.textures = [];
  87. this.animations = [];
  88. this.imageData = {};
  89. this.convertToRightHandedSystem = this.babylonScene.useRightHandedSystem ? false : true;
  90. var _options = options || {};
  91. this.shouldExportMesh = _options.shouldExportMesh ? _options.shouldExportMesh : (function (mesh) { return true; });
  92. this.animationSampleRate = _options.animationSampleRate ? _options.animationSampleRate : 1 / 60;
  93. }
  94. /**
  95. * Writes mesh attribute data to a data buffer
  96. * Returns the bytelength of the data
  97. * @param vertexBufferKind Indicates what kind of vertex data is being passed in
  98. * @param meshAttributeArray Array containing the attribute data
  99. * @param binaryWriter The buffer to write the binary data to
  100. * @returns Byte length of the attribute data
  101. */
  102. _Exporter.prototype.writeAttributeData = function (vertexBufferKind, meshAttributeArray, binaryWriter) {
  103. var stride = BABYLON.VertexBuffer.DeduceStride(vertexBufferKind);
  104. var byteLength = 0;
  105. var vector;
  106. var index;
  107. for (var k = 0, length_1 = meshAttributeArray.length / stride; k < length_1; ++k) {
  108. index = k * stride;
  109. if (vertexBufferKind === BABYLON.VertexBuffer.PositionKind || vertexBufferKind === BABYLON.VertexBuffer.NormalKind) {
  110. var vertexData = BABYLON.Vector3.FromArray(meshAttributeArray, index);
  111. if (this.convertToRightHandedSystem) {
  112. GLTF2._GLTFUtilities.GetRightHandedVector3FromRef(vertexData);
  113. }
  114. vector = vertexData.asArray();
  115. }
  116. else if (vertexBufferKind === BABYLON.VertexBuffer.TangentKind || vertexBufferKind === BABYLON.VertexBuffer.ColorKind) {
  117. var vertexData = BABYLON.Vector4.FromArray(meshAttributeArray, index);
  118. if (this.convertToRightHandedSystem && !(vertexBufferKind === BABYLON.VertexBuffer.ColorKind)) {
  119. GLTF2._GLTFUtilities.GetRightHandedVector4FromRef(vertexData);
  120. }
  121. vector = vertexData.asArray();
  122. }
  123. else if (vertexBufferKind === BABYLON.VertexBuffer.UVKind || vertexBufferKind === BABYLON.VertexBuffer.UV2Kind) {
  124. vector = this.convertToRightHandedSystem ? [meshAttributeArray[index], meshAttributeArray[index + 1]] : [meshAttributeArray[index], meshAttributeArray[index + 1]];
  125. }
  126. else {
  127. BABYLON.Tools.Warn("Unsupported Vertex Buffer Type: " + vertexBufferKind);
  128. vector = [];
  129. }
  130. vector.forEach(function (entry) {
  131. binaryWriter.setFloat32(entry);
  132. });
  133. }
  134. byteLength = meshAttributeArray.length * 4;
  135. return byteLength;
  136. };
  137. /**
  138. * Generates glTF json data
  139. * @param shouldUseGlb Indicates whether the json should be written for a glb file
  140. * @param glTFPrefix Text to use when prefixing a glTF file
  141. * @param prettyPrint Indicates whether the json file should be pretty printed (true) or not (false)
  142. * @returns json data as string
  143. */
  144. _Exporter.prototype.generateJSON = function (shouldUseGlb, glTFPrefix, prettyPrint) {
  145. var buffer = { byteLength: this.totalByteLength };
  146. var imageName;
  147. var imageData;
  148. var bufferView;
  149. var byteOffset = this.totalByteLength;
  150. var glTF = {
  151. asset: this.asset
  152. };
  153. if (buffer.byteLength) {
  154. glTF.buffers = [buffer];
  155. }
  156. if (this.nodes && this.nodes.length) {
  157. glTF.nodes = this.nodes;
  158. }
  159. if (this.meshes && this.meshes.length) {
  160. glTF.meshes = this.meshes;
  161. }
  162. if (this.scenes && this.scenes.length) {
  163. glTF.scenes = this.scenes;
  164. glTF.scene = 0;
  165. }
  166. if (this.bufferViews && this.bufferViews.length) {
  167. glTF.bufferViews = this.bufferViews;
  168. }
  169. if (this.accessors && this.accessors.length) {
  170. glTF.accessors = this.accessors;
  171. }
  172. if (this.animations && this.animations.length) {
  173. glTF.animations = this.animations;
  174. }
  175. if (this.materials && this.materials.length) {
  176. glTF.materials = this.materials;
  177. }
  178. if (this.textures && this.textures.length) {
  179. glTF.textures = this.textures;
  180. }
  181. if (this.images && this.images.length) {
  182. if (!shouldUseGlb) {
  183. glTF.images = this.images;
  184. }
  185. else {
  186. glTF.images = [];
  187. var self_1 = this;
  188. this.images.forEach(function (image) {
  189. if (image.uri) {
  190. imageData = self_1.imageData[image.uri];
  191. imageName = image.uri.split('.')[0] + " image";
  192. bufferView = GLTF2._GLTFUtilities.CreateBufferView(0, byteOffset, imageData.data.length, undefined, imageName);
  193. byteOffset += imageData.data.buffer.byteLength;
  194. self_1.bufferViews.push(bufferView);
  195. image.bufferView = self_1.bufferViews.length - 1;
  196. image.name = imageName;
  197. image.mimeType = imageData.mimeType;
  198. image.uri = undefined;
  199. if (!glTF.images) {
  200. glTF.images = [];
  201. }
  202. glTF.images.push(image);
  203. }
  204. });
  205. // Replace uri with bufferview and mime type for glb
  206. buffer.byteLength = byteOffset;
  207. }
  208. }
  209. if (!shouldUseGlb) {
  210. buffer.uri = glTFPrefix + ".bin";
  211. }
  212. var jsonText = prettyPrint ? JSON.stringify(glTF, null, 2) : JSON.stringify(glTF);
  213. return jsonText;
  214. };
  215. /**
  216. * Generates data for .gltf and .bin files based on the glTF prefix string
  217. * @param glTFPrefix Text to use when prefixing a glTF file
  218. * @returns GLTFData with glTF file data
  219. */
  220. _Exporter.prototype._generateGLTF = function (glTFPrefix) {
  221. var binaryBuffer = this.generateBinary();
  222. var jsonText = this.generateJSON(false, glTFPrefix, true);
  223. var bin = new Blob([binaryBuffer], { type: 'application/octet-stream' });
  224. var glTFFileName = glTFPrefix + '.gltf';
  225. var glTFBinFile = glTFPrefix + '.bin';
  226. var container = new BABYLON.GLTFData();
  227. container.glTFFiles[glTFFileName] = jsonText;
  228. container.glTFFiles[glTFBinFile] = bin;
  229. if (this.imageData) {
  230. for (var image in this.imageData) {
  231. container.glTFFiles[image] = new Blob([this.imageData[image].data], { type: this.imageData[image].mimeType });
  232. }
  233. }
  234. return container;
  235. };
  236. /**
  237. * Creates a binary buffer for glTF
  238. * @returns array buffer for binary data
  239. */
  240. _Exporter.prototype.generateBinary = function () {
  241. var binaryWriter = new _BinaryWriter(4);
  242. this.createScene(this.babylonScene, binaryWriter);
  243. return binaryWriter.getArrayBuffer();
  244. };
  245. /**
  246. * Pads the number to a multiple of 4
  247. * @param num number to pad
  248. * @returns padded number
  249. */
  250. _Exporter.prototype._getPadding = function (num) {
  251. var remainder = num % 4;
  252. var padding = remainder === 0 ? remainder : 4 - remainder;
  253. return padding;
  254. };
  255. /**
  256. * Generates a glb file from the json and binary data
  257. * Returns an object with the glb file name as the key and data as the value
  258. * @param glTFPrefix
  259. * @returns object with glb filename as key and data as value
  260. */
  261. _Exporter.prototype._generateGLB = function (glTFPrefix) {
  262. var binaryBuffer = this.generateBinary();
  263. var jsonText = this.generateJSON(true);
  264. var glbFileName = glTFPrefix + '.glb';
  265. var headerLength = 12;
  266. var chunkLengthPrefix = 8;
  267. var jsonLength = jsonText.length;
  268. var imageByteLength = 0;
  269. for (var key in this.imageData) {
  270. imageByteLength += this.imageData[key].data.byteLength;
  271. }
  272. var jsonPadding = this._getPadding(jsonLength);
  273. var binPadding = this._getPadding(binaryBuffer.byteLength);
  274. var imagePadding = this._getPadding(imageByteLength);
  275. var byteLength = headerLength + (2 * chunkLengthPrefix) + jsonLength + jsonPadding + binaryBuffer.byteLength + binPadding + imageByteLength + imagePadding;
  276. //header
  277. var headerBuffer = new ArrayBuffer(headerLength);
  278. var headerBufferView = new DataView(headerBuffer);
  279. headerBufferView.setUint32(0, 0x46546C67, true); //glTF
  280. headerBufferView.setUint32(4, 2, true); // version
  281. headerBufferView.setUint32(8, byteLength, true); // total bytes in file
  282. //json chunk
  283. var jsonChunkBuffer = new ArrayBuffer(chunkLengthPrefix + jsonLength + jsonPadding);
  284. var jsonChunkBufferView = new DataView(jsonChunkBuffer);
  285. jsonChunkBufferView.setUint32(0, jsonLength + jsonPadding, true);
  286. jsonChunkBufferView.setUint32(4, 0x4E4F534A, true);
  287. //json chunk bytes
  288. var jsonData = new Uint8Array(jsonChunkBuffer, chunkLengthPrefix);
  289. for (var i = 0; i < jsonLength; ++i) {
  290. jsonData[i] = jsonText.charCodeAt(i);
  291. }
  292. //json padding
  293. var jsonPaddingView = new Uint8Array(jsonChunkBuffer, chunkLengthPrefix + jsonLength);
  294. for (var i = 0; i < jsonPadding; ++i) {
  295. jsonPaddingView[i] = 0x20;
  296. }
  297. //binary chunk
  298. var binaryChunkBuffer = new ArrayBuffer(chunkLengthPrefix);
  299. var binaryChunkBufferView = new DataView(binaryChunkBuffer);
  300. binaryChunkBufferView.setUint32(0, binaryBuffer.byteLength + imageByteLength + imagePadding, true);
  301. binaryChunkBufferView.setUint32(4, 0x004E4942, true);
  302. // binary padding
  303. var binPaddingBuffer = new ArrayBuffer(binPadding);
  304. var binPaddingView = new Uint8Array(binPaddingBuffer);
  305. for (var i = 0; i < binPadding; ++i) {
  306. binPaddingView[i] = 0;
  307. }
  308. var imagePaddingBuffer = new ArrayBuffer(imagePadding);
  309. var imagePaddingView = new Uint8Array(imagePaddingBuffer);
  310. for (var i = 0; i < imagePadding; ++i) {
  311. imagePaddingView[i] = 0;
  312. }
  313. var glbData = [headerBuffer, jsonChunkBuffer, binaryChunkBuffer, binaryBuffer];
  314. // binary data
  315. for (var key in this.imageData) {
  316. glbData.push(this.imageData[key].data.buffer);
  317. }
  318. glbData.push(binPaddingBuffer);
  319. glbData.push(imagePaddingBuffer);
  320. var glbFile = new Blob(glbData, { type: 'application/octet-stream' });
  321. var container = new BABYLON.GLTFData();
  322. container.glTFFiles[glbFileName] = glbFile;
  323. return container;
  324. };
  325. /**
  326. * Sets the TRS for each node
  327. * @param node glTF Node for storing the transformation data
  328. * @param babylonMesh Babylon mesh used as the source for the transformation data
  329. */
  330. _Exporter.prototype.setNodeTransformation = function (node, babylonMesh) {
  331. if (!babylonMesh.position.equalsToFloats(0, 0, 0)) {
  332. node.translation = this.convertToRightHandedSystem ? GLTF2._GLTFUtilities.GetRightHandedVector3(babylonMesh.position).asArray() : babylonMesh.position.asArray();
  333. }
  334. if (!babylonMesh.scaling.equalsToFloats(1, 1, 1)) {
  335. node.scale = babylonMesh.scaling.asArray();
  336. }
  337. var rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(babylonMesh.rotation.y, babylonMesh.rotation.x, babylonMesh.rotation.z);
  338. if (babylonMesh.rotationQuaternion) {
  339. rotationQuaternion = rotationQuaternion.multiply(babylonMesh.rotationQuaternion);
  340. }
  341. if (!(rotationQuaternion.x === 0 && rotationQuaternion.y === 0 && rotationQuaternion.z === 0 && rotationQuaternion.w === 1)) {
  342. if (this.convertToRightHandedSystem) {
  343. GLTF2._GLTFUtilities.GetRightHandedQuaternionFromRef(rotationQuaternion);
  344. }
  345. node.rotation = rotationQuaternion.normalize().asArray();
  346. }
  347. };
  348. /**
  349. * Creates a bufferview based on the vertices type for the Babylon mesh
  350. * @param kind Indicates the type of vertices data
  351. * @param babylonMesh The Babylon mesh to get the vertices data from
  352. * @param binaryWriter The buffer to write the bufferview data to
  353. */
  354. _Exporter.prototype.createBufferViewKind = function (kind, babylonMesh, binaryWriter, byteStride) {
  355. var bufferMesh = null;
  356. var byteLength;
  357. var vertexData;
  358. var bufferView;
  359. if (babylonMesh instanceof BABYLON.Mesh) {
  360. bufferMesh = babylonMesh;
  361. }
  362. else if (babylonMesh instanceof BABYLON.InstancedMesh) {
  363. bufferMesh = babylonMesh.sourceMesh;
  364. }
  365. if (bufferMesh) {
  366. vertexData = bufferMesh.getVerticesData(kind);
  367. if (vertexData) {
  368. byteLength = vertexData.length * 4;
  369. bufferView = GLTF2._GLTFUtilities.CreateBufferView(0, binaryWriter.getByteOffset(), byteLength, byteStride, kind + " - " + bufferMesh.name);
  370. this.bufferViews.push(bufferView);
  371. this.writeAttributeData(kind, vertexData, binaryWriter);
  372. }
  373. }
  374. };
  375. /**
  376. * Sets data for the primitive attributes of each submesh
  377. * @param mesh glTF Mesh object to store the primitive attribute information
  378. * @param babylonMesh Babylon mesh to get the primitive attribute data from
  379. * @param binaryWriter Buffer to write the attribute data to
  380. */
  381. _Exporter.prototype.setPrimitiveAttributes = function (mesh, babylonMesh, binaryWriter) {
  382. var bufferMesh = null;
  383. var attributeKind;
  384. var indices;
  385. var byteLength;
  386. var bufferView;
  387. var uvCoordsPresent;
  388. var meshPrimitive;
  389. var vertexData;
  390. var stride;
  391. var minMax;
  392. var newMat;
  393. var babylonMultiMaterial;
  394. var material;
  395. var materialIndex = null;
  396. var indexBufferViewIndex = null;
  397. var accessor;
  398. var bufferViewIndex;
  399. if (babylonMesh instanceof BABYLON.Mesh) {
  400. bufferMesh = babylonMesh;
  401. }
  402. else if (babylonMesh instanceof BABYLON.InstancedMesh) {
  403. bufferMesh = babylonMesh.sourceMesh;
  404. }
  405. var attributeData = [
  406. { kind: BABYLON.VertexBuffer.PositionKind, accessorType: "VEC3" /* VEC3 */, byteStride: 12 },
  407. { kind: BABYLON.VertexBuffer.NormalKind, accessorType: "VEC3" /* VEC3 */, byteStride: 12 },
  408. { kind: BABYLON.VertexBuffer.ColorKind, accessorType: "VEC4" /* VEC4 */, byteStride: 16 },
  409. { kind: BABYLON.VertexBuffer.TangentKind, accessorType: "VEC4" /* VEC4 */, byteStride: 16 },
  410. { kind: BABYLON.VertexBuffer.UVKind, accessorType: "VEC2" /* VEC2 */, byteStride: 8 },
  411. { kind: BABYLON.VertexBuffer.UV2Kind, accessorType: "VEC2" /* VEC2 */, byteStride: 8 },
  412. ];
  413. if (bufferMesh) {
  414. // For each BabylonMesh, create bufferviews for each 'kind'
  415. for (var _i = 0, attributeData_1 = attributeData; _i < attributeData_1.length; _i++) {
  416. var attribute = attributeData_1[_i];
  417. attributeKind = attribute.kind;
  418. if (bufferMesh.isVerticesDataPresent(attributeKind)) {
  419. this.createBufferViewKind(attributeKind, babylonMesh, binaryWriter, attribute.byteStride);
  420. attribute.bufferViewIndex = this.bufferViews.length - 1;
  421. }
  422. }
  423. if (bufferMesh.getTotalIndices()) {
  424. indices = bufferMesh.getIndices();
  425. if (indices) {
  426. byteLength = indices.length * 4;
  427. bufferView = GLTF2._GLTFUtilities.CreateBufferView(0, binaryWriter.getByteOffset(), byteLength, undefined, "Indices - " + bufferMesh.name);
  428. this.bufferViews.push(bufferView);
  429. indexBufferViewIndex = this.bufferViews.length - 1;
  430. for (var k = 0, length_2 = indices.length; k < length_2; ++k) {
  431. binaryWriter.setUInt32(indices[k]);
  432. }
  433. }
  434. }
  435. if (babylonMesh.subMeshes) {
  436. uvCoordsPresent = false;
  437. // go through all mesh primitives (submeshes)
  438. for (var _a = 0, _b = babylonMesh.subMeshes; _a < _b.length; _a++) {
  439. var submesh = _b[_a];
  440. meshPrimitive = { attributes: {} };
  441. for (var _c = 0, attributeData_2 = attributeData; _c < attributeData_2.length; _c++) {
  442. var attribute = attributeData_2[_c];
  443. attributeKind = attribute.kind;
  444. vertexData = bufferMesh.getVerticesData(attributeKind);
  445. if (vertexData) {
  446. stride = BABYLON.VertexBuffer.DeduceStride(attributeKind);
  447. bufferViewIndex = attribute.bufferViewIndex;
  448. if (bufferViewIndex != undefined) { // check to see if bufferviewindex has a numeric value assigned.
  449. minMax = { min: null, max: null };
  450. if (attributeKind == BABYLON.VertexBuffer.PositionKind) {
  451. minMax = GLTF2._GLTFUtilities.CalculateMinMaxPositions(vertexData, 0, vertexData.length / stride, this.convertToRightHandedSystem);
  452. }
  453. accessor = GLTF2._GLTFUtilities.CreateAccessor(bufferViewIndex, attributeKind + " - " + babylonMesh.name, attribute.accessorType, 5126 /* FLOAT */, vertexData.length / stride, 0, minMax.min, minMax.max);
  454. this.accessors.push(accessor);
  455. switch (attributeKind) {
  456. case BABYLON.VertexBuffer.PositionKind: {
  457. meshPrimitive.attributes.POSITION = this.accessors.length - 1;
  458. break;
  459. }
  460. case BABYLON.VertexBuffer.NormalKind: {
  461. meshPrimitive.attributes.NORMAL = this.accessors.length - 1;
  462. break;
  463. }
  464. case BABYLON.VertexBuffer.ColorKind: {
  465. meshPrimitive.attributes.COLOR_0 = this.accessors.length - 1;
  466. break;
  467. }
  468. case BABYLON.VertexBuffer.TangentKind: {
  469. meshPrimitive.attributes.TANGENT = this.accessors.length - 1;
  470. break;
  471. }
  472. case BABYLON.VertexBuffer.UVKind: {
  473. meshPrimitive.attributes.TEXCOORD_0 = this.accessors.length - 1;
  474. uvCoordsPresent = true;
  475. break;
  476. }
  477. case BABYLON.VertexBuffer.UV2Kind: {
  478. meshPrimitive.attributes.TEXCOORD_1 = this.accessors.length - 1;
  479. uvCoordsPresent = true;
  480. break;
  481. }
  482. default: {
  483. BABYLON.Tools.Warn("Unsupported Vertex Buffer Type: " + attributeKind);
  484. }
  485. }
  486. }
  487. }
  488. }
  489. if (indexBufferViewIndex) {
  490. // Create accessor
  491. accessor = GLTF2._GLTFUtilities.CreateAccessor(indexBufferViewIndex, "indices - " + babylonMesh.name, "SCALAR" /* SCALAR */, 5125 /* UNSIGNED_INT */, submesh.indexCount, submesh.indexStart * 4, null, null);
  492. this.accessors.push(accessor);
  493. meshPrimitive.indices = this.accessors.length - 1;
  494. }
  495. if (bufferMesh.material) {
  496. materialIndex = null;
  497. if (bufferMesh.material instanceof BABYLON.StandardMaterial || bufferMesh.material instanceof BABYLON.PBRMetallicRoughnessMaterial || bufferMesh.material instanceof BABYLON.PBRMaterial) {
  498. materialIndex = babylonMesh.getScene().materials.indexOf(bufferMesh.material);
  499. }
  500. else if (bufferMesh.material instanceof BABYLON.MultiMaterial) {
  501. babylonMultiMaterial = bufferMesh.material;
  502. material = babylonMultiMaterial.subMaterials[submesh.materialIndex];
  503. if (material) {
  504. materialIndex = babylonMesh.getScene().materials.indexOf(material);
  505. }
  506. }
  507. else {
  508. BABYLON.Tools.Warn("Material type " + bufferMesh.material.getClassName() + " for material " + bufferMesh.material.name + " is not yet implemented in glTF serializer.");
  509. }
  510. if (materialIndex != null && Object.keys(meshPrimitive.attributes).length > 0) {
  511. if (uvCoordsPresent) {
  512. if (!GLTF2._GLTFMaterial._HasTexturesPresent(this.materials[materialIndex])) {
  513. delete meshPrimitive.attributes.TEXCOORD_0;
  514. delete meshPrimitive.attributes.TEXCOORD_1;
  515. }
  516. meshPrimitive.material = materialIndex;
  517. }
  518. else {
  519. if (GLTF2._GLTFMaterial._HasTexturesPresent(this.materials[materialIndex])) {
  520. newMat = GLTF2._GLTFMaterial._StripTexturesFromMaterial(this.materials[materialIndex]);
  521. this.materials.push(newMat);
  522. meshPrimitive.material = this.materials.length - 1;
  523. }
  524. }
  525. }
  526. }
  527. mesh.primitives.push(meshPrimitive);
  528. }
  529. }
  530. }
  531. };
  532. /**
  533. * Creates a glTF scene based on the array of meshes
  534. * Returns the the total byte offset
  535. * @param babylonScene Babylon scene to get the mesh data from
  536. * @param binaryWriter Buffer to write binary data to
  537. * @returns bytelength + byteoffset
  538. */
  539. _Exporter.prototype.createScene = function (babylonScene, binaryWriter) {
  540. if (babylonScene.meshes.length) {
  541. var babylonMeshes = babylonScene.meshes;
  542. var scene_1 = { nodes: [] };
  543. var glTFNodeIndex_1;
  544. var glTFNode_1;
  545. var directDescendents_1;
  546. GLTF2._GLTFMaterial._ConvertMaterialsToGLTF(babylonScene.materials, "image/png" /* PNG */, this.images, this.textures, this.materials, this.imageData, true);
  547. this.nodeMap = this.createNodeMapAndAnimations(babylonScene, binaryWriter);
  548. this.totalByteLength = binaryWriter.getByteOffset();
  549. var self_2 = this;
  550. // Build Hierarchy with the node map.
  551. babylonMeshes.forEach(function (babylonMesh) {
  552. glTFNodeIndex_1 = self_2.nodeMap[babylonMesh.uniqueId];
  553. glTFNode_1 = self_2.nodes[glTFNodeIndex_1];
  554. if (!babylonMesh.parent) {
  555. if (!self_2.shouldExportMesh(babylonMesh)) {
  556. BABYLON.Tools.Log("Omitting " + babylonMesh.name + " from scene.");
  557. }
  558. else {
  559. scene_1.nodes.push(glTFNodeIndex_1);
  560. }
  561. }
  562. directDescendents_1 = babylonMesh.getDescendants(true);
  563. if (!glTFNode_1.children && directDescendents_1 && directDescendents_1.length) {
  564. glTFNode_1.children = [];
  565. for (var _i = 0, directDescendents_2 = directDescendents_1; _i < directDescendents_2.length; _i++) {
  566. var descendent = directDescendents_2[_i];
  567. glTFNode_1.children.push(self_2.nodeMap[descendent.uniqueId]);
  568. }
  569. }
  570. });
  571. this.scenes.push(scene_1);
  572. }
  573. };
  574. /**
  575. * Creates a mapping of Node unique id to node index and handles animations
  576. * @param scene Babylon Scene
  577. * @param binaryWriter Buffer to write binary data to
  578. * @returns Node mapping of unique id to index
  579. */
  580. _Exporter.prototype.createNodeMapAndAnimations = function (scene, binaryWriter) {
  581. var nodeMap = {};
  582. var nodeIndex;
  583. var runtimeGLTFAnimation = {
  584. name: 'runtime animations',
  585. channels: [],
  586. samplers: []
  587. };
  588. var idleGLTFAnimations = [];
  589. var node;
  590. var self = this;
  591. scene.meshes.forEach(function (babylonMesh) {
  592. node = self.createNode(babylonMesh, binaryWriter);
  593. self.nodes.push(node);
  594. nodeIndex = self.nodes.length - 1;
  595. nodeMap[babylonMesh.uniqueId] = nodeIndex;
  596. if (!scene.animationGroups.length && babylonMesh.animations.length) {
  597. GLTF2._GLTFAnimation._CreateNodeAnimationFromMeshAnimations(babylonMesh, runtimeGLTFAnimation, idleGLTFAnimations, nodeMap, self.nodes, binaryWriter, self.bufferViews, self.accessors, self.convertToRightHandedSystem, self.animationSampleRate);
  598. }
  599. });
  600. if (runtimeGLTFAnimation.channels.length && runtimeGLTFAnimation.samplers.length) {
  601. this.animations.push(runtimeGLTFAnimation);
  602. }
  603. idleGLTFAnimations.forEach(function (idleGLTFAnimation) {
  604. if (idleGLTFAnimation.channels.length && idleGLTFAnimation.samplers.length) {
  605. self.animations.push(idleGLTFAnimation);
  606. }
  607. });
  608. if (scene.animationGroups.length) {
  609. GLTF2._GLTFAnimation._CreateNodeAnimationFromAnimationGroups(scene, self.animations, nodeMap, this.nodes, binaryWriter, this.bufferViews, this.accessors, this.convertToRightHandedSystem, self.animationSampleRate);
  610. }
  611. return nodeMap;
  612. };
  613. /**
  614. * Creates a glTF node from a Babylon mesh
  615. * @param babylonMesh Source Babylon mesh
  616. * @param binaryWriter Buffer for storing geometry data
  617. * @returns glTF node
  618. */
  619. _Exporter.prototype.createNode = function (babylonMesh, binaryWriter) {
  620. // create node to hold translation/rotation/scale and the mesh
  621. var node = {};
  622. // create mesh
  623. var mesh = { primitives: [] };
  624. if (babylonMesh.name) {
  625. node.name = babylonMesh.name;
  626. }
  627. // Set transformation
  628. this.setNodeTransformation(node, babylonMesh);
  629. this.setPrimitiveAttributes(mesh, babylonMesh, binaryWriter);
  630. if (mesh.primitives.length) {
  631. this.meshes.push(mesh);
  632. node.mesh = this.meshes.length - 1;
  633. }
  634. return node;
  635. };
  636. return _Exporter;
  637. }());
  638. GLTF2._Exporter = _Exporter;
  639. /**
  640. * @hidden
  641. *
  642. * Stores glTF binary data. If the array buffer byte length is exceeded, it doubles in size dynamically
  643. */
  644. var _BinaryWriter = /** @class */ (function () {
  645. /**
  646. * Initialize binary writer with an initial byte length
  647. * @param byteLength Initial byte length of the array buffer
  648. */
  649. function _BinaryWriter(byteLength) {
  650. this._arrayBuffer = new ArrayBuffer(byteLength);
  651. this._dataView = new DataView(this._arrayBuffer);
  652. this._byteOffset = 0;
  653. }
  654. /**
  655. * Resize the array buffer to the specified byte length
  656. * @param byteLength
  657. */
  658. _BinaryWriter.prototype.resizeBuffer = function (byteLength) {
  659. var newBuffer = new ArrayBuffer(byteLength);
  660. var oldUint8Array = new Uint8Array(this._arrayBuffer);
  661. var newUint8Array = new Uint8Array(newBuffer);
  662. for (var i = 0, length_3 = newUint8Array.byteLength; i < length_3; ++i) {
  663. newUint8Array[i] = oldUint8Array[i];
  664. }
  665. this._arrayBuffer = newBuffer;
  666. this._dataView = new DataView(this._arrayBuffer);
  667. };
  668. /**
  669. * Get an array buffer with the length of the byte offset
  670. * @returns ArrayBuffer resized to the byte offset
  671. */
  672. _BinaryWriter.prototype.getArrayBuffer = function () {
  673. this.resizeBuffer(this.getByteOffset());
  674. return this._arrayBuffer;
  675. };
  676. /**
  677. * Get the byte offset of the array buffer
  678. * @returns byte offset
  679. */
  680. _BinaryWriter.prototype.getByteOffset = function () {
  681. return this._byteOffset;
  682. };
  683. /**
  684. * Stores an UInt8 in the array buffer
  685. * @param entry
  686. */
  687. _BinaryWriter.prototype.setUInt8 = function (entry) {
  688. if (this._byteOffset + 1 > this._arrayBuffer.byteLength) {
  689. this.resizeBuffer(this._arrayBuffer.byteLength * 2);
  690. }
  691. this._dataView.setUint8(this._byteOffset++, entry);
  692. };
  693. /**
  694. * Stores a Float32 in the array buffer
  695. * @param entry
  696. */
  697. _BinaryWriter.prototype.setFloat32 = function (entry) {
  698. if (this._byteOffset + 4 > this._arrayBuffer.byteLength) {
  699. this.resizeBuffer(this._arrayBuffer.byteLength * 2);
  700. }
  701. this._dataView.setFloat32(this._byteOffset, entry, true);
  702. this._byteOffset += 4;
  703. };
  704. /**
  705. * Stores an UInt32 in the array buffer
  706. * @param entry
  707. */
  708. _BinaryWriter.prototype.setUInt32 = function (entry) {
  709. if (this._byteOffset + 4 > this._arrayBuffer.byteLength) {
  710. this.resizeBuffer(this._arrayBuffer.byteLength * 2);
  711. }
  712. this._dataView.setUint32(this._byteOffset, entry, true);
  713. this._byteOffset += 4;
  714. };
  715. return _BinaryWriter;
  716. }());
  717. GLTF2._BinaryWriter = _BinaryWriter;
  718. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  719. })(BABYLON || (BABYLON = {}));
  720. //# sourceMappingURL=babylon.glTFExporter.js.map
  721. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  722. var BABYLON;
  723. (function (BABYLON) {
  724. /**
  725. * Class for holding and downloading glTF file data
  726. */
  727. var GLTFData = /** @class */ (function () {
  728. /**
  729. * Initializes the glTF file object
  730. */
  731. function GLTFData() {
  732. this.glTFFiles = {};
  733. }
  734. /**
  735. * Downloads the glTF data as files based on their names and data
  736. */
  737. GLTFData.prototype.downloadFiles = function () {
  738. /**
  739. * Checks for a matching suffix at the end of a string (for ES5 and lower)
  740. * @param str Source string
  741. * @param suffix Suffix to search for in the source string
  742. * @returns Boolean indicating whether the suffix was found (true) or not (false)
  743. */
  744. function endsWith(str, suffix) {
  745. return str.indexOf(suffix, str.length - suffix.length) !== -1;
  746. }
  747. for (var key in this.glTFFiles) {
  748. var link = document.createElement('a');
  749. document.body.appendChild(link);
  750. link.setAttribute("type", "hidden");
  751. link.download = key;
  752. var blob = this.glTFFiles[key];
  753. var mimeType = void 0;
  754. if (endsWith(key, ".glb")) {
  755. mimeType = { type: "model/gltf-binary" };
  756. }
  757. else if (endsWith(key, ".bin")) {
  758. mimeType = { type: "application/octet-stream" };
  759. }
  760. else if (endsWith(key, ".gltf")) {
  761. mimeType = { type: "model/gltf+json" };
  762. }
  763. else if (endsWith(key, ".jpeg" || ".jpg")) {
  764. mimeType = { type: "image/jpeg" /* JPEG */ };
  765. }
  766. else if (endsWith(key, ".png")) {
  767. mimeType = { type: "image/png" /* PNG */ };
  768. }
  769. link.href = window.URL.createObjectURL(new Blob([blob], mimeType));
  770. link.click();
  771. }
  772. };
  773. return GLTFData;
  774. }());
  775. BABYLON.GLTFData = GLTFData;
  776. })(BABYLON || (BABYLON = {}));
  777. //# sourceMappingURL=babylon.glTFData.js.map
  778. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  779. var BABYLON;
  780. (function (BABYLON) {
  781. var GLTF2;
  782. (function (GLTF2) {
  783. /**
  784. * Interface for storing specular glossiness factors
  785. * @hidden
  786. */
  787. /**
  788. * Utility methods for working with glTF material conversion properties. This class should only be used internally
  789. * @hidden
  790. */
  791. var _GLTFMaterial = /** @class */ (function () {
  792. function _GLTFMaterial() {
  793. }
  794. /**
  795. * Specifies if two colors are approximately equal in value
  796. * @param color1 first color to compare to
  797. * @param color2 second color to compare to
  798. * @param epsilon threshold value
  799. */
  800. _GLTFMaterial.FuzzyEquals = function (color1, color2, epsilon) {
  801. return BABYLON.Scalar.WithinEpsilon(color1.r, color2.r, epsilon) &&
  802. BABYLON.Scalar.WithinEpsilon(color1.g, color2.g, epsilon) &&
  803. BABYLON.Scalar.WithinEpsilon(color1.b, color2.b, epsilon);
  804. };
  805. /**
  806. * Gets the materials from a Babylon scene and converts them to glTF materials
  807. * @param scene babylonjs scene
  808. * @param mimeType texture mime type
  809. * @param images array of images
  810. * @param textures array of textures
  811. * @param materials array of materials
  812. * @param imageData mapping of texture names to base64 textures
  813. * @param hasTextureCoords specifies if texture coordinates are present on the material
  814. */
  815. _GLTFMaterial._ConvertMaterialsToGLTF = function (babylonMaterials, mimeType, images, textures, materials, imageData, hasTextureCoords) {
  816. for (var i = 0; i < babylonMaterials.length; ++i) {
  817. var babylonMaterial = babylonMaterials[i];
  818. if (babylonMaterial instanceof BABYLON.StandardMaterial) {
  819. _GLTFMaterial._ConvertStandardMaterial(babylonMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords);
  820. }
  821. else if (babylonMaterial instanceof BABYLON.PBRMetallicRoughnessMaterial) {
  822. _GLTFMaterial._ConvertPBRMetallicRoughnessMaterial(babylonMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords);
  823. }
  824. else if (babylonMaterial instanceof BABYLON.PBRMaterial) {
  825. _GLTFMaterial._ConvertPBRMaterial(babylonMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords);
  826. }
  827. else {
  828. BABYLON.Tools.Error("Unsupported material type: " + babylonMaterial.name);
  829. }
  830. }
  831. };
  832. /**
  833. * Makes a copy of the glTF material without the texture parameters
  834. * @param originalMaterial original glTF material
  835. * @returns glTF material without texture parameters
  836. */
  837. _GLTFMaterial._StripTexturesFromMaterial = function (originalMaterial) {
  838. var newMaterial = {};
  839. if (originalMaterial) {
  840. newMaterial.name = originalMaterial.name;
  841. newMaterial.doubleSided = originalMaterial.doubleSided;
  842. newMaterial.alphaMode = originalMaterial.alphaMode;
  843. newMaterial.alphaCutoff = originalMaterial.alphaCutoff;
  844. newMaterial.emissiveFactor = originalMaterial.emissiveFactor;
  845. var originalPBRMetallicRoughness = originalMaterial.pbrMetallicRoughness;
  846. if (originalPBRMetallicRoughness) {
  847. newMaterial.pbrMetallicRoughness = {};
  848. newMaterial.pbrMetallicRoughness.baseColorFactor = originalPBRMetallicRoughness.baseColorFactor;
  849. newMaterial.pbrMetallicRoughness.metallicFactor = originalPBRMetallicRoughness.metallicFactor;
  850. newMaterial.pbrMetallicRoughness.roughnessFactor = originalPBRMetallicRoughness.roughnessFactor;
  851. }
  852. }
  853. return newMaterial;
  854. };
  855. /**
  856. * Specifies if the material has any texture parameters present
  857. * @param material glTF Material
  858. * @returns boolean specifying if texture parameters are present
  859. */
  860. _GLTFMaterial._HasTexturesPresent = function (material) {
  861. if (material.emissiveTexture || material.normalTexture || material.occlusionTexture) {
  862. return true;
  863. }
  864. var pbrMat = material.pbrMetallicRoughness;
  865. if (pbrMat) {
  866. if (pbrMat.baseColorTexture || pbrMat.metallicRoughnessTexture) {
  867. return true;
  868. }
  869. }
  870. return false;
  871. };
  872. /**
  873. * Converts a Babylon StandardMaterial to a glTF Metallic Roughness Material
  874. * @param babylonStandardMaterial
  875. * @returns glTF Metallic Roughness Material representation
  876. */
  877. _GLTFMaterial._ConvertToGLTFPBRMetallicRoughness = function (babylonStandardMaterial) {
  878. var P0 = new BABYLON.Vector2(0, 1);
  879. var P1 = new BABYLON.Vector2(0, 0.1);
  880. var P2 = new BABYLON.Vector2(0, 0.1);
  881. var P3 = new BABYLON.Vector2(1300, 0.1);
  882. /**
  883. * Given the control points, solve for x based on a given t for a cubic bezier curve
  884. * @param t a value between 0 and 1
  885. * @param p0 first control point
  886. * @param p1 second control point
  887. * @param p2 third control point
  888. * @param p3 fourth control point
  889. * @returns number result of cubic bezier curve at the specified t
  890. */
  891. function _cubicBezierCurve(t, p0, p1, p2, p3) {
  892. return ((1 - t) * (1 - t) * (1 - t) * p0 +
  893. 3 * (1 - t) * (1 - t) * t * p1 +
  894. 3 * (1 - t) * t * t * p2 +
  895. t * t * t * p3);
  896. }
  897. /**
  898. * Evaluates a specified specular power value to determine the appropriate roughness value,
  899. * based on a pre-defined cubic bezier curve with specular on the abscissa axis (x-axis)
  900. * and roughness on the ordinant axis (y-axis)
  901. * @param specularPower specular power of standard material
  902. * @returns Number representing the roughness value
  903. */
  904. function _solveForRoughness(specularPower) {
  905. var t = Math.pow(specularPower / P3.x, 0.333333);
  906. return _cubicBezierCurve(t, P0.y, P1.y, P2.y, P3.y);
  907. }
  908. var diffuse = babylonStandardMaterial.diffuseColor.toLinearSpace().scale(0.5);
  909. var opacity = babylonStandardMaterial.alpha;
  910. var specularPower = BABYLON.Scalar.Clamp(babylonStandardMaterial.specularPower, 0, this._maxSpecularPower);
  911. var roughness = _solveForRoughness(specularPower);
  912. var glTFPbrMetallicRoughness = {
  913. baseColorFactor: [
  914. diffuse.r,
  915. diffuse.g,
  916. diffuse.b,
  917. opacity
  918. ],
  919. metallicFactor: 0,
  920. roughnessFactor: roughness,
  921. };
  922. return glTFPbrMetallicRoughness;
  923. };
  924. /**
  925. * Computes the metallic factor
  926. * @param diffuse diffused value
  927. * @param specular specular value
  928. * @param oneMinusSpecularStrength one minus the specular strength
  929. * @returns metallic value
  930. */
  931. _GLTFMaterial._SolveMetallic = function (diffuse, specular, oneMinusSpecularStrength) {
  932. if (specular < _GLTFMaterial._dielectricSpecular.r) {
  933. _GLTFMaterial._dielectricSpecular;
  934. return 0;
  935. }
  936. var a = _GLTFMaterial._dielectricSpecular.r;
  937. var b = diffuse * oneMinusSpecularStrength / (1.0 - _GLTFMaterial._dielectricSpecular.r) + specular - 2.0 * _GLTFMaterial._dielectricSpecular.r;
  938. var c = _GLTFMaterial._dielectricSpecular.r - specular;
  939. var D = b * b - 4.0 * a * c;
  940. return BABYLON.Scalar.Clamp((-b + Math.sqrt(D)) / (2.0 * a), 0, 1);
  941. };
  942. /**
  943. * Gets the glTF alpha mode from the Babylon Material
  944. * @param babylonMaterial Babylon Material
  945. * @returns The Babylon alpha mode value
  946. */
  947. _GLTFMaterial._GetAlphaMode = function (babylonMaterial) {
  948. if (babylonMaterial instanceof BABYLON.StandardMaterial) {
  949. var babylonStandardMaterial = babylonMaterial;
  950. if ((babylonStandardMaterial.alpha != 1.0) ||
  951. (babylonStandardMaterial.diffuseTexture != null && babylonStandardMaterial.diffuseTexture.hasAlpha) ||
  952. (babylonStandardMaterial.opacityTexture != null)) {
  953. return "BLEND" /* BLEND */;
  954. }
  955. else {
  956. return "OPAQUE" /* OPAQUE */;
  957. }
  958. }
  959. else if (babylonMaterial instanceof BABYLON.PBRMetallicRoughnessMaterial) {
  960. var babylonPBRMetallicRoughness = babylonMaterial;
  961. switch (babylonPBRMetallicRoughness.transparencyMode) {
  962. case BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE: {
  963. return "OPAQUE" /* OPAQUE */;
  964. }
  965. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND: {
  966. return "BLEND" /* BLEND */;
  967. }
  968. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST: {
  969. return "MASK" /* MASK */;
  970. }
  971. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND: {
  972. BABYLON.Tools.Warn(babylonMaterial.name + ": GLTF Exporter | Alpha test and blend mode not supported in glTF. Alpha blend used instead.");
  973. return "BLEND" /* BLEND */;
  974. }
  975. default: {
  976. BABYLON.Tools.Error("Unsupported alpha mode " + babylonPBRMetallicRoughness.transparencyMode);
  977. return null;
  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. BABYLON.Tools.Error("Unsupported alpha mode " + babylonPBRMaterial.transparencyMode);
  999. return null;
  1000. }
  1001. }
  1002. }
  1003. else {
  1004. BABYLON.Tools.Error("Unsupported Babylon material type");
  1005. return null;
  1006. }
  1007. };
  1008. /**
  1009. * Converts a Babylon Standard Material to a glTF Material
  1010. * @param babylonStandardMaterial BJS Standard Material
  1011. * @param mimeType mime type to use for the textures
  1012. * @param images array of glTF image interfaces
  1013. * @param textures array of glTF texture interfaces
  1014. * @param materials array of glTF material interfaces
  1015. * @param imageData map of image file name to data
  1016. * @param hasTextureCoords specifies if texture coordinates are present on the submesh to determine if textures should be applied
  1017. */
  1018. _GLTFMaterial._ConvertStandardMaterial = function (babylonStandardMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords) {
  1019. var glTFPbrMetallicRoughness = _GLTFMaterial._ConvertToGLTFPBRMetallicRoughness(babylonStandardMaterial);
  1020. var glTFMaterial = { name: babylonStandardMaterial.name };
  1021. if (babylonStandardMaterial.backFaceCulling != null && !babylonStandardMaterial.backFaceCulling) {
  1022. if (!babylonStandardMaterial.twoSidedLighting) {
  1023. BABYLON.Tools.Warn(babylonStandardMaterial.name + ": Back-face culling enabled and two-sided lighting disabled is not supported in glTF.");
  1024. }
  1025. glTFMaterial.doubleSided = true;
  1026. }
  1027. if (hasTextureCoords) {
  1028. if (babylonStandardMaterial.diffuseTexture) {
  1029. var glTFTexture = _GLTFMaterial._ExportTexture(babylonStandardMaterial.diffuseTexture, mimeType, images, textures, imageData);
  1030. if (glTFTexture != null) {
  1031. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  1032. }
  1033. }
  1034. if (babylonStandardMaterial.bumpTexture) {
  1035. var glTFTexture = _GLTFMaterial._ExportTexture(babylonStandardMaterial.bumpTexture, mimeType, images, textures, imageData);
  1036. if (glTFTexture) {
  1037. glTFMaterial.normalTexture = glTFTexture;
  1038. }
  1039. }
  1040. if (babylonStandardMaterial.emissiveTexture) {
  1041. var glTFEmissiveTexture = _GLTFMaterial._ExportTexture(babylonStandardMaterial.emissiveTexture, mimeType, images, textures, imageData);
  1042. if (glTFEmissiveTexture) {
  1043. glTFMaterial.emissiveTexture = glTFEmissiveTexture;
  1044. }
  1045. glTFMaterial.emissiveFactor = [1.0, 1.0, 1.0];
  1046. }
  1047. if (babylonStandardMaterial.ambientTexture) {
  1048. var glTFTexture = _GLTFMaterial._ExportTexture(babylonStandardMaterial.ambientTexture, mimeType, images, textures, imageData);
  1049. if (glTFTexture) {
  1050. var occlusionTexture = {
  1051. index: glTFTexture.index
  1052. };
  1053. glTFMaterial.occlusionTexture = occlusionTexture;
  1054. occlusionTexture.strength = 1.0;
  1055. }
  1056. }
  1057. }
  1058. if (babylonStandardMaterial.alpha < 1.0 || babylonStandardMaterial.opacityTexture) {
  1059. if (babylonStandardMaterial.alphaMode === BABYLON.Engine.ALPHA_COMBINE) {
  1060. glTFMaterial.alphaMode = "BLEND" /* BLEND */;
  1061. }
  1062. else {
  1063. BABYLON.Tools.Warn(babylonStandardMaterial.name + ": glTF 2.0 does not support alpha mode: " + babylonStandardMaterial.alphaMode.toString());
  1064. }
  1065. }
  1066. if (babylonStandardMaterial.emissiveColor && !this.FuzzyEquals(babylonStandardMaterial.emissiveColor, BABYLON.Color3.Black(), this._epsilon)) {
  1067. glTFMaterial.emissiveFactor = babylonStandardMaterial.emissiveColor.asArray();
  1068. }
  1069. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  1070. materials.push(glTFMaterial);
  1071. };
  1072. /**
  1073. * Converts a Babylon PBR Metallic Roughness Material to a glTF Material
  1074. * @param babylonPBRMetalRoughMaterial BJS PBR Metallic Roughness Material
  1075. * @param mimeType mime type to use for the textures
  1076. * @param images array of glTF image interfaces
  1077. * @param textures array of glTF texture interfaces
  1078. * @param materials array of glTF material interfaces
  1079. * @param imageData map of image file name to data
  1080. * @param hasTextureCoords specifies if texture coordinates are present on the submesh to determine if textures should be applied
  1081. */
  1082. _GLTFMaterial._ConvertPBRMetallicRoughnessMaterial = function (babylonPBRMetalRoughMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords) {
  1083. var glTFPbrMetallicRoughness = {};
  1084. if (babylonPBRMetalRoughMaterial.baseColor) {
  1085. glTFPbrMetallicRoughness.baseColorFactor = [
  1086. babylonPBRMetalRoughMaterial.baseColor.r,
  1087. babylonPBRMetalRoughMaterial.baseColor.g,
  1088. babylonPBRMetalRoughMaterial.baseColor.b,
  1089. babylonPBRMetalRoughMaterial.alpha
  1090. ];
  1091. }
  1092. if (babylonPBRMetalRoughMaterial.metallic != null && babylonPBRMetalRoughMaterial.metallic !== 1) {
  1093. glTFPbrMetallicRoughness.metallicFactor = babylonPBRMetalRoughMaterial.metallic;
  1094. }
  1095. if (babylonPBRMetalRoughMaterial.roughness != null && babylonPBRMetalRoughMaterial.roughness !== 1) {
  1096. glTFPbrMetallicRoughness.roughnessFactor = babylonPBRMetalRoughMaterial.roughness;
  1097. }
  1098. var glTFMaterial = {
  1099. name: babylonPBRMetalRoughMaterial.name
  1100. };
  1101. if (babylonPBRMetalRoughMaterial.doubleSided) {
  1102. glTFMaterial.doubleSided = babylonPBRMetalRoughMaterial.doubleSided;
  1103. }
  1104. if (hasTextureCoords) {
  1105. if (babylonPBRMetalRoughMaterial.baseTexture != null) {
  1106. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMetalRoughMaterial.baseTexture, mimeType, images, textures, imageData);
  1107. if (glTFTexture != null) {
  1108. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  1109. }
  1110. }
  1111. if (babylonPBRMetalRoughMaterial.normalTexture) {
  1112. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMetalRoughMaterial.normalTexture, mimeType, images, textures, imageData);
  1113. if (glTFTexture) {
  1114. glTFMaterial.normalTexture = glTFTexture;
  1115. }
  1116. }
  1117. if (babylonPBRMetalRoughMaterial.occlusionTexture) {
  1118. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMetalRoughMaterial.occlusionTexture, mimeType, images, textures, imageData);
  1119. if (glTFTexture) {
  1120. glTFMaterial.occlusionTexture = glTFTexture;
  1121. if (babylonPBRMetalRoughMaterial.occlusionStrength != null) {
  1122. glTFMaterial.occlusionTexture.strength = babylonPBRMetalRoughMaterial.occlusionStrength;
  1123. }
  1124. }
  1125. }
  1126. if (babylonPBRMetalRoughMaterial.emissiveTexture) {
  1127. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMetalRoughMaterial.emissiveTexture, mimeType, images, textures, imageData);
  1128. if (glTFTexture != null) {
  1129. glTFMaterial.emissiveTexture = glTFTexture;
  1130. }
  1131. }
  1132. }
  1133. if (this.FuzzyEquals(babylonPBRMetalRoughMaterial.emissiveColor, BABYLON.Color3.Black(), this._epsilon)) {
  1134. glTFMaterial.emissiveFactor = babylonPBRMetalRoughMaterial.emissiveColor.asArray();
  1135. }
  1136. if (babylonPBRMetalRoughMaterial.transparencyMode != null) {
  1137. var alphaMode = _GLTFMaterial._GetAlphaMode(babylonPBRMetalRoughMaterial);
  1138. if (alphaMode) {
  1139. if (alphaMode !== "OPAQUE" /* OPAQUE */) { //glTF defaults to opaque
  1140. glTFMaterial.alphaMode = alphaMode;
  1141. if (alphaMode === "BLEND" /* BLEND */) {
  1142. glTFMaterial.alphaCutoff = babylonPBRMetalRoughMaterial.alphaCutOff;
  1143. }
  1144. }
  1145. }
  1146. }
  1147. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  1148. materials.push(glTFMaterial);
  1149. };
  1150. /**
  1151. * Converts an image typed array buffer to a base64 image
  1152. * @param buffer typed array buffer
  1153. * @param width width of the image
  1154. * @param height height of the image
  1155. * @param mimeType mimetype of the image
  1156. * @returns base64 image string
  1157. */
  1158. _GLTFMaterial._CreateBase64FromCanvas = function (buffer, width, height, mimeType) {
  1159. var imageCanvas = document.createElement('canvas');
  1160. imageCanvas.id = "WriteCanvas";
  1161. var ctx = imageCanvas.getContext('2d');
  1162. imageCanvas.width = width;
  1163. imageCanvas.height = height;
  1164. var imgData = ctx.createImageData(width, height);
  1165. imgData.data.set(buffer);
  1166. ctx.putImageData(imgData, 0, 0);
  1167. return imageCanvas.toDataURL(mimeType);
  1168. };
  1169. /**
  1170. * Generates a white texture based on the specified width and height
  1171. * @param width width of the texture in pixels
  1172. * @param height height of the texture in pixels
  1173. * @param scene babylonjs scene
  1174. * @returns white texture
  1175. */
  1176. _GLTFMaterial._CreateWhiteTexture = function (width, height, scene) {
  1177. var data = new Uint8Array(width * height * 4);
  1178. for (var i = 0; i < data.length; ++i) {
  1179. data[i] = 255;
  1180. }
  1181. var rawTexture = BABYLON.RawTexture.CreateRGBATexture(data, width, height, scene);
  1182. return rawTexture;
  1183. };
  1184. /**
  1185. * 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
  1186. * @param texture1 first texture to resize
  1187. * @param texture2 second texture to resize
  1188. * @param scene babylonjs scene
  1189. * @returns resized textures or null
  1190. */
  1191. _GLTFMaterial._ResizeTexturesToSameDimensions = function (texture1, texture2, scene) {
  1192. var texture1Size = texture1 ? texture1.getSize() : { width: 0, height: 0 };
  1193. var texture2Size = texture2 ? texture2.getSize() : { width: 0, height: 0 };
  1194. var resizedTexture1;
  1195. var resizedTexture2;
  1196. if (texture1Size.width < texture2Size.width) {
  1197. if (texture1) {
  1198. resizedTexture1 = BABYLON.TextureTools.CreateResizedCopy(texture1, texture2Size.width, texture2Size.height, true);
  1199. }
  1200. else {
  1201. resizedTexture1 = this._CreateWhiteTexture(texture2Size.width, texture2Size.height, scene);
  1202. }
  1203. resizedTexture2 = texture2;
  1204. }
  1205. else if (texture1Size.width > texture2Size.width) {
  1206. if (texture2) {
  1207. resizedTexture2 = BABYLON.TextureTools.CreateResizedCopy(texture2, texture1Size.width, texture1Size.height, true);
  1208. }
  1209. else {
  1210. resizedTexture2 = this._CreateWhiteTexture(texture1Size.width, texture1Size.height, scene);
  1211. }
  1212. resizedTexture1 = texture1;
  1213. }
  1214. else {
  1215. resizedTexture1 = texture1;
  1216. resizedTexture2 = texture2;
  1217. }
  1218. return {
  1219. "texture1": resizedTexture1,
  1220. "texture2": resizedTexture2
  1221. };
  1222. };
  1223. /**
  1224. * Convert Specular Glossiness Textures to Metallic Roughness
  1225. * See link below for info on the material conversions from PBR Metallic/Roughness and Specular/Glossiness
  1226. * @link https://github.com/KhronosGroup/glTF/blob/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness/examples/convert-between-workflows-bjs/js/babylon.pbrUtilities.js
  1227. * @param diffuseTexture texture used to store diffuse information
  1228. * @param specularGlossinessTexture texture used to store specular and glossiness information
  1229. * @param factors specular glossiness material factors
  1230. * @param mimeType the mime type to use for the texture
  1231. * @returns pbr metallic roughness interface or null
  1232. */
  1233. _GLTFMaterial._ConvertSpecularGlossinessTexturesToMetallicRoughness = function (diffuseTexture, specularGlossinessTexture, factors, mimeType) {
  1234. if (!(diffuseTexture || specularGlossinessTexture)) {
  1235. return null;
  1236. }
  1237. var scene = diffuseTexture ? diffuseTexture.getScene() : specularGlossinessTexture.getScene();
  1238. if (!scene) {
  1239. BABYLON.Tools.Error("_ConvertSpecularGlossinessTexturesToMetallicRoughness: Scene from textures is missing!");
  1240. return null;
  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. BABYLON.Tools.Error("_ConvertSpecularGlossinessTexturesToMetallicRoughness: Pixel array buffer type not supported for texture: " + resizedTextures.texture1.name);
  1254. return null;
  1255. }
  1256. pixels = resizedTextures.texture2.readPixels();
  1257. if (pixels instanceof Uint8Array) {
  1258. specularGlossinessBuffer = (resizedTextures.texture2.readPixels());
  1259. }
  1260. else {
  1261. BABYLON.Tools.Error("_ConvertSpecularGlossinessTexturesToMetallicRoughness: Pixel array buffer type not supported for texture: " + resizedTextures.texture2.name);
  1262. return null;
  1263. }
  1264. var byteLength = specularGlossinessBuffer.byteLength;
  1265. var metallicRoughnessBuffer = new Uint8Array(byteLength);
  1266. var baseColorBuffer = new Uint8Array(byteLength);
  1267. var strideSize = 4;
  1268. var maxBaseColor = BABYLON.Color3.Black();
  1269. var maxMetallic = 0;
  1270. var maxRoughness = 0;
  1271. for (var h = 0; h < height; ++h) {
  1272. for (var w = 0; w < width; ++w) {
  1273. var offset = (width * h + w) * strideSize;
  1274. var diffuseColor = BABYLON.Color3.FromInts(diffuseBuffer[offset], diffuseBuffer[offset + 1], diffuseBuffer[offset + 2]).toLinearSpace().multiply(factors.diffuseColor);
  1275. var specularColor = BABYLON.Color3.FromInts(specularGlossinessBuffer[offset], specularGlossinessBuffer[offset + 1], specularGlossinessBuffer[offset + 2]).toLinearSpace().multiply(factors.specularColor);
  1276. var glossiness = (specularGlossinessBuffer[offset + 3] / 255) * factors.glossiness;
  1277. var specularGlossiness = {
  1278. diffuseColor: diffuseColor,
  1279. specularColor: specularColor,
  1280. glossiness: glossiness
  1281. };
  1282. var metallicRoughness = this._ConvertSpecularGlossinessToMetallicRoughness(specularGlossiness);
  1283. maxBaseColor.r = Math.max(maxBaseColor.r, metallicRoughness.baseColor.r);
  1284. maxBaseColor.g = Math.max(maxBaseColor.g, metallicRoughness.baseColor.g);
  1285. maxBaseColor.b = Math.max(maxBaseColor.b, metallicRoughness.baseColor.b);
  1286. maxMetallic = Math.max(maxMetallic, metallicRoughness.metallic);
  1287. maxRoughness = Math.max(maxRoughness, metallicRoughness.roughness);
  1288. baseColorBuffer[offset] = metallicRoughness.baseColor.r * 255;
  1289. baseColorBuffer[offset + 1] = metallicRoughness.baseColor.g * 255;
  1290. baseColorBuffer[offset + 2] = metallicRoughness.baseColor.b * 255;
  1291. baseColorBuffer[offset + 3] = resizedTextures.texture1.hasAlpha ? diffuseBuffer[offset + 3] : 255;
  1292. metallicRoughnessBuffer[offset] = 0;
  1293. metallicRoughnessBuffer[offset + 1] = metallicRoughness.roughness * 255;
  1294. metallicRoughnessBuffer[offset + 2] = metallicRoughness.metallic * 255;
  1295. metallicRoughnessBuffer[offset + 3] = 255;
  1296. }
  1297. }
  1298. // Retrieves the metallic roughness factors from the maximum texture values.
  1299. var metallicRoughnessFactors = {
  1300. baseColor: maxBaseColor,
  1301. metallic: maxMetallic,
  1302. roughness: maxRoughness
  1303. };
  1304. var writeOutMetallicRoughnessTexture = false;
  1305. var writeOutBaseColorTexture = false;
  1306. for (var h = 0; h < height; ++h) {
  1307. for (var w = 0; w < width; ++w) {
  1308. var destinationOffset = (width * h + w) * strideSize;
  1309. baseColorBuffer[destinationOffset] /= metallicRoughnessFactors.baseColor.r > this._epsilon ? metallicRoughnessFactors.baseColor.r : 1;
  1310. baseColorBuffer[destinationOffset + 1] /= metallicRoughnessFactors.baseColor.g > this._epsilon ? metallicRoughnessFactors.baseColor.g : 1;
  1311. baseColorBuffer[destinationOffset + 2] /= metallicRoughnessFactors.baseColor.b > this._epsilon ? metallicRoughnessFactors.baseColor.b : 1;
  1312. var linearBaseColorPixel = BABYLON.Color3.FromInts(baseColorBuffer[destinationOffset], baseColorBuffer[destinationOffset + 1], baseColorBuffer[destinationOffset + 2]);
  1313. var sRGBBaseColorPixel = linearBaseColorPixel.toGammaSpace();
  1314. baseColorBuffer[destinationOffset] = sRGBBaseColorPixel.r * 255;
  1315. baseColorBuffer[destinationOffset + 1] = sRGBBaseColorPixel.g * 255;
  1316. baseColorBuffer[destinationOffset + 2] = sRGBBaseColorPixel.b * 255;
  1317. if (!this.FuzzyEquals(sRGBBaseColorPixel, BABYLON.Color3.White(), this._epsilon)) {
  1318. writeOutBaseColorTexture = true;
  1319. }
  1320. metallicRoughnessBuffer[destinationOffset + 1] /= metallicRoughnessFactors.roughness > this._epsilon ? metallicRoughnessFactors.roughness : 1;
  1321. metallicRoughnessBuffer[destinationOffset + 2] /= metallicRoughnessFactors.metallic > this._epsilon ? metallicRoughnessFactors.metallic : 1;
  1322. var metallicRoughnessPixel = BABYLON.Color3.FromInts(255, metallicRoughnessBuffer[destinationOffset + 1], metallicRoughnessBuffer[destinationOffset + 2]);
  1323. if (!this.FuzzyEquals(metallicRoughnessPixel, BABYLON.Color3.White(), this._epsilon)) {
  1324. writeOutMetallicRoughnessTexture = true;
  1325. }
  1326. }
  1327. }
  1328. if (writeOutMetallicRoughnessTexture) {
  1329. var metallicRoughnessBase64 = this._CreateBase64FromCanvas(metallicRoughnessBuffer, width, height, mimeType);
  1330. metallicRoughnessFactors.metallicRoughnessTextureBase64 = metallicRoughnessBase64;
  1331. }
  1332. if (writeOutBaseColorTexture) {
  1333. var baseColorBase64 = this._CreateBase64FromCanvas(baseColorBuffer, width, height, mimeType);
  1334. metallicRoughnessFactors.baseColorTextureBase64 = baseColorBase64;
  1335. }
  1336. return metallicRoughnessFactors;
  1337. };
  1338. /**
  1339. * Converts specular glossiness material properties to metallic roughness
  1340. * @param specularGlossiness interface with specular glossiness material properties
  1341. * @returns interface with metallic roughness material properties
  1342. */
  1343. _GLTFMaterial._ConvertSpecularGlossinessToMetallicRoughness = function (specularGlossiness) {
  1344. var diffusePerceivedBrightness = _GLTFMaterial._GetPerceivedBrightness(specularGlossiness.diffuseColor);
  1345. var specularPerceivedBrightness = _GLTFMaterial._GetPerceivedBrightness(specularGlossiness.specularColor);
  1346. var oneMinusSpecularStrength = 1 - _GLTFMaterial._GetMaxComponent(specularGlossiness.specularColor);
  1347. var metallic = _GLTFMaterial._SolveMetallic(diffusePerceivedBrightness, specularPerceivedBrightness, oneMinusSpecularStrength);
  1348. var baseColorFromDiffuse = specularGlossiness.diffuseColor.scale(oneMinusSpecularStrength / (1.0 - this._dielectricSpecular.r) / Math.max(1 - metallic, this._epsilon));
  1349. var baseColorFromSpecular = specularGlossiness.specularColor.subtract(this._dielectricSpecular.scale(1 - metallic)).scale(1 / Math.max(metallic, this._epsilon));
  1350. var baseColor = BABYLON.Color3.Lerp(baseColorFromDiffuse, baseColorFromSpecular, metallic * metallic);
  1351. baseColor = baseColor.clampToRef(0, 1, baseColor);
  1352. var metallicRoughness = {
  1353. baseColor: baseColor,
  1354. metallic: metallic,
  1355. roughness: 1 - specularGlossiness.glossiness
  1356. };
  1357. return metallicRoughness;
  1358. };
  1359. /**
  1360. * Calculates the surface reflectance, independent of lighting conditions
  1361. * @param color Color source to calculate brightness from
  1362. * @returns number representing the perceived brightness, or zero if color is undefined
  1363. */
  1364. _GLTFMaterial._GetPerceivedBrightness = function (color) {
  1365. if (color) {
  1366. return Math.sqrt(0.299 * color.r * color.r + 0.587 * color.g * color.g + 0.114 * color.b * color.b);
  1367. }
  1368. return 0;
  1369. };
  1370. /**
  1371. * Returns the maximum color component value
  1372. * @param color
  1373. * @returns maximum color component value, or zero if color is null or undefined
  1374. */
  1375. _GLTFMaterial._GetMaxComponent = function (color) {
  1376. if (color) {
  1377. return Math.max(color.r, Math.max(color.g, color.b));
  1378. }
  1379. return 0;
  1380. };
  1381. /**
  1382. * Convert a PBRMaterial (Metallic/Roughness) to Metallic Roughness factors
  1383. * @param babylonPBRMaterial BJS PBR Metallic Roughness Material
  1384. * @param mimeType mime type to use for the textures
  1385. * @param images array of glTF image interfaces
  1386. * @param textures array of glTF texture interfaces
  1387. * @param glTFPbrMetallicRoughness glTF PBR Metallic Roughness interface
  1388. * @param imageData map of image file name to data
  1389. * @param hasTextureCoords specifies if texture coordinates are present on the submesh to determine if textures should be applied
  1390. * @returns glTF PBR Metallic Roughness factors
  1391. */
  1392. _GLTFMaterial._ConvertMetalRoughFactorsToMetallicRoughness = function (babylonPBRMaterial, mimeType, images, textures, glTFPbrMetallicRoughness, imageData, hasTextureCoords) {
  1393. var metallicRoughness = {
  1394. baseColor: babylonPBRMaterial.albedoColor,
  1395. metallic: babylonPBRMaterial.metallic,
  1396. roughness: babylonPBRMaterial.roughness
  1397. };
  1398. if (hasTextureCoords) {
  1399. if (babylonPBRMaterial.albedoTexture) {
  1400. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMaterial.albedoTexture, mimeType, images, textures, imageData);
  1401. if (glTFTexture) {
  1402. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  1403. }
  1404. }
  1405. if (babylonPBRMaterial.metallicTexture) {
  1406. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMaterial.metallicTexture, mimeType, images, textures, imageData);
  1407. if (glTFTexture != null) {
  1408. glTFPbrMetallicRoughness.metallicRoughnessTexture = glTFTexture;
  1409. }
  1410. }
  1411. }
  1412. return metallicRoughness;
  1413. };
  1414. /**
  1415. * Convert a PBRMaterial (Specular/Glossiness) to Metallic Roughness factors
  1416. * @param babylonPBRMaterial BJS PBR Metallic Roughness Material
  1417. * @param mimeType mime type to use for the textures
  1418. * @param images array of glTF image interfaces
  1419. * @param textures array of glTF texture interfaces
  1420. * @param glTFPbrMetallicRoughness glTF PBR Metallic Roughness interface
  1421. * @param imageData map of image file name to data
  1422. * @param hasTextureCoords specifies if texture coordinates are present on the submesh to determine if textures should be applied
  1423. * @returns glTF PBR Metallic Roughness factors
  1424. */
  1425. _GLTFMaterial._ConvertSpecGlossFactorsToMetallicRoughness = function (babylonPBRMaterial, mimeType, images, textures, glTFPbrMetallicRoughness, imageData, hasTextureCoords) {
  1426. var specGloss = {
  1427. diffuseColor: babylonPBRMaterial.albedoColor || BABYLON.Color3.White(),
  1428. specularColor: babylonPBRMaterial.reflectivityColor || BABYLON.Color3.White(),
  1429. glossiness: babylonPBRMaterial.microSurface || 1,
  1430. };
  1431. if (babylonPBRMaterial.reflectivityTexture && !babylonPBRMaterial.useMicroSurfaceFromReflectivityMapAlpha) {
  1432. BABYLON.Tools.Error("_ConvertPBRMaterial: Glossiness values not included in the reflectivity texture currently not supported");
  1433. return null;
  1434. }
  1435. var metallicRoughnessFactors = this._ConvertSpecularGlossinessTexturesToMetallicRoughness(babylonPBRMaterial.albedoTexture, babylonPBRMaterial.reflectivityTexture, specGloss, mimeType);
  1436. if (!metallicRoughnessFactors) {
  1437. metallicRoughnessFactors = this._ConvertSpecularGlossinessToMetallicRoughness(specGloss);
  1438. }
  1439. else {
  1440. if (hasTextureCoords) {
  1441. if (metallicRoughnessFactors.baseColorTextureBase64) {
  1442. var glTFBaseColorTexture = _GLTFMaterial._GetTextureInfoFromBase64(metallicRoughnessFactors.baseColorTextureBase64, "bjsBaseColorTexture_" + (textures.length) + ".png", mimeType, images, textures, imageData);
  1443. if (glTFBaseColorTexture != null) {
  1444. glTFPbrMetallicRoughness.baseColorTexture = glTFBaseColorTexture;
  1445. }
  1446. }
  1447. if (metallicRoughnessFactors.metallicRoughnessTextureBase64) {
  1448. var glTFMRColorTexture = _GLTFMaterial._GetTextureInfoFromBase64(metallicRoughnessFactors.metallicRoughnessTextureBase64, "bjsMetallicRoughnessTexture_" + (textures.length) + ".png", mimeType, images, textures, imageData);
  1449. if (glTFMRColorTexture != null) {
  1450. glTFPbrMetallicRoughness.metallicRoughnessTexture = glTFMRColorTexture;
  1451. }
  1452. }
  1453. }
  1454. }
  1455. return metallicRoughnessFactors;
  1456. };
  1457. /**
  1458. * Converts a Babylon PBR Metallic Roughness Material to a glTF Material
  1459. * @param babylonPBRMaterial BJS PBR Metallic Roughness Material
  1460. * @param mimeType mime type to use for the textures
  1461. * @param images array of glTF image interfaces
  1462. * @param textures array of glTF texture interfaces
  1463. * @param materials array of glTF material interfaces
  1464. * @param imageData map of image file name to data
  1465. * @param hasTextureCoords specifies if texture coordinates are present on the submesh to determine if textures should be applied
  1466. */
  1467. _GLTFMaterial._ConvertPBRMaterial = function (babylonPBRMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords) {
  1468. var glTFPbrMetallicRoughness = {};
  1469. var metallicRoughness;
  1470. var glTFMaterial = {
  1471. name: babylonPBRMaterial.name
  1472. };
  1473. var useMetallicRoughness = babylonPBRMaterial.isMetallicWorkflow();
  1474. if (useMetallicRoughness) {
  1475. metallicRoughness = this._ConvertMetalRoughFactorsToMetallicRoughness(babylonPBRMaterial, mimeType, images, textures, glTFPbrMetallicRoughness, imageData, hasTextureCoords);
  1476. }
  1477. else {
  1478. metallicRoughness = this._ConvertSpecGlossFactorsToMetallicRoughness(babylonPBRMaterial, mimeType, images, textures, glTFPbrMetallicRoughness, imageData, hasTextureCoords);
  1479. }
  1480. if (metallicRoughness) {
  1481. if (!(this.FuzzyEquals(metallicRoughness.baseColor, BABYLON.Color3.White(), this._epsilon) && babylonPBRMaterial.alpha >= this._epsilon)) {
  1482. glTFPbrMetallicRoughness.baseColorFactor = [
  1483. metallicRoughness.baseColor.r,
  1484. metallicRoughness.baseColor.g,
  1485. metallicRoughness.baseColor.b,
  1486. babylonPBRMaterial.alpha
  1487. ];
  1488. }
  1489. if (metallicRoughness.metallic != null && metallicRoughness.metallic !== 1) {
  1490. glTFPbrMetallicRoughness.metallicFactor = metallicRoughness.metallic;
  1491. }
  1492. if (metallicRoughness.roughness != null && metallicRoughness.roughness !== 1) {
  1493. glTFPbrMetallicRoughness.roughnessFactor = metallicRoughness.roughness;
  1494. }
  1495. if (babylonPBRMaterial.backFaceCulling != null && !babylonPBRMaterial.backFaceCulling) {
  1496. if (!babylonPBRMaterial.twoSidedLighting) {
  1497. BABYLON.Tools.Warn(babylonPBRMaterial.name + ": Back-face culling enabled and two-sided lighting disabled is not supported in glTF.");
  1498. }
  1499. glTFMaterial.doubleSided = true;
  1500. }
  1501. if (hasTextureCoords) {
  1502. if (babylonPBRMaterial.bumpTexture) {
  1503. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMaterial.bumpTexture, mimeType, images, textures, imageData);
  1504. if (glTFTexture) {
  1505. glTFMaterial.normalTexture = glTFTexture;
  1506. }
  1507. }
  1508. if (babylonPBRMaterial.ambientTexture) {
  1509. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMaterial.ambientTexture, mimeType, images, textures, imageData);
  1510. if (glTFTexture) {
  1511. var occlusionTexture = {
  1512. index: glTFTexture.index
  1513. };
  1514. glTFMaterial.occlusionTexture = occlusionTexture;
  1515. if (babylonPBRMaterial.ambientTextureStrength) {
  1516. occlusionTexture.strength = babylonPBRMaterial.ambientTextureStrength;
  1517. }
  1518. }
  1519. }
  1520. if (babylonPBRMaterial.emissiveTexture) {
  1521. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMaterial.emissiveTexture, mimeType, images, textures, imageData);
  1522. if (glTFTexture != null) {
  1523. glTFMaterial.emissiveTexture = glTFTexture;
  1524. }
  1525. }
  1526. }
  1527. if (!this.FuzzyEquals(babylonPBRMaterial.emissiveColor, BABYLON.Color3.Black(), this._epsilon)) {
  1528. glTFMaterial.emissiveFactor = babylonPBRMaterial.emissiveColor.asArray();
  1529. }
  1530. if (babylonPBRMaterial.transparencyMode != null) {
  1531. var alphaMode = _GLTFMaterial._GetAlphaMode(babylonPBRMaterial);
  1532. if (alphaMode) {
  1533. if (alphaMode !== "OPAQUE" /* OPAQUE */) { //glTF defaults to opaque
  1534. glTFMaterial.alphaMode = alphaMode;
  1535. if (alphaMode === "BLEND" /* BLEND */) {
  1536. glTFMaterial.alphaCutoff = babylonPBRMaterial.alphaCutOff;
  1537. }
  1538. }
  1539. }
  1540. }
  1541. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  1542. materials.push(glTFMaterial);
  1543. }
  1544. };
  1545. _GLTFMaterial.GetPixelsFromTexture = function (babylonTexture) {
  1546. var pixels = babylonTexture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT ? babylonTexture.readPixels() : babylonTexture.readPixels();
  1547. return pixels;
  1548. };
  1549. /**
  1550. * Extracts a texture from a Babylon texture into file data and glTF data
  1551. * @param babylonTexture Babylon texture to extract
  1552. * @param mimeType Mime Type of the babylonTexture
  1553. * @param images Array of glTF images
  1554. * @param textures Array of glTF textures
  1555. * @param imageData map of image file name and data
  1556. * @return glTF texture info, or null if the texture format is not supported
  1557. */
  1558. _GLTFMaterial._ExportTexture = function (babylonTexture, mimeType, images, textures, imageData) {
  1559. var textureName = "texture_" + (textures.length - 1).toString();
  1560. var textureData = babylonTexture.getInternalTexture();
  1561. if (textureData != null) {
  1562. textureName = textureData.url || textureName;
  1563. }
  1564. textureName = BABYLON.Tools.GetFilename(textureName);
  1565. var baseFile = textureName.split('.')[0];
  1566. var extension = "";
  1567. if (mimeType === "image/jpeg" /* JPEG */) {
  1568. extension = ".jpg";
  1569. }
  1570. else if (mimeType === "image/png" /* PNG */) {
  1571. extension = ".png";
  1572. }
  1573. else {
  1574. BABYLON.Tools.Error("Unsupported mime type " + mimeType);
  1575. return null;
  1576. }
  1577. textureName = baseFile + extension;
  1578. var pixels = _GLTFMaterial.GetPixelsFromTexture(babylonTexture);
  1579. var size = babylonTexture.getSize();
  1580. var base64Data = this._CreateBase64FromCanvas(pixels, size.width, size.height, mimeType);
  1581. return this._GetTextureInfoFromBase64(base64Data, textureName, mimeType, images, textures, imageData);
  1582. };
  1583. /**
  1584. * Builds a texture from base64 string
  1585. * @param base64Texture base64 texture string
  1586. * @param textureName Name to use for the texture
  1587. * @param mimeType image mime type for the texture
  1588. * @param images array of images
  1589. * @param textures array of textures
  1590. * @param imageData map of image data
  1591. * @returns glTF texture info, or null if the texture format is not supported
  1592. */
  1593. _GLTFMaterial._GetTextureInfoFromBase64 = function (base64Texture, textureName, mimeType, images, textures, imageData) {
  1594. var textureInfo = null;
  1595. var glTFTexture = {
  1596. source: images.length
  1597. };
  1598. var binStr = atob(base64Texture.split(',')[1]);
  1599. var arrBuff = new ArrayBuffer(binStr.length);
  1600. var arr = new Uint8Array(arrBuff);
  1601. for (var i = 0, length_1 = binStr.length; i < length_1; ++i) {
  1602. arr[i] = binStr.charCodeAt(i);
  1603. }
  1604. var imageValues = { data: arr, mimeType: mimeType };
  1605. imageData[textureName] = imageValues;
  1606. if (mimeType === "image/jpeg" /* JPEG */ || mimeType === "image/png" /* PNG */) {
  1607. var glTFImage = {
  1608. uri: textureName
  1609. };
  1610. var foundIndex = -1;
  1611. for (var i = 0; i < images.length; ++i) {
  1612. if (images[i].uri === textureName) {
  1613. foundIndex = i;
  1614. break;
  1615. }
  1616. }
  1617. if (foundIndex === -1) {
  1618. images.push(glTFImage);
  1619. glTFTexture.source = images.length - 1;
  1620. textures.push({
  1621. source: images.length - 1
  1622. });
  1623. textureInfo = {
  1624. index: images.length - 1
  1625. };
  1626. }
  1627. else {
  1628. glTFTexture.source = foundIndex;
  1629. textureInfo = {
  1630. index: foundIndex
  1631. };
  1632. }
  1633. }
  1634. return textureInfo;
  1635. };
  1636. /**
  1637. * Represents the dielectric specular values for R, G and B
  1638. */
  1639. _GLTFMaterial._dielectricSpecular = new BABYLON.Color3(0.04, 0.04, 0.04);
  1640. /**
  1641. * Allows the maximum specular power to be defined for material calculations
  1642. */
  1643. _GLTFMaterial._maxSpecularPower = 1024;
  1644. /**
  1645. * Numeric tolerance value
  1646. */
  1647. _GLTFMaterial._epsilon = 1e-6;
  1648. return _GLTFMaterial;
  1649. }());
  1650. GLTF2._GLTFMaterial = _GLTFMaterial;
  1651. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1652. })(BABYLON || (BABYLON = {}));
  1653. //# sourceMappingURL=babylon.glTFMaterial.js.map
  1654. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  1655. var BABYLON;
  1656. (function (BABYLON) {
  1657. var GLTF2;
  1658. (function (GLTF2) {
  1659. /**
  1660. * @hidden
  1661. * Enum for handling in tangent and out tangent.
  1662. */
  1663. var _TangentType;
  1664. (function (_TangentType) {
  1665. /**
  1666. * Specifies that input tangents are used.
  1667. */
  1668. _TangentType[_TangentType["INTANGENT"] = 0] = "INTANGENT";
  1669. /**
  1670. * Specifies that output tangents are used.
  1671. */
  1672. _TangentType[_TangentType["OUTTANGENT"] = 1] = "OUTTANGENT";
  1673. })(_TangentType || (_TangentType = {}));
  1674. /**
  1675. * @hidden
  1676. * Utility class for generating glTF animation data from BabylonJS.
  1677. */
  1678. var _GLTFAnimation = /** @class */ (function () {
  1679. function _GLTFAnimation() {
  1680. }
  1681. /**
  1682. *
  1683. * Creates glTF channel animation from BabylonJS animation.
  1684. * @param babylonMesh - BabylonJS mesh.
  1685. * @param animation - animation.
  1686. * @param animationChannelTargetPath - The target animation channel.
  1687. * @param convertToRightHandedSystem - Specifies if the values should be converted to right-handed.
  1688. * @param useQuaternion - Specifies if quaternions are used.
  1689. * @returns nullable IAnimationData
  1690. */
  1691. _GLTFAnimation._CreateNodeAnimation = function (babylonMesh, animation, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion, animationSampleRate) {
  1692. var inputs = [];
  1693. var outputs = [];
  1694. var keyFrames = animation.getKeys();
  1695. var minMaxKeyFrames = _GLTFAnimation.calculateMinMaxKeyFrames(keyFrames);
  1696. var interpolationOrBake = _GLTFAnimation._DeduceInterpolation(keyFrames, animationChannelTargetPath, useQuaternion);
  1697. var frameDelta = minMaxKeyFrames.max - minMaxKeyFrames.min;
  1698. var interpolation = interpolationOrBake.interpolationType;
  1699. var shouldBakeAnimation = interpolationOrBake.shouldBakeAnimation;
  1700. if (shouldBakeAnimation) {
  1701. _GLTFAnimation._CreateBakedAnimation(babylonMesh, animation, animationChannelTargetPath, minMaxKeyFrames.min, minMaxKeyFrames.max, animation.framePerSecond, animationSampleRate, inputs, outputs, minMaxKeyFrames, convertToRightHandedSystem, useQuaternion);
  1702. }
  1703. else {
  1704. if (interpolation === "LINEAR" /* LINEAR */ || interpolation === "STEP" /* STEP */) {
  1705. _GLTFAnimation._CreateLinearOrStepAnimation(babylonMesh, animation, animationChannelTargetPath, frameDelta, inputs, outputs, convertToRightHandedSystem, useQuaternion);
  1706. }
  1707. else if (interpolation === "CUBICSPLINE" /* CUBICSPLINE */) {
  1708. _GLTFAnimation._CreateCubicSplineAnimation(babylonMesh, animation, animationChannelTargetPath, frameDelta, inputs, outputs, convertToRightHandedSystem, useQuaternion);
  1709. }
  1710. else {
  1711. _GLTFAnimation._CreateBakedAnimation(babylonMesh, animation, animationChannelTargetPath, minMaxKeyFrames.min, minMaxKeyFrames.max, animation.framePerSecond, animationSampleRate, inputs, outputs, minMaxKeyFrames, convertToRightHandedSystem, useQuaternion);
  1712. }
  1713. }
  1714. if (inputs.length && outputs.length) {
  1715. var result = {
  1716. inputs: inputs,
  1717. outputs: outputs,
  1718. samplerInterpolation: interpolation,
  1719. inputsMin: shouldBakeAnimation ? minMaxKeyFrames.min : BABYLON.Tools.FloatRound(minMaxKeyFrames.min / animation.framePerSecond),
  1720. inputsMax: shouldBakeAnimation ? minMaxKeyFrames.max : BABYLON.Tools.FloatRound(minMaxKeyFrames.max / animation.framePerSecond)
  1721. };
  1722. return result;
  1723. }
  1724. return null;
  1725. };
  1726. _GLTFAnimation._DeduceAnimationInfo = function (animation) {
  1727. var animationChannelTargetPath = null;
  1728. var dataAccessorType = "VEC3" /* VEC3 */;
  1729. var useQuaternion = false;
  1730. var property = animation.targetProperty.split('.');
  1731. switch (property[0]) {
  1732. case 'scaling': {
  1733. animationChannelTargetPath = "scale" /* SCALE */;
  1734. break;
  1735. }
  1736. case 'position': {
  1737. animationChannelTargetPath = "translation" /* TRANSLATION */;
  1738. break;
  1739. }
  1740. case 'rotation': {
  1741. dataAccessorType = "VEC4" /* VEC4 */;
  1742. animationChannelTargetPath = "rotation" /* ROTATION */;
  1743. break;
  1744. }
  1745. case 'rotationQuaternion': {
  1746. dataAccessorType = "VEC4" /* VEC4 */;
  1747. useQuaternion = true;
  1748. animationChannelTargetPath = "rotation" /* ROTATION */;
  1749. break;
  1750. }
  1751. default: {
  1752. BABYLON.Tools.Error("Unsupported animatable property " + property[0]);
  1753. }
  1754. }
  1755. if (animationChannelTargetPath) {
  1756. return { animationChannelTargetPath: animationChannelTargetPath, dataAccessorType: dataAccessorType, useQuaternion: useQuaternion };
  1757. }
  1758. else {
  1759. BABYLON.Tools.Error('animation channel target path and data accessor type could be deduced');
  1760. }
  1761. return null;
  1762. };
  1763. /**
  1764. *
  1765. * @param babylonMesh
  1766. * @param runtimeGLTFAnimation
  1767. * @param idleGLTFAnimations
  1768. * @param nodeMap
  1769. * @param nodes
  1770. * @param binaryWriter
  1771. * @param bufferViews
  1772. * @param accessors
  1773. * @param convertToRightHandedSystem
  1774. */
  1775. _GLTFAnimation._CreateNodeAnimationFromMeshAnimations = function (babylonMesh, runtimeGLTFAnimation, idleGLTFAnimations, nodeMap, nodes, binaryWriter, bufferViews, accessors, convertToRightHandedSystem, animationSampleRate) {
  1776. var glTFAnimation;
  1777. if (babylonMesh.animations) {
  1778. babylonMesh.animations.forEach(function (animation) {
  1779. var animationInfo = _GLTFAnimation._DeduceAnimationInfo(animation);
  1780. if (animationInfo) {
  1781. glTFAnimation = {
  1782. name: animation.name,
  1783. samplers: [],
  1784. channels: []
  1785. };
  1786. _GLTFAnimation.AddAnimation("" + animation.name, animation.hasRunningRuntimeAnimations ? runtimeGLTFAnimation : glTFAnimation, babylonMesh, animation, animationInfo.dataAccessorType, animationInfo.animationChannelTargetPath, nodeMap, binaryWriter, bufferViews, accessors, convertToRightHandedSystem, animationInfo.useQuaternion, animationSampleRate);
  1787. if (glTFAnimation.samplers.length && glTFAnimation.channels.length) {
  1788. idleGLTFAnimations.push(glTFAnimation);
  1789. }
  1790. }
  1791. });
  1792. }
  1793. };
  1794. /**
  1795. *
  1796. * @param babylonScene
  1797. * @param glTFAnimations
  1798. * @param nodeMap
  1799. * @param nodes
  1800. * @param binaryWriter
  1801. * @param bufferViews
  1802. * @param accessors
  1803. * @param convertToRightHandedSystem
  1804. */
  1805. _GLTFAnimation._CreateNodeAnimationFromAnimationGroups = function (babylonScene, glTFAnimations, nodeMap, nodes, binaryWriter, bufferViews, accessors, convertToRightHandedSystem, animationSampleRate) {
  1806. var glTFAnimation;
  1807. if (babylonScene.animationGroups) {
  1808. var animationGroups = babylonScene.animationGroups;
  1809. animationGroups.forEach(function (animationGroup) {
  1810. glTFAnimation = {
  1811. name: animationGroup.name,
  1812. channels: [],
  1813. samplers: []
  1814. };
  1815. animationGroup.targetedAnimations.forEach(function (targetAnimation) {
  1816. var target = targetAnimation.target;
  1817. var animation = targetAnimation.animation;
  1818. if (target instanceof BABYLON.Mesh) {
  1819. var animationInfo = _GLTFAnimation._DeduceAnimationInfo(targetAnimation.animation);
  1820. if (animationInfo) {
  1821. var babylonMesh = target;
  1822. _GLTFAnimation.AddAnimation("" + animation.name, glTFAnimation, babylonMesh, animation, animationInfo.dataAccessorType, animationInfo.animationChannelTargetPath, nodeMap, binaryWriter, bufferViews, accessors, convertToRightHandedSystem, animationInfo.useQuaternion, animationSampleRate);
  1823. }
  1824. }
  1825. });
  1826. if (glTFAnimation.channels.length && glTFAnimation.samplers.length) {
  1827. glTFAnimations.push(glTFAnimation);
  1828. }
  1829. });
  1830. }
  1831. };
  1832. _GLTFAnimation.AddAnimation = function (name, glTFAnimation, babylonMesh, animation, dataAccessorType, animationChannelTargetPath, nodeMap, binaryWriter, bufferViews, accessors, convertToRightHandedSystem, useQuaternion, animationSampleRate) {
  1833. var animationData = _GLTFAnimation._CreateNodeAnimation(babylonMesh, animation, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion, animationSampleRate);
  1834. var bufferView;
  1835. var accessor;
  1836. var keyframeAccessorIndex;
  1837. var dataAccessorIndex;
  1838. var outputLength;
  1839. var animationSampler;
  1840. var animationChannel;
  1841. if (animationData) {
  1842. var nodeIndex = nodeMap[babylonMesh.uniqueId];
  1843. // Creates buffer view and accessor for key frames.
  1844. var byteLength = animationData.inputs.length * 4;
  1845. bufferView = GLTF2._GLTFUtilities.CreateBufferView(0, binaryWriter.getByteOffset(), byteLength, undefined, name + " keyframe data view");
  1846. bufferViews.push(bufferView);
  1847. animationData.inputs.forEach(function (input) {
  1848. binaryWriter.setFloat32(input);
  1849. });
  1850. accessor = GLTF2._GLTFUtilities.CreateAccessor(bufferViews.length - 1, name + " keyframes", "SCALAR" /* SCALAR */, 5126 /* FLOAT */, animationData.inputs.length, null, [animationData.inputsMin], [animationData.inputsMax]);
  1851. accessors.push(accessor);
  1852. keyframeAccessorIndex = accessors.length - 1;
  1853. // create bufferview and accessor for keyed values.
  1854. outputLength = animationData.outputs.length;
  1855. byteLength = dataAccessorType === "VEC3" /* VEC3 */ ? animationData.outputs.length * 12 : animationData.outputs.length * 16;
  1856. // check for in and out tangents
  1857. bufferView = GLTF2._GLTFUtilities.CreateBufferView(0, binaryWriter.getByteOffset(), byteLength, undefined, name + " data view");
  1858. bufferViews.push(bufferView);
  1859. animationData.outputs.forEach(function (output) {
  1860. output.forEach(function (entry) {
  1861. binaryWriter.setFloat32(entry);
  1862. });
  1863. });
  1864. accessor = GLTF2._GLTFUtilities.CreateAccessor(bufferViews.length - 1, name + " data", dataAccessorType, 5126 /* FLOAT */, outputLength, null, null, null);
  1865. accessors.push(accessor);
  1866. dataAccessorIndex = accessors.length - 1;
  1867. // create sampler
  1868. animationSampler = {
  1869. interpolation: animationData.samplerInterpolation,
  1870. input: keyframeAccessorIndex,
  1871. output: dataAccessorIndex
  1872. };
  1873. glTFAnimation.samplers.push(animationSampler);
  1874. // create channel
  1875. animationChannel = {
  1876. sampler: glTFAnimation.samplers.length - 1,
  1877. target: {
  1878. node: nodeIndex,
  1879. path: animationChannelTargetPath
  1880. }
  1881. };
  1882. glTFAnimation.channels.push(animationChannel);
  1883. }
  1884. };
  1885. /**
  1886. * Create a baked animation
  1887. * @param babylonMesh BabylonJS mesh
  1888. * @param animation BabylonJS animation corresponding to the BabylonJS mesh
  1889. * @param animationChannelTargetPath animation target channel
  1890. * @param minFrame minimum animation frame
  1891. * @param maxFrame maximum animation frame
  1892. * @param fps frames per second of the animation
  1893. * @param inputs input key frames of the animation
  1894. * @param outputs output key frame data of the animation
  1895. * @param convertToRightHandedSystem converts the values to right-handed
  1896. * @param useQuaternion specifies if quaternions should be used
  1897. */
  1898. _GLTFAnimation._CreateBakedAnimation = function (babylonMesh, animation, animationChannelTargetPath, minFrame, maxFrame, fps, sampleRate, inputs, outputs, minMaxFrames, convertToRightHandedSystem, useQuaternion) {
  1899. var value;
  1900. var quaternionCache = BABYLON.Quaternion.Identity();
  1901. var previousTime = null;
  1902. var time;
  1903. var maxUsedFrame = null;
  1904. var currKeyFrame = null;
  1905. var nextKeyFrame = null;
  1906. var prevKeyFrame = null;
  1907. var endFrame = null;
  1908. minMaxFrames.min = BABYLON.Tools.FloatRound(minFrame / fps);
  1909. var keyFrames = animation.getKeys();
  1910. for (var i = 0, length_1 = keyFrames.length; i < length_1; ++i) {
  1911. endFrame = null;
  1912. currKeyFrame = keyFrames[i];
  1913. if (i + 1 < length_1) {
  1914. nextKeyFrame = keyFrames[i + 1];
  1915. if (currKeyFrame.value.equals(nextKeyFrame.value)) {
  1916. if (i === 0) { // set the first frame to itself
  1917. endFrame = currKeyFrame.frame;
  1918. }
  1919. else {
  1920. continue;
  1921. }
  1922. }
  1923. else {
  1924. endFrame = nextKeyFrame.frame;
  1925. }
  1926. }
  1927. else {
  1928. // at the last key frame
  1929. prevKeyFrame = keyFrames[i - 1];
  1930. if (currKeyFrame.value.equals(prevKeyFrame.value)) {
  1931. continue;
  1932. }
  1933. else {
  1934. endFrame = maxFrame;
  1935. }
  1936. }
  1937. if (endFrame) {
  1938. for (var f = currKeyFrame.frame; f <= endFrame; f += sampleRate) {
  1939. time = BABYLON.Tools.FloatRound(f / fps);
  1940. if (time === previousTime) {
  1941. continue;
  1942. }
  1943. previousTime = time;
  1944. maxUsedFrame = time;
  1945. value = animation._interpolate(f, 0, undefined, animation.loopMode);
  1946. _GLTFAnimation._SetInterpolatedValue(babylonMesh, value, time, animation, animationChannelTargetPath, quaternionCache, inputs, outputs, convertToRightHandedSystem, useQuaternion);
  1947. }
  1948. }
  1949. }
  1950. if (maxUsedFrame) {
  1951. minMaxFrames.max = maxUsedFrame;
  1952. }
  1953. };
  1954. _GLTFAnimation._ConvertFactorToVector3OrQuaternion = function (factor, babylonMesh, animation, animationType, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion) {
  1955. var property;
  1956. var componentName;
  1957. var value = null;
  1958. var basePositionRotationOrScale = _GLTFAnimation._GetBasePositionRotationOrScale(babylonMesh, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion);
  1959. if (animationType === BABYLON.Animation.ANIMATIONTYPE_FLOAT) { // handles single component x, y, z or w component animation by using a base property and animating over a component.
  1960. property = animation.targetProperty.split('.');
  1961. componentName = property ? property[1] : ''; // x, y, or z component
  1962. value = useQuaternion ? BABYLON.Quaternion.FromArray(basePositionRotationOrScale).normalize() : BABYLON.Vector3.FromArray(basePositionRotationOrScale);
  1963. switch (componentName) {
  1964. case 'x':
  1965. case 'y': {
  1966. value[componentName] = (convertToRightHandedSystem && useQuaternion) ? -factor : factor;
  1967. break;
  1968. }
  1969. case 'z': {
  1970. value[componentName] = (convertToRightHandedSystem && !useQuaternion && !(animationChannelTargetPath === "scale" /* SCALE */)) ? -factor : factor;
  1971. break;
  1972. }
  1973. case 'w': {
  1974. value.w = factor;
  1975. break;
  1976. }
  1977. default: {
  1978. BABYLON.Tools.Error("glTFAnimation: Unsupported component type \"" + componentName + "\" for scale animation!");
  1979. }
  1980. }
  1981. }
  1982. return value;
  1983. };
  1984. _GLTFAnimation._SetInterpolatedValue = function (babylonMesh, value, time, animation, animationChannelTargetPath, quaternionCache, inputs, outputs, convertToRightHandedSystem, useQuaternion) {
  1985. var animationType = animation.dataType;
  1986. var cacheValue;
  1987. inputs.push(time);
  1988. if (typeof value === "number") {
  1989. value = this._ConvertFactorToVector3OrQuaternion(value, babylonMesh, animation, animationType, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion);
  1990. }
  1991. if (value) {
  1992. if (animationChannelTargetPath === "rotation" /* ROTATION */) {
  1993. if (useQuaternion) {
  1994. quaternionCache = value;
  1995. }
  1996. else {
  1997. cacheValue = value;
  1998. BABYLON.Quaternion.RotationYawPitchRollToRef(cacheValue.y, cacheValue.x, cacheValue.z, quaternionCache);
  1999. }
  2000. if (convertToRightHandedSystem) {
  2001. quaternionCache.x *= -1;
  2002. quaternionCache.y *= -1;
  2003. outputs.push(quaternionCache.asArray());
  2004. }
  2005. }
  2006. else {
  2007. cacheValue = value;
  2008. if (convertToRightHandedSystem && (animationChannelTargetPath !== "scale" /* SCALE */)) {
  2009. cacheValue.z *= -1;
  2010. }
  2011. outputs.push(cacheValue.asArray());
  2012. }
  2013. }
  2014. };
  2015. /**
  2016. * Creates linear animation from the animation key frames
  2017. * @param babylonMesh BabylonJS mesh
  2018. * @param animation BabylonJS animation
  2019. * @param animationChannelTargetPath The target animation channel
  2020. * @param frameDelta The difference between the last and first frame of the animation
  2021. * @param inputs Array to store the key frame times
  2022. * @param outputs Array to store the key frame data
  2023. * @param convertToRightHandedSystem Specifies if the position data should be converted to right handed
  2024. * @param useQuaternion Specifies if quaternions are used in the animation
  2025. */
  2026. _GLTFAnimation._CreateLinearOrStepAnimation = function (babylonMesh, animation, animationChannelTargetPath, frameDelta, inputs, outputs, convertToRightHandedSystem, useQuaternion) {
  2027. animation.getKeys().forEach(function (keyFrame) {
  2028. inputs.push(keyFrame.frame / animation.framePerSecond); // keyframes in seconds.
  2029. _GLTFAnimation._AddKeyframeValue(keyFrame, animation, outputs, animationChannelTargetPath, babylonMesh, convertToRightHandedSystem, useQuaternion);
  2030. });
  2031. };
  2032. /**
  2033. * Creates cubic spline animation from the animation key frames
  2034. * @param babylonMesh BabylonJS mesh
  2035. * @param animation BabylonJS animation
  2036. * @param animationChannelTargetPath The target animation channel
  2037. * @param frameDelta The difference between the last and first frame of the animation
  2038. * @param inputs Array to store the key frame times
  2039. * @param outputs Array to store the key frame data
  2040. * @param convertToRightHandedSystem Specifies if the position data should be converted to right handed
  2041. * @param useQuaternion Specifies if quaternions are used in the animation
  2042. */
  2043. _GLTFAnimation._CreateCubicSplineAnimation = function (babylonMesh, animation, animationChannelTargetPath, frameDelta, inputs, outputs, convertToRightHandedSystem, useQuaternion) {
  2044. animation.getKeys().forEach(function (keyFrame) {
  2045. inputs.push(keyFrame.frame / animation.framePerSecond); // keyframes in seconds.
  2046. _GLTFAnimation.AddSplineTangent(_TangentType.INTANGENT, outputs, animationChannelTargetPath, "CUBICSPLINE" /* CUBICSPLINE */, keyFrame, frameDelta, useQuaternion, convertToRightHandedSystem);
  2047. _GLTFAnimation._AddKeyframeValue(keyFrame, animation, outputs, animationChannelTargetPath, babylonMesh, convertToRightHandedSystem, useQuaternion);
  2048. _GLTFAnimation.AddSplineTangent(_TangentType.OUTTANGENT, outputs, animationChannelTargetPath, "CUBICSPLINE" /* CUBICSPLINE */, keyFrame, frameDelta, useQuaternion, convertToRightHandedSystem);
  2049. });
  2050. };
  2051. _GLTFAnimation._GetBasePositionRotationOrScale = function (babylonMesh, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion) {
  2052. var basePositionRotationOrScale;
  2053. if (animationChannelTargetPath === "rotation" /* ROTATION */) {
  2054. if (useQuaternion) {
  2055. if (babylonMesh.rotationQuaternion) {
  2056. basePositionRotationOrScale = babylonMesh.rotationQuaternion.asArray();
  2057. if (convertToRightHandedSystem) {
  2058. basePositionRotationOrScale[0] *= -1;
  2059. basePositionRotationOrScale[1] *= -1;
  2060. }
  2061. }
  2062. else {
  2063. basePositionRotationOrScale = BABYLON.Quaternion.Identity().asArray();
  2064. }
  2065. }
  2066. else {
  2067. basePositionRotationOrScale = babylonMesh.rotation.asArray();
  2068. basePositionRotationOrScale[2] *= -1;
  2069. }
  2070. }
  2071. else if (animationChannelTargetPath === "translation" /* TRANSLATION */) {
  2072. basePositionRotationOrScale = babylonMesh.position.asArray();
  2073. if (convertToRightHandedSystem) {
  2074. basePositionRotationOrScale[2] *= -1;
  2075. }
  2076. }
  2077. else { // scale
  2078. basePositionRotationOrScale = babylonMesh.scaling.asArray();
  2079. }
  2080. return basePositionRotationOrScale;
  2081. };
  2082. /**
  2083. * Adds a key frame value
  2084. * @param keyFrame
  2085. * @param animation
  2086. * @param outputs
  2087. * @param animationChannelTargetPath
  2088. * @param basePositionRotationOrScale
  2089. * @param convertToRightHandedSystem
  2090. * @param useQuaternion
  2091. */
  2092. _GLTFAnimation._AddKeyframeValue = function (keyFrame, animation, outputs, animationChannelTargetPath, babylonMesh, convertToRightHandedSystem, useQuaternion) {
  2093. var value;
  2094. var newPositionRotationOrScale;
  2095. var animationType = animation.dataType;
  2096. if (animationType === BABYLON.Animation.ANIMATIONTYPE_VECTOR3) {
  2097. value = keyFrame.value.asArray();
  2098. if (convertToRightHandedSystem && !(animationChannelTargetPath === "scale" /* SCALE */)) {
  2099. value[2] *= -1;
  2100. }
  2101. if (animationChannelTargetPath === "rotation" /* ROTATION */) {
  2102. outputs.push(BABYLON.Vector3.FromArray(value).toQuaternion().asArray());
  2103. }
  2104. else {
  2105. outputs.push(value); // scale or position vector.
  2106. }
  2107. }
  2108. else if (animationType === BABYLON.Animation.ANIMATIONTYPE_FLOAT) { // handles single component x, y, z or w component animation by using a base property and animating over a component.
  2109. newPositionRotationOrScale = this._ConvertFactorToVector3OrQuaternion(keyFrame.value, babylonMesh, animation, animationType, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion);
  2110. if (newPositionRotationOrScale) {
  2111. if (animationChannelTargetPath === "rotation" /* ROTATION */) {
  2112. useQuaternion ? outputs.push(newPositionRotationOrScale.normalize().asArray()) : outputs.push(newPositionRotationOrScale.toQuaternion().normalize().asArray());
  2113. }
  2114. else {
  2115. outputs.push(newPositionRotationOrScale.asArray());
  2116. }
  2117. }
  2118. }
  2119. else if (animationType === BABYLON.Animation.ANIMATIONTYPE_QUATERNION) {
  2120. value = keyFrame.value.normalize().asArray();
  2121. if (convertToRightHandedSystem) {
  2122. value[0] *= -1;
  2123. value[1] *= -1;
  2124. }
  2125. outputs.push(value);
  2126. }
  2127. else {
  2128. BABYLON.Tools.Error('glTFAnimation: Unsupported key frame values for animation!');
  2129. }
  2130. };
  2131. _GLTFAnimation._DeduceInterpolation = function (keyFrames, animationChannelTargetPath, useQuaternion) {
  2132. var interpolationType;
  2133. var shouldBakeAnimation = false;
  2134. var key;
  2135. if (animationChannelTargetPath === "rotation" /* ROTATION */ && !useQuaternion) {
  2136. return { interpolationType: "LINEAR" /* LINEAR */, shouldBakeAnimation: true };
  2137. }
  2138. for (var i = 0, length_2 = keyFrames.length; i < length_2; ++i) {
  2139. key = keyFrames[i];
  2140. if (key.inTangent || key.outTangent) {
  2141. if (interpolationType) {
  2142. if (interpolationType !== "CUBICSPLINE" /* CUBICSPLINE */) {
  2143. interpolationType = "LINEAR" /* LINEAR */;
  2144. shouldBakeAnimation = true;
  2145. break;
  2146. }
  2147. }
  2148. else {
  2149. interpolationType = "CUBICSPLINE" /* CUBICSPLINE */;
  2150. }
  2151. }
  2152. else {
  2153. if (interpolationType) {
  2154. if (interpolationType === "CUBICSPLINE" /* CUBICSPLINE */ ||
  2155. (key.interpolation && (key.interpolation === BABYLON.AnimationKeyInterpolation.STEP) && interpolationType !== "STEP" /* STEP */)) {
  2156. interpolationType = "LINEAR" /* LINEAR */;
  2157. shouldBakeAnimation = true;
  2158. break;
  2159. }
  2160. }
  2161. else {
  2162. if (key.interpolation && (key.interpolation === BABYLON.AnimationKeyInterpolation.STEP)) {
  2163. interpolationType = "STEP" /* STEP */;
  2164. }
  2165. else {
  2166. interpolationType = "LINEAR" /* LINEAR */;
  2167. }
  2168. }
  2169. }
  2170. }
  2171. if (!interpolationType) {
  2172. interpolationType = "LINEAR" /* LINEAR */;
  2173. }
  2174. return { interpolationType: interpolationType, shouldBakeAnimation: shouldBakeAnimation };
  2175. };
  2176. /**
  2177. * Adds an input tangent or output tangent to the output data
  2178. * If an input tangent or output tangent is missing, it uses the zero vector or zero quaternion
  2179. * @param tangentType Specifies which type of tangent to handle (inTangent or outTangent)
  2180. * @param outputs The animation data by keyframe
  2181. * @param animationChannelTargetPath The target animation channel
  2182. * @param interpolation The interpolation type
  2183. * @param keyFrame The key frame with the animation data
  2184. * @param frameDelta Time difference between two frames used to scale the tangent by the frame delta
  2185. * @param useQuaternion Specifies if quaternions are used
  2186. * @param convertToRightHandedSystem Specifies if the values should be converted to right-handed
  2187. */
  2188. _GLTFAnimation.AddSplineTangent = function (tangentType, outputs, animationChannelTargetPath, interpolation, keyFrame, frameDelta, useQuaternion, convertToRightHandedSystem) {
  2189. var tangent;
  2190. var tangentValue = tangentType === _TangentType.INTANGENT ? keyFrame.inTangent : keyFrame.outTangent;
  2191. if (interpolation === "CUBICSPLINE" /* CUBICSPLINE */) {
  2192. if (animationChannelTargetPath === "rotation" /* ROTATION */) {
  2193. if (tangentValue) {
  2194. tangent = useQuaternion ? tangentValue.scale(frameDelta).asArray() : tangentValue.scale(frameDelta).toQuaternion().asArray();
  2195. if (convertToRightHandedSystem) {
  2196. tangent[0] *= -1;
  2197. tangent[1] *= -1;
  2198. }
  2199. }
  2200. else {
  2201. tangent = [0, 0, 0, 0];
  2202. }
  2203. }
  2204. else {
  2205. if (tangentValue) {
  2206. tangent = tangentValue.scale(frameDelta).asArray();
  2207. if (convertToRightHandedSystem) {
  2208. tangent[2] *= -1;
  2209. }
  2210. }
  2211. else {
  2212. tangent = [0, 0, 0];
  2213. }
  2214. }
  2215. outputs.push(tangent);
  2216. }
  2217. };
  2218. /**
  2219. * Get the minimum and maximum key frames' frame values
  2220. * @param keyFrames animation key frames
  2221. * @returns the minimum and maximum key frame value
  2222. */
  2223. _GLTFAnimation.calculateMinMaxKeyFrames = function (keyFrames) {
  2224. var min = Infinity;
  2225. var max = -Infinity;
  2226. keyFrames.forEach(function (keyFrame) {
  2227. min = Math.min(min, keyFrame.frame);
  2228. max = Math.max(max, keyFrame.frame);
  2229. });
  2230. return { min: min, max: max };
  2231. };
  2232. return _GLTFAnimation;
  2233. }());
  2234. GLTF2._GLTFAnimation = _GLTFAnimation;
  2235. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2236. })(BABYLON || (BABYLON = {}));
  2237. //# sourceMappingURL=babylon.glTFAnimation.js.map
  2238. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  2239. var BABYLON;
  2240. (function (BABYLON) {
  2241. var GLTF2;
  2242. (function (GLTF2) {
  2243. /**
  2244. * @hidden
  2245. */
  2246. var _GLTFUtilities = /** @class */ (function () {
  2247. function _GLTFUtilities() {
  2248. }
  2249. /**
  2250. * Creates a buffer view based on the supplied arguments
  2251. * @param bufferIndex index value of the specified buffer
  2252. * @param byteOffset byte offset value
  2253. * @param byteLength byte length of the bufferView
  2254. * @param byteStride byte distance between conequential elements
  2255. * @param name name of the buffer view
  2256. * @returns bufferView for glTF
  2257. */
  2258. _GLTFUtilities.CreateBufferView = function (bufferIndex, byteOffset, byteLength, byteStride, name) {
  2259. var bufferview = { buffer: bufferIndex, byteLength: byteLength };
  2260. if (byteOffset) {
  2261. bufferview.byteOffset = byteOffset;
  2262. }
  2263. if (name) {
  2264. bufferview.name = name;
  2265. }
  2266. if (byteStride) {
  2267. bufferview.byteStride = byteStride;
  2268. }
  2269. return bufferview;
  2270. };
  2271. /**
  2272. * Creates an accessor based on the supplied arguments
  2273. * @param bufferviewIndex The index of the bufferview referenced by this accessor
  2274. * @param name The name of the accessor
  2275. * @param type The type of the accessor
  2276. * @param componentType The datatype of components in the attribute
  2277. * @param count The number of attributes referenced by this accessor
  2278. * @param byteOffset The offset relative to the start of the bufferView in bytes
  2279. * @param min Minimum value of each component in this attribute
  2280. * @param max Maximum value of each component in this attribute
  2281. * @returns accessor for glTF
  2282. */
  2283. _GLTFUtilities.CreateAccessor = function (bufferviewIndex, name, type, componentType, count, byteOffset, min, max) {
  2284. var accessor = { name: name, bufferView: bufferviewIndex, componentType: componentType, count: count, type: type };
  2285. if (min) {
  2286. accessor.min = min;
  2287. }
  2288. if (max) {
  2289. accessor.max = max;
  2290. }
  2291. if (byteOffset) {
  2292. accessor.byteOffset = byteOffset;
  2293. }
  2294. return accessor;
  2295. };
  2296. /**
  2297. * Calculates the minimum and maximum values of an array of position floats
  2298. * @param positions Positions array of a mesh
  2299. * @param vertexStart Starting vertex offset to calculate min and max values
  2300. * @param vertexCount Number of vertices to check for min and max values
  2301. * @returns min number array and max number array
  2302. */
  2303. _GLTFUtilities.CalculateMinMaxPositions = function (positions, vertexStart, vertexCount, convertToRightHandedSystem) {
  2304. var min = [Infinity, Infinity, Infinity];
  2305. var max = [-Infinity, -Infinity, -Infinity];
  2306. var positionStrideSize = 3;
  2307. var indexOffset;
  2308. var position;
  2309. var vector;
  2310. if (vertexCount) {
  2311. for (var i = vertexStart, length_1 = vertexStart + vertexCount; i < length_1; ++i) {
  2312. indexOffset = positionStrideSize * i;
  2313. position = BABYLON.Vector3.FromArray(positions, indexOffset);
  2314. if (convertToRightHandedSystem) {
  2315. _GLTFUtilities.GetRightHandedVector3FromRef(position);
  2316. }
  2317. vector = position.asArray();
  2318. for (var j = 0; j < positionStrideSize; ++j) {
  2319. var num = vector[j];
  2320. if (num < min[j]) {
  2321. min[j] = num;
  2322. }
  2323. if (num > max[j]) {
  2324. max[j] = num;
  2325. }
  2326. ++indexOffset;
  2327. }
  2328. }
  2329. }
  2330. return { min: min, max: max };
  2331. };
  2332. /**
  2333. * Converts a new right-handed Vector3
  2334. * @param vector vector3 array
  2335. * @returns right-handed Vector3
  2336. */
  2337. _GLTFUtilities.GetRightHandedVector3 = function (vector) {
  2338. return new BABYLON.Vector3(vector.x, vector.y, -vector.z);
  2339. };
  2340. /**
  2341. * Converts a Vector3 to right-handed
  2342. * @param vector Vector3 to convert to right-handed
  2343. */
  2344. _GLTFUtilities.GetRightHandedVector3FromRef = function (vector) {
  2345. vector.z *= -1;
  2346. };
  2347. /**
  2348. * Converts a Vector4 to right-handed
  2349. * @param vector Vector4 to convert to right-handed
  2350. */
  2351. _GLTFUtilities.GetRightHandedVector4FromRef = function (vector) {
  2352. vector.z *= -1;
  2353. vector.w *= -1;
  2354. };
  2355. /**
  2356. * Converts a Quaternion to right-handed
  2357. * @param quaternion Source quaternion to convert to right-handed
  2358. */
  2359. _GLTFUtilities.GetRightHandedQuaternionFromRef = function (quaternion) {
  2360. quaternion.x *= -1;
  2361. quaternion.y *= -1;
  2362. };
  2363. return _GLTFUtilities;
  2364. }());
  2365. GLTF2._GLTFUtilities = _GLTFUtilities;
  2366. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2367. })(BABYLON || (BABYLON = {}));
  2368. //# sourceMappingURL=babylon.glTFUtilities.js.map