babylon.glTF2Serializer.js 191 KB

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