babylonjs.serializers.js 195 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459
  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 geometry 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. BABYLON.Tools.Warn("No geometry is present on the mesh");
  56. continue;
  57. }
  58. var trunkVerts = g.getVerticesData('position');
  59. var trunkNormals = g.getVerticesData('normal');
  60. var trunkUV = g.getVerticesData('uv');
  61. var trunkFaces = g.getIndices();
  62. var curV = 0;
  63. if (!trunkVerts || !trunkFaces) {
  64. BABYLON.Tools.Warn("There are no position vertices or indices on the mesh!");
  65. continue;
  66. }
  67. for (var i = 0; i < trunkVerts.length; i += 3) {
  68. output.push("v " + trunkVerts[i] + " " + trunkVerts[i + 1] + " " + trunkVerts[i + 2]);
  69. curV++;
  70. }
  71. if (trunkNormals != null) {
  72. for (i = 0; i < trunkNormals.length; i += 3) {
  73. output.push("vn " + trunkNormals[i] + " " + trunkNormals[i + 1] + " " + trunkNormals[i + 2]);
  74. }
  75. }
  76. if (trunkUV != null) {
  77. for (i = 0; i < trunkUV.length; i += 2) {
  78. output.push("vt " + trunkUV[i] + " " + trunkUV[i + 1]);
  79. }
  80. }
  81. for (i = 0; i < trunkFaces.length; i += 3) {
  82. var indices = [String(trunkFaces[i + 2] + v), String(trunkFaces[i + 1] + v), String(trunkFaces[i] + v)];
  83. var blanks = ["", "", ""];
  84. var facePositions = indices;
  85. var faceUVs = trunkUV != null ? indices : blanks;
  86. var faceNormals = trunkNormals != null ? indices : blanks;
  87. output.push("f " + facePositions[0] + "/" + faceUVs[0] + "/" + faceNormals[0] +
  88. " " + facePositions[1] + "/" + faceUVs[1] + "/" + faceNormals[1] +
  89. " " + facePositions[2] + "/" + faceUVs[2] + "/" + faceNormals[2]);
  90. }
  91. //back de previous matrix, to not change the original mesh in the scene
  92. if (globalposition && lastMatrix) {
  93. mesh[j].bakeTransformIntoVertices(lastMatrix);
  94. }
  95. v += curV;
  96. }
  97. var text = output.join("\n");
  98. return (text);
  99. };
  100. //Exports the material(s) of a mesh in .MTL file format (text)
  101. //TODO: Export the materials of mesh array
  102. OBJExport.MTL = function (mesh) {
  103. var output = [];
  104. var m = mesh.material;
  105. output.push("newmtl mat1");
  106. output.push(" Ns " + m.specularPower.toFixed(4));
  107. output.push(" Ni 1.5000");
  108. output.push(" d " + m.alpha.toFixed(4));
  109. output.push(" Tr 0.0000");
  110. output.push(" Tf 1.0000 1.0000 1.0000");
  111. output.push(" illum 2");
  112. output.push(" Ka " + m.ambientColor.r.toFixed(4) + " " + m.ambientColor.g.toFixed(4) + " " + m.ambientColor.b.toFixed(4));
  113. output.push(" Kd " + m.diffuseColor.r.toFixed(4) + " " + m.diffuseColor.g.toFixed(4) + " " + m.diffuseColor.b.toFixed(4));
  114. output.push(" Ks " + m.specularColor.r.toFixed(4) + " " + m.specularColor.g.toFixed(4) + " " + m.specularColor.b.toFixed(4));
  115. output.push(" Ke " + m.emissiveColor.r.toFixed(4) + " " + m.emissiveColor.g.toFixed(4) + " " + m.emissiveColor.b.toFixed(4));
  116. //TODO: uv scale, offset, wrap
  117. //TODO: UV mirrored in Blender? second UV channel? lightMap? reflection textures?
  118. var uvscale = "";
  119. if (m.ambientTexture) {
  120. output.push(" map_Ka " + uvscale + m.ambientTexture.name);
  121. }
  122. if (m.diffuseTexture) {
  123. output.push(" map_Kd " + uvscale + m.diffuseTexture.name);
  124. //TODO: alpha testing, opacity in diffuse texture alpha channel (diffuseTexture.hasAlpha -> map_d)
  125. }
  126. if (m.specularTexture) {
  127. output.push(" map_Ks " + uvscale + m.specularTexture.name);
  128. /* TODO: glossiness = specular highlight component is in alpha channel of specularTexture. (???)
  129. if (m.useGlossinessFromSpecularMapAlpha) {
  130. output.push(" map_Ns "+uvscale + m.specularTexture.name);
  131. }
  132. */
  133. }
  134. /* TODO: emissive texture not in .MAT format (???)
  135. if (m.emissiveTexture) {
  136. output.push(" map_d "+uvscale+m.emissiveTexture.name);
  137. }
  138. */
  139. if (m.bumpTexture) {
  140. output.push(" map_bump -imfchan z " + uvscale + m.bumpTexture.name);
  141. }
  142. if (m.opacityTexture) {
  143. output.push(" map_d " + uvscale + m.opacityTexture.name);
  144. }
  145. var text = output.join("\n");
  146. return (text);
  147. };
  148. return OBJExport;
  149. }());
  150. BABYLON.OBJExport = OBJExport;
  151. })(BABYLON || (BABYLON = {}));
  152. //# sourceMappingURL=babylon.objSerializer.js.map
  153. var BABYLON;
  154. (function (BABYLON) {
  155. ;
  156. /**
  157. * Class for generating glTF data from a Babylon scene.
  158. */
  159. var GLTF2Export = /** @class */ (function () {
  160. function GLTF2Export() {
  161. }
  162. /**
  163. * Exports the geometry of the scene to .gltf file format asynchronously
  164. * @param scene Babylon scene with scene hierarchy information
  165. * @param filePrefix File prefix to use when generating the glTF file
  166. * @param options Exporter options
  167. * @returns Returns an object with a .gltf file and associates texture names
  168. * as keys and their data and paths as values
  169. */
  170. GLTF2Export.GLTFAsync = function (scene, filePrefix, options) {
  171. return scene.whenReadyAsync().then(function () {
  172. var glTFPrefix = filePrefix.replace(/\.[^/.]+$/, "");
  173. var gltfGenerator = new BABYLON.GLTF2._Exporter(scene, options);
  174. return gltfGenerator._generateGLTFAsync(glTFPrefix);
  175. });
  176. };
  177. /**
  178. * Exports the geometry of the scene to .glb file format asychronously
  179. * @param scene Babylon scene with scene hierarchy information
  180. * @param filePrefix File prefix to use when generating glb file
  181. * @param options Exporter options
  182. * @returns Returns an object with a .glb filename as key and data as value
  183. */
  184. GLTF2Export.GLBAsync = function (scene, filePrefix, options) {
  185. return scene.whenReadyAsync().then(function () {
  186. var glTFPrefix = filePrefix.replace(/\.[^/.]+$/, "");
  187. var gltfGenerator = new BABYLON.GLTF2._Exporter(scene, options);
  188. return gltfGenerator._generateGLBAsync(glTFPrefix);
  189. });
  190. };
  191. return GLTF2Export;
  192. }());
  193. BABYLON.GLTF2Export = GLTF2Export;
  194. })(BABYLON || (BABYLON = {}));
  195. //# sourceMappingURL=babylon.glTFSerializer.js.map
  196. var BABYLON;
  197. (function (BABYLON) {
  198. var GLTF2;
  199. (function (GLTF2) {
  200. /**
  201. * Utility interface for storing vertex attribute data
  202. * @hidden
  203. */
  204. /**
  205. * Converts Babylon Scene into glTF 2.0.
  206. * @hidden
  207. */
  208. var _Exporter = /** @class */ (function () {
  209. /**
  210. * Creates a glTF Exporter instance, which can accept optional exporter options
  211. * @param babylonScene Babylon scene object
  212. * @param options Options to modify the behavior of the exporter
  213. */
  214. function _Exporter(babylonScene, options) {
  215. this._asset = { generator: "BabylonJS", version: "2.0" };
  216. this._babylonScene = babylonScene;
  217. this._bufferViews = [];
  218. this._accessors = [];
  219. this._meshes = [];
  220. this._scenes = [];
  221. this._nodes = [];
  222. this._images = [];
  223. this._materials = [];
  224. this._materialMap = [];
  225. this._textures = [];
  226. this._samplers = [];
  227. this._animations = [];
  228. this._imageData = {};
  229. this._convertToRightHandedSystem = this._babylonScene.useRightHandedSystem ? false : true;
  230. var _options = options || {};
  231. this._shouldExportTransformNode = _options.shouldExportTransformNode ? _options.shouldExportTransformNode : function (babylonTransformNode) { return true; };
  232. this._animationSampleRate = _options.animationSampleRate ? _options.animationSampleRate : 1 / 60;
  233. this._glTFMaterialExporter = new GLTF2._GLTFMaterialExporter(this);
  234. }
  235. /**
  236. * Lazy load a local engine with premultiplied alpha set to false
  237. */
  238. _Exporter.prototype._getLocalEngine = function () {
  239. if (!this._localEngine) {
  240. var localCanvas = document.createElement('canvas');
  241. localCanvas.id = "WriteCanvas";
  242. localCanvas.width = 2048;
  243. localCanvas.height = 2048;
  244. this._localEngine = new BABYLON.Engine(localCanvas, true, { premultipliedAlpha: false, preserveDrawingBuffer: true });
  245. this._localEngine.setViewport(new BABYLON.Viewport(0, 0, 1, 1));
  246. }
  247. return this._localEngine;
  248. };
  249. _Exporter.prototype.reorderIndicesBasedOnPrimitiveMode = function (submesh, primitiveMode, babylonIndices, byteOffset, binaryWriter) {
  250. switch (primitiveMode) {
  251. case BABYLON.Material.TriangleFillMode: {
  252. if (!byteOffset) {
  253. byteOffset = 0;
  254. }
  255. for (var i = submesh.indexStart, length_1 = submesh.indexStart + submesh.indexCount; i < length_1; i = i + 3) {
  256. var index = byteOffset + i * 4;
  257. // swap the second and third indices
  258. var secondIndex = binaryWriter.getUInt32(index + 4);
  259. var thirdIndex = binaryWriter.getUInt32(index + 8);
  260. binaryWriter.setUInt32(thirdIndex, index + 4);
  261. binaryWriter.setUInt32(secondIndex, index + 8);
  262. }
  263. break;
  264. }
  265. case BABYLON.Material.TriangleFanDrawMode: {
  266. for (var i = submesh.indexStart + submesh.indexCount - 1, start = submesh.indexStart; i >= start; --i) {
  267. binaryWriter.setUInt32(babylonIndices[i], byteOffset);
  268. byteOffset += 4;
  269. }
  270. break;
  271. }
  272. case BABYLON.Material.TriangleStripDrawMode: {
  273. if (submesh.indexCount >= 3) {
  274. binaryWriter.setUInt32(babylonIndices[submesh.indexStart + 2], byteOffset + 4);
  275. binaryWriter.setUInt32(babylonIndices[submesh.indexStart + 1], byteOffset + 8);
  276. }
  277. break;
  278. }
  279. }
  280. };
  281. /**
  282. * Reorders the vertex attribute data based on the primitive mode. This is necessary when indices are not available and the winding order is
  283. * clock-wise during export to glTF
  284. * @param submesh BabylonJS submesh
  285. * @param primitiveMode Primitive mode of the mesh
  286. * @param sideOrientation the winding order of the submesh
  287. * @param vertexBufferKind The type of vertex attribute
  288. * @param meshAttributeArray The vertex attribute data
  289. * @param byteOffset The offset to the binary data
  290. * @param binaryWriter The binary data for the glTF file
  291. */
  292. _Exporter.prototype.reorderVertexAttributeDataBasedOnPrimitiveMode = function (submesh, primitiveMode, sideOrientation, vertexBufferKind, meshAttributeArray, byteOffset, binaryWriter) {
  293. if (this._convertToRightHandedSystem && sideOrientation === BABYLON.Material.ClockWiseSideOrientation) {
  294. switch (primitiveMode) {
  295. case BABYLON.Material.TriangleFillMode: {
  296. this.reorderTriangleFillMode(submesh, primitiveMode, sideOrientation, vertexBufferKind, meshAttributeArray, byteOffset, binaryWriter);
  297. break;
  298. }
  299. case BABYLON.Material.TriangleStripDrawMode: {
  300. this.reorderTriangleStripDrawMode(submesh, primitiveMode, sideOrientation, vertexBufferKind, meshAttributeArray, byteOffset, binaryWriter);
  301. break;
  302. }
  303. case BABYLON.Material.TriangleFanDrawMode: {
  304. this.reorderTriangleFanMode(submesh, primitiveMode, sideOrientation, vertexBufferKind, meshAttributeArray, byteOffset, binaryWriter);
  305. break;
  306. }
  307. }
  308. }
  309. };
  310. /**
  311. * Reorders the vertex attributes in the correct triangle mode order . This is necessary when indices are not available and the winding order is
  312. * clock-wise during export to glTF
  313. * @param submesh BabylonJS submesh
  314. * @param primitiveMode Primitive mode of the mesh
  315. * @param sideOrientation the winding order of the submesh
  316. * @param vertexBufferKind The type of vertex attribute
  317. * @param meshAttributeArray The vertex attribute data
  318. * @param byteOffset The offset to the binary data
  319. * @param binaryWriter The binary data for the glTF file
  320. */
  321. _Exporter.prototype.reorderTriangleFillMode = function (submesh, primitiveMode, sideOrientation, vertexBufferKind, meshAttributeArray, byteOffset, binaryWriter) {
  322. var vertexBuffer = this.getVertexBufferFromMesh(vertexBufferKind, submesh.getMesh());
  323. if (vertexBuffer) {
  324. var stride = vertexBuffer.byteStride / BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  325. if (submesh.verticesCount % 3 !== 0) {
  326. BABYLON.Tools.Error('The submesh vertices for the triangle fill mode is not divisible by 3!');
  327. }
  328. else {
  329. var vertexData = [];
  330. var index = 0;
  331. switch (vertexBufferKind) {
  332. case BABYLON.VertexBuffer.PositionKind:
  333. case BABYLON.VertexBuffer.NormalKind: {
  334. for (var x = submesh.verticesStart; x < submesh.verticesStart + submesh.verticesCount; x = x + 3) {
  335. index = x * stride;
  336. vertexData.push(BABYLON.Vector3.FromArray(meshAttributeArray, index));
  337. vertexData.push(BABYLON.Vector3.FromArray(meshAttributeArray, index + 2 * stride));
  338. vertexData.push(BABYLON.Vector3.FromArray(meshAttributeArray, index + stride));
  339. }
  340. break;
  341. }
  342. case BABYLON.VertexBuffer.TangentKind: {
  343. for (var x = submesh.verticesStart; x < submesh.verticesStart + submesh.verticesCount; x = x + 3) {
  344. index = x * stride;
  345. vertexData.push(BABYLON.Vector4.FromArray(meshAttributeArray, index));
  346. vertexData.push(BABYLON.Vector4.FromArray(meshAttributeArray, index + 2 * stride));
  347. vertexData.push(BABYLON.Vector4.FromArray(meshAttributeArray, index + stride));
  348. }
  349. break;
  350. }
  351. case BABYLON.VertexBuffer.ColorKind: {
  352. var size = vertexBuffer.getSize();
  353. for (var x = submesh.verticesStart; x < submesh.verticesStart + submesh.verticesCount; x = x + size) {
  354. index = x * stride;
  355. if (size === 4) {
  356. vertexData.push(BABYLON.Vector4.FromArray(meshAttributeArray, index));
  357. vertexData.push(BABYLON.Vector4.FromArray(meshAttributeArray, index + 2 * stride));
  358. vertexData.push(BABYLON.Vector4.FromArray(meshAttributeArray, index + stride));
  359. }
  360. else {
  361. vertexData.push(BABYLON.Vector3.FromArray(meshAttributeArray, index));
  362. vertexData.push(BABYLON.Vector3.FromArray(meshAttributeArray, index + 2 * stride));
  363. vertexData.push(BABYLON.Vector3.FromArray(meshAttributeArray, index + stride));
  364. }
  365. }
  366. break;
  367. }
  368. case BABYLON.VertexBuffer.UVKind:
  369. case BABYLON.VertexBuffer.UV2Kind: {
  370. for (var x = submesh.verticesStart; x < submesh.verticesStart + submesh.verticesCount; x = x + 3) {
  371. index = x * stride;
  372. vertexData.push(BABYLON.Vector2.FromArray(meshAttributeArray, index));
  373. vertexData.push(BABYLON.Vector2.FromArray(meshAttributeArray, index + 2 * stride));
  374. vertexData.push(BABYLON.Vector2.FromArray(meshAttributeArray, index + stride));
  375. }
  376. break;
  377. }
  378. default: {
  379. BABYLON.Tools.Error("Unsupported Vertex Buffer type: " + vertexBufferKind);
  380. }
  381. }
  382. this.writeVertexAttributeData(vertexData, byteOffset, vertexBufferKind, meshAttributeArray, binaryWriter);
  383. }
  384. }
  385. else {
  386. BABYLON.Tools.Warn("reorderTriangleFillMode: Vertex Buffer Kind " + vertexBufferKind + " not present!");
  387. }
  388. };
  389. /**
  390. * Reorders the vertex attributes in the correct triangle strip order. This is necessary when indices are not available and the winding order is
  391. * clock-wise during export to glTF
  392. * @param submesh BabylonJS submesh
  393. * @param primitiveMode Primitive mode of the mesh
  394. * @param sideOrientation the winding order of the submesh
  395. * @param vertexBufferKind The type of vertex attribute
  396. * @param meshAttributeArray The vertex attribute data
  397. * @param byteOffset The offset to the binary data
  398. * @param binaryWriter The binary data for the glTF file
  399. */
  400. _Exporter.prototype.reorderTriangleStripDrawMode = function (submesh, primitiveMode, sideOrientation, vertexBufferKind, meshAttributeArray, byteOffset, binaryWriter) {
  401. var vertexBuffer = this.getVertexBufferFromMesh(vertexBufferKind, submesh.getMesh());
  402. if (vertexBuffer) {
  403. var stride = vertexBuffer.byteStride / BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  404. var vertexData = [];
  405. var index = 0;
  406. switch (vertexBufferKind) {
  407. case BABYLON.VertexBuffer.PositionKind:
  408. case BABYLON.VertexBuffer.NormalKind: {
  409. index = submesh.verticesStart;
  410. vertexData.push(BABYLON.Vector3.FromArray(meshAttributeArray, index + 2 * stride));
  411. vertexData.push(BABYLON.Vector3.FromArray(meshAttributeArray, index + stride));
  412. break;
  413. }
  414. case BABYLON.VertexBuffer.TangentKind: {
  415. for (var x = submesh.verticesStart + submesh.verticesCount - 1; x >= submesh.verticesStart; --x) {
  416. index = x * stride;
  417. vertexData.push(BABYLON.Vector4.FromArray(meshAttributeArray, index));
  418. }
  419. break;
  420. }
  421. case BABYLON.VertexBuffer.ColorKind: {
  422. for (var x = submesh.verticesStart + submesh.verticesCount - 1; x >= submesh.verticesStart; --x) {
  423. index = x * stride;
  424. vertexBuffer.getSize() === 4 ? vertexData.push(BABYLON.Vector4.FromArray(meshAttributeArray, index)) : vertexData.push(BABYLON.Vector3.FromArray(meshAttributeArray, index));
  425. }
  426. break;
  427. }
  428. case BABYLON.VertexBuffer.UVKind:
  429. case BABYLON.VertexBuffer.UV2Kind: {
  430. for (var x = submesh.verticesStart + submesh.verticesCount - 1; x >= submesh.verticesStart; --x) {
  431. index = x * stride;
  432. vertexData.push(BABYLON.Vector2.FromArray(meshAttributeArray, index));
  433. }
  434. break;
  435. }
  436. default: {
  437. BABYLON.Tools.Error("Unsupported Vertex Buffer type: " + vertexBufferKind);
  438. }
  439. }
  440. this.writeVertexAttributeData(vertexData, byteOffset + 12, vertexBufferKind, meshAttributeArray, binaryWriter);
  441. }
  442. else {
  443. BABYLON.Tools.Warn("reorderTriangleStripDrawMode: Vertex buffer kind " + vertexBufferKind + " not present!");
  444. }
  445. };
  446. /**
  447. * Reorders the vertex attributes in the correct triangle fan order. This is necessary when indices are not available and the winding order is
  448. * clock-wise during export to glTF
  449. * @param submesh BabylonJS submesh
  450. * @param primitiveMode Primitive mode of the mesh
  451. * @param sideOrientation the winding order of the submesh
  452. * @param vertexBufferKind The type of vertex attribute
  453. * @param meshAttributeArray The vertex attribute data
  454. * @param byteOffset The offset to the binary data
  455. * @param binaryWriter The binary data for the glTF file
  456. */
  457. _Exporter.prototype.reorderTriangleFanMode = function (submesh, primitiveMode, sideOrientation, vertexBufferKind, meshAttributeArray, byteOffset, binaryWriter) {
  458. var vertexBuffer = this.getVertexBufferFromMesh(vertexBufferKind, submesh.getMesh());
  459. if (vertexBuffer) {
  460. var stride = vertexBuffer.byteStride / BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  461. var vertexData = [];
  462. var index = 0;
  463. switch (vertexBufferKind) {
  464. case BABYLON.VertexBuffer.PositionKind:
  465. case BABYLON.VertexBuffer.NormalKind: {
  466. for (var x = submesh.verticesStart + submesh.verticesCount - 1; x >= submesh.verticesStart; --x) {
  467. index = x * stride;
  468. vertexData.push(BABYLON.Vector3.FromArray(meshAttributeArray, index));
  469. }
  470. break;
  471. }
  472. case BABYLON.VertexBuffer.TangentKind: {
  473. for (var x = submesh.verticesStart + submesh.verticesCount - 1; x >= submesh.verticesStart; --x) {
  474. index = x * stride;
  475. vertexData.push(BABYLON.Vector4.FromArray(meshAttributeArray, index));
  476. }
  477. break;
  478. }
  479. case BABYLON.VertexBuffer.ColorKind: {
  480. for (var x = submesh.verticesStart + submesh.verticesCount - 1; x >= submesh.verticesStart; --x) {
  481. index = x * stride;
  482. vertexData.push(BABYLON.Vector4.FromArray(meshAttributeArray, index));
  483. vertexBuffer.getSize() === 4 ? vertexData.push(BABYLON.Vector4.FromArray(meshAttributeArray, index)) : vertexData.push(BABYLON.Vector3.FromArray(meshAttributeArray, index));
  484. }
  485. break;
  486. }
  487. case BABYLON.VertexBuffer.UVKind:
  488. case BABYLON.VertexBuffer.UV2Kind: {
  489. for (var x = submesh.verticesStart + submesh.verticesCount - 1; x >= submesh.verticesStart; --x) {
  490. index = x * stride;
  491. vertexData.push(BABYLON.Vector2.FromArray(meshAttributeArray, index));
  492. }
  493. break;
  494. }
  495. default: {
  496. BABYLON.Tools.Error("Unsupported Vertex Buffer type: " + vertexBufferKind);
  497. }
  498. }
  499. this.writeVertexAttributeData(vertexData, byteOffset, vertexBufferKind, meshAttributeArray, binaryWriter);
  500. }
  501. else {
  502. BABYLON.Tools.Warn("reorderTriangleFanMode: Vertex buffer kind " + vertexBufferKind + " not present!");
  503. }
  504. };
  505. /**
  506. * Writes the vertex attribute data to binary
  507. * @param vertices The vertices to write to the binary writer
  508. * @param byteOffset The offset into the binary writer to overwrite binary data
  509. * @param vertexAttributeKind The vertex attribute type
  510. * @param meshAttributeArray The vertex attribute data
  511. * @param binaryWriter The writer containing the binary data
  512. */
  513. _Exporter.prototype.writeVertexAttributeData = function (vertices, byteOffset, vertexAttributeKind, meshAttributeArray, binaryWriter) {
  514. for (var _i = 0, vertices_1 = vertices; _i < vertices_1.length; _i++) {
  515. var vertex = vertices_1[_i];
  516. if (this._convertToRightHandedSystem && !(vertexAttributeKind === BABYLON.VertexBuffer.ColorKind) && !(vertex instanceof BABYLON.Vector2)) {
  517. if (vertex instanceof BABYLON.Vector3) {
  518. if (vertexAttributeKind === BABYLON.VertexBuffer.NormalKind) {
  519. GLTF2._GLTFUtilities._GetRightHandedNormalVector3FromRef(vertex);
  520. }
  521. else if (vertexAttributeKind === BABYLON.VertexBuffer.PositionKind) {
  522. GLTF2._GLTFUtilities._GetRightHandedPositionVector3FromRef(vertex);
  523. }
  524. else {
  525. BABYLON.Tools.Error('Unsupported vertex attribute kind!');
  526. }
  527. }
  528. else {
  529. GLTF2._GLTFUtilities._GetRightHandedVector4FromRef(vertex);
  530. }
  531. }
  532. if (vertexAttributeKind === BABYLON.VertexBuffer.NormalKind) {
  533. vertex.normalize();
  534. }
  535. else if (vertexAttributeKind === BABYLON.VertexBuffer.TangentKind && vertex instanceof BABYLON.Vector4) {
  536. GLTF2._GLTFUtilities._NormalizeTangentFromRef(vertex);
  537. }
  538. for (var _a = 0, _b = vertex.asArray(); _a < _b.length; _a++) {
  539. var component = _b[_a];
  540. binaryWriter.setFloat32(component, byteOffset);
  541. byteOffset += 4;
  542. }
  543. }
  544. };
  545. /**
  546. * Writes mesh attribute data to a data buffer
  547. * Returns the bytelength of the data
  548. * @param vertexBufferKind Indicates what kind of vertex data is being passed in
  549. * @param meshAttributeArray Array containing the attribute data
  550. * @param binaryWriter The buffer to write the binary data to
  551. * @param indices Used to specify the order of the vertex data
  552. */
  553. _Exporter.prototype.writeAttributeData = function (vertexBufferKind, meshAttributeArray, byteStride, binaryWriter) {
  554. var stride = byteStride / 4;
  555. var vertexAttributes = [];
  556. var index;
  557. switch (vertexBufferKind) {
  558. case BABYLON.VertexBuffer.PositionKind: {
  559. for (var k = 0, length_2 = meshAttributeArray.length / stride; k < length_2; ++k) {
  560. index = k * stride;
  561. var vertexData = BABYLON.Vector3.FromArray(meshAttributeArray, index);
  562. if (this._convertToRightHandedSystem) {
  563. GLTF2._GLTFUtilities._GetRightHandedPositionVector3FromRef(vertexData);
  564. }
  565. vertexAttributes.push(vertexData.asArray());
  566. }
  567. break;
  568. }
  569. case BABYLON.VertexBuffer.NormalKind: {
  570. for (var k = 0, length_3 = meshAttributeArray.length / stride; k < length_3; ++k) {
  571. index = k * stride;
  572. var vertexData = BABYLON.Vector3.FromArray(meshAttributeArray, index);
  573. if (this._convertToRightHandedSystem) {
  574. GLTF2._GLTFUtilities._GetRightHandedNormalVector3FromRef(vertexData);
  575. }
  576. vertexData.normalize();
  577. vertexAttributes.push(vertexData.asArray());
  578. }
  579. break;
  580. }
  581. case BABYLON.VertexBuffer.TangentKind: {
  582. for (var k = 0, length_4 = meshAttributeArray.length / stride; k < length_4; ++k) {
  583. index = k * stride;
  584. var vertexData = BABYLON.Vector4.FromArray(meshAttributeArray, index);
  585. if (this._convertToRightHandedSystem) {
  586. GLTF2._GLTFUtilities._GetRightHandedVector4FromRef(vertexData);
  587. }
  588. GLTF2._GLTFUtilities._NormalizeTangentFromRef(vertexData);
  589. vertexAttributes.push(vertexData.asArray());
  590. }
  591. break;
  592. }
  593. case BABYLON.VertexBuffer.ColorKind: {
  594. for (var k = 0, length_5 = meshAttributeArray.length / stride; k < length_5; ++k) {
  595. index = k * stride;
  596. var vertexData = stride === 3 ? BABYLON.Vector3.FromArray(meshAttributeArray, index) : BABYLON.Vector4.FromArray(meshAttributeArray, index);
  597. vertexAttributes.push(vertexData.asArray());
  598. }
  599. break;
  600. }
  601. case BABYLON.VertexBuffer.UVKind:
  602. case BABYLON.VertexBuffer.UV2Kind: {
  603. for (var k = 0, length_6 = meshAttributeArray.length / stride; k < length_6; ++k) {
  604. index = k * stride;
  605. vertexAttributes.push(this._convertToRightHandedSystem ? [meshAttributeArray[index], meshAttributeArray[index + 1]] : [meshAttributeArray[index], meshAttributeArray[index + 1]]);
  606. }
  607. break;
  608. }
  609. default: {
  610. BABYLON.Tools.Warn("Unsupported Vertex Buffer Type: " + vertexBufferKind);
  611. vertexAttributes = [];
  612. }
  613. }
  614. for (var _i = 0, vertexAttributes_1 = vertexAttributes; _i < vertexAttributes_1.length; _i++) {
  615. var vertexAttribute = vertexAttributes_1[_i];
  616. for (var _a = 0, vertexAttribute_1 = vertexAttribute; _a < vertexAttribute_1.length; _a++) {
  617. var component = vertexAttribute_1[_a];
  618. binaryWriter.setFloat32(component);
  619. }
  620. }
  621. };
  622. /**
  623. * Generates glTF json data
  624. * @param shouldUseGlb Indicates whether the json should be written for a glb file
  625. * @param glTFPrefix Text to use when prefixing a glTF file
  626. * @param prettyPrint Indicates whether the json file should be pretty printed (true) or not (false)
  627. * @returns json data as string
  628. */
  629. _Exporter.prototype.generateJSON = function (shouldUseGlb, glTFPrefix, prettyPrint) {
  630. var _this = this;
  631. var buffer = { byteLength: this._totalByteLength };
  632. var imageName;
  633. var imageData;
  634. var bufferView;
  635. var byteOffset = this._totalByteLength;
  636. var glTF = {
  637. asset: this._asset
  638. };
  639. if (buffer.byteLength) {
  640. glTF.buffers = [buffer];
  641. }
  642. if (this._nodes && this._nodes.length) {
  643. glTF.nodes = this._nodes;
  644. }
  645. if (this._meshes && this._meshes.length) {
  646. glTF.meshes = this._meshes;
  647. }
  648. if (this._scenes && this._scenes.length) {
  649. glTF.scenes = this._scenes;
  650. glTF.scene = 0;
  651. }
  652. if (this._bufferViews && this._bufferViews.length) {
  653. glTF.bufferViews = this._bufferViews;
  654. }
  655. if (this._accessors && this._accessors.length) {
  656. glTF.accessors = this._accessors;
  657. }
  658. if (this._animations && this._animations.length) {
  659. glTF.animations = this._animations;
  660. }
  661. if (this._materials && this._materials.length) {
  662. glTF.materials = this._materials;
  663. }
  664. if (this._textures && this._textures.length) {
  665. glTF.textures = this._textures;
  666. }
  667. if (this._samplers && this._samplers.length) {
  668. glTF.samplers = this._samplers;
  669. }
  670. if (this._images && this._images.length) {
  671. if (!shouldUseGlb) {
  672. glTF.images = this._images;
  673. }
  674. else {
  675. glTF.images = [];
  676. this._images.forEach(function (image) {
  677. if (image.uri) {
  678. imageData = _this._imageData[image.uri];
  679. imageName = image.uri.split('.')[0] + " image";
  680. bufferView = GLTF2._GLTFUtilities._CreateBufferView(0, byteOffset, imageData.data.length, undefined, imageName);
  681. byteOffset += imageData.data.buffer.byteLength;
  682. _this._bufferViews.push(bufferView);
  683. image.bufferView = _this._bufferViews.length - 1;
  684. image.name = imageName;
  685. image.mimeType = imageData.mimeType;
  686. image.uri = undefined;
  687. if (!glTF.images) {
  688. glTF.images = [];
  689. }
  690. glTF.images.push(image);
  691. }
  692. });
  693. // Replace uri with bufferview and mime type for glb
  694. buffer.byteLength = byteOffset;
  695. }
  696. }
  697. if (!shouldUseGlb) {
  698. buffer.uri = glTFPrefix + ".bin";
  699. }
  700. var jsonText = prettyPrint ? JSON.stringify(glTF, null, 2) : JSON.stringify(glTF);
  701. return jsonText;
  702. };
  703. /**
  704. * Generates data for .gltf and .bin files based on the glTF prefix string
  705. * @param glTFPrefix Text to use when prefixing a glTF file
  706. * @returns GLTFData with glTF file data
  707. */
  708. _Exporter.prototype._generateGLTFAsync = function (glTFPrefix) {
  709. var _this = this;
  710. return this._generateBinaryAsync().then(function (binaryBuffer) {
  711. var jsonText = _this.generateJSON(false, glTFPrefix, true);
  712. var bin = new Blob([binaryBuffer], { type: 'application/octet-stream' });
  713. var glTFFileName = glTFPrefix + '.gltf';
  714. var glTFBinFile = glTFPrefix + '.bin';
  715. var container = new BABYLON.GLTFData();
  716. container.glTFFiles[glTFFileName] = jsonText;
  717. container.glTFFiles[glTFBinFile] = bin;
  718. if (_this._imageData) {
  719. for (var image in _this._imageData) {
  720. container.glTFFiles[image] = new Blob([_this._imageData[image].data], { type: _this._imageData[image].mimeType });
  721. }
  722. }
  723. return container;
  724. });
  725. };
  726. /**
  727. * Creates a binary buffer for glTF
  728. * @returns array buffer for binary data
  729. */
  730. _Exporter.prototype._generateBinaryAsync = function () {
  731. var _this = this;
  732. var binaryWriter = new _BinaryWriter(4);
  733. return this.createSceneAsync(this._babylonScene, binaryWriter).then(function () {
  734. if (_this._localEngine) {
  735. _this._localEngine.dispose();
  736. }
  737. return binaryWriter.getArrayBuffer();
  738. });
  739. };
  740. /**
  741. * Pads the number to a multiple of 4
  742. * @param num number to pad
  743. * @returns padded number
  744. */
  745. _Exporter.prototype._getPadding = function (num) {
  746. var remainder = num % 4;
  747. var padding = remainder === 0 ? remainder : 4 - remainder;
  748. return padding;
  749. };
  750. /**
  751. * Generates a glb file from the json and binary data
  752. * Returns an object with the glb file name as the key and data as the value
  753. * @param glTFPrefix
  754. * @returns object with glb filename as key and data as value
  755. */
  756. _Exporter.prototype._generateGLBAsync = function (glTFPrefix) {
  757. var _this = this;
  758. return this._generateBinaryAsync().then(function (binaryBuffer) {
  759. var jsonText = _this.generateJSON(true);
  760. var glbFileName = glTFPrefix + '.glb';
  761. var headerLength = 12;
  762. var chunkLengthPrefix = 8;
  763. var jsonLength = jsonText.length;
  764. var imageByteLength = 0;
  765. for (var key in _this._imageData) {
  766. imageByteLength += _this._imageData[key].data.byteLength;
  767. }
  768. var jsonPadding = _this._getPadding(jsonLength);
  769. var binPadding = _this._getPadding(binaryBuffer.byteLength);
  770. var imagePadding = _this._getPadding(imageByteLength);
  771. var byteLength = headerLength + (2 * chunkLengthPrefix) + jsonLength + jsonPadding + binaryBuffer.byteLength + binPadding + imageByteLength + imagePadding;
  772. //header
  773. var headerBuffer = new ArrayBuffer(headerLength);
  774. var headerBufferView = new DataView(headerBuffer);
  775. headerBufferView.setUint32(0, 0x46546C67, true); //glTF
  776. headerBufferView.setUint32(4, 2, true); // version
  777. headerBufferView.setUint32(8, byteLength, true); // total bytes in file
  778. //json chunk
  779. var jsonChunkBuffer = new ArrayBuffer(chunkLengthPrefix + jsonLength + jsonPadding);
  780. var jsonChunkBufferView = new DataView(jsonChunkBuffer);
  781. jsonChunkBufferView.setUint32(0, jsonLength + jsonPadding, true);
  782. jsonChunkBufferView.setUint32(4, 0x4E4F534A, true);
  783. //json chunk bytes
  784. var jsonData = new Uint8Array(jsonChunkBuffer, chunkLengthPrefix);
  785. for (var i = 0; i < jsonLength; ++i) {
  786. jsonData[i] = jsonText.charCodeAt(i);
  787. }
  788. //json padding
  789. var jsonPaddingView = new Uint8Array(jsonChunkBuffer, chunkLengthPrefix + jsonLength);
  790. for (var i = 0; i < jsonPadding; ++i) {
  791. jsonPaddingView[i] = 0x20;
  792. }
  793. //binary chunk
  794. var binaryChunkBuffer = new ArrayBuffer(chunkLengthPrefix);
  795. var binaryChunkBufferView = new DataView(binaryChunkBuffer);
  796. binaryChunkBufferView.setUint32(0, binaryBuffer.byteLength + imageByteLength + imagePadding, true);
  797. binaryChunkBufferView.setUint32(4, 0x004E4942, true);
  798. // binary padding
  799. var binPaddingBuffer = new ArrayBuffer(binPadding);
  800. var binPaddingView = new Uint8Array(binPaddingBuffer);
  801. for (var i = 0; i < binPadding; ++i) {
  802. binPaddingView[i] = 0;
  803. }
  804. var imagePaddingBuffer = new ArrayBuffer(imagePadding);
  805. var imagePaddingView = new Uint8Array(imagePaddingBuffer);
  806. for (var i = 0; i < imagePadding; ++i) {
  807. imagePaddingView[i] = 0;
  808. }
  809. var glbData = [headerBuffer, jsonChunkBuffer, binaryChunkBuffer, binaryBuffer];
  810. // binary data
  811. for (var key in _this._imageData) {
  812. glbData.push(_this._imageData[key].data.buffer);
  813. }
  814. glbData.push(binPaddingBuffer);
  815. glbData.push(imagePaddingBuffer);
  816. var glbFile = new Blob(glbData, { type: 'application/octet-stream' });
  817. var container = new BABYLON.GLTFData();
  818. container.glTFFiles[glbFileName] = glbFile;
  819. if (_this._localEngine != null) {
  820. _this._localEngine.dispose();
  821. }
  822. return container;
  823. });
  824. };
  825. /**
  826. * Sets the TRS for each node
  827. * @param node glTF Node for storing the transformation data
  828. * @param babylonTransformNode Babylon mesh used as the source for the transformation data
  829. */
  830. _Exporter.prototype.setNodeTransformation = function (node, babylonTransformNode) {
  831. if (!babylonTransformNode.getPivotPoint().equalsToFloats(0, 0, 0)) {
  832. BABYLON.Tools.Warn("Pivot points are not supported in the glTF serializer");
  833. }
  834. if (!babylonTransformNode.position.equalsToFloats(0, 0, 0)) {
  835. node.translation = this._convertToRightHandedSystem ? GLTF2._GLTFUtilities._GetRightHandedPositionVector3(babylonTransformNode.position).asArray() : babylonTransformNode.position.asArray();
  836. }
  837. if (!babylonTransformNode.scaling.equalsToFloats(1, 1, 1)) {
  838. node.scale = babylonTransformNode.scaling.asArray();
  839. }
  840. var rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(babylonTransformNode.rotation.y, babylonTransformNode.rotation.x, babylonTransformNode.rotation.z);
  841. if (babylonTransformNode.rotationQuaternion) {
  842. rotationQuaternion.multiplyInPlace(babylonTransformNode.rotationQuaternion);
  843. }
  844. if (!(rotationQuaternion.x === 0 && rotationQuaternion.y === 0 && rotationQuaternion.z === 0 && rotationQuaternion.w === 1)) {
  845. if (this._convertToRightHandedSystem) {
  846. GLTF2._GLTFUtilities._GetRightHandedQuaternionFromRef(rotationQuaternion);
  847. }
  848. node.rotation = rotationQuaternion.normalize().asArray();
  849. }
  850. };
  851. _Exporter.prototype.getVertexBufferFromMesh = function (attributeKind, bufferMesh) {
  852. if (bufferMesh.isVerticesDataPresent(attributeKind)) {
  853. var vertexBuffer = bufferMesh.getVertexBuffer(attributeKind);
  854. if (vertexBuffer) {
  855. return vertexBuffer;
  856. }
  857. }
  858. return null;
  859. };
  860. /**
  861. * Creates a bufferview based on the vertices type for the Babylon mesh
  862. * @param kind Indicates the type of vertices data
  863. * @param babylonTransformNode The Babylon mesh to get the vertices data from
  864. * @param binaryWriter The buffer to write the bufferview data to
  865. */
  866. _Exporter.prototype.createBufferViewKind = function (kind, babylonTransformNode, binaryWriter, byteStride) {
  867. var bufferMesh = babylonTransformNode instanceof BABYLON.Mesh ?
  868. babylonTransformNode : babylonTransformNode instanceof BABYLON.InstancedMesh ?
  869. babylonTransformNode.sourceMesh : null;
  870. if (bufferMesh) {
  871. var vertexData = bufferMesh.getVerticesData(kind);
  872. if (vertexData) {
  873. var byteLength = vertexData.length * 4;
  874. var bufferView = GLTF2._GLTFUtilities._CreateBufferView(0, binaryWriter.getByteOffset(), byteLength, byteStride, kind + " - " + bufferMesh.name);
  875. this._bufferViews.push(bufferView);
  876. this.writeAttributeData(kind, vertexData, byteStride, binaryWriter);
  877. }
  878. }
  879. };
  880. /**
  881. * The primitive mode of the Babylon mesh
  882. * @param babylonMesh The BabylonJS mesh
  883. */
  884. _Exporter.prototype.getMeshPrimitiveMode = function (babylonMesh) {
  885. if (babylonMesh instanceof BABYLON.LinesMesh) {
  886. return BABYLON.Material.LineListDrawMode;
  887. }
  888. return babylonMesh.material ? babylonMesh.material.fillMode : BABYLON.Material.TriangleFillMode;
  889. };
  890. /**
  891. * Sets the primitive mode of the glTF mesh primitive
  892. * @param meshPrimitive glTF mesh primitive
  893. * @param primitiveMode The primitive mode
  894. */
  895. _Exporter.prototype.setPrimitiveMode = function (meshPrimitive, primitiveMode) {
  896. switch (primitiveMode) {
  897. case BABYLON.Material.TriangleFillMode: {
  898. // glTF defaults to using Triangle Mode
  899. break;
  900. }
  901. case BABYLON.Material.TriangleStripDrawMode: {
  902. meshPrimitive.mode = 5 /* TRIANGLE_STRIP */;
  903. break;
  904. }
  905. case BABYLON.Material.TriangleFanDrawMode: {
  906. meshPrimitive.mode = 6 /* TRIANGLE_FAN */;
  907. break;
  908. }
  909. case BABYLON.Material.PointListDrawMode: {
  910. meshPrimitive.mode = 0 /* POINTS */;
  911. }
  912. case BABYLON.Material.PointFillMode: {
  913. meshPrimitive.mode = 0 /* POINTS */;
  914. break;
  915. }
  916. case BABYLON.Material.LineLoopDrawMode: {
  917. meshPrimitive.mode = 2 /* LINE_LOOP */;
  918. break;
  919. }
  920. case BABYLON.Material.LineListDrawMode: {
  921. meshPrimitive.mode = 1 /* LINES */;
  922. break;
  923. }
  924. case BABYLON.Material.LineStripDrawMode: {
  925. meshPrimitive.mode = 3 /* LINE_STRIP */;
  926. break;
  927. }
  928. }
  929. };
  930. /**
  931. * Sets the vertex attribute accessor based of the glTF mesh primitive
  932. * @param meshPrimitive glTF mesh primitive
  933. * @param attributeKind vertex attribute
  934. * @returns boolean specifying if uv coordinates are present
  935. */
  936. _Exporter.prototype.setAttributeKind = function (meshPrimitive, attributeKind) {
  937. switch (attributeKind) {
  938. case BABYLON.VertexBuffer.PositionKind: {
  939. meshPrimitive.attributes.POSITION = this._accessors.length - 1;
  940. break;
  941. }
  942. case BABYLON.VertexBuffer.NormalKind: {
  943. meshPrimitive.attributes.NORMAL = this._accessors.length - 1;
  944. break;
  945. }
  946. case BABYLON.VertexBuffer.ColorKind: {
  947. meshPrimitive.attributes.COLOR_0 = this._accessors.length - 1;
  948. break;
  949. }
  950. case BABYLON.VertexBuffer.TangentKind: {
  951. meshPrimitive.attributes.TANGENT = this._accessors.length - 1;
  952. break;
  953. }
  954. case BABYLON.VertexBuffer.UVKind: {
  955. meshPrimitive.attributes.TEXCOORD_0 = this._accessors.length - 1;
  956. break;
  957. }
  958. case BABYLON.VertexBuffer.UV2Kind: {
  959. meshPrimitive.attributes.TEXCOORD_1 = this._accessors.length - 1;
  960. break;
  961. }
  962. default: {
  963. BABYLON.Tools.Warn("Unsupported Vertex Buffer Type: " + attributeKind);
  964. }
  965. }
  966. };
  967. /**
  968. * Sets data for the primitive attributes of each submesh
  969. * @param mesh glTF Mesh object to store the primitive attribute information
  970. * @param babylonTransformNode Babylon mesh to get the primitive attribute data from
  971. * @param binaryWriter Buffer to write the attribute data to
  972. */
  973. _Exporter.prototype.setPrimitiveAttributes = function (mesh, babylonTransformNode, binaryWriter) {
  974. var bufferMesh = null;
  975. var bufferView;
  976. var uvCoordsPresent;
  977. var minMax;
  978. if (babylonTransformNode instanceof BABYLON.Mesh) {
  979. bufferMesh = babylonTransformNode;
  980. }
  981. else if (babylonTransformNode instanceof BABYLON.InstancedMesh) {
  982. bufferMesh = babylonTransformNode.sourceMesh;
  983. }
  984. var attributeData = [
  985. { kind: BABYLON.VertexBuffer.PositionKind, accessorType: "VEC3" /* VEC3 */, byteStride: 12 },
  986. { kind: BABYLON.VertexBuffer.NormalKind, accessorType: "VEC3" /* VEC3 */, byteStride: 12 },
  987. { kind: BABYLON.VertexBuffer.ColorKind, accessorType: "VEC4" /* VEC4 */, byteStride: 16 },
  988. { kind: BABYLON.VertexBuffer.TangentKind, accessorType: "VEC4" /* VEC4 */, byteStride: 16 },
  989. { kind: BABYLON.VertexBuffer.UVKind, accessorType: "VEC2" /* VEC2 */, byteStride: 8 },
  990. { kind: BABYLON.VertexBuffer.UV2Kind, accessorType: "VEC2" /* VEC2 */, byteStride: 8 },
  991. ];
  992. if (bufferMesh) {
  993. var indexBufferViewIndex = null;
  994. var primitiveMode = this.getMeshPrimitiveMode(bufferMesh);
  995. var vertexAttributeBufferViews = {};
  996. // For each BabylonMesh, create bufferviews for each 'kind'
  997. for (var _i = 0, attributeData_1 = attributeData; _i < attributeData_1.length; _i++) {
  998. var attribute = attributeData_1[_i];
  999. var attributeKind = attribute.kind;
  1000. if (bufferMesh.isVerticesDataPresent(attributeKind)) {
  1001. var vertexBuffer = this.getVertexBufferFromMesh(attributeKind, bufferMesh);
  1002. attribute.byteStride = vertexBuffer ? vertexBuffer.getSize() * 4 : BABYLON.VertexBuffer.DeduceStride(attributeKind) * 4;
  1003. if (attribute.byteStride === 12) {
  1004. attribute.accessorType = "VEC3" /* VEC3 */;
  1005. }
  1006. this.createBufferViewKind(attributeKind, babylonTransformNode, binaryWriter, attribute.byteStride);
  1007. attribute.bufferViewIndex = this._bufferViews.length - 1;
  1008. vertexAttributeBufferViews[attributeKind] = attribute.bufferViewIndex;
  1009. }
  1010. }
  1011. if (bufferMesh.getTotalIndices()) {
  1012. var indices = bufferMesh.getIndices();
  1013. if (indices) {
  1014. var byteLength = indices.length * 4;
  1015. bufferView = GLTF2._GLTFUtilities._CreateBufferView(0, binaryWriter.getByteOffset(), byteLength, undefined, "Indices - " + bufferMesh.name);
  1016. this._bufferViews.push(bufferView);
  1017. indexBufferViewIndex = this._bufferViews.length - 1;
  1018. for (var k = 0, length_7 = indices.length; k < length_7; ++k) {
  1019. binaryWriter.setUInt32(indices[k]);
  1020. }
  1021. }
  1022. }
  1023. if (bufferMesh.subMeshes) {
  1024. // go through all mesh primitives (submeshes)
  1025. for (var _a = 0, _b = bufferMesh.subMeshes; _a < _b.length; _a++) {
  1026. var submesh = _b[_a];
  1027. uvCoordsPresent = false;
  1028. var babylonMaterial = submesh.getMaterial() || bufferMesh.getScene().defaultMaterial;
  1029. var materialIndex = null;
  1030. if (babylonMaterial) {
  1031. if (bufferMesh instanceof BABYLON.LinesMesh) {
  1032. // get the color from the lines mesh and set it in the material
  1033. var material = {
  1034. name: bufferMesh.name + ' material'
  1035. };
  1036. if (!bufferMesh.color.equals(BABYLON.Color3.White()) || bufferMesh.alpha < 1) {
  1037. material.pbrMetallicRoughness = {
  1038. baseColorFactor: bufferMesh.color.asArray().concat([bufferMesh.alpha])
  1039. };
  1040. }
  1041. this._materials.push(material);
  1042. materialIndex = this._materials.length - 1;
  1043. }
  1044. else if (babylonMaterial instanceof BABYLON.MultiMaterial) {
  1045. var subMaterial = babylonMaterial.subMaterials[submesh.materialIndex];
  1046. if (subMaterial) {
  1047. babylonMaterial = subMaterial;
  1048. materialIndex = this._materialMap[babylonMaterial.uniqueId];
  1049. }
  1050. }
  1051. else {
  1052. materialIndex = this._materialMap[babylonMaterial.uniqueId];
  1053. }
  1054. }
  1055. var glTFMaterial = materialIndex != null ? this._materials[materialIndex] : null;
  1056. var meshPrimitive = { attributes: {} };
  1057. this.setPrimitiveMode(meshPrimitive, primitiveMode);
  1058. for (var _c = 0, attributeData_2 = attributeData; _c < attributeData_2.length; _c++) {
  1059. var attribute = attributeData_2[_c];
  1060. var attributeKind = attribute.kind;
  1061. if (attributeKind === BABYLON.VertexBuffer.UVKind || attributeKind === BABYLON.VertexBuffer.UV2Kind) {
  1062. if (glTFMaterial && !this._glTFMaterialExporter._hasTexturesPresent(glTFMaterial)) {
  1063. continue;
  1064. }
  1065. }
  1066. var vertexData = bufferMesh.getVerticesData(attributeKind);
  1067. if (vertexData) {
  1068. var vertexBuffer = this.getVertexBufferFromMesh(attributeKind, bufferMesh);
  1069. if (vertexBuffer) {
  1070. var stride = vertexBuffer.getSize();
  1071. var bufferViewIndex = attribute.bufferViewIndex;
  1072. if (bufferViewIndex != undefined) { // check to see if bufferviewindex has a numeric value assigned.
  1073. minMax = { min: null, max: null };
  1074. if (attributeKind == BABYLON.VertexBuffer.PositionKind) {
  1075. minMax = GLTF2._GLTFUtilities._CalculateMinMaxPositions(vertexData, 0, vertexData.length / stride, this._convertToRightHandedSystem);
  1076. }
  1077. var accessor = GLTF2._GLTFUtilities._CreateAccessor(bufferViewIndex, attributeKind + " - " + babylonTransformNode.name, attribute.accessorType, 5126 /* FLOAT */, vertexData.length / stride, 0, minMax.min, minMax.max);
  1078. this._accessors.push(accessor);
  1079. this.setAttributeKind(meshPrimitive, attributeKind);
  1080. if (meshPrimitive.attributes.TEXCOORD_0 != null || meshPrimitive.attributes.TEXCOORD_1 != null) {
  1081. uvCoordsPresent = true;
  1082. }
  1083. }
  1084. }
  1085. }
  1086. }
  1087. if (indexBufferViewIndex) {
  1088. // Create accessor
  1089. var accessor = GLTF2._GLTFUtilities._CreateAccessor(indexBufferViewIndex, "indices - " + babylonTransformNode.name, "SCALAR" /* SCALAR */, 5125 /* UNSIGNED_INT */, submesh.indexCount, submesh.indexStart * 4, null, null);
  1090. this._accessors.push(accessor);
  1091. meshPrimitive.indices = this._accessors.length - 1;
  1092. }
  1093. if (materialIndex != null && Object.keys(meshPrimitive.attributes).length > 0) {
  1094. var sideOrientation = babylonMaterial.sideOrientation;
  1095. if (this._convertToRightHandedSystem && sideOrientation === BABYLON.Material.ClockWiseSideOrientation) {
  1096. //Overwrite the indices to be counter-clockwise
  1097. var byteOffset = indexBufferViewIndex != null ? this._bufferViews[indexBufferViewIndex].byteOffset : null;
  1098. if (byteOffset == null) {
  1099. byteOffset = 0;
  1100. }
  1101. var babylonIndices = null;
  1102. if (indexBufferViewIndex != null) {
  1103. babylonIndices = bufferMesh.getIndices();
  1104. }
  1105. if (babylonIndices) {
  1106. this.reorderIndicesBasedOnPrimitiveMode(submesh, primitiveMode, babylonIndices, byteOffset, binaryWriter);
  1107. }
  1108. else {
  1109. for (var _d = 0, attributeData_3 = attributeData; _d < attributeData_3.length; _d++) {
  1110. var attribute = attributeData_3[_d];
  1111. var vertexData = bufferMesh.getVerticesData(attribute.kind);
  1112. if (vertexData) {
  1113. var byteOffset_1 = this._bufferViews[vertexAttributeBufferViews[attribute.kind]].byteOffset;
  1114. if (!byteOffset_1) {
  1115. byteOffset_1 = 0;
  1116. }
  1117. this.reorderVertexAttributeDataBasedOnPrimitiveMode(submesh, primitiveMode, sideOrientation, attribute.kind, vertexData, byteOffset_1, binaryWriter);
  1118. }
  1119. }
  1120. }
  1121. }
  1122. if (!uvCoordsPresent && this._glTFMaterialExporter._hasTexturesPresent(this._materials[materialIndex])) {
  1123. var newMat = this._glTFMaterialExporter._stripTexturesFromMaterial(this._materials[materialIndex]);
  1124. this._materials.push(newMat);
  1125. materialIndex = this._materials.length - 1;
  1126. }
  1127. meshPrimitive.material = materialIndex;
  1128. }
  1129. mesh.primitives.push(meshPrimitive);
  1130. }
  1131. }
  1132. }
  1133. };
  1134. /**
  1135. * Creates a glTF scene based on the array of meshes
  1136. * Returns the the total byte offset
  1137. * @param babylonScene Babylon scene to get the mesh data from
  1138. * @param binaryWriter Buffer to write binary data to
  1139. */
  1140. _Exporter.prototype.createSceneAsync = function (babylonScene, binaryWriter) {
  1141. var _this = this;
  1142. var scene = { nodes: [] };
  1143. var glTFNodeIndex;
  1144. var glTFNode;
  1145. var directDescendents;
  1146. var nodes = babylonScene.transformNodes.concat(babylonScene.meshes);
  1147. return this._glTFMaterialExporter._convertMaterialsToGLTFAsync(babylonScene.materials, "image/png" /* PNG */, true).then(function () {
  1148. _this._nodeMap = _this.createNodeMapAndAnimations(babylonScene, nodes, _this._shouldExportTransformNode, binaryWriter);
  1149. _this._totalByteLength = binaryWriter.getByteOffset();
  1150. // Build Hierarchy with the node map.
  1151. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  1152. var babylonTransformNode = nodes_1[_i];
  1153. glTFNodeIndex = _this._nodeMap[babylonTransformNode.uniqueId];
  1154. if (glTFNodeIndex != null) {
  1155. glTFNode = _this._nodes[glTFNodeIndex];
  1156. if (!babylonTransformNode.parent) {
  1157. if (!_this._shouldExportTransformNode(babylonTransformNode)) {
  1158. BABYLON.Tools.Log("Omitting " + babylonTransformNode.name + " from scene.");
  1159. }
  1160. else {
  1161. if (_this._convertToRightHandedSystem) {
  1162. if (glTFNode.translation) {
  1163. glTFNode.translation[2] *= -1;
  1164. glTFNode.translation[0] *= -1;
  1165. }
  1166. glTFNode.rotation = glTFNode.rotation ? BABYLON.Quaternion.FromArray([0, 1, 0, 0]).multiply(BABYLON.Quaternion.FromArray(glTFNode.rotation)).asArray() : (BABYLON.Quaternion.FromArray([0, 1, 0, 0])).asArray();
  1167. }
  1168. scene.nodes.push(glTFNodeIndex);
  1169. }
  1170. }
  1171. directDescendents = babylonTransformNode.getDescendants(true);
  1172. if (!glTFNode.children && directDescendents && directDescendents.length) {
  1173. var children = [];
  1174. for (var _a = 0, directDescendents_1 = directDescendents; _a < directDescendents_1.length; _a++) {
  1175. var descendent = directDescendents_1[_a];
  1176. if (_this._nodeMap[descendent.uniqueId] != null) {
  1177. children.push(_this._nodeMap[descendent.uniqueId]);
  1178. }
  1179. }
  1180. if (children.length) {
  1181. glTFNode.children = children;
  1182. }
  1183. }
  1184. }
  1185. }
  1186. ;
  1187. if (scene.nodes.length) {
  1188. _this._scenes.push(scene);
  1189. }
  1190. });
  1191. };
  1192. /**
  1193. * Creates a mapping of Node unique id to node index and handles animations
  1194. * @param babylonScene Babylon Scene
  1195. * @param nodes Babylon transform nodes
  1196. * @param shouldExportTransformNode Callback specifying if a transform node should be exported
  1197. * @param binaryWriter Buffer to write binary data to
  1198. * @returns Node mapping of unique id to index
  1199. */
  1200. _Exporter.prototype.createNodeMapAndAnimations = function (babylonScene, nodes, shouldExportTransformNode, binaryWriter) {
  1201. var _this = this;
  1202. var nodeMap = {};
  1203. var nodeIndex;
  1204. var runtimeGLTFAnimation = {
  1205. name: 'runtime animations',
  1206. channels: [],
  1207. samplers: []
  1208. };
  1209. var idleGLTFAnimations = [];
  1210. var node;
  1211. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  1212. var babylonTransformNode = nodes_2[_i];
  1213. if (shouldExportTransformNode(babylonTransformNode)) {
  1214. node = this.createNode(babylonTransformNode, binaryWriter);
  1215. var directDescendents = babylonTransformNode.getDescendants(true, function (node) { return (node instanceof BABYLON.TransformNode); });
  1216. if (directDescendents.length || node.mesh != null) {
  1217. this._nodes.push(node);
  1218. nodeIndex = this._nodes.length - 1;
  1219. nodeMap[babylonTransformNode.uniqueId] = nodeIndex;
  1220. }
  1221. if (!babylonScene.animationGroups.length && babylonTransformNode.animations.length) {
  1222. GLTF2._GLTFAnimation._CreateNodeAnimationFromTransformNodeAnimations(babylonTransformNode, runtimeGLTFAnimation, idleGLTFAnimations, nodeMap, this._nodes, binaryWriter, this._bufferViews, this._accessors, this._convertToRightHandedSystem, this._animationSampleRate);
  1223. }
  1224. }
  1225. else {
  1226. "Excluding mesh " + babylonTransformNode.name;
  1227. }
  1228. }
  1229. ;
  1230. if (runtimeGLTFAnimation.channels.length && runtimeGLTFAnimation.samplers.length) {
  1231. this._animations.push(runtimeGLTFAnimation);
  1232. }
  1233. idleGLTFAnimations.forEach(function (idleGLTFAnimation) {
  1234. if (idleGLTFAnimation.channels.length && idleGLTFAnimation.samplers.length) {
  1235. _this._animations.push(idleGLTFAnimation);
  1236. }
  1237. });
  1238. if (babylonScene.animationGroups.length) {
  1239. GLTF2._GLTFAnimation._CreateNodeAnimationFromAnimationGroups(babylonScene, this._animations, nodeMap, this._nodes, binaryWriter, this._bufferViews, this._accessors, this._convertToRightHandedSystem, this._animationSampleRate);
  1240. }
  1241. return nodeMap;
  1242. };
  1243. /**
  1244. * Creates a glTF node from a Babylon mesh
  1245. * @param babylonMesh Source Babylon mesh
  1246. * @param binaryWriter Buffer for storing geometry data
  1247. * @returns glTF node
  1248. */
  1249. _Exporter.prototype.createNode = function (babylonTransformNode, binaryWriter) {
  1250. // create node to hold translation/rotation/scale and the mesh
  1251. var node = {};
  1252. // create mesh
  1253. var mesh = { primitives: [] };
  1254. if (babylonTransformNode.name) {
  1255. node.name = babylonTransformNode.name;
  1256. }
  1257. // Set transformation
  1258. this.setNodeTransformation(node, babylonTransformNode);
  1259. this.setPrimitiveAttributes(mesh, babylonTransformNode, binaryWriter);
  1260. if (mesh.primitives.length) {
  1261. this._meshes.push(mesh);
  1262. node.mesh = this._meshes.length - 1;
  1263. }
  1264. return node;
  1265. };
  1266. return _Exporter;
  1267. }());
  1268. GLTF2._Exporter = _Exporter;
  1269. /**
  1270. * @hidden
  1271. *
  1272. * Stores glTF binary data. If the array buffer byte length is exceeded, it doubles in size dynamically
  1273. */
  1274. var _BinaryWriter = /** @class */ (function () {
  1275. /**
  1276. * Initialize binary writer with an initial byte length
  1277. * @param byteLength Initial byte length of the array buffer
  1278. */
  1279. function _BinaryWriter(byteLength) {
  1280. this._arrayBuffer = new ArrayBuffer(byteLength);
  1281. this._dataView = new DataView(this._arrayBuffer);
  1282. this._byteOffset = 0;
  1283. }
  1284. /**
  1285. * Resize the array buffer to the specified byte length
  1286. * @param byteLength
  1287. */
  1288. _BinaryWriter.prototype.resizeBuffer = function (byteLength) {
  1289. var newBuffer = new ArrayBuffer(byteLength);
  1290. var oldUint8Array = new Uint8Array(this._arrayBuffer);
  1291. var newUint8Array = new Uint8Array(newBuffer);
  1292. for (var i = 0, length_8 = newUint8Array.byteLength; i < length_8; ++i) {
  1293. newUint8Array[i] = oldUint8Array[i];
  1294. }
  1295. this._arrayBuffer = newBuffer;
  1296. this._dataView = new DataView(this._arrayBuffer);
  1297. };
  1298. /**
  1299. * Get an array buffer with the length of the byte offset
  1300. * @returns ArrayBuffer resized to the byte offset
  1301. */
  1302. _BinaryWriter.prototype.getArrayBuffer = function () {
  1303. this.resizeBuffer(this.getByteOffset());
  1304. return this._arrayBuffer;
  1305. };
  1306. /**
  1307. * Get the byte offset of the array buffer
  1308. * @returns byte offset
  1309. */
  1310. _BinaryWriter.prototype.getByteOffset = function () {
  1311. return this._byteOffset;
  1312. };
  1313. /**
  1314. * Stores an UInt8 in the array buffer
  1315. * @param entry
  1316. * @param byteOffset If defined, specifies where to set the value as an offset.
  1317. */
  1318. _BinaryWriter.prototype.setUInt8 = function (entry, byteOffset) {
  1319. if (byteOffset != null) {
  1320. if (byteOffset < this._byteOffset) {
  1321. this._dataView.setUint8(byteOffset, entry);
  1322. }
  1323. else {
  1324. BABYLON.Tools.Error('BinaryWriter: byteoffset is greater than the current binary buffer length!');
  1325. }
  1326. }
  1327. else {
  1328. if (this._byteOffset + 1 > this._arrayBuffer.byteLength) {
  1329. this.resizeBuffer(this._arrayBuffer.byteLength * 2);
  1330. }
  1331. this._dataView.setUint8(this._byteOffset++, entry);
  1332. }
  1333. };
  1334. /**
  1335. * Gets an UInt32 in the array buffer
  1336. * @param entry
  1337. * @param byteOffset If defined, specifies where to set the value as an offset.
  1338. */
  1339. _BinaryWriter.prototype.getUInt32 = function (byteOffset) {
  1340. if (byteOffset < this._byteOffset) {
  1341. return this._dataView.getUint32(byteOffset, true);
  1342. }
  1343. else {
  1344. BABYLON.Tools.Error('BinaryWriter: byteoffset is greater than the current binary buffer length!');
  1345. throw new Error('BinaryWriter: byteoffset is greater than the current binary buffer length!');
  1346. }
  1347. };
  1348. _BinaryWriter.prototype.getVector3Float32FromRef = function (vector3, byteOffset) {
  1349. if (byteOffset + 8 > this._byteOffset) {
  1350. BABYLON.Tools.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!");
  1351. }
  1352. else {
  1353. vector3.x = this._dataView.getFloat32(byteOffset, true);
  1354. vector3.y = this._dataView.getFloat32(byteOffset + 4, true);
  1355. vector3.z = this._dataView.getFloat32(byteOffset + 8, true);
  1356. }
  1357. };
  1358. _BinaryWriter.prototype.setVector3Float32FromRef = function (vector3, byteOffset) {
  1359. if (byteOffset + 8 > this._byteOffset) {
  1360. BABYLON.Tools.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!");
  1361. }
  1362. else {
  1363. this._dataView.setFloat32(byteOffset, vector3.x, true);
  1364. this._dataView.setFloat32(byteOffset + 4, vector3.y, true);
  1365. this._dataView.setFloat32(byteOffset + 8, vector3.z, true);
  1366. }
  1367. };
  1368. _BinaryWriter.prototype.getVector4Float32FromRef = function (vector4, byteOffset) {
  1369. if (byteOffset + 12 > this._byteOffset) {
  1370. BABYLON.Tools.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!");
  1371. }
  1372. else {
  1373. vector4.x = this._dataView.getFloat32(byteOffset, true);
  1374. vector4.y = this._dataView.getFloat32(byteOffset + 4, true);
  1375. vector4.z = this._dataView.getFloat32(byteOffset + 8, true);
  1376. vector4.w = this._dataView.getFloat32(byteOffset + 12, true);
  1377. }
  1378. };
  1379. _BinaryWriter.prototype.setVector4Float32FromRef = function (vector4, byteOffset) {
  1380. if (byteOffset + 12 > this._byteOffset) {
  1381. BABYLON.Tools.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!");
  1382. }
  1383. else {
  1384. this._dataView.setFloat32(byteOffset, vector4.x, true);
  1385. this._dataView.setFloat32(byteOffset + 4, vector4.y, true);
  1386. this._dataView.setFloat32(byteOffset + 8, vector4.z, true);
  1387. this._dataView.setFloat32(byteOffset + 12, vector4.w, true);
  1388. }
  1389. };
  1390. /**
  1391. * Stores a Float32 in the array buffer
  1392. * @param entry
  1393. */
  1394. _BinaryWriter.prototype.setFloat32 = function (entry, byteOffset) {
  1395. if (isNaN(entry)) {
  1396. BABYLON.Tools.Error('Invalid data being written!');
  1397. }
  1398. if (byteOffset != null) {
  1399. if (byteOffset < this._byteOffset) {
  1400. this._dataView.setFloat32(byteOffset, entry, true);
  1401. }
  1402. else {
  1403. BABYLON.Tools.Error('BinaryWriter: byteoffset is greater than the current binary length!');
  1404. }
  1405. }
  1406. if (this._byteOffset + 4 > this._arrayBuffer.byteLength) {
  1407. this.resizeBuffer(this._arrayBuffer.byteLength * 2);
  1408. }
  1409. this._dataView.setFloat32(this._byteOffset, entry, true);
  1410. this._byteOffset += 4;
  1411. };
  1412. /**
  1413. * Stores an UInt32 in the array buffer
  1414. * @param entry
  1415. * @param byteOffset If defined, specifies where to set the value as an offset.
  1416. */
  1417. _BinaryWriter.prototype.setUInt32 = function (entry, byteOffset) {
  1418. if (byteOffset != null) {
  1419. if (byteOffset < this._byteOffset) {
  1420. this._dataView.setUint32(byteOffset, entry, true);
  1421. }
  1422. else {
  1423. BABYLON.Tools.Error('BinaryWriter: byteoffset is greater than the current binary buffer length!');
  1424. }
  1425. }
  1426. else {
  1427. if (this._byteOffset + 4 > this._arrayBuffer.byteLength) {
  1428. this.resizeBuffer(this._arrayBuffer.byteLength * 2);
  1429. }
  1430. this._dataView.setUint32(this._byteOffset, entry, true);
  1431. this._byteOffset += 4;
  1432. }
  1433. };
  1434. return _BinaryWriter;
  1435. }());
  1436. GLTF2._BinaryWriter = _BinaryWriter;
  1437. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1438. })(BABYLON || (BABYLON = {}));
  1439. //# sourceMappingURL=babylon.glTFExporter.js.map
  1440. var BABYLON;
  1441. (function (BABYLON) {
  1442. /**
  1443. * Class for holding and downloading glTF file data
  1444. */
  1445. var GLTFData = /** @class */ (function () {
  1446. /**
  1447. * Initializes the glTF file object
  1448. */
  1449. function GLTFData() {
  1450. this.glTFFiles = {};
  1451. }
  1452. /**
  1453. * Downloads the glTF data as files based on their names and data
  1454. */
  1455. GLTFData.prototype.downloadFiles = function () {
  1456. /**
  1457. * Checks for a matching suffix at the end of a string (for ES5 and lower)
  1458. * @param str Source string
  1459. * @param suffix Suffix to search for in the source string
  1460. * @returns Boolean indicating whether the suffix was found (true) or not (false)
  1461. */
  1462. function endsWith(str, suffix) {
  1463. return str.indexOf(suffix, str.length - suffix.length) !== -1;
  1464. }
  1465. for (var key in this.glTFFiles) {
  1466. var link = document.createElement('a');
  1467. document.body.appendChild(link);
  1468. link.setAttribute("type", "hidden");
  1469. link.download = key;
  1470. var blob = this.glTFFiles[key];
  1471. var mimeType = void 0;
  1472. if (endsWith(key, ".glb")) {
  1473. mimeType = { type: "model/gltf-binary" };
  1474. }
  1475. else if (endsWith(key, ".bin")) {
  1476. mimeType = { type: "application/octet-stream" };
  1477. }
  1478. else if (endsWith(key, ".gltf")) {
  1479. mimeType = { type: "model/gltf+json" };
  1480. }
  1481. else if (endsWith(key, ".jpeg" || ".jpg")) {
  1482. mimeType = { type: "image/jpeg" /* JPEG */ };
  1483. }
  1484. else if (endsWith(key, ".png")) {
  1485. mimeType = { type: "image/png" /* PNG */ };
  1486. }
  1487. link.href = window.URL.createObjectURL(new Blob([blob], mimeType));
  1488. link.click();
  1489. }
  1490. };
  1491. return GLTFData;
  1492. }());
  1493. BABYLON.GLTFData = GLTFData;
  1494. })(BABYLON || (BABYLON = {}));
  1495. //# sourceMappingURL=babylon.glTFData.js.map
  1496. var BABYLON;
  1497. (function (BABYLON) {
  1498. var GLTF2;
  1499. (function (GLTF2) {
  1500. /**
  1501. * Utility methods for working with glTF material conversion properties. This class should only be used internally
  1502. * @hidden
  1503. */
  1504. var _GLTFMaterialExporter = /** @class */ (function () {
  1505. function _GLTFMaterialExporter(exporter) {
  1506. /**
  1507. * Mapping to store textures
  1508. */
  1509. this._textureMap = {};
  1510. this._textureMap = {};
  1511. this._exporter = exporter;
  1512. }
  1513. /**
  1514. * Specifies if two colors are approximately equal in value
  1515. * @param color1 first color to compare to
  1516. * @param color2 second color to compare to
  1517. * @param epsilon threshold value
  1518. */
  1519. _GLTFMaterialExporter.FuzzyEquals = function (color1, color2, epsilon) {
  1520. return BABYLON.Scalar.WithinEpsilon(color1.r, color2.r, epsilon) &&
  1521. BABYLON.Scalar.WithinEpsilon(color1.g, color2.g, epsilon) &&
  1522. BABYLON.Scalar.WithinEpsilon(color1.b, color2.b, epsilon);
  1523. };
  1524. /**
  1525. * Gets the materials from a Babylon scene and converts them to glTF materials
  1526. * @param scene babylonjs scene
  1527. * @param mimeType texture mime type
  1528. * @param images array of images
  1529. * @param textures array of textures
  1530. * @param materials array of materials
  1531. * @param imageData mapping of texture names to base64 textures
  1532. * @param hasTextureCoords specifies if texture coordinates are present on the material
  1533. */
  1534. _GLTFMaterialExporter.prototype._convertMaterialsToGLTFAsync = function (babylonMaterials, mimeType, hasTextureCoords) {
  1535. var promises = [];
  1536. for (var _i = 0, babylonMaterials_1 = babylonMaterials; _i < babylonMaterials_1.length; _i++) {
  1537. var babylonMaterial = babylonMaterials_1[_i];
  1538. if (babylonMaterial instanceof BABYLON.StandardMaterial) {
  1539. promises.push(this._convertStandardMaterialAsync(babylonMaterial, mimeType, hasTextureCoords));
  1540. }
  1541. else if (babylonMaterial instanceof BABYLON.PBRMetallicRoughnessMaterial) {
  1542. promises.push(this._convertPBRMetallicRoughnessMaterialAsync(babylonMaterial, mimeType, hasTextureCoords));
  1543. }
  1544. else if (babylonMaterial instanceof BABYLON.PBRMaterial) {
  1545. promises.push(this._convertPBRMaterialAsync(babylonMaterial, mimeType, hasTextureCoords));
  1546. }
  1547. else {
  1548. BABYLON.Tools.Warn("Unsupported material type: " + babylonMaterial.name);
  1549. }
  1550. }
  1551. return Promise.all(promises).then(function () { });
  1552. };
  1553. /**
  1554. * Makes a copy of the glTF material without the texture parameters
  1555. * @param originalMaterial original glTF material
  1556. * @returns glTF material without texture parameters
  1557. */
  1558. _GLTFMaterialExporter.prototype._stripTexturesFromMaterial = function (originalMaterial) {
  1559. var newMaterial = {};
  1560. if (originalMaterial) {
  1561. newMaterial.name = originalMaterial.name;
  1562. newMaterial.doubleSided = originalMaterial.doubleSided;
  1563. newMaterial.alphaMode = originalMaterial.alphaMode;
  1564. newMaterial.alphaCutoff = originalMaterial.alphaCutoff;
  1565. newMaterial.emissiveFactor = originalMaterial.emissiveFactor;
  1566. var originalPBRMetallicRoughness = originalMaterial.pbrMetallicRoughness;
  1567. if (originalPBRMetallicRoughness) {
  1568. newMaterial.pbrMetallicRoughness = {};
  1569. newMaterial.pbrMetallicRoughness.baseColorFactor = originalPBRMetallicRoughness.baseColorFactor;
  1570. newMaterial.pbrMetallicRoughness.metallicFactor = originalPBRMetallicRoughness.metallicFactor;
  1571. newMaterial.pbrMetallicRoughness.roughnessFactor = originalPBRMetallicRoughness.roughnessFactor;
  1572. }
  1573. }
  1574. return newMaterial;
  1575. };
  1576. /**
  1577. * Specifies if the material has any texture parameters present
  1578. * @param material glTF Material
  1579. * @returns boolean specifying if texture parameters are present
  1580. */
  1581. _GLTFMaterialExporter.prototype._hasTexturesPresent = function (material) {
  1582. if (material.emissiveTexture || material.normalTexture || material.occlusionTexture) {
  1583. return true;
  1584. }
  1585. var pbrMat = material.pbrMetallicRoughness;
  1586. if (pbrMat) {
  1587. if (pbrMat.baseColorTexture || pbrMat.metallicRoughnessTexture) {
  1588. return true;
  1589. }
  1590. }
  1591. return false;
  1592. };
  1593. /**
  1594. * Converts a Babylon StandardMaterial to a glTF Metallic Roughness Material
  1595. * @param babylonStandardMaterial
  1596. * @returns glTF Metallic Roughness Material representation
  1597. */
  1598. _GLTFMaterialExporter.prototype._convertToGLTFPBRMetallicRoughness = function (babylonStandardMaterial) {
  1599. var P0 = new BABYLON.Vector2(0, 1);
  1600. var P1 = new BABYLON.Vector2(0, 0.1);
  1601. var P2 = new BABYLON.Vector2(0, 0.1);
  1602. var P3 = new BABYLON.Vector2(1300, 0.1);
  1603. /**
  1604. * Given the control points, solve for x based on a given t for a cubic bezier curve
  1605. * @param t a value between 0 and 1
  1606. * @param p0 first control point
  1607. * @param p1 second control point
  1608. * @param p2 third control point
  1609. * @param p3 fourth control point
  1610. * @returns number result of cubic bezier curve at the specified t
  1611. */
  1612. function _cubicBezierCurve(t, p0, p1, p2, p3) {
  1613. return ((1 - t) * (1 - t) * (1 - t) * p0 +
  1614. 3 * (1 - t) * (1 - t) * t * p1 +
  1615. 3 * (1 - t) * t * t * p2 +
  1616. t * t * t * p3);
  1617. }
  1618. /**
  1619. * Evaluates a specified specular power value to determine the appropriate roughness value,
  1620. * based on a pre-defined cubic bezier curve with specular on the abscissa axis (x-axis)
  1621. * and roughness on the ordinant axis (y-axis)
  1622. * @param specularPower specular power of standard material
  1623. * @returns Number representing the roughness value
  1624. */
  1625. function _solveForRoughness(specularPower) {
  1626. var t = Math.pow(specularPower / P3.x, 0.333333);
  1627. return _cubicBezierCurve(t, P0.y, P1.y, P2.y, P3.y);
  1628. }
  1629. var diffuse = babylonStandardMaterial.diffuseColor.toLinearSpace().scale(0.5);
  1630. var opacity = babylonStandardMaterial.alpha;
  1631. var specularPower = BABYLON.Scalar.Clamp(babylonStandardMaterial.specularPower, 0, _GLTFMaterialExporter._MaxSpecularPower);
  1632. var roughness = _solveForRoughness(specularPower);
  1633. var glTFPbrMetallicRoughness = {
  1634. baseColorFactor: [
  1635. diffuse.r,
  1636. diffuse.g,
  1637. diffuse.b,
  1638. opacity
  1639. ],
  1640. metallicFactor: 0,
  1641. roughnessFactor: roughness,
  1642. };
  1643. return glTFPbrMetallicRoughness;
  1644. };
  1645. /**
  1646. * Computes the metallic factor
  1647. * @param diffuse diffused value
  1648. * @param specular specular value
  1649. * @param oneMinusSpecularStrength one minus the specular strength
  1650. * @returns metallic value
  1651. */
  1652. _GLTFMaterialExporter._SolveMetallic = function (diffuse, specular, oneMinusSpecularStrength) {
  1653. if (specular < this._DielectricSpecular.r) {
  1654. this._DielectricSpecular;
  1655. return 0;
  1656. }
  1657. var a = this._DielectricSpecular.r;
  1658. var b = diffuse * oneMinusSpecularStrength / (1.0 - this._DielectricSpecular.r) + specular - 2.0 * this._DielectricSpecular.r;
  1659. var c = this._DielectricSpecular.r - specular;
  1660. var D = b * b - 4.0 * a * c;
  1661. return BABYLON.Scalar.Clamp((-b + Math.sqrt(D)) / (2.0 * a), 0, 1);
  1662. };
  1663. /**
  1664. * Gets the glTF alpha mode from the Babylon Material
  1665. * @param babylonMaterial Babylon Material
  1666. * @returns The Babylon alpha mode value
  1667. */
  1668. _GLTFMaterialExporter.prototype._getAlphaMode = function (babylonMaterial) {
  1669. if (babylonMaterial.needAlphaBlending()) {
  1670. return "BLEND" /* BLEND */;
  1671. }
  1672. else if (babylonMaterial.needAlphaTesting()) {
  1673. return "MASK" /* MASK */;
  1674. }
  1675. else {
  1676. return "OPAQUE" /* OPAQUE */;
  1677. }
  1678. };
  1679. /**
  1680. * Converts a Babylon Standard Material to a glTF Material
  1681. * @param babylonStandardMaterial BJS Standard Material
  1682. * @param mimeType mime type to use for the textures
  1683. * @param images array of glTF image interfaces
  1684. * @param textures array of glTF texture interfaces
  1685. * @param materials array of glTF material interfaces
  1686. * @param imageData map of image file name to data
  1687. * @param hasTextureCoords specifies if texture coordinates are present on the submesh to determine if textures should be applied
  1688. */
  1689. _GLTFMaterialExporter.prototype._convertStandardMaterialAsync = function (babylonStandardMaterial, mimeType, hasTextureCoords) {
  1690. var materialMap = this._exporter._materialMap;
  1691. var materials = this._exporter._materials;
  1692. var alphaMode = this._getAlphaMode(babylonStandardMaterial);
  1693. var promises = [];
  1694. var glTFPbrMetallicRoughness = this._convertToGLTFPBRMetallicRoughness(babylonStandardMaterial);
  1695. var glTFMaterial = { name: babylonStandardMaterial.name };
  1696. if (babylonStandardMaterial.backFaceCulling != null && !babylonStandardMaterial.backFaceCulling) {
  1697. if (!babylonStandardMaterial.twoSidedLighting) {
  1698. BABYLON.Tools.Warn(babylonStandardMaterial.name + ": Back-face culling enabled and two-sided lighting disabled is not supported in glTF.");
  1699. }
  1700. glTFMaterial.doubleSided = true;
  1701. }
  1702. if (hasTextureCoords) {
  1703. if (babylonStandardMaterial.diffuseTexture) {
  1704. promises.push(this._exportTextureAsync(babylonStandardMaterial.diffuseTexture, mimeType).then(function (glTFTexture) {
  1705. if (glTFTexture) {
  1706. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  1707. }
  1708. }));
  1709. }
  1710. if (babylonStandardMaterial.bumpTexture) {
  1711. promises.push(this._exportTextureAsync(babylonStandardMaterial.bumpTexture, mimeType).then(function (glTFTexture) {
  1712. if (glTFTexture) {
  1713. glTFMaterial.normalTexture = glTFTexture;
  1714. if (babylonStandardMaterial.bumpTexture != null && babylonStandardMaterial.bumpTexture.level !== 1) {
  1715. glTFMaterial.normalTexture.scale = babylonStandardMaterial.bumpTexture.level;
  1716. }
  1717. }
  1718. }));
  1719. }
  1720. if (babylonStandardMaterial.emissiveTexture) {
  1721. glTFMaterial.emissiveFactor = [1.0, 1.0, 1.0];
  1722. promises.push(this._exportTextureAsync(babylonStandardMaterial.emissiveTexture, mimeType).then(function (glTFEmissiveTexture) {
  1723. if (glTFEmissiveTexture) {
  1724. glTFMaterial.emissiveTexture = glTFEmissiveTexture;
  1725. }
  1726. }));
  1727. }
  1728. if (babylonStandardMaterial.ambientTexture) {
  1729. promises.push(this._exportTextureAsync(babylonStandardMaterial.ambientTexture, mimeType).then(function (glTFTexture) {
  1730. if (glTFTexture) {
  1731. var occlusionTexture = {
  1732. index: glTFTexture.index
  1733. };
  1734. glTFMaterial.occlusionTexture = occlusionTexture;
  1735. occlusionTexture.strength = 1.0;
  1736. }
  1737. }));
  1738. }
  1739. }
  1740. if (babylonStandardMaterial.alpha < 1.0 || babylonStandardMaterial.opacityTexture) {
  1741. if (babylonStandardMaterial.alphaMode === BABYLON.Engine.ALPHA_COMBINE) {
  1742. glTFMaterial.alphaMode = "BLEND" /* BLEND */;
  1743. }
  1744. else {
  1745. BABYLON.Tools.Warn(babylonStandardMaterial.name + ": glTF 2.0 does not support alpha mode: " + babylonStandardMaterial.alphaMode.toString());
  1746. }
  1747. }
  1748. if (babylonStandardMaterial.emissiveColor && !_GLTFMaterialExporter.FuzzyEquals(babylonStandardMaterial.emissiveColor, BABYLON.Color3.Black(), _GLTFMaterialExporter._Epsilon)) {
  1749. glTFMaterial.emissiveFactor = babylonStandardMaterial.emissiveColor.asArray();
  1750. }
  1751. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  1752. if (alphaMode !== "OPAQUE" /* OPAQUE */) {
  1753. switch (alphaMode) {
  1754. case "BLEND" /* BLEND */: {
  1755. glTFMaterial.alphaMode = "BLEND" /* BLEND */;
  1756. break;
  1757. }
  1758. case "MASK" /* MASK */: {
  1759. glTFMaterial.alphaMode = "MASK" /* MASK */;
  1760. glTFMaterial.alphaCutoff = babylonStandardMaterial.alphaCutOff;
  1761. break;
  1762. }
  1763. default: {
  1764. BABYLON.Tools.Warn("Unsupported alpha mode " + alphaMode);
  1765. }
  1766. }
  1767. }
  1768. materials.push(glTFMaterial);
  1769. materialMap[babylonStandardMaterial.uniqueId] = materials.length - 1;
  1770. return Promise.all(promises).then(function () { });
  1771. };
  1772. /**
  1773. * Converts a Babylon PBR Metallic Roughness Material to a glTF Material
  1774. * @param babylonPBRMetalRoughMaterial BJS PBR Metallic Roughness Material
  1775. * @param mimeType mime type to use for the textures
  1776. * @param images array of glTF image interfaces
  1777. * @param textures array of glTF texture interfaces
  1778. * @param materials array of glTF material interfaces
  1779. * @param imageData map of image file name to data
  1780. * @param hasTextureCoords specifies if texture coordinates are present on the submesh to determine if textures should be applied
  1781. */
  1782. _GLTFMaterialExporter.prototype._convertPBRMetallicRoughnessMaterialAsync = function (babylonPBRMetalRoughMaterial, mimeType, hasTextureCoords) {
  1783. var materialMap = this._exporter._materialMap;
  1784. var materials = this._exporter._materials;
  1785. var promises = [];
  1786. var glTFPbrMetallicRoughness = {};
  1787. if (babylonPBRMetalRoughMaterial.baseColor) {
  1788. glTFPbrMetallicRoughness.baseColorFactor = [
  1789. babylonPBRMetalRoughMaterial.baseColor.r,
  1790. babylonPBRMetalRoughMaterial.baseColor.g,
  1791. babylonPBRMetalRoughMaterial.baseColor.b,
  1792. babylonPBRMetalRoughMaterial.alpha
  1793. ];
  1794. }
  1795. if (babylonPBRMetalRoughMaterial.metallic != null && babylonPBRMetalRoughMaterial.metallic !== 1) {
  1796. glTFPbrMetallicRoughness.metallicFactor = babylonPBRMetalRoughMaterial.metallic;
  1797. }
  1798. if (babylonPBRMetalRoughMaterial.roughness != null && babylonPBRMetalRoughMaterial.roughness !== 1) {
  1799. glTFPbrMetallicRoughness.roughnessFactor = babylonPBRMetalRoughMaterial.roughness;
  1800. }
  1801. var glTFMaterial = {
  1802. name: babylonPBRMetalRoughMaterial.name
  1803. };
  1804. if (babylonPBRMetalRoughMaterial.doubleSided) {
  1805. glTFMaterial.doubleSided = babylonPBRMetalRoughMaterial.doubleSided;
  1806. }
  1807. var alphaMode = null;
  1808. if (babylonPBRMetalRoughMaterial.transparencyMode != null) {
  1809. alphaMode = this._getAlphaMode(babylonPBRMetalRoughMaterial);
  1810. if (alphaMode) {
  1811. if (alphaMode !== "OPAQUE" /* OPAQUE */) { //glTF defaults to opaque
  1812. glTFMaterial.alphaMode = alphaMode;
  1813. if (alphaMode === "MASK" /* MASK */) {
  1814. glTFMaterial.alphaCutoff = babylonPBRMetalRoughMaterial.alphaCutOff;
  1815. }
  1816. }
  1817. }
  1818. }
  1819. if (hasTextureCoords) {
  1820. if (babylonPBRMetalRoughMaterial.baseTexture != null) {
  1821. promises.push(this._exportTextureAsync(babylonPBRMetalRoughMaterial.baseTexture, mimeType).then(function (glTFTexture) {
  1822. if (glTFTexture) {
  1823. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  1824. }
  1825. }));
  1826. }
  1827. if (babylonPBRMetalRoughMaterial.normalTexture) {
  1828. promises.push(this._exportTextureAsync(babylonPBRMetalRoughMaterial.normalTexture, mimeType).then(function (glTFTexture) {
  1829. if (glTFTexture) {
  1830. glTFMaterial.normalTexture = glTFTexture;
  1831. if (babylonPBRMetalRoughMaterial.normalTexture.level !== 1) {
  1832. glTFMaterial.normalTexture.scale = babylonPBRMetalRoughMaterial.normalTexture.level;
  1833. }
  1834. }
  1835. }));
  1836. }
  1837. if (babylonPBRMetalRoughMaterial.occlusionTexture) {
  1838. promises.push(this._exportTextureAsync(babylonPBRMetalRoughMaterial.occlusionTexture, mimeType).then(function (glTFTexture) {
  1839. if (glTFTexture) {
  1840. glTFMaterial.occlusionTexture = glTFTexture;
  1841. if (babylonPBRMetalRoughMaterial.occlusionStrength != null) {
  1842. glTFMaterial.occlusionTexture.strength = babylonPBRMetalRoughMaterial.occlusionStrength;
  1843. }
  1844. }
  1845. }));
  1846. }
  1847. if (babylonPBRMetalRoughMaterial.emissiveTexture) {
  1848. promises.push(this._exportTextureAsync(babylonPBRMetalRoughMaterial.emissiveTexture, mimeType).then(function (glTFTexture) {
  1849. if (glTFTexture) {
  1850. glTFMaterial.emissiveTexture = glTFTexture;
  1851. }
  1852. }));
  1853. }
  1854. }
  1855. if (_GLTFMaterialExporter.FuzzyEquals(babylonPBRMetalRoughMaterial.emissiveColor, BABYLON.Color3.Black(), _GLTFMaterialExporter._Epsilon)) {
  1856. glTFMaterial.emissiveFactor = babylonPBRMetalRoughMaterial.emissiveColor.asArray();
  1857. }
  1858. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  1859. materials.push(glTFMaterial);
  1860. materialMap[babylonPBRMetalRoughMaterial.uniqueId] = materials.length - 1;
  1861. return Promise.all(promises).then(function () { });
  1862. };
  1863. /**
  1864. * Converts an image typed array buffer to a base64 image
  1865. * @param buffer typed array buffer
  1866. * @param width width of the image
  1867. * @param height height of the image
  1868. * @param mimeType mimetype of the image
  1869. * @returns base64 image string
  1870. */
  1871. _GLTFMaterialExporter.prototype._createBase64FromCanvasAsync = function (buffer, width, height, mimeType) {
  1872. var _this = this;
  1873. return new Promise(function (resolve, reject) {
  1874. var hostingScene;
  1875. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  1876. var engine = _this._exporter._getLocalEngine();
  1877. hostingScene = new BABYLON.Scene(engine);
  1878. // Create a temporary texture with the texture buffer data
  1879. var tempTexture = engine.createRawTexture(buffer, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, true, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  1880. var postProcess = new BABYLON.PostProcess("pass", "pass", null, null, 1, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, undefined, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, undefined, null, false);
  1881. postProcess.getEffect().executeWhenCompiled(function () {
  1882. postProcess.onApply = function (effect) {
  1883. effect._bindTexture("textureSampler", tempTexture);
  1884. };
  1885. // Set the size of the texture
  1886. engine.setSize(width, height);
  1887. hostingScene.postProcessManager.directRender([postProcess], null);
  1888. postProcess.dispose();
  1889. tempTexture.dispose();
  1890. // Read data from WebGL
  1891. var canvas = engine.getRenderingCanvas();
  1892. if (canvas) {
  1893. BABYLON.Tools.ToBlob(canvas, function (blob) {
  1894. if (blob) {
  1895. var fileReader = new FileReader();
  1896. fileReader.onload = function (event) {
  1897. var base64String = event.target.result;
  1898. hostingScene.dispose();
  1899. resolve(base64String);
  1900. };
  1901. fileReader.readAsDataURL(blob);
  1902. }
  1903. else {
  1904. reject("Failed to get blob from image canvas!");
  1905. }
  1906. });
  1907. }
  1908. else {
  1909. reject("Engine is missing a canvas!");
  1910. }
  1911. });
  1912. });
  1913. };
  1914. /**
  1915. * Generates a white texture based on the specified width and height
  1916. * @param width width of the texture in pixels
  1917. * @param height height of the texture in pixels
  1918. * @param scene babylonjs scene
  1919. * @returns white texture
  1920. */
  1921. _GLTFMaterialExporter.prototype._createWhiteTexture = function (width, height, scene) {
  1922. var data = new Uint8Array(width * height * 4);
  1923. for (var i = 0; i < data.length; i = i + 4) {
  1924. data[i] = data[i + 1] = data[i + 2] = data[i + 3] = 0xFF;
  1925. }
  1926. var rawTexture = BABYLON.RawTexture.CreateRGBATexture(data, width, height, scene);
  1927. return rawTexture;
  1928. };
  1929. /**
  1930. * 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
  1931. * @param texture1 first texture to resize
  1932. * @param texture2 second texture to resize
  1933. * @param scene babylonjs scene
  1934. * @returns resized textures or null
  1935. */
  1936. _GLTFMaterialExporter.prototype._resizeTexturesToSameDimensions = function (texture1, texture2, scene) {
  1937. var texture1Size = texture1 ? texture1.getSize() : { width: 0, height: 0 };
  1938. var texture2Size = texture2 ? texture2.getSize() : { width: 0, height: 0 };
  1939. var resizedTexture1;
  1940. var resizedTexture2;
  1941. if (texture1Size.width < texture2Size.width) {
  1942. if (texture1 && texture1 instanceof BABYLON.Texture) {
  1943. resizedTexture1 = BABYLON.TextureTools.CreateResizedCopy(texture1, texture2Size.width, texture2Size.height, true);
  1944. }
  1945. else {
  1946. resizedTexture1 = this._createWhiteTexture(texture2Size.width, texture2Size.height, scene);
  1947. }
  1948. resizedTexture2 = texture2;
  1949. }
  1950. else if (texture1Size.width > texture2Size.width) {
  1951. if (texture2 && texture2 instanceof BABYLON.Texture) {
  1952. resizedTexture2 = BABYLON.TextureTools.CreateResizedCopy(texture2, texture1Size.width, texture1Size.height, true);
  1953. }
  1954. else {
  1955. resizedTexture2 = this._createWhiteTexture(texture1Size.width, texture1Size.height, scene);
  1956. }
  1957. resizedTexture1 = texture1;
  1958. }
  1959. else {
  1960. resizedTexture1 = texture1;
  1961. resizedTexture2 = texture2;
  1962. }
  1963. return {
  1964. "texture1": resizedTexture1,
  1965. "texture2": resizedTexture2
  1966. };
  1967. };
  1968. /**
  1969. * Converts an array of pixels to a Float32Array
  1970. * Throws an error if the pixel format is not supported
  1971. * @param pixels - array buffer containing pixel values
  1972. * @returns Float32 of pixels
  1973. */
  1974. _GLTFMaterialExporter.prototype._convertPixelArrayToFloat32 = function (pixels) {
  1975. if (pixels instanceof Uint8Array) {
  1976. var length_1 = pixels.length;
  1977. var buffer = new Float32Array(pixels.length);
  1978. for (var i = 0; i < length_1; ++i) {
  1979. buffer[i] = pixels[i] / 255;
  1980. }
  1981. return buffer;
  1982. }
  1983. else if (pixels instanceof Float32Array) {
  1984. return pixels;
  1985. }
  1986. else {
  1987. throw new Error('Unsupported pixel format!');
  1988. }
  1989. };
  1990. /**
  1991. * Convert Specular Glossiness Textures to Metallic Roughness
  1992. * See link below for info on the material conversions from PBR Metallic/Roughness and Specular/Glossiness
  1993. * @link https://github.com/KhronosGroup/glTF/blob/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness/examples/convert-between-workflows-bjs/js/babylon.pbrUtilities.js
  1994. * @param diffuseTexture texture used to store diffuse information
  1995. * @param specularGlossinessTexture texture used to store specular and glossiness information
  1996. * @param factors specular glossiness material factors
  1997. * @param mimeType the mime type to use for the texture
  1998. * @returns pbr metallic roughness interface or null
  1999. */
  2000. _GLTFMaterialExporter.prototype._convertSpecularGlossinessTexturesToMetallicRoughnessAsync = function (diffuseTexture, specularGlossinessTexture, factors, mimeType) {
  2001. var promises = [];
  2002. if (!(diffuseTexture || specularGlossinessTexture)) {
  2003. return Promise.reject('_ConvertSpecularGlosinessTexturesToMetallicRoughness: diffuse and specular glossiness textures are not defined!');
  2004. }
  2005. var scene = diffuseTexture ? diffuseTexture.getScene() : specularGlossinessTexture ? specularGlossinessTexture.getScene() : null;
  2006. if (scene) {
  2007. var resizedTextures = this._resizeTexturesToSameDimensions(diffuseTexture, specularGlossinessTexture, scene);
  2008. var diffuseSize = resizedTextures.texture1.getSize();
  2009. var diffuseBuffer = void 0;
  2010. var specularGlossinessBuffer = void 0;
  2011. var width = diffuseSize.width;
  2012. var height = diffuseSize.height;
  2013. var diffusePixels = resizedTextures.texture1.readPixels();
  2014. var specularPixels = resizedTextures.texture2.readPixels();
  2015. if (diffusePixels) {
  2016. diffuseBuffer = this._convertPixelArrayToFloat32(diffusePixels);
  2017. }
  2018. else {
  2019. return Promise.reject("Failed to retrieve pixels from diffuse texture!");
  2020. }
  2021. if (specularPixels) {
  2022. specularGlossinessBuffer = this._convertPixelArrayToFloat32(specularPixels);
  2023. }
  2024. else {
  2025. return Promise.reject("Failed to retrieve pixels from specular glossiness texture!");
  2026. }
  2027. var byteLength = specularGlossinessBuffer.byteLength;
  2028. var metallicRoughnessBuffer = new Uint8Array(byteLength);
  2029. var baseColorBuffer = new Uint8Array(byteLength);
  2030. var strideSize = 4;
  2031. var maxBaseColor = BABYLON.Color3.Black();
  2032. var maxMetallic = 0;
  2033. var maxRoughness = 0;
  2034. for (var h = 0; h < height; ++h) {
  2035. for (var w = 0; w < width; ++w) {
  2036. var offset = (width * h + w) * strideSize;
  2037. var diffuseColor = new BABYLON.Color3(diffuseBuffer[offset], diffuseBuffer[offset + 1], diffuseBuffer[offset + 2]).toLinearSpace().multiply(factors.diffuseColor);
  2038. var specularColor = new BABYLON.Color3(specularGlossinessBuffer[offset], specularGlossinessBuffer[offset + 1], specularGlossinessBuffer[offset + 2]).toLinearSpace().multiply(factors.specularColor);
  2039. var glossiness = (specularGlossinessBuffer[offset + 3]) * factors.glossiness;
  2040. var specularGlossiness = {
  2041. diffuseColor: diffuseColor,
  2042. specularColor: specularColor,
  2043. glossiness: glossiness
  2044. };
  2045. var metallicRoughness = this._convertSpecularGlossinessToMetallicRoughness(specularGlossiness);
  2046. maxBaseColor.r = Math.max(maxBaseColor.r, metallicRoughness.baseColor.r);
  2047. maxBaseColor.g = Math.max(maxBaseColor.g, metallicRoughness.baseColor.g);
  2048. maxBaseColor.b = Math.max(maxBaseColor.b, metallicRoughness.baseColor.b);
  2049. maxMetallic = Math.max(maxMetallic, metallicRoughness.metallic);
  2050. maxRoughness = Math.max(maxRoughness, metallicRoughness.roughness);
  2051. baseColorBuffer[offset] = metallicRoughness.baseColor.r * 255;
  2052. baseColorBuffer[offset + 1] = metallicRoughness.baseColor.g * 255;
  2053. baseColorBuffer[offset + 2] = metallicRoughness.baseColor.b * 255;
  2054. baseColorBuffer[offset + 3] = resizedTextures.texture1.hasAlpha ? diffuseBuffer[offset + 3] * 255 : 255;
  2055. metallicRoughnessBuffer[offset] = 0;
  2056. metallicRoughnessBuffer[offset + 1] = metallicRoughness.roughness * 255;
  2057. metallicRoughnessBuffer[offset + 2] = metallicRoughness.metallic * 255;
  2058. metallicRoughnessBuffer[offset + 3] = 255;
  2059. }
  2060. }
  2061. // Retrieves the metallic roughness factors from the maximum texture values.
  2062. var metallicRoughnessFactors_1 = {
  2063. baseColor: maxBaseColor,
  2064. metallic: maxMetallic,
  2065. roughness: maxRoughness
  2066. };
  2067. var writeOutMetallicRoughnessTexture = false;
  2068. var writeOutBaseColorTexture = false;
  2069. for (var h = 0; h < height; ++h) {
  2070. for (var w = 0; w < width; ++w) {
  2071. var destinationOffset = (width * h + w) * strideSize;
  2072. baseColorBuffer[destinationOffset] /= metallicRoughnessFactors_1.baseColor.r > _GLTFMaterialExporter._Epsilon ? metallicRoughnessFactors_1.baseColor.r : 1;
  2073. baseColorBuffer[destinationOffset + 1] /= metallicRoughnessFactors_1.baseColor.g > _GLTFMaterialExporter._Epsilon ? metallicRoughnessFactors_1.baseColor.g : 1;
  2074. baseColorBuffer[destinationOffset + 2] /= metallicRoughnessFactors_1.baseColor.b > _GLTFMaterialExporter._Epsilon ? metallicRoughnessFactors_1.baseColor.b : 1;
  2075. var linearBaseColorPixel = BABYLON.Color3.FromInts(baseColorBuffer[destinationOffset], baseColorBuffer[destinationOffset + 1], baseColorBuffer[destinationOffset + 2]);
  2076. var sRGBBaseColorPixel = linearBaseColorPixel.toGammaSpace();
  2077. baseColorBuffer[destinationOffset] = sRGBBaseColorPixel.r * 255;
  2078. baseColorBuffer[destinationOffset + 1] = sRGBBaseColorPixel.g * 255;
  2079. baseColorBuffer[destinationOffset + 2] = sRGBBaseColorPixel.b * 255;
  2080. if (!_GLTFMaterialExporter.FuzzyEquals(sRGBBaseColorPixel, BABYLON.Color3.White(), _GLTFMaterialExporter._Epsilon)) {
  2081. writeOutBaseColorTexture = true;
  2082. }
  2083. metallicRoughnessBuffer[destinationOffset + 1] /= metallicRoughnessFactors_1.roughness > _GLTFMaterialExporter._Epsilon ? metallicRoughnessFactors_1.roughness : 1;
  2084. metallicRoughnessBuffer[destinationOffset + 2] /= metallicRoughnessFactors_1.metallic > _GLTFMaterialExporter._Epsilon ? metallicRoughnessFactors_1.metallic : 1;
  2085. var metallicRoughnessPixel = BABYLON.Color3.FromInts(255, metallicRoughnessBuffer[destinationOffset + 1], metallicRoughnessBuffer[destinationOffset + 2]);
  2086. if (!_GLTFMaterialExporter.FuzzyEquals(metallicRoughnessPixel, BABYLON.Color3.White(), _GLTFMaterialExporter._Epsilon)) {
  2087. writeOutMetallicRoughnessTexture = true;
  2088. }
  2089. }
  2090. }
  2091. if (writeOutMetallicRoughnessTexture) {
  2092. var promise = this._createBase64FromCanvasAsync(metallicRoughnessBuffer, width, height, mimeType).then(function (metallicRoughnessBase64) {
  2093. metallicRoughnessFactors_1.metallicRoughnessTextureBase64 = metallicRoughnessBase64;
  2094. });
  2095. promises.push(promise);
  2096. }
  2097. if (writeOutBaseColorTexture) {
  2098. var promise = this._createBase64FromCanvasAsync(baseColorBuffer, width, height, mimeType).then(function (baseColorBase64) {
  2099. metallicRoughnessFactors_1.baseColorTextureBase64 = baseColorBase64;
  2100. });
  2101. promises.push(promise);
  2102. }
  2103. return Promise.all(promises).then(function () {
  2104. return metallicRoughnessFactors_1;
  2105. });
  2106. }
  2107. else {
  2108. return Promise.reject("_ConvertSpecularGlossinessTexturesToMetallicRoughness: Scene from textures is missing!");
  2109. }
  2110. };
  2111. /**
  2112. * Converts specular glossiness material properties to metallic roughness
  2113. * @param specularGlossiness interface with specular glossiness material properties
  2114. * @returns interface with metallic roughness material properties
  2115. */
  2116. _GLTFMaterialExporter.prototype._convertSpecularGlossinessToMetallicRoughness = function (specularGlossiness) {
  2117. var diffusePerceivedBrightness = this._getPerceivedBrightness(specularGlossiness.diffuseColor);
  2118. var specularPerceivedBrightness = this._getPerceivedBrightness(specularGlossiness.specularColor);
  2119. var oneMinusSpecularStrength = 1 - this._getMaxComponent(specularGlossiness.specularColor);
  2120. var metallic = _GLTFMaterialExporter._SolveMetallic(diffusePerceivedBrightness, specularPerceivedBrightness, oneMinusSpecularStrength);
  2121. var baseColorFromDiffuse = specularGlossiness.diffuseColor.scale(oneMinusSpecularStrength / (1.0 - _GLTFMaterialExporter._DielectricSpecular.r) / Math.max(1 - metallic, _GLTFMaterialExporter._Epsilon));
  2122. var baseColorFromSpecular = specularGlossiness.specularColor.subtract(_GLTFMaterialExporter._DielectricSpecular.scale(1 - metallic)).scale(1 / Math.max(metallic, _GLTFMaterialExporter._Epsilon));
  2123. var baseColor = BABYLON.Color3.Lerp(baseColorFromDiffuse, baseColorFromSpecular, metallic * metallic);
  2124. baseColor = baseColor.clampToRef(0, 1, baseColor);
  2125. var metallicRoughness = {
  2126. baseColor: baseColor,
  2127. metallic: metallic,
  2128. roughness: 1 - specularGlossiness.glossiness
  2129. };
  2130. return metallicRoughness;
  2131. };
  2132. /**
  2133. * Calculates the surface reflectance, independent of lighting conditions
  2134. * @param color Color source to calculate brightness from
  2135. * @returns number representing the perceived brightness, or zero if color is undefined
  2136. */
  2137. _GLTFMaterialExporter.prototype._getPerceivedBrightness = function (color) {
  2138. if (color) {
  2139. return Math.sqrt(0.299 * color.r * color.r + 0.587 * color.g * color.g + 0.114 * color.b * color.b);
  2140. }
  2141. return 0;
  2142. };
  2143. /**
  2144. * Returns the maximum color component value
  2145. * @param color
  2146. * @returns maximum color component value, or zero if color is null or undefined
  2147. */
  2148. _GLTFMaterialExporter.prototype._getMaxComponent = function (color) {
  2149. if (color) {
  2150. return Math.max(color.r, Math.max(color.g, color.b));
  2151. }
  2152. return 0;
  2153. };
  2154. /**
  2155. * Convert a PBRMaterial (Metallic/Roughness) to Metallic Roughness factors
  2156. * @param babylonPBRMaterial BJS PBR Metallic Roughness Material
  2157. * @param mimeType mime type to use for the textures
  2158. * @param images array of glTF image interfaces
  2159. * @param textures array of glTF texture interfaces
  2160. * @param glTFPbrMetallicRoughness glTF PBR Metallic Roughness interface
  2161. * @param imageData map of image file name to data
  2162. * @param hasTextureCoords specifies if texture coordinates are present on the submesh to determine if textures should be applied
  2163. * @returns glTF PBR Metallic Roughness factors
  2164. */
  2165. _GLTFMaterialExporter.prototype._convertMetalRoughFactorsToMetallicRoughnessAsync = function (babylonPBRMaterial, mimeType, glTFPbrMetallicRoughness, hasTextureCoords) {
  2166. var promises = [];
  2167. var metallicRoughness = {
  2168. baseColor: babylonPBRMaterial.albedoColor,
  2169. metallic: babylonPBRMaterial.metallic,
  2170. roughness: babylonPBRMaterial.roughness
  2171. };
  2172. if (hasTextureCoords) {
  2173. if (babylonPBRMaterial.albedoTexture) {
  2174. promises.push(this._exportTextureAsync(babylonPBRMaterial.albedoTexture, mimeType).then(function (glTFTexture) {
  2175. if (glTFTexture) {
  2176. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  2177. }
  2178. }));
  2179. }
  2180. if (babylonPBRMaterial.metallicTexture) {
  2181. promises.push(this._exportTextureAsync(babylonPBRMaterial.metallicTexture, mimeType).then(function (glTFTexture) {
  2182. if (glTFTexture) {
  2183. glTFPbrMetallicRoughness.metallicRoughnessTexture = glTFTexture;
  2184. }
  2185. }));
  2186. }
  2187. }
  2188. return Promise.all(promises).then(function () {
  2189. return metallicRoughness;
  2190. });
  2191. };
  2192. _GLTFMaterialExporter.prototype._getGLTFTextureSampler = function (texture) {
  2193. var sampler = this._getGLTFTextureWrapModesSampler(texture);
  2194. var samplingMode = texture instanceof BABYLON.Texture ? texture.samplingMode : null;
  2195. if (samplingMode != null) {
  2196. switch (samplingMode) {
  2197. case BABYLON.Texture.LINEAR_LINEAR: {
  2198. sampler.magFilter = 9729 /* LINEAR */;
  2199. sampler.minFilter = 9729 /* LINEAR */;
  2200. break;
  2201. }
  2202. case BABYLON.Texture.LINEAR_NEAREST: {
  2203. sampler.magFilter = 9729 /* LINEAR */;
  2204. sampler.minFilter = 9728 /* NEAREST */;
  2205. break;
  2206. }
  2207. case BABYLON.Texture.NEAREST_LINEAR: {
  2208. sampler.magFilter = 9728 /* NEAREST */;
  2209. sampler.minFilter = 9729 /* LINEAR */;
  2210. break;
  2211. }
  2212. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR: {
  2213. sampler.magFilter = 9728 /* NEAREST */;
  2214. sampler.minFilter = 9987 /* LINEAR_MIPMAP_LINEAR */;
  2215. break;
  2216. }
  2217. case BABYLON.Texture.NEAREST_NEAREST: {
  2218. sampler.magFilter = 9728 /* NEAREST */;
  2219. sampler.minFilter = 9728 /* NEAREST */;
  2220. break;
  2221. }
  2222. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST: {
  2223. sampler.magFilter = 9728 /* NEAREST */;
  2224. sampler.minFilter = 9985 /* LINEAR_MIPMAP_NEAREST */;
  2225. break;
  2226. }
  2227. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST: {
  2228. sampler.magFilter = 9729 /* LINEAR */;
  2229. sampler.minFilter = 9984 /* NEAREST_MIPMAP_NEAREST */;
  2230. break;
  2231. }
  2232. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR: {
  2233. sampler.magFilter = 9729 /* LINEAR */;
  2234. sampler.minFilter = 9986 /* NEAREST_MIPMAP_LINEAR */;
  2235. break;
  2236. }
  2237. case BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR: {
  2238. sampler.magFilter = 9728 /* NEAREST */;
  2239. sampler.minFilter = 9986 /* NEAREST_MIPMAP_LINEAR */;
  2240. break;
  2241. }
  2242. case BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR: {
  2243. sampler.magFilter = 9729 /* LINEAR */;
  2244. sampler.minFilter = 9987 /* LINEAR_MIPMAP_LINEAR */;
  2245. break;
  2246. }
  2247. case BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST: {
  2248. sampler.magFilter = 9729 /* LINEAR */;
  2249. sampler.minFilter = 9985 /* LINEAR_MIPMAP_NEAREST */;
  2250. break;
  2251. }
  2252. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST: {
  2253. sampler.magFilter = 9728 /* NEAREST */;
  2254. sampler.minFilter = 9984 /* NEAREST_MIPMAP_NEAREST */;
  2255. break;
  2256. }
  2257. }
  2258. }
  2259. return sampler;
  2260. };
  2261. _GLTFMaterialExporter.prototype._getGLTFTextureWrapMode = function (wrapMode) {
  2262. switch (wrapMode) {
  2263. case BABYLON.Texture.WRAP_ADDRESSMODE: {
  2264. return 10497 /* REPEAT */;
  2265. }
  2266. case BABYLON.Texture.CLAMP_ADDRESSMODE: {
  2267. return 33071 /* CLAMP_TO_EDGE */;
  2268. }
  2269. case BABYLON.Texture.MIRROR_ADDRESSMODE: {
  2270. return 33648 /* MIRRORED_REPEAT */;
  2271. }
  2272. default: {
  2273. BABYLON.Tools.Error("Unsupported Texture Wrap Mode " + wrapMode + "!");
  2274. return 10497 /* REPEAT */;
  2275. }
  2276. }
  2277. };
  2278. _GLTFMaterialExporter.prototype._getGLTFTextureWrapModesSampler = function (texture) {
  2279. var wrapS = this._getGLTFTextureWrapMode(texture instanceof BABYLON.Texture ? texture.wrapU : BABYLON.Texture.WRAP_ADDRESSMODE);
  2280. var wrapT = this._getGLTFTextureWrapMode(texture instanceof BABYLON.Texture ? texture.wrapV : BABYLON.Texture.WRAP_ADDRESSMODE);
  2281. if (wrapS === 10497 /* REPEAT */ && wrapT === 10497 /* REPEAT */) { // default wrapping mode in glTF, so omitting
  2282. return {};
  2283. }
  2284. return { wrapS: wrapS, wrapT: wrapT };
  2285. };
  2286. /**
  2287. * Convert a PBRMaterial (Specular/Glossiness) to Metallic Roughness factors
  2288. * @param babylonPBRMaterial BJS PBR Metallic Roughness Material
  2289. * @param mimeType mime type to use for the textures
  2290. * @param images array of glTF image interfaces
  2291. * @param textures array of glTF texture interfaces
  2292. * @param glTFPbrMetallicRoughness glTF PBR Metallic Roughness interface
  2293. * @param imageData map of image file name to data
  2294. * @param hasTextureCoords specifies if texture coordinates are present on the submesh to determine if textures should be applied
  2295. * @returns glTF PBR Metallic Roughness factors
  2296. */
  2297. _GLTFMaterialExporter.prototype._convertSpecGlossFactorsToMetallicRoughnessAsync = function (babylonPBRMaterial, mimeType, glTFPbrMetallicRoughness, hasTextureCoords) {
  2298. var _this = this;
  2299. return Promise.resolve().then(function () {
  2300. var samplers = _this._exporter._samplers;
  2301. var textures = _this._exporter._textures;
  2302. var specGloss = {
  2303. diffuseColor: babylonPBRMaterial.albedoColor || BABYLON.Color3.White(),
  2304. specularColor: babylonPBRMaterial.reflectivityColor || BABYLON.Color3.White(),
  2305. glossiness: babylonPBRMaterial.microSurface || 1,
  2306. };
  2307. var samplerIndex = null;
  2308. var sampler = _this._getGLTFTextureSampler(babylonPBRMaterial.albedoTexture);
  2309. if (sampler.magFilter != null && sampler.minFilter != null && sampler.wrapS != null && sampler.wrapT != null) {
  2310. samplers.push(sampler);
  2311. samplerIndex = samplers.length - 1;
  2312. }
  2313. if (babylonPBRMaterial.reflectivityTexture && !babylonPBRMaterial.useMicroSurfaceFromReflectivityMapAlpha) {
  2314. return Promise.reject("_ConvertPBRMaterial: Glossiness values not included in the reflectivity texture are currently not supported");
  2315. }
  2316. if ((babylonPBRMaterial.albedoTexture || babylonPBRMaterial.reflectivityTexture) && hasTextureCoords) {
  2317. return _this._convertSpecularGlossinessTexturesToMetallicRoughnessAsync(babylonPBRMaterial.albedoTexture, babylonPBRMaterial.reflectivityTexture, specGloss, mimeType).then(function (metallicRoughnessFactors) {
  2318. if (metallicRoughnessFactors.baseColorTextureBase64) {
  2319. var glTFBaseColorTexture = _this._getTextureInfoFromBase64(metallicRoughnessFactors.baseColorTextureBase64, "bjsBaseColorTexture_" + (textures.length) + ".png", mimeType, babylonPBRMaterial.albedoTexture ? babylonPBRMaterial.albedoTexture.coordinatesIndex : null, samplerIndex);
  2320. if (glTFBaseColorTexture) {
  2321. glTFPbrMetallicRoughness.baseColorTexture = glTFBaseColorTexture;
  2322. }
  2323. }
  2324. if (metallicRoughnessFactors.metallicRoughnessTextureBase64) {
  2325. var glTFMRColorTexture = _this._getTextureInfoFromBase64(metallicRoughnessFactors.metallicRoughnessTextureBase64, "bjsMetallicRoughnessTexture_" + (textures.length) + ".png", mimeType, babylonPBRMaterial.reflectivityTexture ? babylonPBRMaterial.reflectivityTexture.coordinatesIndex : null, samplerIndex);
  2326. if (glTFMRColorTexture) {
  2327. glTFPbrMetallicRoughness.metallicRoughnessTexture = glTFMRColorTexture;
  2328. }
  2329. }
  2330. return metallicRoughnessFactors;
  2331. });
  2332. }
  2333. else {
  2334. return _this._convertSpecularGlossinessToMetallicRoughness(specGloss);
  2335. }
  2336. });
  2337. };
  2338. /**
  2339. * Converts a Babylon PBR Metallic Roughness Material to a glTF Material
  2340. * @param babylonPBRMaterial BJS PBR Metallic Roughness Material
  2341. * @param mimeType mime type to use for the textures
  2342. * @param images array of glTF image interfaces
  2343. * @param textures array of glTF texture interfaces
  2344. * @param materials array of glTF material interfaces
  2345. * @param imageData map of image file name to data
  2346. * @param hasTextureCoords specifies if texture coordinates are present on the submesh to determine if textures should be applied
  2347. */
  2348. _GLTFMaterialExporter.prototype._convertPBRMaterialAsync = function (babylonPBRMaterial, mimeType, hasTextureCoords) {
  2349. var _this = this;
  2350. var glTFPbrMetallicRoughness = {};
  2351. var glTFMaterial = {
  2352. name: babylonPBRMaterial.name
  2353. };
  2354. var useMetallicRoughness = babylonPBRMaterial.isMetallicWorkflow();
  2355. if (useMetallicRoughness) {
  2356. if (babylonPBRMaterial.albedoColor) {
  2357. glTFPbrMetallicRoughness.baseColorFactor = [
  2358. babylonPBRMaterial.albedoColor.r,
  2359. babylonPBRMaterial.albedoColor.g,
  2360. babylonPBRMaterial.albedoColor.b,
  2361. babylonPBRMaterial.alpha
  2362. ];
  2363. }
  2364. return this._convertMetalRoughFactorsToMetallicRoughnessAsync(babylonPBRMaterial, mimeType, glTFPbrMetallicRoughness, hasTextureCoords).then(function (metallicRoughness) {
  2365. return _this.setMetallicRoughnessPbrMaterial(metallicRoughness, babylonPBRMaterial, glTFMaterial, glTFPbrMetallicRoughness, mimeType, hasTextureCoords);
  2366. });
  2367. }
  2368. else {
  2369. return this._convertSpecGlossFactorsToMetallicRoughnessAsync(babylonPBRMaterial, mimeType, glTFPbrMetallicRoughness, hasTextureCoords).then(function (metallicRoughness) {
  2370. return _this.setMetallicRoughnessPbrMaterial(metallicRoughness, babylonPBRMaterial, glTFMaterial, glTFPbrMetallicRoughness, mimeType, hasTextureCoords);
  2371. });
  2372. }
  2373. };
  2374. _GLTFMaterialExporter.prototype.setMetallicRoughnessPbrMaterial = function (metallicRoughness, babylonPBRMaterial, glTFMaterial, glTFPbrMetallicRoughness, mimeType, hasTextureCoords) {
  2375. var materialMap = this._exporter._materialMap;
  2376. var materials = this._exporter._materials;
  2377. var promises = [];
  2378. if (metallicRoughness) {
  2379. var alphaMode = null;
  2380. if (babylonPBRMaterial.transparencyMode != null) {
  2381. alphaMode = this._getAlphaMode(babylonPBRMaterial);
  2382. if (alphaMode) {
  2383. if (alphaMode !== "OPAQUE" /* OPAQUE */) { //glTF defaults to opaque
  2384. glTFMaterial.alphaMode = alphaMode;
  2385. if (alphaMode === "MASK" /* MASK */) {
  2386. glTFMaterial.alphaCutoff = babylonPBRMaterial.alphaCutOff;
  2387. }
  2388. }
  2389. }
  2390. }
  2391. if (!(_GLTFMaterialExporter.FuzzyEquals(metallicRoughness.baseColor, BABYLON.Color3.White(), _GLTFMaterialExporter._Epsilon) && babylonPBRMaterial.alpha >= _GLTFMaterialExporter._Epsilon)) {
  2392. glTFPbrMetallicRoughness.baseColorFactor = [
  2393. metallicRoughness.baseColor.r,
  2394. metallicRoughness.baseColor.g,
  2395. metallicRoughness.baseColor.b,
  2396. babylonPBRMaterial.alpha
  2397. ];
  2398. }
  2399. if (metallicRoughness.metallic != null && metallicRoughness.metallic !== 1) {
  2400. glTFPbrMetallicRoughness.metallicFactor = metallicRoughness.metallic;
  2401. }
  2402. if (metallicRoughness.roughness != null && metallicRoughness.roughness !== 1) {
  2403. glTFPbrMetallicRoughness.roughnessFactor = metallicRoughness.roughness;
  2404. }
  2405. if (babylonPBRMaterial.backFaceCulling != null && !babylonPBRMaterial.backFaceCulling) {
  2406. if (!babylonPBRMaterial.twoSidedLighting) {
  2407. BABYLON.Tools.Warn(babylonPBRMaterial.name + ": Back-face culling enabled and two-sided lighting disabled is not supported in glTF.");
  2408. }
  2409. glTFMaterial.doubleSided = true;
  2410. }
  2411. if (hasTextureCoords) {
  2412. if (babylonPBRMaterial.bumpTexture) {
  2413. var promise = this._exportTextureAsync(babylonPBRMaterial.bumpTexture, mimeType).then(function (glTFTexture) {
  2414. if (glTFTexture) {
  2415. glTFMaterial.normalTexture = glTFTexture;
  2416. if (babylonPBRMaterial.bumpTexture.level !== 1) {
  2417. glTFMaterial.normalTexture.scale = babylonPBRMaterial.bumpTexture.level;
  2418. }
  2419. }
  2420. });
  2421. promises.push(promise);
  2422. }
  2423. if (babylonPBRMaterial.ambientTexture) {
  2424. var promise = this._exportTextureAsync(babylonPBRMaterial.ambientTexture, mimeType).then(function (glTFTexture) {
  2425. if (glTFTexture) {
  2426. var occlusionTexture = {
  2427. index: glTFTexture.index
  2428. };
  2429. glTFMaterial.occlusionTexture = occlusionTexture;
  2430. if (babylonPBRMaterial.ambientTextureStrength) {
  2431. occlusionTexture.strength = babylonPBRMaterial.ambientTextureStrength;
  2432. }
  2433. }
  2434. });
  2435. promises.push(promise);
  2436. }
  2437. if (babylonPBRMaterial.emissiveTexture) {
  2438. var promise = this._exportTextureAsync(babylonPBRMaterial.emissiveTexture, mimeType).then(function (glTFTexture) {
  2439. if (glTFTexture) {
  2440. glTFMaterial.emissiveTexture = glTFTexture;
  2441. }
  2442. });
  2443. promises.push(promise);
  2444. }
  2445. }
  2446. if (!_GLTFMaterialExporter.FuzzyEquals(babylonPBRMaterial.emissiveColor, BABYLON.Color3.Black(), _GLTFMaterialExporter._Epsilon)) {
  2447. glTFMaterial.emissiveFactor = babylonPBRMaterial.emissiveColor.asArray();
  2448. }
  2449. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  2450. materials.push(glTFMaterial);
  2451. materialMap[babylonPBRMaterial.uniqueId] = materials.length - 1;
  2452. }
  2453. return Promise.all(promises).then(function (result) { });
  2454. };
  2455. _GLTFMaterialExporter.prototype.getPixelsFromTexture = function (babylonTexture) {
  2456. var pixels = babylonTexture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT ? babylonTexture.readPixels() : babylonTexture.readPixels();
  2457. return pixels;
  2458. };
  2459. /**
  2460. * Extracts a texture from a Babylon texture into file data and glTF data
  2461. * @param babylonTexture Babylon texture to extract
  2462. * @param mimeType Mime Type of the babylonTexture
  2463. * @param images Array of glTF images
  2464. * @param textures Array of glTF textures
  2465. * @param imageData map of image file name and data
  2466. * @return glTF texture info, or null if the texture format is not supported
  2467. */
  2468. _GLTFMaterialExporter.prototype._exportTextureAsync = function (babylonTexture, mimeType) {
  2469. var _this = this;
  2470. return Promise.resolve().then(function () {
  2471. var textureUid = babylonTexture.uid;
  2472. if (textureUid in _this._textureMap) {
  2473. return _this._textureMap[textureUid];
  2474. }
  2475. else {
  2476. var samplers = _this._exporter._samplers;
  2477. var sampler = _this._getGLTFTextureSampler(babylonTexture);
  2478. var samplerIndex_1 = null;
  2479. // if a pre-existing sampler with identical parameters exists, then reuse the previous sampler
  2480. var foundSamplerIndex = null;
  2481. for (var i = 0; i < samplers.length; ++i) {
  2482. var s = samplers[i];
  2483. if (s.minFilter === sampler.minFilter && s.magFilter === sampler.magFilter &&
  2484. s.wrapS === sampler.wrapS && s.wrapT === sampler.wrapT) {
  2485. foundSamplerIndex = i;
  2486. break;
  2487. }
  2488. }
  2489. if (foundSamplerIndex == null) {
  2490. samplers.push(sampler);
  2491. samplerIndex_1 = samplers.length - 1;
  2492. }
  2493. else {
  2494. samplerIndex_1 = foundSamplerIndex;
  2495. }
  2496. var pixels = _this.getPixelsFromTexture(babylonTexture);
  2497. var size = babylonTexture.getSize();
  2498. return _this._createBase64FromCanvasAsync(pixels, size.width, size.height, mimeType).then(function (base64Data) {
  2499. var textureInfo = _this._getTextureInfoFromBase64(base64Data, babylonTexture.name.replace(/\.\/|\/|\.\\|\\/g, "_"), mimeType, babylonTexture.coordinatesIndex, samplerIndex_1);
  2500. if (textureInfo) {
  2501. _this._textureMap[textureUid] = textureInfo;
  2502. }
  2503. return textureInfo;
  2504. });
  2505. }
  2506. });
  2507. };
  2508. /**
  2509. * Builds a texture from base64 string
  2510. * @param base64Texture base64 texture string
  2511. * @param baseTextureName Name to use for the texture
  2512. * @param mimeType image mime type for the texture
  2513. * @param images array of images
  2514. * @param textures array of textures
  2515. * @param imageData map of image data
  2516. * @returns glTF texture info, or null if the texture format is not supported
  2517. */
  2518. _GLTFMaterialExporter.prototype._getTextureInfoFromBase64 = function (base64Texture, baseTextureName, mimeType, texCoordIndex, samplerIndex) {
  2519. var textures = this._exporter._textures;
  2520. var images = this._exporter._images;
  2521. var imageData = this._exporter._imageData;
  2522. var textureInfo = null;
  2523. var glTFTexture = {
  2524. source: images.length,
  2525. name: baseTextureName
  2526. };
  2527. if (samplerIndex != null) {
  2528. glTFTexture.sampler = samplerIndex;
  2529. }
  2530. var binStr = atob(base64Texture.split(',')[1]);
  2531. var arrBuff = new ArrayBuffer(binStr.length);
  2532. var arr = new Uint8Array(arrBuff);
  2533. for (var i = 0, length_2 = binStr.length; i < length_2; ++i) {
  2534. arr[i] = binStr.charCodeAt(i);
  2535. }
  2536. var imageValues = { data: arr, mimeType: mimeType };
  2537. var extension = mimeType === "image/jpeg" /* JPEG */ ? '.jpeg' : '.png';
  2538. var textureName = baseTextureName + extension;
  2539. if (textureName in imageData) {
  2540. textureName = baseTextureName + "_" + BABYLON.Tools.RandomId() + extension;
  2541. }
  2542. imageData[textureName] = imageValues;
  2543. if (mimeType === "image/jpeg" /* JPEG */ || mimeType === "image/png" /* PNG */) {
  2544. var glTFImage = {
  2545. name: baseTextureName,
  2546. uri: textureName
  2547. };
  2548. var foundIndex = null;
  2549. for (var i = 0; i < images.length; ++i) {
  2550. if (images[i].uri === textureName) {
  2551. foundIndex = i;
  2552. break;
  2553. }
  2554. }
  2555. if (foundIndex == null) {
  2556. images.push(glTFImage);
  2557. glTFTexture.source = images.length - 1;
  2558. }
  2559. else {
  2560. glTFTexture.source = foundIndex;
  2561. }
  2562. textures.push(glTFTexture);
  2563. textureInfo = {
  2564. index: textures.length - 1
  2565. };
  2566. if (texCoordIndex != null) {
  2567. textureInfo.texCoord = texCoordIndex;
  2568. }
  2569. }
  2570. else {
  2571. BABYLON.Tools.Error("Unsupported texture mime type " + mimeType);
  2572. }
  2573. return textureInfo;
  2574. };
  2575. /**
  2576. * Represents the dielectric specular values for R, G and B
  2577. */
  2578. _GLTFMaterialExporter._DielectricSpecular = new BABYLON.Color3(0.04, 0.04, 0.04);
  2579. /**
  2580. * Allows the maximum specular power to be defined for material calculations
  2581. */
  2582. _GLTFMaterialExporter._MaxSpecularPower = 1024;
  2583. /**
  2584. * Numeric tolerance value
  2585. */
  2586. _GLTFMaterialExporter._Epsilon = 1e-6;
  2587. return _GLTFMaterialExporter;
  2588. }());
  2589. GLTF2._GLTFMaterialExporter = _GLTFMaterialExporter;
  2590. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2591. })(BABYLON || (BABYLON = {}));
  2592. //# sourceMappingURL=babylon.glTFMaterialExporter.js.map
  2593. var BABYLON;
  2594. (function (BABYLON) {
  2595. var GLTF2;
  2596. (function (GLTF2) {
  2597. /**
  2598. * @hidden
  2599. * Enum for handling in tangent and out tangent.
  2600. */
  2601. var _TangentType;
  2602. (function (_TangentType) {
  2603. /**
  2604. * Specifies that input tangents are used.
  2605. */
  2606. _TangentType[_TangentType["INTANGENT"] = 0] = "INTANGENT";
  2607. /**
  2608. * Specifies that output tangents are used.
  2609. */
  2610. _TangentType[_TangentType["OUTTANGENT"] = 1] = "OUTTANGENT";
  2611. })(_TangentType || (_TangentType = {}));
  2612. /**
  2613. * @hidden
  2614. * Utility class for generating glTF animation data from BabylonJS.
  2615. */
  2616. var _GLTFAnimation = /** @class */ (function () {
  2617. function _GLTFAnimation() {
  2618. }
  2619. /**
  2620. * @ignore
  2621. *
  2622. * Creates glTF channel animation from BabylonJS animation.
  2623. * @param babylonTransformNode - BabylonJS mesh.
  2624. * @param animation - animation.
  2625. * @param animationChannelTargetPath - The target animation channel.
  2626. * @param convertToRightHandedSystem - Specifies if the values should be converted to right-handed.
  2627. * @param useQuaternion - Specifies if quaternions are used.
  2628. * @returns nullable IAnimationData
  2629. */
  2630. _GLTFAnimation._CreateNodeAnimation = function (babylonTransformNode, animation, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion, animationSampleRate) {
  2631. var inputs = [];
  2632. var outputs = [];
  2633. var keyFrames = animation.getKeys();
  2634. var minMaxKeyFrames = _GLTFAnimation.calculateMinMaxKeyFrames(keyFrames);
  2635. var interpolationOrBake = _GLTFAnimation._DeduceInterpolation(keyFrames, animationChannelTargetPath, useQuaternion);
  2636. var frameDelta = minMaxKeyFrames.max - minMaxKeyFrames.min;
  2637. var interpolation = interpolationOrBake.interpolationType;
  2638. var shouldBakeAnimation = interpolationOrBake.shouldBakeAnimation;
  2639. if (shouldBakeAnimation) {
  2640. _GLTFAnimation._CreateBakedAnimation(babylonTransformNode, animation, animationChannelTargetPath, minMaxKeyFrames.min, minMaxKeyFrames.max, animation.framePerSecond, animationSampleRate, inputs, outputs, minMaxKeyFrames, convertToRightHandedSystem, useQuaternion);
  2641. }
  2642. else {
  2643. if (interpolation === "LINEAR" /* LINEAR */ || interpolation === "STEP" /* STEP */) {
  2644. _GLTFAnimation._CreateLinearOrStepAnimation(babylonTransformNode, animation, animationChannelTargetPath, frameDelta, inputs, outputs, convertToRightHandedSystem, useQuaternion);
  2645. }
  2646. else if (interpolation === "CUBICSPLINE" /* CUBICSPLINE */) {
  2647. _GLTFAnimation._CreateCubicSplineAnimation(babylonTransformNode, animation, animationChannelTargetPath, frameDelta, inputs, outputs, convertToRightHandedSystem, useQuaternion);
  2648. }
  2649. else {
  2650. _GLTFAnimation._CreateBakedAnimation(babylonTransformNode, animation, animationChannelTargetPath, minMaxKeyFrames.min, minMaxKeyFrames.max, animation.framePerSecond, animationSampleRate, inputs, outputs, minMaxKeyFrames, convertToRightHandedSystem, useQuaternion);
  2651. }
  2652. }
  2653. if (inputs.length && outputs.length) {
  2654. var result = {
  2655. inputs: inputs,
  2656. outputs: outputs,
  2657. samplerInterpolation: interpolation,
  2658. inputsMin: shouldBakeAnimation ? minMaxKeyFrames.min : BABYLON.Tools.FloatRound(minMaxKeyFrames.min / animation.framePerSecond),
  2659. inputsMax: shouldBakeAnimation ? minMaxKeyFrames.max : BABYLON.Tools.FloatRound(minMaxKeyFrames.max / animation.framePerSecond)
  2660. };
  2661. return result;
  2662. }
  2663. return null;
  2664. };
  2665. _GLTFAnimation._DeduceAnimationInfo = function (animation) {
  2666. var animationChannelTargetPath = null;
  2667. var dataAccessorType = "VEC3" /* VEC3 */;
  2668. var useQuaternion = false;
  2669. var property = animation.targetProperty.split('.');
  2670. switch (property[0]) {
  2671. case 'scaling': {
  2672. animationChannelTargetPath = "scale" /* SCALE */;
  2673. break;
  2674. }
  2675. case 'position': {
  2676. animationChannelTargetPath = "translation" /* TRANSLATION */;
  2677. break;
  2678. }
  2679. case 'rotation': {
  2680. dataAccessorType = "VEC4" /* VEC4 */;
  2681. animationChannelTargetPath = "rotation" /* ROTATION */;
  2682. break;
  2683. }
  2684. case 'rotationQuaternion': {
  2685. dataAccessorType = "VEC4" /* VEC4 */;
  2686. useQuaternion = true;
  2687. animationChannelTargetPath = "rotation" /* ROTATION */;
  2688. break;
  2689. }
  2690. default: {
  2691. BABYLON.Tools.Error("Unsupported animatable property " + property[0]);
  2692. }
  2693. }
  2694. if (animationChannelTargetPath) {
  2695. return { animationChannelTargetPath: animationChannelTargetPath, dataAccessorType: dataAccessorType, useQuaternion: useQuaternion };
  2696. }
  2697. else {
  2698. BABYLON.Tools.Error('animation channel target path and data accessor type could be deduced');
  2699. }
  2700. return null;
  2701. };
  2702. /**
  2703. * @ignore
  2704. * Create node animations from the transform node animations
  2705. * @param babylonTransformNode
  2706. * @param runtimeGLTFAnimation
  2707. * @param idleGLTFAnimations
  2708. * @param nodeMap
  2709. * @param nodes
  2710. * @param binaryWriter
  2711. * @param bufferViews
  2712. * @param accessors
  2713. * @param convertToRightHandedSystem
  2714. */
  2715. _GLTFAnimation._CreateNodeAnimationFromTransformNodeAnimations = function (babylonTransformNode, runtimeGLTFAnimation, idleGLTFAnimations, nodeMap, nodes, binaryWriter, bufferViews, accessors, convertToRightHandedSystem, animationSampleRate) {
  2716. var glTFAnimation;
  2717. if (babylonTransformNode.animations) {
  2718. for (var _i = 0, _a = babylonTransformNode.animations; _i < _a.length; _i++) {
  2719. var animation = _a[_i];
  2720. var animationInfo = _GLTFAnimation._DeduceAnimationInfo(animation);
  2721. if (animationInfo) {
  2722. glTFAnimation = {
  2723. name: animation.name,
  2724. samplers: [],
  2725. channels: []
  2726. };
  2727. _GLTFAnimation.AddAnimation("" + animation.name, animation.hasRunningRuntimeAnimations ? runtimeGLTFAnimation : glTFAnimation, babylonTransformNode, animation, animationInfo.dataAccessorType, animationInfo.animationChannelTargetPath, nodeMap, binaryWriter, bufferViews, accessors, convertToRightHandedSystem, animationInfo.useQuaternion, animationSampleRate);
  2728. if (glTFAnimation.samplers.length && glTFAnimation.channels.length) {
  2729. idleGLTFAnimations.push(glTFAnimation);
  2730. }
  2731. }
  2732. }
  2733. ;
  2734. }
  2735. };
  2736. /**
  2737. * @ignore
  2738. * Create node animations from the animation groups
  2739. * @param babylonScene
  2740. * @param glTFAnimations
  2741. * @param nodeMap
  2742. * @param nodes
  2743. * @param binaryWriter
  2744. * @param bufferViews
  2745. * @param accessors
  2746. * @param convertToRightHandedSystem
  2747. */
  2748. _GLTFAnimation._CreateNodeAnimationFromAnimationGroups = function (babylonScene, glTFAnimations, nodeMap, nodes, binaryWriter, bufferViews, accessors, convertToRightHandedSystem, animationSampleRate) {
  2749. var glTFAnimation;
  2750. if (babylonScene.animationGroups) {
  2751. var animationGroups = babylonScene.animationGroups;
  2752. for (var _i = 0, animationGroups_1 = animationGroups; _i < animationGroups_1.length; _i++) {
  2753. var animationGroup = animationGroups_1[_i];
  2754. glTFAnimation = {
  2755. name: animationGroup.name,
  2756. channels: [],
  2757. samplers: []
  2758. };
  2759. for (var _a = 0, _b = animationGroup.targetedAnimations; _a < _b.length; _a++) {
  2760. var targetAnimation = _b[_a];
  2761. var target = targetAnimation.target;
  2762. var animation = targetAnimation.animation;
  2763. if (target instanceof BABYLON.Mesh || target.length === 1 && target[0] instanceof BABYLON.Mesh) { // TODO: Update to support bones
  2764. var animationInfo = _GLTFAnimation._DeduceAnimationInfo(targetAnimation.animation);
  2765. if (animationInfo) {
  2766. var babylonMesh = target instanceof BABYLON.Mesh ? target : target[0];
  2767. _GLTFAnimation.AddAnimation("" + animation.name, glTFAnimation, babylonMesh, animation, animationInfo.dataAccessorType, animationInfo.animationChannelTargetPath, nodeMap, binaryWriter, bufferViews, accessors, convertToRightHandedSystem, animationInfo.useQuaternion, animationSampleRate);
  2768. }
  2769. }
  2770. }
  2771. ;
  2772. if (glTFAnimation.channels.length && glTFAnimation.samplers.length) {
  2773. glTFAnimations.push(glTFAnimation);
  2774. }
  2775. }
  2776. ;
  2777. }
  2778. };
  2779. _GLTFAnimation.AddAnimation = function (name, glTFAnimation, babylonTransformNode, animation, dataAccessorType, animationChannelTargetPath, nodeMap, binaryWriter, bufferViews, accessors, convertToRightHandedSystem, useQuaternion, animationSampleRate) {
  2780. var animationData = _GLTFAnimation._CreateNodeAnimation(babylonTransformNode, animation, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion, animationSampleRate);
  2781. var bufferView;
  2782. var accessor;
  2783. var keyframeAccessorIndex;
  2784. var dataAccessorIndex;
  2785. var outputLength;
  2786. var animationSampler;
  2787. var animationChannel;
  2788. if (animationData) {
  2789. var nodeIndex = nodeMap[babylonTransformNode.uniqueId];
  2790. // Creates buffer view and accessor for key frames.
  2791. var byteLength = animationData.inputs.length * 4;
  2792. bufferView = GLTF2._GLTFUtilities._CreateBufferView(0, binaryWriter.getByteOffset(), byteLength, undefined, name + " keyframe data view");
  2793. bufferViews.push(bufferView);
  2794. animationData.inputs.forEach(function (input) {
  2795. binaryWriter.setFloat32(input);
  2796. });
  2797. accessor = GLTF2._GLTFUtilities._CreateAccessor(bufferViews.length - 1, name + " keyframes", "SCALAR" /* SCALAR */, 5126 /* FLOAT */, animationData.inputs.length, null, [animationData.inputsMin], [animationData.inputsMax]);
  2798. accessors.push(accessor);
  2799. keyframeAccessorIndex = accessors.length - 1;
  2800. // create bufferview and accessor for keyed values.
  2801. outputLength = animationData.outputs.length;
  2802. byteLength = dataAccessorType === "VEC3" /* VEC3 */ ? animationData.outputs.length * 12 : animationData.outputs.length * 16;
  2803. // check for in and out tangents
  2804. bufferView = GLTF2._GLTFUtilities._CreateBufferView(0, binaryWriter.getByteOffset(), byteLength, undefined, name + " data view");
  2805. bufferViews.push(bufferView);
  2806. animationData.outputs.forEach(function (output) {
  2807. output.forEach(function (entry) {
  2808. binaryWriter.setFloat32(entry);
  2809. });
  2810. });
  2811. accessor = GLTF2._GLTFUtilities._CreateAccessor(bufferViews.length - 1, name + " data", dataAccessorType, 5126 /* FLOAT */, outputLength, null, null, null);
  2812. accessors.push(accessor);
  2813. dataAccessorIndex = accessors.length - 1;
  2814. // create sampler
  2815. animationSampler = {
  2816. interpolation: animationData.samplerInterpolation,
  2817. input: keyframeAccessorIndex,
  2818. output: dataAccessorIndex
  2819. };
  2820. glTFAnimation.samplers.push(animationSampler);
  2821. // create channel
  2822. animationChannel = {
  2823. sampler: glTFAnimation.samplers.length - 1,
  2824. target: {
  2825. node: nodeIndex,
  2826. path: animationChannelTargetPath
  2827. }
  2828. };
  2829. glTFAnimation.channels.push(animationChannel);
  2830. }
  2831. };
  2832. /**
  2833. * Create a baked animation
  2834. * @param babylonTransformNode BabylonJS mesh
  2835. * @param animation BabylonJS animation corresponding to the BabylonJS mesh
  2836. * @param animationChannelTargetPath animation target channel
  2837. * @param minFrame minimum animation frame
  2838. * @param maxFrame maximum animation frame
  2839. * @param fps frames per second of the animation
  2840. * @param inputs input key frames of the animation
  2841. * @param outputs output key frame data of the animation
  2842. * @param convertToRightHandedSystem converts the values to right-handed
  2843. * @param useQuaternion specifies if quaternions should be used
  2844. */
  2845. _GLTFAnimation._CreateBakedAnimation = function (babylonTransformNode, animation, animationChannelTargetPath, minFrame, maxFrame, fps, sampleRate, inputs, outputs, minMaxFrames, convertToRightHandedSystem, useQuaternion) {
  2846. var value;
  2847. var quaternionCache = BABYLON.Quaternion.Identity();
  2848. var previousTime = null;
  2849. var time;
  2850. var maxUsedFrame = null;
  2851. var currKeyFrame = null;
  2852. var nextKeyFrame = null;
  2853. var prevKeyFrame = null;
  2854. var endFrame = null;
  2855. minMaxFrames.min = BABYLON.Tools.FloatRound(minFrame / fps);
  2856. var keyFrames = animation.getKeys();
  2857. for (var i = 0, length_1 = keyFrames.length; i < length_1; ++i) {
  2858. endFrame = null;
  2859. currKeyFrame = keyFrames[i];
  2860. if (i + 1 < length_1) {
  2861. nextKeyFrame = keyFrames[i + 1];
  2862. if (currKeyFrame.value.equals(nextKeyFrame.value)) {
  2863. if (i === 0) { // set the first frame to itself
  2864. endFrame = currKeyFrame.frame;
  2865. }
  2866. else {
  2867. continue;
  2868. }
  2869. }
  2870. else {
  2871. endFrame = nextKeyFrame.frame;
  2872. }
  2873. }
  2874. else {
  2875. // at the last key frame
  2876. prevKeyFrame = keyFrames[i - 1];
  2877. if (currKeyFrame.value.equals(prevKeyFrame.value)) {
  2878. continue;
  2879. }
  2880. else {
  2881. endFrame = maxFrame;
  2882. }
  2883. }
  2884. if (endFrame) {
  2885. for (var f = currKeyFrame.frame; f <= endFrame; f += sampleRate) {
  2886. time = BABYLON.Tools.FloatRound(f / fps);
  2887. if (time === previousTime) {
  2888. continue;
  2889. }
  2890. previousTime = time;
  2891. maxUsedFrame = time;
  2892. value = animation._interpolate(f, 0, undefined, animation.loopMode);
  2893. _GLTFAnimation._SetInterpolatedValue(babylonTransformNode, value, time, animation, animationChannelTargetPath, quaternionCache, inputs, outputs, convertToRightHandedSystem, useQuaternion);
  2894. }
  2895. }
  2896. }
  2897. if (maxUsedFrame) {
  2898. minMaxFrames.max = maxUsedFrame;
  2899. }
  2900. };
  2901. _GLTFAnimation._ConvertFactorToVector3OrQuaternion = function (factor, babylonTransformNode, animation, animationType, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion) {
  2902. var property;
  2903. var componentName;
  2904. var value = null;
  2905. var basePositionRotationOrScale = _GLTFAnimation._GetBasePositionRotationOrScale(babylonTransformNode, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion);
  2906. 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.
  2907. property = animation.targetProperty.split('.');
  2908. componentName = property ? property[1] : ''; // x, y, or z component
  2909. value = useQuaternion ? BABYLON.Quaternion.FromArray(basePositionRotationOrScale).normalize() : BABYLON.Vector3.FromArray(basePositionRotationOrScale);
  2910. switch (componentName) {
  2911. case 'x': {
  2912. value[componentName] = (convertToRightHandedSystem && useQuaternion && (animationChannelTargetPath !== "scale" /* SCALE */)) ? -factor : factor;
  2913. break;
  2914. }
  2915. case 'y': {
  2916. value[componentName] = (convertToRightHandedSystem && useQuaternion && (animationChannelTargetPath !== "scale" /* SCALE */)) ? -factor : factor;
  2917. break;
  2918. }
  2919. case 'z': {
  2920. value[componentName] = (convertToRightHandedSystem && !useQuaternion && (animationChannelTargetPath !== "scale" /* SCALE */)) ? -factor : factor;
  2921. break;
  2922. }
  2923. case 'w': {
  2924. value.w = factor;
  2925. break;
  2926. }
  2927. default: {
  2928. BABYLON.Tools.Error("glTFAnimation: Unsupported component type \"" + componentName + "\" for scale animation!");
  2929. }
  2930. }
  2931. }
  2932. return value;
  2933. };
  2934. _GLTFAnimation._SetInterpolatedValue = function (babylonTransformNode, value, time, animation, animationChannelTargetPath, quaternionCache, inputs, outputs, convertToRightHandedSystem, useQuaternion) {
  2935. var animationType = animation.dataType;
  2936. var cacheValue;
  2937. inputs.push(time);
  2938. if (typeof value === "number") {
  2939. value = this._ConvertFactorToVector3OrQuaternion(value, babylonTransformNode, animation, animationType, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion);
  2940. }
  2941. if (value) {
  2942. if (animationChannelTargetPath === "rotation" /* ROTATION */) {
  2943. if (useQuaternion) {
  2944. quaternionCache = value;
  2945. }
  2946. else {
  2947. cacheValue = value;
  2948. BABYLON.Quaternion.RotationYawPitchRollToRef(cacheValue.y, cacheValue.x, cacheValue.z, quaternionCache);
  2949. }
  2950. if (convertToRightHandedSystem) {
  2951. GLTF2._GLTFUtilities._GetRightHandedQuaternionFromRef(quaternionCache);
  2952. if (!babylonTransformNode.parent) {
  2953. quaternionCache = BABYLON.Quaternion.FromArray([0, 1, 0, 0]).multiply(quaternionCache);
  2954. }
  2955. }
  2956. outputs.push(quaternionCache.asArray());
  2957. }
  2958. else {
  2959. cacheValue = value;
  2960. if (convertToRightHandedSystem && (animationChannelTargetPath !== "scale" /* SCALE */)) {
  2961. GLTF2._GLTFUtilities._GetRightHandedPositionVector3FromRef(cacheValue);
  2962. if (!babylonTransformNode.parent) {
  2963. cacheValue.x *= -1;
  2964. cacheValue.z *= -1;
  2965. }
  2966. }
  2967. outputs.push(cacheValue.asArray());
  2968. }
  2969. }
  2970. };
  2971. /**
  2972. * Creates linear animation from the animation key frames
  2973. * @param babylonTransformNode BabylonJS mesh
  2974. * @param animation BabylonJS animation
  2975. * @param animationChannelTargetPath The target animation channel
  2976. * @param frameDelta The difference between the last and first frame of the animation
  2977. * @param inputs Array to store the key frame times
  2978. * @param outputs Array to store the key frame data
  2979. * @param convertToRightHandedSystem Specifies if the position data should be converted to right handed
  2980. * @param useQuaternion Specifies if quaternions are used in the animation
  2981. */
  2982. _GLTFAnimation._CreateLinearOrStepAnimation = function (babylonTransformNode, animation, animationChannelTargetPath, frameDelta, inputs, outputs, convertToRightHandedSystem, useQuaternion) {
  2983. for (var _i = 0, _a = animation.getKeys(); _i < _a.length; _i++) {
  2984. var keyFrame = _a[_i];
  2985. inputs.push(keyFrame.frame / animation.framePerSecond); // keyframes in seconds.
  2986. _GLTFAnimation._AddKeyframeValue(keyFrame, animation, outputs, animationChannelTargetPath, babylonTransformNode, convertToRightHandedSystem, useQuaternion);
  2987. }
  2988. ;
  2989. };
  2990. /**
  2991. * Creates cubic spline animation from the animation key frames
  2992. * @param babylonTransformNode BabylonJS mesh
  2993. * @param animation BabylonJS animation
  2994. * @param animationChannelTargetPath The target animation channel
  2995. * @param frameDelta The difference between the last and first frame of the animation
  2996. * @param inputs Array to store the key frame times
  2997. * @param outputs Array to store the key frame data
  2998. * @param convertToRightHandedSystem Specifies if the position data should be converted to right handed
  2999. * @param useQuaternion Specifies if quaternions are used in the animation
  3000. */
  3001. _GLTFAnimation._CreateCubicSplineAnimation = function (babylonTransformNode, animation, animationChannelTargetPath, frameDelta, inputs, outputs, convertToRightHandedSystem, useQuaternion) {
  3002. animation.getKeys().forEach(function (keyFrame) {
  3003. inputs.push(keyFrame.frame / animation.framePerSecond); // keyframes in seconds.
  3004. _GLTFAnimation.AddSplineTangent(babylonTransformNode, _TangentType.INTANGENT, outputs, animationChannelTargetPath, "CUBICSPLINE" /* CUBICSPLINE */, keyFrame, frameDelta, useQuaternion, convertToRightHandedSystem);
  3005. _GLTFAnimation._AddKeyframeValue(keyFrame, animation, outputs, animationChannelTargetPath, babylonTransformNode, convertToRightHandedSystem, useQuaternion);
  3006. _GLTFAnimation.AddSplineTangent(babylonTransformNode, _TangentType.OUTTANGENT, outputs, animationChannelTargetPath, "CUBICSPLINE" /* CUBICSPLINE */, keyFrame, frameDelta, useQuaternion, convertToRightHandedSystem);
  3007. });
  3008. };
  3009. _GLTFAnimation._GetBasePositionRotationOrScale = function (babylonTransformNode, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion) {
  3010. var basePositionRotationOrScale;
  3011. if (animationChannelTargetPath === "rotation" /* ROTATION */) {
  3012. if (useQuaternion) {
  3013. if (babylonTransformNode.rotationQuaternion) {
  3014. basePositionRotationOrScale = babylonTransformNode.rotationQuaternion.asArray();
  3015. if (convertToRightHandedSystem) {
  3016. GLTF2._GLTFUtilities._GetRightHandedQuaternionArrayFromRef(basePositionRotationOrScale);
  3017. if (!babylonTransformNode.parent) {
  3018. basePositionRotationOrScale = BABYLON.Quaternion.FromArray([0, 1, 0, 0]).multiply(BABYLON.Quaternion.FromArray(basePositionRotationOrScale)).asArray();
  3019. }
  3020. }
  3021. }
  3022. else {
  3023. basePositionRotationOrScale = BABYLON.Quaternion.Identity().asArray();
  3024. }
  3025. }
  3026. else {
  3027. basePositionRotationOrScale = babylonTransformNode.rotation.asArray();
  3028. GLTF2._GLTFUtilities._GetRightHandedNormalArray3FromRef(basePositionRotationOrScale);
  3029. }
  3030. }
  3031. else if (animationChannelTargetPath === "translation" /* TRANSLATION */) {
  3032. basePositionRotationOrScale = babylonTransformNode.position.asArray();
  3033. if (convertToRightHandedSystem) {
  3034. GLTF2._GLTFUtilities._GetRightHandedPositionArray3FromRef(basePositionRotationOrScale);
  3035. }
  3036. }
  3037. else { // scale
  3038. basePositionRotationOrScale = babylonTransformNode.scaling.asArray();
  3039. }
  3040. return basePositionRotationOrScale;
  3041. };
  3042. /**
  3043. * Adds a key frame value
  3044. * @param keyFrame
  3045. * @param animation
  3046. * @param outputs
  3047. * @param animationChannelTargetPath
  3048. * @param basePositionRotationOrScale
  3049. * @param convertToRightHandedSystem
  3050. * @param useQuaternion
  3051. */
  3052. _GLTFAnimation._AddKeyframeValue = function (keyFrame, animation, outputs, animationChannelTargetPath, babylonTransformNode, convertToRightHandedSystem, useQuaternion) {
  3053. var value;
  3054. var newPositionRotationOrScale;
  3055. var animationType = animation.dataType;
  3056. if (animationType === BABYLON.Animation.ANIMATIONTYPE_VECTOR3) {
  3057. value = keyFrame.value.asArray();
  3058. if (animationChannelTargetPath === "rotation" /* ROTATION */) {
  3059. var array = BABYLON.Vector3.FromArray(value);
  3060. var rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(array.y, array.x, array.z);
  3061. if (convertToRightHandedSystem) {
  3062. GLTF2._GLTFUtilities._GetRightHandedQuaternionFromRef(rotationQuaternion);
  3063. if (!babylonTransformNode.parent) {
  3064. rotationQuaternion = BABYLON.Quaternion.FromArray([0, 1, 0, 0]).multiply(rotationQuaternion);
  3065. }
  3066. }
  3067. value = rotationQuaternion.asArray();
  3068. }
  3069. else if (animationChannelTargetPath === "translation" /* TRANSLATION */) {
  3070. if (convertToRightHandedSystem) {
  3071. GLTF2._GLTFUtilities._GetRightHandedNormalArray3FromRef(value);
  3072. if (!babylonTransformNode.parent) {
  3073. value[0] *= -1;
  3074. value[2] *= -1;
  3075. }
  3076. }
  3077. }
  3078. outputs.push(value); // scale vector.
  3079. }
  3080. 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.
  3081. newPositionRotationOrScale = this._ConvertFactorToVector3OrQuaternion(keyFrame.value, babylonTransformNode, animation, animationType, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion);
  3082. if (newPositionRotationOrScale) {
  3083. if (animationChannelTargetPath === "rotation" /* ROTATION */) {
  3084. var posRotScale = useQuaternion ? newPositionRotationOrScale : BABYLON.Quaternion.RotationYawPitchRoll(newPositionRotationOrScale.y, newPositionRotationOrScale.x, newPositionRotationOrScale.z).normalize();
  3085. if (convertToRightHandedSystem) {
  3086. GLTF2._GLTFUtilities._GetRightHandedQuaternionFromRef(posRotScale);
  3087. if (!babylonTransformNode.parent) {
  3088. posRotScale = BABYLON.Quaternion.FromArray([0, 1, 0, 0]).multiply(posRotScale);
  3089. }
  3090. }
  3091. outputs.push(posRotScale.asArray());
  3092. }
  3093. else if (animationChannelTargetPath === "translation" /* TRANSLATION */) {
  3094. if (convertToRightHandedSystem) {
  3095. GLTF2._GLTFUtilities._GetRightHandedNormalVector3FromRef(newPositionRotationOrScale);
  3096. if (!babylonTransformNode.parent) {
  3097. newPositionRotationOrScale.x *= -1;
  3098. newPositionRotationOrScale.z *= -1;
  3099. }
  3100. }
  3101. }
  3102. outputs.push(newPositionRotationOrScale.asArray());
  3103. }
  3104. }
  3105. else if (animationType === BABYLON.Animation.ANIMATIONTYPE_QUATERNION) {
  3106. value = keyFrame.value.normalize().asArray();
  3107. if (convertToRightHandedSystem) {
  3108. GLTF2._GLTFUtilities._GetRightHandedQuaternionArrayFromRef(value);
  3109. if (!babylonTransformNode.parent) {
  3110. value = BABYLON.Quaternion.FromArray([0, 1, 0, 0]).multiply(BABYLON.Quaternion.FromArray(value)).asArray();
  3111. }
  3112. }
  3113. outputs.push(value);
  3114. }
  3115. else {
  3116. BABYLON.Tools.Error('glTFAnimation: Unsupported key frame values for animation!');
  3117. }
  3118. };
  3119. /**
  3120. * Determine the interpolation based on the key frames
  3121. * @param keyFrames
  3122. * @param animationChannelTargetPath
  3123. * @param useQuaternion
  3124. */
  3125. _GLTFAnimation._DeduceInterpolation = function (keyFrames, animationChannelTargetPath, useQuaternion) {
  3126. var interpolationType;
  3127. var shouldBakeAnimation = false;
  3128. var key;
  3129. if (animationChannelTargetPath === "rotation" /* ROTATION */ && !useQuaternion) {
  3130. return { interpolationType: "LINEAR" /* LINEAR */, shouldBakeAnimation: true };
  3131. }
  3132. for (var i = 0, length_2 = keyFrames.length; i < length_2; ++i) {
  3133. key = keyFrames[i];
  3134. if (key.inTangent || key.outTangent) {
  3135. if (interpolationType) {
  3136. if (interpolationType !== "CUBICSPLINE" /* CUBICSPLINE */) {
  3137. interpolationType = "LINEAR" /* LINEAR */;
  3138. shouldBakeAnimation = true;
  3139. break;
  3140. }
  3141. }
  3142. else {
  3143. interpolationType = "CUBICSPLINE" /* CUBICSPLINE */;
  3144. }
  3145. }
  3146. else {
  3147. if (interpolationType) {
  3148. if (interpolationType === "CUBICSPLINE" /* CUBICSPLINE */ ||
  3149. (key.interpolation && (key.interpolation === BABYLON.AnimationKeyInterpolation.STEP) && interpolationType !== "STEP" /* STEP */)) {
  3150. interpolationType = "LINEAR" /* LINEAR */;
  3151. shouldBakeAnimation = true;
  3152. break;
  3153. }
  3154. }
  3155. else {
  3156. if (key.interpolation && (key.interpolation === BABYLON.AnimationKeyInterpolation.STEP)) {
  3157. interpolationType = "STEP" /* STEP */;
  3158. }
  3159. else {
  3160. interpolationType = "LINEAR" /* LINEAR */;
  3161. }
  3162. }
  3163. }
  3164. }
  3165. if (!interpolationType) {
  3166. interpolationType = "LINEAR" /* LINEAR */;
  3167. }
  3168. return { interpolationType: interpolationType, shouldBakeAnimation: shouldBakeAnimation };
  3169. };
  3170. /**
  3171. * Adds an input tangent or output tangent to the output data
  3172. * If an input tangent or output tangent is missing, it uses the zero vector or zero quaternion
  3173. * @param tangentType Specifies which type of tangent to handle (inTangent or outTangent)
  3174. * @param outputs The animation data by keyframe
  3175. * @param animationChannelTargetPath The target animation channel
  3176. * @param interpolation The interpolation type
  3177. * @param keyFrame The key frame with the animation data
  3178. * @param frameDelta Time difference between two frames used to scale the tangent by the frame delta
  3179. * @param useQuaternion Specifies if quaternions are used
  3180. * @param convertToRightHandedSystem Specifies if the values should be converted to right-handed
  3181. */
  3182. _GLTFAnimation.AddSplineTangent = function (babylonTransformNode, tangentType, outputs, animationChannelTargetPath, interpolation, keyFrame, frameDelta, useQuaternion, convertToRightHandedSystem) {
  3183. var tangent;
  3184. var tangentValue = tangentType === _TangentType.INTANGENT ? keyFrame.inTangent : keyFrame.outTangent;
  3185. if (interpolation === "CUBICSPLINE" /* CUBICSPLINE */) {
  3186. if (animationChannelTargetPath === "rotation" /* ROTATION */) {
  3187. if (tangentValue) {
  3188. if (useQuaternion) {
  3189. tangent = tangentValue.scale(frameDelta).asArray();
  3190. }
  3191. else {
  3192. var array = tangentValue.scale(frameDelta);
  3193. tangent = BABYLON.Quaternion.RotationYawPitchRoll(array.y, array.x, array.z).asArray();
  3194. }
  3195. if (convertToRightHandedSystem) {
  3196. GLTF2._GLTFUtilities._GetRightHandedQuaternionArrayFromRef(tangent);
  3197. if (!babylonTransformNode.parent) {
  3198. tangent = BABYLON.Quaternion.FromArray([0, 1, 0, 0]).multiply(BABYLON.Quaternion.FromArray(tangent)).asArray();
  3199. }
  3200. }
  3201. }
  3202. else {
  3203. tangent = [0, 0, 0, 0];
  3204. }
  3205. }
  3206. else {
  3207. if (tangentValue) {
  3208. tangent = tangentValue.scale(frameDelta).asArray();
  3209. if (convertToRightHandedSystem) {
  3210. if (animationChannelTargetPath === "translation" /* TRANSLATION */) {
  3211. GLTF2._GLTFUtilities._GetRightHandedPositionArray3FromRef(tangent);
  3212. if (!babylonTransformNode.parent) {
  3213. tangent[0] *= -1; // x
  3214. tangent[2] *= -1; // z
  3215. }
  3216. }
  3217. }
  3218. }
  3219. else {
  3220. tangent = [0, 0, 0];
  3221. }
  3222. }
  3223. outputs.push(tangent);
  3224. }
  3225. };
  3226. /**
  3227. * Get the minimum and maximum key frames' frame values
  3228. * @param keyFrames animation key frames
  3229. * @returns the minimum and maximum key frame value
  3230. */
  3231. _GLTFAnimation.calculateMinMaxKeyFrames = function (keyFrames) {
  3232. var min = Infinity;
  3233. var max = -Infinity;
  3234. keyFrames.forEach(function (keyFrame) {
  3235. min = Math.min(min, keyFrame.frame);
  3236. max = Math.max(max, keyFrame.frame);
  3237. });
  3238. return { min: min, max: max };
  3239. };
  3240. return _GLTFAnimation;
  3241. }());
  3242. GLTF2._GLTFAnimation = _GLTFAnimation;
  3243. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3244. })(BABYLON || (BABYLON = {}));
  3245. //# sourceMappingURL=babylon.glTFAnimation.js.map
  3246. var BABYLON;
  3247. (function (BABYLON) {
  3248. var GLTF2;
  3249. (function (GLTF2) {
  3250. /**
  3251. * @hidden
  3252. */
  3253. var _GLTFUtilities = /** @class */ (function () {
  3254. function _GLTFUtilities() {
  3255. }
  3256. /**
  3257. * Creates a buffer view based on the supplied arguments
  3258. * @param bufferIndex index value of the specified buffer
  3259. * @param byteOffset byte offset value
  3260. * @param byteLength byte length of the bufferView
  3261. * @param byteStride byte distance between conequential elements
  3262. * @param name name of the buffer view
  3263. * @returns bufferView for glTF
  3264. */
  3265. _GLTFUtilities._CreateBufferView = function (bufferIndex, byteOffset, byteLength, byteStride, name) {
  3266. var bufferview = { buffer: bufferIndex, byteLength: byteLength };
  3267. if (byteOffset) {
  3268. bufferview.byteOffset = byteOffset;
  3269. }
  3270. if (name) {
  3271. bufferview.name = name;
  3272. }
  3273. if (byteStride) {
  3274. bufferview.byteStride = byteStride;
  3275. }
  3276. return bufferview;
  3277. };
  3278. /**
  3279. * Creates an accessor based on the supplied arguments
  3280. * @param bufferviewIndex The index of the bufferview referenced by this accessor
  3281. * @param name The name of the accessor
  3282. * @param type The type of the accessor
  3283. * @param componentType The datatype of components in the attribute
  3284. * @param count The number of attributes referenced by this accessor
  3285. * @param byteOffset The offset relative to the start of the bufferView in bytes
  3286. * @param min Minimum value of each component in this attribute
  3287. * @param max Maximum value of each component in this attribute
  3288. * @returns accessor for glTF
  3289. */
  3290. _GLTFUtilities._CreateAccessor = function (bufferviewIndex, name, type, componentType, count, byteOffset, min, max) {
  3291. var accessor = { name: name, bufferView: bufferviewIndex, componentType: componentType, count: count, type: type };
  3292. if (min != null) {
  3293. accessor.min = min;
  3294. }
  3295. if (max != null) {
  3296. accessor.max = max;
  3297. }
  3298. if (byteOffset != null) {
  3299. accessor.byteOffset = byteOffset;
  3300. }
  3301. return accessor;
  3302. };
  3303. /**
  3304. * Calculates the minimum and maximum values of an array of position floats
  3305. * @param positions Positions array of a mesh
  3306. * @param vertexStart Starting vertex offset to calculate min and max values
  3307. * @param vertexCount Number of vertices to check for min and max values
  3308. * @returns min number array and max number array
  3309. */
  3310. _GLTFUtilities._CalculateMinMaxPositions = function (positions, vertexStart, vertexCount, convertToRightHandedSystem) {
  3311. var min = [Infinity, Infinity, Infinity];
  3312. var max = [-Infinity, -Infinity, -Infinity];
  3313. var positionStrideSize = 3;
  3314. var indexOffset;
  3315. var position;
  3316. var vector;
  3317. if (vertexCount) {
  3318. for (var i = vertexStart, length_1 = vertexStart + vertexCount; i < length_1; ++i) {
  3319. indexOffset = positionStrideSize * i;
  3320. position = BABYLON.Vector3.FromArray(positions, indexOffset);
  3321. if (convertToRightHandedSystem) {
  3322. _GLTFUtilities._GetRightHandedPositionVector3FromRef(position);
  3323. }
  3324. vector = position.asArray();
  3325. for (var j = 0; j < positionStrideSize; ++j) {
  3326. var num = vector[j];
  3327. if (num < min[j]) {
  3328. min[j] = num;
  3329. }
  3330. if (num > max[j]) {
  3331. max[j] = num;
  3332. }
  3333. ++indexOffset;
  3334. }
  3335. }
  3336. }
  3337. return { min: min, max: max };
  3338. };
  3339. /**
  3340. * Converts a new right-handed Vector3
  3341. * @param vector vector3 array
  3342. * @returns right-handed Vector3
  3343. */
  3344. _GLTFUtilities._GetRightHandedPositionVector3 = function (vector) {
  3345. return new BABYLON.Vector3(vector.x, vector.y, -vector.z);
  3346. };
  3347. /**
  3348. * Converts a Vector3 to right-handed
  3349. * @param vector Vector3 to convert to right-handed
  3350. */
  3351. _GLTFUtilities._GetRightHandedPositionVector3FromRef = function (vector) {
  3352. vector.z *= -1;
  3353. };
  3354. /**
  3355. * Converts a three element number array to right-handed
  3356. * @param vector number array to convert to right-handed
  3357. */
  3358. _GLTFUtilities._GetRightHandedPositionArray3FromRef = function (vector) {
  3359. vector[2] *= -1;
  3360. };
  3361. /**
  3362. * Converts a new right-handed Vector3
  3363. * @param vector vector3 array
  3364. * @returns right-handed Vector3
  3365. */
  3366. _GLTFUtilities._GetRightHandedNormalVector3 = function (vector) {
  3367. return new BABYLON.Vector3(vector.x, vector.y, -vector.z);
  3368. };
  3369. /**
  3370. * Converts a Vector3 to right-handed
  3371. * @param vector Vector3 to convert to right-handed
  3372. */
  3373. _GLTFUtilities._GetRightHandedNormalVector3FromRef = function (vector) {
  3374. vector.z *= -1;
  3375. };
  3376. /**
  3377. * Converts a three element number array to right-handed
  3378. * @param vector number array to convert to right-handed
  3379. */
  3380. _GLTFUtilities._GetRightHandedNormalArray3FromRef = function (vector) {
  3381. vector[2] *= -1;
  3382. };
  3383. /**
  3384. * Converts a Vector4 to right-handed
  3385. * @param vector Vector4 to convert to right-handed
  3386. */
  3387. _GLTFUtilities._GetRightHandedVector4FromRef = function (vector) {
  3388. vector.z *= -1;
  3389. vector.w *= -1;
  3390. };
  3391. /**
  3392. * Converts a Vector4 to right-handed
  3393. * @param vector Vector4 to convert to right-handed
  3394. */
  3395. _GLTFUtilities._GetRightHandedArray4FromRef = function (vector) {
  3396. vector[2] *= -1;
  3397. vector[3] *= -1;
  3398. };
  3399. /**
  3400. * Converts a Quaternion to right-handed
  3401. * @param quaternion Source quaternion to convert to right-handed
  3402. */
  3403. _GLTFUtilities._GetRightHandedQuaternionFromRef = function (quaternion) {
  3404. quaternion.x *= -1;
  3405. quaternion.y *= -1;
  3406. };
  3407. /**
  3408. * Converts a Quaternion to right-handed
  3409. * @param quaternion Source quaternion to convert to right-handed
  3410. */
  3411. _GLTFUtilities._GetRightHandedQuaternionArrayFromRef = function (quaternion) {
  3412. quaternion[0] *= -1;
  3413. quaternion[1] *= -1;
  3414. };
  3415. _GLTFUtilities._NormalizeTangentFromRef = function (tangent) {
  3416. var length = Math.sqrt(tangent.x * tangent.x + tangent.y * tangent.y + tangent.z * tangent.z);
  3417. if (length > 0) {
  3418. tangent.x /= length;
  3419. tangent.y /= length;
  3420. tangent.z /= length;
  3421. }
  3422. };
  3423. return _GLTFUtilities;
  3424. }());
  3425. GLTF2._GLTFUtilities = _GLTFUtilities;
  3426. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3427. })(BABYLON || (BABYLON = {}));
  3428. //# sourceMappingURL=babylon.glTFUtilities.js.map
  3429. return BABYLON;
  3430. });