babylonjs.serializers.js 138 KB

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