babylonjs.serializers.js 198 KB

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