babylon.glTF2Serializer.js 210 KB

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