babylonjs.serializers.js 245 KB

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