babylon.glTF2Serializer.js 190 KB

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