babylonjs.serializers.js 222 KB

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