babylon.glTF2FileLoader.js 183 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956
  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-loaders", ["babylonjs"], factory);
  6. else if(typeof exports === 'object')
  7. exports["babylonjs-loaders"] = factory(require("babylonjs"));
  8. else
  9. root["LOADERS"] = 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-glTF2FileLoader.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-glTF2FileLoader.ts":
  122. /*!******************************************!*\
  123. !*** ./legacy/legacy-glTF2FileLoader.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 FileLoader = __webpack_require__(/*! ../src/glTF/glTFFileLoader */ "./src/glTF/glTFFileLoader.ts");
  134. var LoadersV2 = __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 key in FileLoader) {
  142. globalObject.BABYLON[key] = FileLoader[key];
  143. }
  144. for (var key in LoadersV2) {
  145. globalObject.BABYLON[key] = FileLoader[key];
  146. }
  147. }
  148. __export(__webpack_require__(/*! ../src/glTF/glTFFileLoader */ "./src/glTF/glTFFileLoader.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/EXT_lights_image_based.ts":
  153. /*!***********************************************************!*\
  154. !*** ./src/glTF/2.0/Extensions/EXT_lights_image_based.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 glTFLoader_1 = __webpack_require__(/*! ../glTFLoader */ "./src/glTF/2.0/glTFLoader.ts");
  162. var NAME = "EXT_lights_image_based";
  163. /**
  164. * [Specification](https://github.com/KhronosGroup/glTF/blob/eb3e32332042e04691a5f35103f8c261e50d8f1e/extensions/2.0/Khronos/EXT_lights_image_based/README.md) (Experimental)
  165. */
  166. var EXT_lights_image_based = /** @class */ (function () {
  167. /** @hidden */
  168. function EXT_lights_image_based(loader) {
  169. /** The name of this extension. */
  170. this.name = NAME;
  171. /** Defines whether this extension is enabled. */
  172. this.enabled = true;
  173. this._loader = loader;
  174. }
  175. /** @hidden */
  176. EXT_lights_image_based.prototype.dispose = function () {
  177. delete this._loader;
  178. delete this._lights;
  179. };
  180. /** @hidden */
  181. EXT_lights_image_based.prototype.onLoading = function () {
  182. var extensions = this._loader.gltf.extensions;
  183. if (extensions && extensions[this.name]) {
  184. var extension = extensions[this.name];
  185. this._lights = extension.lights;
  186. }
  187. };
  188. /** @hidden */
  189. EXT_lights_image_based.prototype.loadSceneAsync = function (context, scene) {
  190. var _this = this;
  191. return glTFLoader_1.GLTFLoaderV2.LoadExtensionAsync(context, scene, this.name, function (extensionContext, extension) {
  192. var promises = new Array();
  193. promises.push(_this._loader.loadSceneAsync(context, scene));
  194. _this._loader.logOpen("" + extensionContext);
  195. var light = glTFLoader_1.ArrayItem.Get(extensionContext + "/light", _this._lights, extension.light);
  196. promises.push(_this._loadLightAsync("#/extensions/" + _this.name + "/lights/" + extension.light, light).then(function (texture) {
  197. _this._loader.babylonScene.environmentTexture = texture;
  198. }));
  199. _this._loader.logClose();
  200. return Promise.all(promises).then(function () { });
  201. });
  202. };
  203. EXT_lights_image_based.prototype._loadLightAsync = function (context, light) {
  204. var _this = this;
  205. if (!light._loaded) {
  206. var promises = new Array();
  207. this._loader.logOpen("" + context);
  208. var imageData_1 = new Array(light.specularImages.length);
  209. var _loop_1 = function (mipmap) {
  210. var faces = light.specularImages[mipmap];
  211. imageData_1[mipmap] = new Array(faces.length);
  212. var _loop_2 = function (face) {
  213. var specularImageContext = context + "/specularImages/" + mipmap + "/" + face;
  214. this_1._loader.logOpen("" + specularImageContext);
  215. var index = faces[face];
  216. var image = glTFLoader_1.ArrayItem.Get(specularImageContext, this_1._loader.gltf.images, index);
  217. promises.push(this_1._loader.loadImageAsync("#/images/" + index, image).then(function (data) {
  218. imageData_1[mipmap][face] = data;
  219. }));
  220. this_1._loader.logClose();
  221. };
  222. for (var face = 0; face < faces.length; face++) {
  223. _loop_2(face);
  224. }
  225. };
  226. var this_1 = this;
  227. for (var mipmap = 0; mipmap < light.specularImages.length; mipmap++) {
  228. _loop_1(mipmap);
  229. }
  230. this._loader.logClose();
  231. light._loaded = Promise.all(promises).then(function () {
  232. var babylonTexture = new babylonjs_1.RawCubeTexture(_this._loader.babylonScene, null, light.specularImageSize);
  233. light._babylonTexture = babylonTexture;
  234. if (light.intensity != undefined) {
  235. babylonTexture.level = light.intensity;
  236. }
  237. if (light.rotation) {
  238. var rotation = babylonjs_1.Quaternion.FromArray(light.rotation);
  239. // Invert the rotation so that positive rotation is counter-clockwise.
  240. if (!_this._loader.babylonScene.useRightHandedSystem) {
  241. rotation = babylonjs_1.Quaternion.Inverse(rotation);
  242. }
  243. babylonjs_1.Matrix.FromQuaternionToRef(rotation, babylonTexture.getReflectionTextureMatrix());
  244. }
  245. var sphericalHarmonics = babylonjs_1.SphericalHarmonics.FromArray(light.irradianceCoefficients);
  246. sphericalHarmonics.scale(light.intensity);
  247. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  248. var sphericalPolynomial = babylonjs_1.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  249. // Compute the lod generation scale to fit exactly to the number of levels available.
  250. var lodGenerationScale = (imageData_1.length - 1) / babylonjs_1.Scalar.Log2(light.specularImageSize);
  251. return babylonTexture.updateRGBDAsync(imageData_1, sphericalPolynomial, lodGenerationScale);
  252. });
  253. }
  254. return light._loaded.then(function () {
  255. return light._babylonTexture;
  256. });
  257. };
  258. return EXT_lights_image_based;
  259. }());
  260. exports.EXT_lights_image_based = EXT_lights_image_based;
  261. glTFLoader_1.GLTFLoaderV2.RegisterExtension(NAME, function (loader) { return new EXT_lights_image_based(loader); });
  262. /***/ }),
  263. /***/ "./src/glTF/2.0/Extensions/KHR_draco_mesh_compression.ts":
  264. /*!***************************************************************!*\
  265. !*** ./src/glTF/2.0/Extensions/KHR_draco_mesh_compression.ts ***!
  266. \***************************************************************/
  267. /*! no static exports found */
  268. /***/ (function(module, exports, __webpack_require__) {
  269. "use strict";
  270. Object.defineProperty(exports, "__esModule", { value: true });
  271. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  272. var glTFLoader_1 = __webpack_require__(/*! ../glTFLoader */ "./src/glTF/2.0/glTFLoader.ts");
  273. var NAME = "KHR_draco_mesh_compression";
  274. /**
  275. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression)
  276. */
  277. var KHR_draco_mesh_compression = /** @class */ (function () {
  278. /** @hidden */
  279. function KHR_draco_mesh_compression(loader) {
  280. /** The name of this extension. */
  281. this.name = NAME;
  282. /** Defines whether this extension is enabled. */
  283. this.enabled = babylonjs_1.DracoCompression.DecoderAvailable;
  284. this._loader = loader;
  285. }
  286. /** @hidden */
  287. KHR_draco_mesh_compression.prototype.dispose = function () {
  288. if (this._dracoCompression) {
  289. this._dracoCompression.dispose();
  290. delete this._dracoCompression;
  291. }
  292. delete this._loader;
  293. };
  294. /** @hidden */
  295. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  296. var _this = this;
  297. return glTFLoader_1.GLTFLoaderV2.LoadExtensionAsync(context, primitive, this.name, function (extensionContext, extension) {
  298. if (primitive.mode != undefined) {
  299. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  300. primitive.mode !== 4 /* TRIANGLES */) {
  301. throw new Error(context + ": Unsupported mode " + primitive.mode);
  302. }
  303. // TODO: handle triangle strips
  304. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  305. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  306. }
  307. }
  308. var attributes = {};
  309. var loadAttribute = function (name, kind) {
  310. var uniqueId = extension.attributes[name];
  311. if (uniqueId == undefined) {
  312. return;
  313. }
  314. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  315. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  316. babylonMesh._delayInfo.push(kind);
  317. }
  318. attributes[kind] = uniqueId;
  319. };
  320. loadAttribute("POSITION", babylonjs_1.VertexBuffer.PositionKind);
  321. loadAttribute("NORMAL", babylonjs_1.VertexBuffer.NormalKind);
  322. loadAttribute("TANGENT", babylonjs_1.VertexBuffer.TangentKind);
  323. loadAttribute("TEXCOORD_0", babylonjs_1.VertexBuffer.UVKind);
  324. loadAttribute("TEXCOORD_1", babylonjs_1.VertexBuffer.UV2Kind);
  325. loadAttribute("JOINTS_0", babylonjs_1.VertexBuffer.MatricesIndicesKind);
  326. loadAttribute("WEIGHTS_0", babylonjs_1.VertexBuffer.MatricesWeightsKind);
  327. loadAttribute("COLOR_0", babylonjs_1.VertexBuffer.ColorKind);
  328. var bufferView = glTFLoader_1.ArrayItem.Get(extensionContext, _this._loader.gltf.bufferViews, extension.bufferView);
  329. if (!bufferView._dracoBabylonGeometry) {
  330. bufferView._dracoBabylonGeometry = _this._loader.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView).then(function (data) {
  331. if (!_this._dracoCompression) {
  332. _this._dracoCompression = new babylonjs_1.DracoCompression();
  333. }
  334. return _this._dracoCompression.decodeMeshAsync(data, attributes).then(function (babylonVertexData) {
  335. var babylonGeometry = new babylonjs_1.Geometry(babylonMesh.name, _this._loader.babylonScene);
  336. babylonVertexData.applyToGeometry(babylonGeometry);
  337. return babylonGeometry;
  338. }).catch(function (error) {
  339. throw new Error(context + ": " + error.message);
  340. });
  341. });
  342. }
  343. return bufferView._dracoBabylonGeometry;
  344. });
  345. };
  346. return KHR_draco_mesh_compression;
  347. }());
  348. exports.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  349. glTFLoader_1.GLTFLoaderV2.RegisterExtension(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  350. /***/ }),
  351. /***/ "./src/glTF/2.0/Extensions/KHR_lights_punctual.ts":
  352. /*!********************************************************!*\
  353. !*** ./src/glTF/2.0/Extensions/KHR_lights_punctual.ts ***!
  354. \********************************************************/
  355. /*! no static exports found */
  356. /***/ (function(module, exports, __webpack_require__) {
  357. "use strict";
  358. Object.defineProperty(exports, "__esModule", { value: true });
  359. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  360. var glTFLoader_1 = __webpack_require__(/*! ../glTFLoader */ "./src/glTF/2.0/glTFLoader.ts");
  361. var NAME = "KHR_lights_punctual";
  362. var LightType;
  363. (function (LightType) {
  364. LightType["DIRECTIONAL"] = "directional";
  365. LightType["POINT"] = "point";
  366. LightType["SPOT"] = "spot";
  367. })(LightType || (LightType = {}));
  368. /**
  369. * [Specification](https://github.com/KhronosGroup/glTF/blob/1048d162a44dbcb05aefc1874bfd423cf60135a6/extensions/2.0/Khronos/KHR_lights_punctual/README.md) (Experimental)
  370. */
  371. var KHR_lights = /** @class */ (function () {
  372. /** @hidden */
  373. function KHR_lights(loader) {
  374. /** The name of this extension. */
  375. this.name = NAME;
  376. /** Defines whether this extension is enabled. */
  377. this.enabled = true;
  378. this._loader = loader;
  379. }
  380. /** @hidden */
  381. KHR_lights.prototype.dispose = function () {
  382. delete this._loader;
  383. delete this._lights;
  384. };
  385. /** @hidden */
  386. KHR_lights.prototype.onLoading = function () {
  387. var extensions = this._loader.gltf.extensions;
  388. if (extensions && extensions[this.name]) {
  389. var extension = extensions[this.name];
  390. this._lights = extension.lights;
  391. }
  392. };
  393. /** @hidden */
  394. KHR_lights.prototype.loadNodeAsync = function (context, node, assign) {
  395. var _this = this;
  396. return glTFLoader_1.GLTFLoaderV2.LoadExtensionAsync(context, node, this.name, function (extensionContext, extension) {
  397. return _this._loader.loadNodeAsync(context, node, function (babylonMesh) {
  398. var babylonLight;
  399. var light = glTFLoader_1.ArrayItem.Get(extensionContext, _this._lights, extension.light);
  400. var name = light.name || babylonMesh.name;
  401. switch (light.type) {
  402. case LightType.DIRECTIONAL: {
  403. babylonLight = new babylonjs_1.DirectionalLight(name, babylonjs_1.Vector3.Backward(), _this._loader.babylonScene);
  404. break;
  405. }
  406. case LightType.POINT: {
  407. babylonLight = new babylonjs_1.PointLight(name, babylonjs_1.Vector3.Zero(), _this._loader.babylonScene);
  408. break;
  409. }
  410. case LightType.SPOT: {
  411. var babylonSpotLight = new babylonjs_1.SpotLight(name, babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Backward(), 0, 1, _this._loader.babylonScene);
  412. babylonSpotLight.angle = ((light.spot && light.spot.outerConeAngle) || Math.PI / 4) * 2;
  413. babylonSpotLight.innerAngle = ((light.spot && light.spot.innerConeAngle) || 0) * 2;
  414. babylonLight = babylonSpotLight;
  415. break;
  416. }
  417. default: {
  418. throw new Error(extensionContext + ": Invalid light type (" + light.type + ")");
  419. }
  420. }
  421. babylonLight.falloffType = babylonjs_1.Light.FALLOFF_GLTF;
  422. babylonLight.diffuse = light.color ? babylonjs_1.Color3.FromArray(light.color) : babylonjs_1.Color3.White();
  423. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  424. babylonLight.range = light.range == undefined ? Number.MAX_VALUE : light.range;
  425. babylonLight.parent = babylonMesh;
  426. assign(babylonMesh);
  427. });
  428. });
  429. };
  430. return KHR_lights;
  431. }());
  432. exports.KHR_lights = KHR_lights;
  433. glTFLoader_1.GLTFLoaderV2.RegisterExtension(NAME, function (loader) { return new KHR_lights(loader); });
  434. /***/ }),
  435. /***/ "./src/glTF/2.0/Extensions/KHR_materials_pbrSpecularGlossiness.ts":
  436. /*!************************************************************************!*\
  437. !*** ./src/glTF/2.0/Extensions/KHR_materials_pbrSpecularGlossiness.ts ***!
  438. \************************************************************************/
  439. /*! no static exports found */
  440. /***/ (function(module, exports, __webpack_require__) {
  441. "use strict";
  442. Object.defineProperty(exports, "__esModule", { value: true });
  443. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  444. var glTFLoader_1 = __webpack_require__(/*! ../glTFLoader */ "./src/glTF/2.0/glTFLoader.ts");
  445. var NAME = "KHR_materials_pbrSpecularGlossiness";
  446. /**
  447. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness)
  448. */
  449. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function () {
  450. /** @hidden */
  451. function KHR_materials_pbrSpecularGlossiness(loader) {
  452. /** The name of this extension. */
  453. this.name = NAME;
  454. /** Defines whether this extension is enabled. */
  455. this.enabled = true;
  456. this._loader = loader;
  457. }
  458. /** @hidden */
  459. KHR_materials_pbrSpecularGlossiness.prototype.dispose = function () {
  460. delete this._loader;
  461. };
  462. /** @hidden */
  463. KHR_materials_pbrSpecularGlossiness.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  464. var _this = this;
  465. return glTFLoader_1.GLTFLoaderV2.LoadExtensionAsync(context, material, this.name, function (extensionContext, extension) {
  466. var promises = new Array();
  467. promises.push(_this._loader.loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  468. promises.push(_this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial));
  469. _this._loader.loadMaterialAlphaProperties(context, material, babylonMaterial);
  470. return Promise.all(promises).then(function () { });
  471. });
  472. };
  473. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  474. if (!(babylonMaterial instanceof babylonjs_1.PBRMaterial)) {
  475. throw new Error(context + ": Material type not supported");
  476. }
  477. var promises = new Array();
  478. babylonMaterial.metallic = null;
  479. babylonMaterial.roughness = null;
  480. if (properties.diffuseFactor) {
  481. babylonMaterial.albedoColor = babylonjs_1.Color3.FromArray(properties.diffuseFactor);
  482. babylonMaterial.alpha = properties.diffuseFactor[3];
  483. }
  484. else {
  485. babylonMaterial.albedoColor = babylonjs_1.Color3.White();
  486. }
  487. babylonMaterial.reflectivityColor = properties.specularFactor ? babylonjs_1.Color3.FromArray(properties.specularFactor) : babylonjs_1.Color3.White();
  488. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  489. if (properties.diffuseTexture) {
  490. promises.push(this._loader.loadTextureInfoAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  491. babylonMaterial.albedoTexture = texture;
  492. return Promise.resolve();
  493. }));
  494. }
  495. if (properties.specularGlossinessTexture) {
  496. promises.push(this._loader.loadTextureInfoAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  497. babylonMaterial.reflectivityTexture = texture;
  498. return Promise.resolve();
  499. }));
  500. babylonMaterial.reflectivityTexture.hasAlpha = true;
  501. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  502. }
  503. return Promise.all(promises).then(function () { });
  504. };
  505. return KHR_materials_pbrSpecularGlossiness;
  506. }());
  507. exports.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  508. glTFLoader_1.GLTFLoaderV2.RegisterExtension(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  509. /***/ }),
  510. /***/ "./src/glTF/2.0/Extensions/KHR_materials_unlit.ts":
  511. /*!********************************************************!*\
  512. !*** ./src/glTF/2.0/Extensions/KHR_materials_unlit.ts ***!
  513. \********************************************************/
  514. /*! no static exports found */
  515. /***/ (function(module, exports, __webpack_require__) {
  516. "use strict";
  517. Object.defineProperty(exports, "__esModule", { value: true });
  518. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  519. var glTFLoader_1 = __webpack_require__(/*! ../glTFLoader */ "./src/glTF/2.0/glTFLoader.ts");
  520. var NAME = "KHR_materials_unlit";
  521. /**
  522. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit)
  523. */
  524. var KHR_materials_unlit = /** @class */ (function () {
  525. /** @hidden */
  526. function KHR_materials_unlit(loader) {
  527. /** The name of this extension. */
  528. this.name = NAME;
  529. /** Defines whether this extension is enabled. */
  530. this.enabled = true;
  531. this._loader = loader;
  532. }
  533. /** @hidden */
  534. KHR_materials_unlit.prototype.dispose = function () {
  535. delete this._loader;
  536. };
  537. /** @hidden */
  538. KHR_materials_unlit.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  539. var _this = this;
  540. return glTFLoader_1.GLTFLoaderV2.LoadExtensionAsync(context, material, this.name, function () {
  541. return _this._loadUnlitPropertiesAsync(context, material, babylonMaterial);
  542. });
  543. };
  544. KHR_materials_unlit.prototype._loadUnlitPropertiesAsync = function (context, material, babylonMaterial) {
  545. if (!(babylonMaterial instanceof babylonjs_1.PBRMaterial)) {
  546. throw new Error(context + ": Material type not supported");
  547. }
  548. var promises = new Array();
  549. babylonMaterial.unlit = true;
  550. var properties = material.pbrMetallicRoughness;
  551. if (properties) {
  552. if (properties.baseColorFactor) {
  553. babylonMaterial.albedoColor = babylonjs_1.Color3.FromArray(properties.baseColorFactor);
  554. babylonMaterial.alpha = properties.baseColorFactor[3];
  555. }
  556. else {
  557. babylonMaterial.albedoColor = babylonjs_1.Color3.White();
  558. }
  559. if (properties.baseColorTexture) {
  560. promises.push(this._loader.loadTextureInfoAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  561. babylonMaterial.albedoTexture = texture;
  562. return Promise.resolve();
  563. }));
  564. }
  565. }
  566. if (material.doubleSided) {
  567. babylonMaterial.backFaceCulling = false;
  568. babylonMaterial.twoSidedLighting = true;
  569. }
  570. this._loader.loadMaterialAlphaProperties(context, material, babylonMaterial);
  571. return Promise.all(promises).then(function () { });
  572. };
  573. return KHR_materials_unlit;
  574. }());
  575. exports.KHR_materials_unlit = KHR_materials_unlit;
  576. glTFLoader_1.GLTFLoaderV2.RegisterExtension(NAME, function (loader) { return new KHR_materials_unlit(loader); });
  577. /***/ }),
  578. /***/ "./src/glTF/2.0/Extensions/KHR_texture_transform.ts":
  579. /*!**********************************************************!*\
  580. !*** ./src/glTF/2.0/Extensions/KHR_texture_transform.ts ***!
  581. \**********************************************************/
  582. /*! no static exports found */
  583. /***/ (function(module, exports, __webpack_require__) {
  584. "use strict";
  585. Object.defineProperty(exports, "__esModule", { value: true });
  586. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  587. var glTFLoader_1 = __webpack_require__(/*! ../glTFLoader */ "./src/glTF/2.0/glTFLoader.ts");
  588. var NAME = "KHR_texture_transform";
  589. /**
  590. * [Specification](https://github.com/KhronosGroup/glTF/blob/master/extensions/2.0/Khronos/KHR_texture_transform/README.md)
  591. */
  592. var KHR_texture_transform = /** @class */ (function () {
  593. /** @hidden */
  594. function KHR_texture_transform(loader) {
  595. /** The name of this extension. */
  596. this.name = NAME;
  597. /** Defines whether this extension is enabled. */
  598. this.enabled = true;
  599. this._loader = loader;
  600. }
  601. /** @hidden */
  602. KHR_texture_transform.prototype.dispose = function () {
  603. delete this._loader;
  604. };
  605. /** @hidden */
  606. KHR_texture_transform.prototype.loadTextureInfoAsync = function (context, textureInfo, assign) {
  607. var _this = this;
  608. return glTFLoader_1.GLTFLoaderV2.LoadExtensionAsync(context, textureInfo, this.name, function (extensionContext, extension) {
  609. return _this._loader.loadTextureInfoAsync(context, textureInfo, function (babylonTexture) {
  610. if (!(babylonTexture instanceof babylonjs_1.Texture)) {
  611. throw new Error(extensionContext + ": Texture type not supported");
  612. }
  613. if (extension.offset) {
  614. babylonTexture.uOffset = extension.offset[0];
  615. babylonTexture.vOffset = extension.offset[1];
  616. }
  617. // Always rotate around the origin.
  618. babylonTexture.uRotationCenter = 0;
  619. babylonTexture.vRotationCenter = 0;
  620. if (extension.rotation) {
  621. babylonTexture.wAng = -extension.rotation;
  622. }
  623. if (extension.scale) {
  624. babylonTexture.uScale = extension.scale[0];
  625. babylonTexture.vScale = extension.scale[1];
  626. }
  627. if (extension.texCoord != undefined) {
  628. babylonTexture.coordinatesIndex = extension.texCoord;
  629. }
  630. assign(babylonTexture);
  631. });
  632. });
  633. };
  634. return KHR_texture_transform;
  635. }());
  636. exports.KHR_texture_transform = KHR_texture_transform;
  637. glTFLoader_1.GLTFLoaderV2.RegisterExtension(NAME, function (loader) { return new KHR_texture_transform(loader); });
  638. /***/ }),
  639. /***/ "./src/glTF/2.0/Extensions/MSFT_audio_emitter.ts":
  640. /*!*******************************************************!*\
  641. !*** ./src/glTF/2.0/Extensions/MSFT_audio_emitter.ts ***!
  642. \*******************************************************/
  643. /*! no static exports found */
  644. /***/ (function(module, exports, __webpack_require__) {
  645. "use strict";
  646. Object.defineProperty(exports, "__esModule", { value: true });
  647. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  648. var glTFLoader_1 = __webpack_require__(/*! ../glTFLoader */ "./src/glTF/2.0/glTFLoader.ts");
  649. var NAME = "MSFT_audio_emitter";
  650. /**
  651. * [Specification](https://github.com/najadojo/glTF/tree/MSFT_audio_emitter/extensions/2.0/Vendor/MSFT_audio_emitter)
  652. */
  653. var MSFT_audio_emitter = /** @class */ (function () {
  654. /** @hidden */
  655. function MSFT_audio_emitter(loader) {
  656. /** The name of this extension. */
  657. this.name = NAME;
  658. /** Defines whether this extension is enabled. */
  659. this.enabled = true;
  660. this._loader = loader;
  661. }
  662. /** @hidden */
  663. MSFT_audio_emitter.prototype.dispose = function () {
  664. delete this._loader;
  665. delete this._clips;
  666. delete this._emitters;
  667. };
  668. /** @hidden */
  669. MSFT_audio_emitter.prototype.onLoading = function () {
  670. var extensions = this._loader.gltf.extensions;
  671. if (extensions && extensions[this.name]) {
  672. var extension = extensions[this.name];
  673. this._clips = extension.clips;
  674. this._emitters = extension.emitters;
  675. glTFLoader_1.ArrayItem.Assign(this._clips);
  676. glTFLoader_1.ArrayItem.Assign(this._emitters);
  677. }
  678. };
  679. /** @hidden */
  680. MSFT_audio_emitter.prototype.loadSceneAsync = function (context, scene) {
  681. var _this = this;
  682. return glTFLoader_1.GLTFLoaderV2.LoadExtensionAsync(context, scene, this.name, function (extensionContext, extension) {
  683. var promises = new Array();
  684. promises.push(_this._loader.loadSceneAsync(context, scene));
  685. for (var _i = 0, _a = extension.emitters; _i < _a.length; _i++) {
  686. var emitterIndex = _a[_i];
  687. var emitter = glTFLoader_1.ArrayItem.Get(extensionContext + "/emitters", _this._emitters, emitterIndex);
  688. if (emitter.refDistance != undefined || emitter.maxDistance != undefined || emitter.rolloffFactor != undefined ||
  689. emitter.distanceModel != undefined || emitter.innerAngle != undefined || emitter.outerAngle != undefined) {
  690. throw new Error(extensionContext + ": Direction or Distance properties are not allowed on emitters attached to a scene");
  691. }
  692. promises.push(_this._loadEmitterAsync(extensionContext + "/emitters/" + emitter.index, emitter));
  693. }
  694. return Promise.all(promises).then(function () { });
  695. });
  696. };
  697. /** @hidden */
  698. MSFT_audio_emitter.prototype.loadNodeAsync = function (context, node, assign) {
  699. var _this = this;
  700. return glTFLoader_1.GLTFLoaderV2.LoadExtensionAsync(context, node, this.name, function (extensionContext, extension) {
  701. var promises = new Array();
  702. return _this._loader.loadNodeAsync(extensionContext, node, function (babylonMesh) {
  703. var _loop_1 = function (emitterIndex) {
  704. var emitter = glTFLoader_1.ArrayItem.Get(extensionContext + "/emitters", _this._emitters, emitterIndex);
  705. promises.push(_this._loadEmitterAsync(extensionContext + "/emitters/" + emitter.index, emitter).then(function () {
  706. for (var _i = 0, _a = emitter._babylonSounds; _i < _a.length; _i++) {
  707. var sound = _a[_i];
  708. sound.attachToMesh(babylonMesh);
  709. if (emitter.innerAngle != undefined || emitter.outerAngle != undefined) {
  710. sound.setLocalDirectionToMesh(babylonjs_1.Vector3.Forward());
  711. sound.setDirectionalCone(2 * babylonjs_1.Tools.ToDegrees(emitter.innerAngle == undefined ? Math.PI : emitter.innerAngle), 2 * babylonjs_1.Tools.ToDegrees(emitter.outerAngle == undefined ? Math.PI : emitter.outerAngle), 0);
  712. }
  713. }
  714. }));
  715. };
  716. for (var _i = 0, _a = extension.emitters; _i < _a.length; _i++) {
  717. var emitterIndex = _a[_i];
  718. _loop_1(emitterIndex);
  719. }
  720. assign(babylonMesh);
  721. }).then(function (babylonMesh) {
  722. return Promise.all(promises).then(function () {
  723. return babylonMesh;
  724. });
  725. });
  726. });
  727. };
  728. /** @hidden */
  729. MSFT_audio_emitter.prototype.loadAnimationAsync = function (context, animation) {
  730. var _this = this;
  731. return glTFLoader_1.GLTFLoaderV2.LoadExtensionAsync(context, animation, this.name, function (extensionContext, extension) {
  732. return _this._loader.loadAnimationAsync(context, animation).then(function (babylonAnimationGroup) {
  733. var promises = new Array();
  734. glTFLoader_1.ArrayItem.Assign(extension.events);
  735. for (var _i = 0, _a = extension.events; _i < _a.length; _i++) {
  736. var event_1 = _a[_i];
  737. promises.push(_this._loadAnimationEventAsync(extensionContext + "/events/" + event_1.index, context, animation, event_1, babylonAnimationGroup));
  738. }
  739. return Promise.all(promises).then(function () {
  740. return babylonAnimationGroup;
  741. });
  742. });
  743. });
  744. };
  745. MSFT_audio_emitter.prototype._loadClipAsync = function (context, clip) {
  746. if (clip._objectURL) {
  747. return clip._objectURL;
  748. }
  749. var promise;
  750. if (clip.uri) {
  751. promise = this._loader.loadUriAsync(context, clip.uri);
  752. }
  753. else {
  754. var bufferView = glTFLoader_1.ArrayItem.Get(context + "/bufferView", this._loader.gltf.bufferViews, clip.bufferView);
  755. promise = this._loader.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView);
  756. }
  757. clip._objectURL = promise.then(function (data) {
  758. return URL.createObjectURL(new Blob([data], { type: clip.mimeType }));
  759. });
  760. return clip._objectURL;
  761. };
  762. MSFT_audio_emitter.prototype._loadEmitterAsync = function (context, emitter) {
  763. var _this = this;
  764. emitter._babylonSounds = emitter._babylonSounds || [];
  765. if (!emitter._babylonData) {
  766. var clipPromises = new Array();
  767. var name_1 = emitter.name || "emitter" + emitter.index;
  768. var options_1 = {
  769. loop: false,
  770. autoplay: false,
  771. volume: emitter.volume == undefined ? 1 : emitter.volume,
  772. };
  773. var _loop_2 = function (i) {
  774. var clipContext = "#/extensions/" + this_1.name + "/clips";
  775. var clip = glTFLoader_1.ArrayItem.Get(clipContext, this_1._clips, emitter.clips[i].clip);
  776. clipPromises.push(this_1._loadClipAsync(clipContext + "/" + emitter.clips[i].clip, clip).then(function (objectURL) {
  777. var sound = emitter._babylonSounds[i] = new babylonjs_1.Sound(name_1, objectURL, _this._loader.babylonScene, null, options_1);
  778. sound.refDistance = emitter.refDistance || 1;
  779. sound.maxDistance = emitter.maxDistance || 256;
  780. sound.rolloffFactor = emitter.rolloffFactor || 1;
  781. sound.distanceModel = emitter.distanceModel || 'exponential';
  782. sound._positionInEmitterSpace = true;
  783. }));
  784. };
  785. var this_1 = this;
  786. for (var i = 0; i < emitter.clips.length; i++) {
  787. _loop_2(i);
  788. }
  789. var promise = Promise.all(clipPromises).then(function () {
  790. var weights = emitter.clips.map(function (clip) { return clip.weight || 1; });
  791. var weightedSound = new babylonjs_1.WeightedSound(emitter.loop || false, emitter._babylonSounds, weights);
  792. if (emitter.innerAngle) {
  793. weightedSound.directionalConeInnerAngle = 2 * babylonjs_1.Tools.ToDegrees(emitter.innerAngle);
  794. }
  795. if (emitter.outerAngle) {
  796. weightedSound.directionalConeOuterAngle = 2 * babylonjs_1.Tools.ToDegrees(emitter.outerAngle);
  797. }
  798. if (emitter.volume) {
  799. weightedSound.volume = emitter.volume;
  800. }
  801. emitter._babylonData.sound = weightedSound;
  802. });
  803. emitter._babylonData = {
  804. loaded: promise
  805. };
  806. }
  807. return emitter._babylonData.loaded;
  808. };
  809. MSFT_audio_emitter.prototype._getEventAction = function (context, sound, action, time, startOffset) {
  810. switch (action) {
  811. case "play" /* play */: {
  812. return function (currentFrame) {
  813. var frameOffset = (startOffset || 0) + (currentFrame - time);
  814. sound.play(frameOffset);
  815. };
  816. }
  817. case "stop" /* stop */: {
  818. return function (currentFrame) {
  819. sound.stop();
  820. };
  821. }
  822. case "pause" /* pause */: {
  823. return function (currentFrame) {
  824. sound.pause();
  825. };
  826. }
  827. default: {
  828. throw new Error(context + ": Unsupported action " + action);
  829. }
  830. }
  831. };
  832. MSFT_audio_emitter.prototype._loadAnimationEventAsync = function (context, animationContext, animation, event, babylonAnimationGroup) {
  833. var _this = this;
  834. if (babylonAnimationGroup.targetedAnimations.length == 0) {
  835. return Promise.resolve();
  836. }
  837. var babylonAnimation = babylonAnimationGroup.targetedAnimations[0];
  838. var emitterIndex = event.emitter;
  839. var emitter = glTFLoader_1.ArrayItem.Get("#/extensions/" + this.name + "/emitters", this._emitters, emitterIndex);
  840. return this._loadEmitterAsync(context, emitter).then(function () {
  841. var sound = emitter._babylonData.sound;
  842. if (sound) {
  843. var babylonAnimationEvent = new babylonjs_1.AnimationEvent(event.time, _this._getEventAction(context, sound, event.action, event.time, event.startOffset));
  844. babylonAnimation.animation.addEvent(babylonAnimationEvent);
  845. // Make sure all started audio stops when this animation is terminated.
  846. babylonAnimationGroup.onAnimationGroupEndObservable.add(function () {
  847. sound.stop();
  848. });
  849. babylonAnimationGroup.onAnimationGroupPauseObservable.add(function () {
  850. sound.pause();
  851. });
  852. }
  853. });
  854. };
  855. return MSFT_audio_emitter;
  856. }());
  857. exports.MSFT_audio_emitter = MSFT_audio_emitter;
  858. glTFLoader_1.GLTFLoaderV2.RegisterExtension(NAME, function (loader) { return new MSFT_audio_emitter(loader); });
  859. /***/ }),
  860. /***/ "./src/glTF/2.0/Extensions/MSFT_lod.ts":
  861. /*!*********************************************!*\
  862. !*** ./src/glTF/2.0/Extensions/MSFT_lod.ts ***!
  863. \*********************************************/
  864. /*! no static exports found */
  865. /***/ (function(module, exports, __webpack_require__) {
  866. "use strict";
  867. Object.defineProperty(exports, "__esModule", { value: true });
  868. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  869. var glTFLoader_1 = __webpack_require__(/*! ../glTFLoader */ "./src/glTF/2.0/glTFLoader.ts");
  870. var NAME = "MSFT_lod";
  871. /**
  872. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_lod)
  873. */
  874. var MSFT_lod = /** @class */ (function () {
  875. /** @hidden */
  876. function MSFT_lod(loader) {
  877. /** The name of this extension. */
  878. this.name = NAME;
  879. /** Defines whether this extension is enabled. */
  880. this.enabled = true;
  881. /**
  882. * Maximum number of LODs to load, starting from the lowest LOD.
  883. */
  884. this.maxLODsToLoad = Number.MAX_VALUE;
  885. /**
  886. * Observable raised when all node LODs of one level are loaded.
  887. * The event data is the index of the loaded LOD starting from zero.
  888. * Dispose the loader to cancel the loading of the next level of LODs.
  889. */
  890. this.onNodeLODsLoadedObservable = new babylonjs_1.Observable();
  891. /**
  892. * Observable raised when all material LODs of one level are loaded.
  893. * The event data is the index of the loaded LOD starting from zero.
  894. * Dispose the loader to cancel the loading of the next level of LODs.
  895. */
  896. this.onMaterialLODsLoadedObservable = new babylonjs_1.Observable();
  897. this._nodeIndexLOD = null;
  898. this._nodeSignalLODs = new Array();
  899. this._nodePromiseLODs = new Array();
  900. this._materialIndexLOD = null;
  901. this._materialSignalLODs = new Array();
  902. this._materialPromiseLODs = new Array();
  903. this._loader = loader;
  904. }
  905. /** @hidden */
  906. MSFT_lod.prototype.dispose = function () {
  907. delete this._loader;
  908. this._nodeIndexLOD = null;
  909. this._nodeSignalLODs.length = 0;
  910. this._nodePromiseLODs.length = 0;
  911. this._materialIndexLOD = null;
  912. this._materialSignalLODs.length = 0;
  913. this._materialPromiseLODs.length = 0;
  914. this.onMaterialLODsLoadedObservable.clear();
  915. this.onNodeLODsLoadedObservable.clear();
  916. };
  917. /** @hidden */
  918. MSFT_lod.prototype.onReady = function () {
  919. var _this = this;
  920. var _loop_1 = function (indexLOD) {
  921. var promise = Promise.all(this_1._nodePromiseLODs[indexLOD]).then(function () {
  922. if (indexLOD !== 0) {
  923. _this._loader.endPerformanceCounter("Node LOD " + indexLOD);
  924. }
  925. _this._loader.log("Loaded node LOD " + indexLOD);
  926. _this.onNodeLODsLoadedObservable.notifyObservers(indexLOD);
  927. if (indexLOD !== _this._nodePromiseLODs.length - 1) {
  928. _this._loader.startPerformanceCounter("Node LOD " + (indexLOD + 1));
  929. if (_this._nodeSignalLODs[indexLOD]) {
  930. _this._nodeSignalLODs[indexLOD].resolve();
  931. }
  932. }
  933. });
  934. this_1._loader._completePromises.push(promise);
  935. };
  936. var this_1 = this;
  937. for (var indexLOD = 0; indexLOD < this._nodePromiseLODs.length; indexLOD++) {
  938. _loop_1(indexLOD);
  939. }
  940. var _loop_2 = function (indexLOD) {
  941. var promise = Promise.all(this_2._materialPromiseLODs[indexLOD]).then(function () {
  942. if (indexLOD !== 0) {
  943. _this._loader.endPerformanceCounter("Material LOD " + indexLOD);
  944. }
  945. _this._loader.log("Loaded material LOD " + indexLOD);
  946. _this.onMaterialLODsLoadedObservable.notifyObservers(indexLOD);
  947. if (indexLOD !== _this._materialPromiseLODs.length - 1) {
  948. _this._loader.startPerformanceCounter("Material LOD " + (indexLOD + 1));
  949. if (_this._materialSignalLODs[indexLOD]) {
  950. _this._materialSignalLODs[indexLOD].resolve();
  951. }
  952. }
  953. });
  954. this_2._loader._completePromises.push(promise);
  955. };
  956. var this_2 = this;
  957. for (var indexLOD = 0; indexLOD < this._materialPromiseLODs.length; indexLOD++) {
  958. _loop_2(indexLOD);
  959. }
  960. };
  961. /** @hidden */
  962. MSFT_lod.prototype.loadNodeAsync = function (context, node, assign) {
  963. var _this = this;
  964. return glTFLoader_1.GLTFLoaderV2.LoadExtensionAsync(context, node, this.name, function (extensionContext, extension) {
  965. var firstPromise;
  966. var nodeLODs = _this._getLODs(extensionContext, node, _this._loader.gltf.nodes, extension.ids);
  967. _this._loader.logOpen("" + extensionContext);
  968. var _loop_3 = function (indexLOD) {
  969. var nodeLOD = nodeLODs[indexLOD];
  970. if (indexLOD !== 0) {
  971. _this._nodeIndexLOD = indexLOD;
  972. _this._nodeSignalLODs[indexLOD] = _this._nodeSignalLODs[indexLOD] || new babylonjs_1.Deferred();
  973. }
  974. var promise = _this._loader.loadNodeAsync("#/nodes/" + nodeLOD.index, nodeLOD).then(function (babylonMesh) {
  975. if (indexLOD !== 0) {
  976. // TODO: should not rely on _babylonMesh
  977. var previousNodeLOD = nodeLODs[indexLOD - 1];
  978. if (previousNodeLOD._babylonMesh) {
  979. previousNodeLOD._babylonMesh.dispose();
  980. delete previousNodeLOD._babylonMesh;
  981. _this._disposeUnusedMaterials();
  982. }
  983. }
  984. return babylonMesh;
  985. });
  986. if (indexLOD === 0) {
  987. firstPromise = promise;
  988. }
  989. else {
  990. _this._nodeIndexLOD = null;
  991. }
  992. _this._nodePromiseLODs[indexLOD] = _this._nodePromiseLODs[indexLOD] || [];
  993. _this._nodePromiseLODs[indexLOD].push(promise);
  994. };
  995. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  996. _loop_3(indexLOD);
  997. }
  998. _this._loader.logClose();
  999. return firstPromise;
  1000. });
  1001. };
  1002. /** @hidden */
  1003. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  1004. var _this = this;
  1005. // Don't load material LODs if already loading a node LOD.
  1006. if (this._nodeIndexLOD) {
  1007. return null;
  1008. }
  1009. return glTFLoader_1.GLTFLoaderV2.LoadExtensionAsync(context, material, this.name, function (extensionContext, extension) {
  1010. var firstPromise;
  1011. var materialLODs = _this._getLODs(extensionContext, material, _this._loader.gltf.materials, extension.ids);
  1012. _this._loader.logOpen("" + extensionContext);
  1013. var _loop_4 = function (indexLOD) {
  1014. var materialLOD = materialLODs[indexLOD];
  1015. if (indexLOD !== 0) {
  1016. _this._materialIndexLOD = indexLOD;
  1017. }
  1018. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD.index, materialLOD, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  1019. if (indexLOD === 0) {
  1020. assign(babylonMaterial);
  1021. }
  1022. }).then(function (babylonMaterial) {
  1023. if (indexLOD !== 0) {
  1024. assign(babylonMaterial);
  1025. // TODO: should not rely on _babylonData
  1026. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  1027. if (previousBabylonDataLOD[babylonDrawMode]) {
  1028. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  1029. delete previousBabylonDataLOD[babylonDrawMode];
  1030. }
  1031. }
  1032. return babylonMaterial;
  1033. });
  1034. if (indexLOD === 0) {
  1035. firstPromise = promise;
  1036. }
  1037. else {
  1038. _this._materialIndexLOD = null;
  1039. }
  1040. _this._materialPromiseLODs[indexLOD] = _this._materialPromiseLODs[indexLOD] || [];
  1041. _this._materialPromiseLODs[indexLOD].push(promise);
  1042. };
  1043. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  1044. _loop_4(indexLOD);
  1045. }
  1046. _this._loader.logClose();
  1047. return firstPromise;
  1048. });
  1049. };
  1050. /** @hidden */
  1051. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  1052. var _this = this;
  1053. // Defer the loading of uris if loading a material or node LOD.
  1054. if (this._materialIndexLOD !== null) {
  1055. this._loader.log("deferred");
  1056. var previousIndexLOD = this._materialIndexLOD - 1;
  1057. this._materialSignalLODs[previousIndexLOD] = this._materialSignalLODs[previousIndexLOD] || new babylonjs_1.Deferred();
  1058. return this._materialSignalLODs[previousIndexLOD].promise.then(function () {
  1059. return _this._loader.loadUriAsync(context, uri);
  1060. });
  1061. }
  1062. else if (this._nodeIndexLOD !== null) {
  1063. this._loader.log("deferred");
  1064. var previousIndexLOD = this._nodeIndexLOD - 1;
  1065. this._nodeSignalLODs[previousIndexLOD] = this._nodeSignalLODs[previousIndexLOD] || new babylonjs_1.Deferred();
  1066. return this._nodeSignalLODs[this._nodeIndexLOD - 1].promise.then(function () {
  1067. return _this._loader.loadUriAsync(context, uri);
  1068. });
  1069. }
  1070. return null;
  1071. };
  1072. /**
  1073. * Gets an array of LOD properties from lowest to highest.
  1074. */
  1075. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  1076. if (this.maxLODsToLoad <= 0) {
  1077. throw new Error("maxLODsToLoad must be greater than zero");
  1078. }
  1079. var properties = new Array();
  1080. for (var i = ids.length - 1; i >= 0; i--) {
  1081. properties.push(glTFLoader_1.ArrayItem.Get(context + "/ids/" + ids[i], array, ids[i]));
  1082. if (properties.length === this.maxLODsToLoad) {
  1083. return properties;
  1084. }
  1085. }
  1086. properties.push(property);
  1087. return properties;
  1088. };
  1089. MSFT_lod.prototype._disposeUnusedMaterials = function () {
  1090. // TODO: should not rely on _babylonData
  1091. var materials = this._loader.gltf.materials;
  1092. if (materials) {
  1093. for (var _i = 0, materials_1 = materials; _i < materials_1.length; _i++) {
  1094. var material = materials_1[_i];
  1095. if (material._babylonData) {
  1096. for (var drawMode in material._babylonData) {
  1097. var babylonData = material._babylonData[drawMode];
  1098. if (babylonData.meshes.length === 0) {
  1099. babylonData.material.dispose(false, true);
  1100. delete material._babylonData[drawMode];
  1101. }
  1102. }
  1103. }
  1104. }
  1105. }
  1106. };
  1107. return MSFT_lod;
  1108. }());
  1109. exports.MSFT_lod = MSFT_lod;
  1110. glTFLoader_1.GLTFLoaderV2.RegisterExtension(NAME, function (loader) { return new MSFT_lod(loader); });
  1111. /***/ }),
  1112. /***/ "./src/glTF/2.0/Extensions/MSFT_minecraftMesh.ts":
  1113. /*!*******************************************************!*\
  1114. !*** ./src/glTF/2.0/Extensions/MSFT_minecraftMesh.ts ***!
  1115. \*******************************************************/
  1116. /*! no static exports found */
  1117. /***/ (function(module, exports, __webpack_require__) {
  1118. "use strict";
  1119. Object.defineProperty(exports, "__esModule", { value: true });
  1120. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  1121. var glTFLoader_1 = __webpack_require__(/*! ../glTFLoader */ "./src/glTF/2.0/glTFLoader.ts");
  1122. var NAME = "MSFT_minecraftMesh";
  1123. /** @hidden */
  1124. var MSFT_minecraftMesh = /** @class */ (function () {
  1125. function MSFT_minecraftMesh(loader) {
  1126. this.name = NAME;
  1127. this.enabled = true;
  1128. this._loader = loader;
  1129. }
  1130. MSFT_minecraftMesh.prototype.dispose = function () {
  1131. delete this._loader;
  1132. };
  1133. MSFT_minecraftMesh.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  1134. var _this = this;
  1135. return glTFLoader_1.GLTFLoaderV2.LoadExtraAsync(context, material, this.name, function (extraContext, extra) {
  1136. if (extra) {
  1137. if (!(babylonMaterial instanceof babylonjs_1.PBRMaterial)) {
  1138. throw new Error(extraContext + ": Material type not supported");
  1139. }
  1140. var promise = _this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial);
  1141. if (babylonMaterial.needAlphaBlending()) {
  1142. babylonMaterial.forceDepthWrite = true;
  1143. babylonMaterial.separateCullingPass = true;
  1144. }
  1145. babylonMaterial.backFaceCulling = babylonMaterial.forceDepthWrite;
  1146. babylonMaterial.twoSidedLighting = true;
  1147. return promise;
  1148. }
  1149. return null;
  1150. });
  1151. };
  1152. return MSFT_minecraftMesh;
  1153. }());
  1154. exports.MSFT_minecraftMesh = MSFT_minecraftMesh;
  1155. glTFLoader_1.GLTFLoaderV2.RegisterExtension(NAME, function (loader) { return new MSFT_minecraftMesh(loader); });
  1156. /***/ }),
  1157. /***/ "./src/glTF/2.0/Extensions/MSFT_sRGBFactors.ts":
  1158. /*!*****************************************************!*\
  1159. !*** ./src/glTF/2.0/Extensions/MSFT_sRGBFactors.ts ***!
  1160. \*****************************************************/
  1161. /*! no static exports found */
  1162. /***/ (function(module, exports, __webpack_require__) {
  1163. "use strict";
  1164. Object.defineProperty(exports, "__esModule", { value: true });
  1165. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  1166. var glTFLoader_1 = __webpack_require__(/*! ../glTFLoader */ "./src/glTF/2.0/glTFLoader.ts");
  1167. var NAME = "MSFT_sRGBFactors";
  1168. /** @hidden */
  1169. var MSFT_sRGBFactors = /** @class */ (function () {
  1170. function MSFT_sRGBFactors(loader) {
  1171. this.name = NAME;
  1172. this.enabled = true;
  1173. this._loader = loader;
  1174. }
  1175. MSFT_sRGBFactors.prototype.dispose = function () {
  1176. delete this._loader;
  1177. };
  1178. MSFT_sRGBFactors.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  1179. var _this = this;
  1180. return glTFLoader_1.GLTFLoaderV2.LoadExtraAsync(context, material, this.name, function (extraContext, extra) {
  1181. if (extra) {
  1182. if (!(babylonMaterial instanceof babylonjs_1.PBRMaterial)) {
  1183. throw new Error(extraContext + ": Material type not supported");
  1184. }
  1185. var promise = _this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial);
  1186. if (!babylonMaterial.albedoTexture) {
  1187. babylonMaterial.albedoColor.toLinearSpaceToRef(babylonMaterial.albedoColor);
  1188. }
  1189. if (!babylonMaterial.reflectivityTexture) {
  1190. babylonMaterial.reflectivityColor.toLinearSpaceToRef(babylonMaterial.reflectivityColor);
  1191. }
  1192. return promise;
  1193. }
  1194. return null;
  1195. });
  1196. };
  1197. return MSFT_sRGBFactors;
  1198. }());
  1199. exports.MSFT_sRGBFactors = MSFT_sRGBFactors;
  1200. glTFLoader_1.GLTFLoaderV2.RegisterExtension(NAME, function (loader) { return new MSFT_sRGBFactors(loader); });
  1201. /***/ }),
  1202. /***/ "./src/glTF/2.0/Extensions/index.ts":
  1203. /*!******************************************!*\
  1204. !*** ./src/glTF/2.0/Extensions/index.ts ***!
  1205. \******************************************/
  1206. /*! no static exports found */
  1207. /***/ (function(module, exports, __webpack_require__) {
  1208. "use strict";
  1209. function __export(m) {
  1210. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  1211. }
  1212. Object.defineProperty(exports, "__esModule", { value: true });
  1213. __export(__webpack_require__(/*! ./EXT_lights_image_based */ "./src/glTF/2.0/Extensions/EXT_lights_image_based.ts"));
  1214. __export(__webpack_require__(/*! ./KHR_draco_mesh_compression */ "./src/glTF/2.0/Extensions/KHR_draco_mesh_compression.ts"));
  1215. __export(__webpack_require__(/*! ./KHR_lights_punctual */ "./src/glTF/2.0/Extensions/KHR_lights_punctual.ts"));
  1216. __export(__webpack_require__(/*! ./KHR_materials_pbrSpecularGlossiness */ "./src/glTF/2.0/Extensions/KHR_materials_pbrSpecularGlossiness.ts"));
  1217. __export(__webpack_require__(/*! ./KHR_materials_unlit */ "./src/glTF/2.0/Extensions/KHR_materials_unlit.ts"));
  1218. __export(__webpack_require__(/*! ./KHR_texture_transform */ "./src/glTF/2.0/Extensions/KHR_texture_transform.ts"));
  1219. __export(__webpack_require__(/*! ./MSFT_audio_emitter */ "./src/glTF/2.0/Extensions/MSFT_audio_emitter.ts"));
  1220. __export(__webpack_require__(/*! ./MSFT_lod */ "./src/glTF/2.0/Extensions/MSFT_lod.ts"));
  1221. __export(__webpack_require__(/*! ./MSFT_minecraftMesh */ "./src/glTF/2.0/Extensions/MSFT_minecraftMesh.ts"));
  1222. __export(__webpack_require__(/*! ./MSFT_sRGBFactors */ "./src/glTF/2.0/Extensions/MSFT_sRGBFactors.ts"));
  1223. /***/ }),
  1224. /***/ "./src/glTF/2.0/glTFLoader.ts":
  1225. /*!************************************!*\
  1226. !*** ./src/glTF/2.0/glTFLoader.ts ***!
  1227. \************************************/
  1228. /*! no static exports found */
  1229. /***/ (function(module, exports, __webpack_require__) {
  1230. "use strict";
  1231. Object.defineProperty(exports, "__esModule", { value: true });
  1232. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  1233. var glTFFileLoader_1 = __webpack_require__(/*! ../glTFFileLoader */ "./src/glTF/glTFFileLoader.ts");
  1234. /**
  1235. * Helper class for working with arrays when loading the glTF asset
  1236. */
  1237. var ArrayItem = /** @class */ (function () {
  1238. function ArrayItem() {
  1239. }
  1240. /**
  1241. * Gets an item from the given array.
  1242. * @param context The context when loading the asset
  1243. * @param array The array to get the item from
  1244. * @param index The index to the array
  1245. * @returns The array item
  1246. */
  1247. ArrayItem.Get = function (context, array, index) {
  1248. if (!array || index == undefined || !array[index]) {
  1249. throw new Error(context + ": Failed to find index (" + index + ")");
  1250. }
  1251. return array[index];
  1252. };
  1253. /**
  1254. * Assign an `index` field to each item of the given array.
  1255. * @param array The array of items
  1256. */
  1257. ArrayItem.Assign = function (array) {
  1258. if (array) {
  1259. for (var index = 0; index < array.length; index++) {
  1260. array[index].index = index;
  1261. }
  1262. }
  1263. };
  1264. return ArrayItem;
  1265. }());
  1266. exports.ArrayItem = ArrayItem;
  1267. /**
  1268. * The glTF 2.0 loader
  1269. */
  1270. var GLTFLoaderV2 = /** @class */ (function () {
  1271. /** @hidden */
  1272. function GLTFLoaderV2(parent) {
  1273. /** @hidden */
  1274. this._completePromises = new Array();
  1275. this._disposed = false;
  1276. this._state = null;
  1277. this._extensions = {};
  1278. this._defaultBabylonMaterialData = {};
  1279. this._requests = new Array();
  1280. this._parent = parent;
  1281. }
  1282. /**
  1283. * Registers a loader extension.
  1284. * @param name The name of the loader extension.
  1285. * @param factory The factory function that creates the loader extension.
  1286. */
  1287. GLTFLoaderV2.RegisterExtension = function (name, factory) {
  1288. if (GLTFLoaderV2.UnregisterExtension(name)) {
  1289. babylonjs_1.Tools.Warn("Extension with the name '" + name + "' already exists");
  1290. }
  1291. GLTFLoaderV2._ExtensionFactories[name] = factory;
  1292. // Keep the order of registration so that extensions registered first are called first.
  1293. GLTFLoaderV2._ExtensionNames.push(name);
  1294. };
  1295. /**
  1296. * Unregisters a loader extension.
  1297. * @param name The name of the loader extenion.
  1298. * @returns A boolean indicating whether the extension has been unregistered
  1299. */
  1300. GLTFLoaderV2.UnregisterExtension = function (name) {
  1301. if (!GLTFLoaderV2._ExtensionFactories[name]) {
  1302. return false;
  1303. }
  1304. delete GLTFLoaderV2._ExtensionFactories[name];
  1305. var index = GLTFLoaderV2._ExtensionNames.indexOf(name);
  1306. if (index !== -1) {
  1307. GLTFLoaderV2._ExtensionNames.splice(index, 1);
  1308. }
  1309. return true;
  1310. };
  1311. Object.defineProperty(GLTFLoaderV2.prototype, "state", {
  1312. /**
  1313. * Gets the loader state.
  1314. */
  1315. get: function () {
  1316. return this._state;
  1317. },
  1318. enumerable: true,
  1319. configurable: true
  1320. });
  1321. /** @hidden */
  1322. GLTFLoaderV2.prototype.dispose = function () {
  1323. if (this._disposed) {
  1324. return;
  1325. }
  1326. this._disposed = true;
  1327. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  1328. var request = _a[_i];
  1329. request.abort();
  1330. }
  1331. this._requests.length = 0;
  1332. delete this.gltf;
  1333. delete this.babylonScene;
  1334. this._completePromises.length = 0;
  1335. for (var name_1 in this._extensions) {
  1336. var extension = this._extensions[name_1];
  1337. if (extension.dispose) {
  1338. this._extensions[name_1].dispose();
  1339. }
  1340. }
  1341. this._extensions = {};
  1342. delete this._rootBabylonMesh;
  1343. delete this._progressCallback;
  1344. this._parent._clear();
  1345. };
  1346. /** @hidden */
  1347. GLTFLoaderV2.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress, fileName) {
  1348. var _this = this;
  1349. return Promise.resolve().then(function () {
  1350. _this.babylonScene = scene;
  1351. _this._rootUrl = rootUrl;
  1352. _this._fileName = fileName || "scene";
  1353. _this._progressCallback = onProgress;
  1354. _this._loadData(data);
  1355. var nodes = null;
  1356. if (meshesNames) {
  1357. var nodeMap_1 = {};
  1358. if (_this.gltf.nodes) {
  1359. for (var _i = 0, _a = _this.gltf.nodes; _i < _a.length; _i++) {
  1360. var node = _a[_i];
  1361. if (node.name) {
  1362. nodeMap_1[node.name] = node.index;
  1363. }
  1364. }
  1365. }
  1366. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  1367. nodes = names.map(function (name) {
  1368. var node = nodeMap_1[name];
  1369. if (node === undefined) {
  1370. throw new Error("Failed to find node '" + name + "'");
  1371. }
  1372. return node;
  1373. });
  1374. }
  1375. return _this._loadAsync(nodes, function () {
  1376. return {
  1377. meshes: _this._getMeshes(),
  1378. particleSystems: [],
  1379. skeletons: _this._getSkeletons(),
  1380. animationGroups: _this._getAnimationGroups()
  1381. };
  1382. });
  1383. });
  1384. };
  1385. /** @hidden */
  1386. GLTFLoaderV2.prototype.loadAsync = function (scene, data, rootUrl, onProgress, fileName) {
  1387. var _this = this;
  1388. return Promise.resolve().then(function () {
  1389. _this.babylonScene = scene;
  1390. _this._rootUrl = rootUrl;
  1391. _this._fileName = fileName || "scene";
  1392. _this._progressCallback = onProgress;
  1393. _this._loadData(data);
  1394. return _this._loadAsync(null, function () { return undefined; });
  1395. });
  1396. };
  1397. GLTFLoaderV2.prototype._loadAsync = function (nodes, resultFunc) {
  1398. var _this = this;
  1399. return Promise.resolve().then(function () {
  1400. _this._uniqueRootUrl = (_this._rootUrl.indexOf("file:") === -1 && _this._fileName) ? _this._rootUrl : "" + _this._rootUrl + Date.now() + "/";
  1401. _this._loadExtensions();
  1402. _this._checkExtensions();
  1403. var loadingToReadyCounterName = glTFFileLoader_1.GLTFLoaderState[glTFFileLoader_1.GLTFLoaderState.LOADING] + " => " + glTFFileLoader_1.GLTFLoaderState[glTFFileLoader_1.GLTFLoaderState.READY];
  1404. var loadingToCompleteCounterName = glTFFileLoader_1.GLTFLoaderState[glTFFileLoader_1.GLTFLoaderState.LOADING] + " => " + glTFFileLoader_1.GLTFLoaderState[glTFFileLoader_1.GLTFLoaderState.COMPLETE];
  1405. _this._parent._startPerformanceCounter(loadingToReadyCounterName);
  1406. _this._parent._startPerformanceCounter(loadingToCompleteCounterName);
  1407. _this._setState(glTFFileLoader_1.GLTFLoaderState.LOADING);
  1408. _this._extensionsOnLoading();
  1409. var promises = new Array();
  1410. if (nodes) {
  1411. promises.push(_this.loadSceneAsync("#/nodes", { nodes: nodes, index: -1 }));
  1412. }
  1413. else {
  1414. var scene = ArrayItem.Get("#/scene", _this.gltf.scenes, _this.gltf.scene || 0);
  1415. promises.push(_this.loadSceneAsync("#/scenes/" + scene.index, scene));
  1416. }
  1417. if (_this._parent.compileMaterials) {
  1418. promises.push(_this._compileMaterialsAsync());
  1419. }
  1420. if (_this._parent.compileShadowGenerators) {
  1421. promises.push(_this._compileShadowGeneratorsAsync());
  1422. }
  1423. var resultPromise = Promise.all(promises).then(function () {
  1424. _this._setState(glTFFileLoader_1.GLTFLoaderState.READY);
  1425. _this._extensionsOnReady();
  1426. _this._startAnimations();
  1427. return resultFunc();
  1428. });
  1429. resultPromise.then(function () {
  1430. _this._parent._endPerformanceCounter(loadingToReadyCounterName);
  1431. babylonjs_1.Tools.SetImmediate(function () {
  1432. if (!_this._disposed) {
  1433. Promise.all(_this._completePromises).then(function () {
  1434. _this._parent._endPerformanceCounter(loadingToCompleteCounterName);
  1435. _this._setState(glTFFileLoader_1.GLTFLoaderState.COMPLETE);
  1436. _this._parent.onCompleteObservable.notifyObservers(undefined);
  1437. _this._parent.onCompleteObservable.clear();
  1438. _this.dispose();
  1439. }, function (error) {
  1440. _this._parent.onErrorObservable.notifyObservers(error);
  1441. _this._parent.onErrorObservable.clear();
  1442. _this.dispose();
  1443. });
  1444. }
  1445. });
  1446. });
  1447. return resultPromise;
  1448. }, function (error) {
  1449. if (!_this._disposed) {
  1450. _this._parent.onErrorObservable.notifyObservers(error);
  1451. _this._parent.onErrorObservable.clear();
  1452. _this.dispose();
  1453. }
  1454. throw error;
  1455. });
  1456. };
  1457. GLTFLoaderV2.prototype._loadData = function (data) {
  1458. this.gltf = data.json;
  1459. this._setupData();
  1460. if (data.bin) {
  1461. var buffers = this.gltf.buffers;
  1462. if (buffers && buffers[0] && !buffers[0].uri) {
  1463. var binaryBuffer = buffers[0];
  1464. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  1465. babylonjs_1.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  1466. }
  1467. binaryBuffer._data = Promise.resolve(data.bin);
  1468. }
  1469. else {
  1470. babylonjs_1.Tools.Warn("Unexpected BIN chunk");
  1471. }
  1472. }
  1473. };
  1474. GLTFLoaderV2.prototype._setupData = function () {
  1475. ArrayItem.Assign(this.gltf.accessors);
  1476. ArrayItem.Assign(this.gltf.animations);
  1477. ArrayItem.Assign(this.gltf.buffers);
  1478. ArrayItem.Assign(this.gltf.bufferViews);
  1479. ArrayItem.Assign(this.gltf.cameras);
  1480. ArrayItem.Assign(this.gltf.images);
  1481. ArrayItem.Assign(this.gltf.materials);
  1482. ArrayItem.Assign(this.gltf.meshes);
  1483. ArrayItem.Assign(this.gltf.nodes);
  1484. ArrayItem.Assign(this.gltf.samplers);
  1485. ArrayItem.Assign(this.gltf.scenes);
  1486. ArrayItem.Assign(this.gltf.skins);
  1487. ArrayItem.Assign(this.gltf.textures);
  1488. if (this.gltf.nodes) {
  1489. var nodeParents = {};
  1490. for (var _i = 0, _a = this.gltf.nodes; _i < _a.length; _i++) {
  1491. var node = _a[_i];
  1492. if (node.children) {
  1493. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  1494. var index = _c[_b];
  1495. nodeParents[index] = node.index;
  1496. }
  1497. }
  1498. }
  1499. var rootNode = this._createRootNode();
  1500. for (var _d = 0, _e = this.gltf.nodes; _d < _e.length; _d++) {
  1501. var node = _e[_d];
  1502. var parentIndex = nodeParents[node.index];
  1503. node.parent = parentIndex === undefined ? rootNode : this.gltf.nodes[parentIndex];
  1504. }
  1505. }
  1506. };
  1507. GLTFLoaderV2.prototype._loadExtensions = function () {
  1508. for (var _i = 0, _a = GLTFLoaderV2._ExtensionNames; _i < _a.length; _i++) {
  1509. var name_2 = _a[_i];
  1510. var extension = GLTFLoaderV2._ExtensionFactories[name_2](this);
  1511. this._extensions[name_2] = extension;
  1512. this._parent.onExtensionLoadedObservable.notifyObservers(extension);
  1513. }
  1514. this._parent.onExtensionLoadedObservable.clear();
  1515. };
  1516. GLTFLoaderV2.prototype._checkExtensions = function () {
  1517. if (this.gltf.extensionsRequired) {
  1518. for (var _i = 0, _a = this.gltf.extensionsRequired; _i < _a.length; _i++) {
  1519. var name_3 = _a[_i];
  1520. var extension = this._extensions[name_3];
  1521. if (!extension || !extension.enabled) {
  1522. throw new Error("Require extension " + name_3 + " is not available");
  1523. }
  1524. }
  1525. }
  1526. };
  1527. GLTFLoaderV2.prototype._setState = function (state) {
  1528. this._state = state;
  1529. this.log(glTFFileLoader_1.GLTFLoaderState[this._state]);
  1530. };
  1531. GLTFLoaderV2.prototype._createRootNode = function () {
  1532. this._rootBabylonMesh = new babylonjs_1.Mesh("__root__", this.babylonScene);
  1533. var rootNode = {
  1534. _babylonMesh: this._rootBabylonMesh,
  1535. index: -1
  1536. };
  1537. switch (this._parent.coordinateSystemMode) {
  1538. case glTFFileLoader_1.GLTFLoaderCoordinateSystemMode.AUTO: {
  1539. if (!this.babylonScene.useRightHandedSystem) {
  1540. rootNode.rotation = [0, 1, 0, 0];
  1541. rootNode.scale = [1, 1, -1];
  1542. GLTFLoaderV2._LoadTransform(rootNode, this._rootBabylonMesh);
  1543. }
  1544. break;
  1545. }
  1546. case glTFFileLoader_1.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  1547. this.babylonScene.useRightHandedSystem = true;
  1548. break;
  1549. }
  1550. default: {
  1551. throw new Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  1552. }
  1553. }
  1554. this._parent.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  1555. return rootNode;
  1556. };
  1557. /**
  1558. * Loads a glTF scene.
  1559. * @param context The context when loading the asset
  1560. * @param scene The glTF scene property
  1561. * @returns A promise that resolves when the load is complete
  1562. */
  1563. GLTFLoaderV2.prototype.loadSceneAsync = function (context, scene) {
  1564. var _this = this;
  1565. var extensionPromise = this._extensionsLoadSceneAsync(context, scene);
  1566. if (extensionPromise) {
  1567. return extensionPromise;
  1568. }
  1569. var promises = new Array();
  1570. this.logOpen(context + " " + (scene.name || ""));
  1571. if (scene.nodes) {
  1572. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  1573. var index = _a[_i];
  1574. var node = ArrayItem.Get(context + "/nodes/" + index, this.gltf.nodes, index);
  1575. promises.push(this.loadNodeAsync("#/nodes/" + node.index, node, function (babylonMesh) {
  1576. babylonMesh.parent = _this._rootBabylonMesh;
  1577. }));
  1578. }
  1579. }
  1580. promises.push(this._loadAnimationsAsync());
  1581. this.logClose();
  1582. return Promise.all(promises).then(function () { });
  1583. };
  1584. GLTFLoaderV2.prototype._forEachPrimitive = function (node, callback) {
  1585. if (node._primitiveBabylonMeshes) {
  1586. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  1587. var babylonMesh = _a[_i];
  1588. callback(babylonMesh);
  1589. }
  1590. }
  1591. else {
  1592. callback(node._babylonMesh);
  1593. }
  1594. };
  1595. GLTFLoaderV2.prototype._getMeshes = function () {
  1596. var meshes = new Array();
  1597. // Root mesh is always first.
  1598. meshes.push(this._rootBabylonMesh);
  1599. var nodes = this.gltf.nodes;
  1600. if (nodes) {
  1601. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  1602. var node = nodes_1[_i];
  1603. if (node._babylonMesh) {
  1604. meshes.push(node._babylonMesh);
  1605. }
  1606. if (node._primitiveBabylonMeshes) {
  1607. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  1608. var babylonMesh = _b[_a];
  1609. meshes.push(babylonMesh);
  1610. }
  1611. }
  1612. }
  1613. }
  1614. return meshes;
  1615. };
  1616. GLTFLoaderV2.prototype._getSkeletons = function () {
  1617. var skeletons = new Array();
  1618. var skins = this.gltf.skins;
  1619. if (skins) {
  1620. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  1621. var skin = skins_1[_i];
  1622. if (skin._babylonSkeleton) {
  1623. skeletons.push(skin._babylonSkeleton);
  1624. }
  1625. }
  1626. }
  1627. return skeletons;
  1628. };
  1629. GLTFLoaderV2.prototype._getAnimationGroups = function () {
  1630. var animationGroups = new Array();
  1631. var animations = this.gltf.animations;
  1632. if (animations) {
  1633. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  1634. var animation = animations_1[_i];
  1635. if (animation._babylonAnimationGroup) {
  1636. animationGroups.push(animation._babylonAnimationGroup);
  1637. }
  1638. }
  1639. }
  1640. return animationGroups;
  1641. };
  1642. GLTFLoaderV2.prototype._startAnimations = function () {
  1643. switch (this._parent.animationStartMode) {
  1644. case glTFFileLoader_1.GLTFLoaderAnimationStartMode.NONE: {
  1645. // do nothing
  1646. break;
  1647. }
  1648. case glTFFileLoader_1.GLTFLoaderAnimationStartMode.FIRST: {
  1649. var babylonAnimationGroups = this._getAnimationGroups();
  1650. if (babylonAnimationGroups.length !== 0) {
  1651. babylonAnimationGroups[0].start(true);
  1652. }
  1653. break;
  1654. }
  1655. case glTFFileLoader_1.GLTFLoaderAnimationStartMode.ALL: {
  1656. var babylonAnimationGroups = this._getAnimationGroups();
  1657. for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) {
  1658. var babylonAnimationGroup = babylonAnimationGroups_1[_i];
  1659. babylonAnimationGroup.start(true);
  1660. }
  1661. break;
  1662. }
  1663. default: {
  1664. babylonjs_1.Tools.Error("Invalid animation start mode (" + this._parent.animationStartMode + ")");
  1665. return;
  1666. }
  1667. }
  1668. };
  1669. /**
  1670. * Loads a glTF node.
  1671. * @param context The context when loading the asset
  1672. * @param node The glTF node property
  1673. * @param assign A function called synchronously after parsing the glTF properties
  1674. * @returns A promise that resolves with the loaded Babylon mesh when the load is complete
  1675. */
  1676. GLTFLoaderV2.prototype.loadNodeAsync = function (context, node, assign) {
  1677. var _this = this;
  1678. if (assign === void 0) { assign = function () { }; }
  1679. var extensionPromise = this._extensionsLoadNodeAsync(context, node, assign);
  1680. if (extensionPromise) {
  1681. return extensionPromise;
  1682. }
  1683. if (node._babylonMesh) {
  1684. throw new Error(context + ": Invalid recursive node hierarchy");
  1685. }
  1686. var promises = new Array();
  1687. this.logOpen(context + " " + (node.name || ""));
  1688. var babylonMesh = new babylonjs_1.Mesh(node.name || "node" + node.index, this.babylonScene);
  1689. node._babylonMesh = babylonMesh;
  1690. babylonMesh.setEnabled(false);
  1691. GLTFLoaderV2._LoadTransform(node, babylonMesh);
  1692. if (node.mesh != undefined) {
  1693. var mesh = ArrayItem.Get(context + "/mesh", this.gltf.meshes, node.mesh);
  1694. promises.push(this._loadMeshAsync("#/meshes/" + mesh.index, node, mesh, babylonMesh));
  1695. }
  1696. if (node.camera != undefined) {
  1697. var camera = ArrayItem.Get(context + "/camera", this.gltf.cameras, node.camera);
  1698. promises.push(this.loadCameraAsync("#/cameras/" + camera.index, camera, function (babylonCamera) {
  1699. babylonCamera.parent = babylonMesh;
  1700. }));
  1701. }
  1702. if (node.children) {
  1703. var _loop_1 = function (index) {
  1704. var childNode = ArrayItem.Get(context + "/children/" + index, this_1.gltf.nodes, index);
  1705. promises.push(this_1.loadNodeAsync("#/nodes/" + node.index, childNode, function (childBabylonMesh) {
  1706. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  1707. if (childNode.skin != undefined) {
  1708. childBabylonMesh.parent = _this._rootBabylonMesh;
  1709. return;
  1710. }
  1711. childBabylonMesh.parent = babylonMesh;
  1712. }));
  1713. };
  1714. var this_1 = this;
  1715. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  1716. var index = _a[_i];
  1717. _loop_1(index);
  1718. }
  1719. }
  1720. assign(babylonMesh);
  1721. this._parent.onMeshLoadedObservable.notifyObservers(babylonMesh);
  1722. this.logClose();
  1723. return Promise.all(promises).then(function () {
  1724. babylonMesh.setEnabled(true);
  1725. return babylonMesh;
  1726. });
  1727. };
  1728. GLTFLoaderV2.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  1729. var _this = this;
  1730. var promises = new Array();
  1731. this.logOpen(context + " " + (mesh.name || ""));
  1732. var primitives = mesh.primitives;
  1733. if (!primitives || primitives.length === 0) {
  1734. throw new Error(context + ": Primitives are missing");
  1735. }
  1736. ArrayItem.Assign(primitives);
  1737. if (primitives.length === 1) {
  1738. var primitive = primitives[0];
  1739. promises.push(this._loadMeshPrimitiveAsync(context + "/primitives/" + primitive.index, node, mesh, primitive, babylonMesh));
  1740. }
  1741. else {
  1742. node._primitiveBabylonMeshes = [];
  1743. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  1744. var primitive = primitives_1[_i];
  1745. var primitiveBabylonMesh = new babylonjs_1.Mesh((mesh.name || babylonMesh.name) + "_" + primitive.index, this.babylonScene, babylonMesh);
  1746. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  1747. promises.push(this._loadMeshPrimitiveAsync(context + "/primitives/" + primitive.index, node, mesh, primitive, primitiveBabylonMesh));
  1748. this._parent.onMeshLoadedObservable.notifyObservers(babylonMesh);
  1749. }
  1750. }
  1751. if (node.skin != undefined) {
  1752. var skin = ArrayItem.Get(context + "/skin", this.gltf.skins, node.skin);
  1753. promises.push(this._loadSkinAsync("#/skins/" + skin.index, node, skin));
  1754. }
  1755. this.logClose();
  1756. return Promise.all(promises).then(function () {
  1757. _this._forEachPrimitive(node, function (babylonMesh) {
  1758. babylonMesh._refreshBoundingInfo(true);
  1759. });
  1760. });
  1761. };
  1762. GLTFLoaderV2.prototype._loadMeshPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  1763. var _this = this;
  1764. var promises = new Array();
  1765. this.logOpen("" + context);
  1766. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  1767. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonGeometry) {
  1768. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(function () {
  1769. babylonGeometry.applyToMesh(babylonMesh);
  1770. });
  1771. }));
  1772. var babylonDrawMode = GLTFLoaderV2._GetDrawMode(context, primitive.mode);
  1773. if (primitive.material == undefined) {
  1774. var babylonMaterial = this._defaultBabylonMaterialData[babylonDrawMode];
  1775. if (!babylonMaterial) {
  1776. babylonMaterial = this._createDefaultMaterial("__gltf_default", babylonDrawMode);
  1777. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  1778. this._defaultBabylonMaterialData[babylonDrawMode] = babylonMaterial;
  1779. }
  1780. babylonMesh.material = babylonMaterial;
  1781. }
  1782. else {
  1783. var material = ArrayItem.Get(context + "/material", this.gltf.materials, primitive.material);
  1784. promises.push(this._loadMaterialAsync("#/materials/" + material.index, material, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  1785. babylonMesh.material = babylonMaterial;
  1786. }));
  1787. }
  1788. this.logClose();
  1789. return Promise.all(promises).then(function () { });
  1790. };
  1791. GLTFLoaderV2.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  1792. var _this = this;
  1793. var extensionPromise = this._extensionsLoadVertexDataAsync(context, primitive, babylonMesh);
  1794. if (extensionPromise) {
  1795. return extensionPromise;
  1796. }
  1797. var attributes = primitive.attributes;
  1798. if (!attributes) {
  1799. throw new Error(context + ": Attributes are missing");
  1800. }
  1801. var promises = new Array();
  1802. var babylonGeometry = new babylonjs_1.Geometry(babylonMesh.name, this.babylonScene);
  1803. if (primitive.indices == undefined) {
  1804. babylonMesh.isUnIndexed = true;
  1805. }
  1806. else {
  1807. var accessor = ArrayItem.Get(context + "/indices", this.gltf.accessors, primitive.indices);
  1808. promises.push(this._loadIndicesAccessorAsync("#/accessors/" + accessor.index, accessor).then(function (data) {
  1809. babylonGeometry.setIndices(data);
  1810. }));
  1811. }
  1812. var loadAttribute = function (attribute, kind, callback) {
  1813. if (attributes[attribute] == undefined) {
  1814. return;
  1815. }
  1816. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  1817. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  1818. babylonMesh._delayInfo.push(kind);
  1819. }
  1820. var accessor = ArrayItem.Get(context + "/attributes/" + attribute, _this.gltf.accessors, attributes[attribute]);
  1821. promises.push(_this._loadVertexAccessorAsync("#/accessors/" + accessor.index, accessor, kind).then(function (babylonVertexBuffer) {
  1822. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  1823. }));
  1824. if (callback) {
  1825. callback(accessor);
  1826. }
  1827. };
  1828. loadAttribute("POSITION", babylonjs_1.VertexBuffer.PositionKind);
  1829. loadAttribute("NORMAL", babylonjs_1.VertexBuffer.NormalKind);
  1830. loadAttribute("TANGENT", babylonjs_1.VertexBuffer.TangentKind);
  1831. loadAttribute("TEXCOORD_0", babylonjs_1.VertexBuffer.UVKind);
  1832. loadAttribute("TEXCOORD_1", babylonjs_1.VertexBuffer.UV2Kind);
  1833. loadAttribute("JOINTS_0", babylonjs_1.VertexBuffer.MatricesIndicesKind);
  1834. loadAttribute("WEIGHTS_0", babylonjs_1.VertexBuffer.MatricesWeightsKind);
  1835. loadAttribute("COLOR_0", babylonjs_1.VertexBuffer.ColorKind, function (accessor) {
  1836. if (accessor.type === "VEC4" /* VEC4 */) {
  1837. babylonMesh.hasVertexAlpha = true;
  1838. }
  1839. });
  1840. return Promise.all(promises).then(function () {
  1841. return babylonGeometry;
  1842. });
  1843. };
  1844. GLTFLoaderV2.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  1845. if (!primitive.targets) {
  1846. return;
  1847. }
  1848. if (node._numMorphTargets == undefined) {
  1849. node._numMorphTargets = primitive.targets.length;
  1850. }
  1851. else if (primitive.targets.length !== node._numMorphTargets) {
  1852. throw new Error(context + ": Primitives do not have the same number of targets");
  1853. }
  1854. babylonMesh.morphTargetManager = new babylonjs_1.MorphTargetManager();
  1855. for (var index = 0; index < primitive.targets.length; index++) {
  1856. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  1857. babylonMesh.morphTargetManager.addTarget(new babylonjs_1.MorphTarget("morphTarget" + index, weight));
  1858. // TODO: tell the target whether it has positions, normals, tangents
  1859. }
  1860. };
  1861. GLTFLoaderV2.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) {
  1862. if (!primitive.targets) {
  1863. return Promise.resolve();
  1864. }
  1865. var promises = new Array();
  1866. var morphTargetManager = babylonMesh.morphTargetManager;
  1867. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  1868. var babylonMorphTarget = morphTargetManager.getTarget(index);
  1869. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  1870. }
  1871. return Promise.all(promises).then(function () { });
  1872. };
  1873. GLTFLoaderV2.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) {
  1874. var _this = this;
  1875. var promises = new Array();
  1876. var loadAttribute = function (attribute, kind, setData) {
  1877. if (attributes[attribute] == undefined) {
  1878. return;
  1879. }
  1880. var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  1881. if (!babylonVertexBuffer) {
  1882. return;
  1883. }
  1884. var accessor = ArrayItem.Get(context + "/" + attribute, _this.gltf.accessors, attributes[attribute]);
  1885. promises.push(_this._loadFloatAccessorAsync("#/accessors/" + accessor.index, accessor).then(function (data) {
  1886. setData(babylonVertexBuffer, data);
  1887. }));
  1888. };
  1889. loadAttribute("POSITION", babylonjs_1.VertexBuffer.PositionKind, function (babylonVertexBuffer, data) {
  1890. babylonVertexBuffer.forEach(data.length, function (value, index) {
  1891. data[index] += value;
  1892. });
  1893. babylonMorphTarget.setPositions(data);
  1894. });
  1895. loadAttribute("NORMAL", babylonjs_1.VertexBuffer.NormalKind, function (babylonVertexBuffer, data) {
  1896. babylonVertexBuffer.forEach(data.length, function (value, index) {
  1897. data[index] += value;
  1898. });
  1899. babylonMorphTarget.setNormals(data);
  1900. });
  1901. loadAttribute("TANGENT", babylonjs_1.VertexBuffer.TangentKind, function (babylonVertexBuffer, data) {
  1902. var dataIndex = 0;
  1903. babylonVertexBuffer.forEach(data.length / 3 * 4, function (value, index) {
  1904. // Tangent data for morph targets is stored as xyz delta.
  1905. // The vertexData.tangent is stored as xyzw.
  1906. // So we need to skip every fourth vertexData.tangent.
  1907. if (((index + 1) % 4) !== 0) {
  1908. data[dataIndex++] += value;
  1909. }
  1910. });
  1911. babylonMorphTarget.setTangents(data);
  1912. });
  1913. return Promise.all(promises).then(function () { });
  1914. };
  1915. GLTFLoaderV2._LoadTransform = function (node, babylonNode) {
  1916. var position = babylonjs_1.Vector3.Zero();
  1917. var rotation = babylonjs_1.Quaternion.Identity();
  1918. var scaling = babylonjs_1.Vector3.One();
  1919. if (node.matrix) {
  1920. var matrix = babylonjs_1.Matrix.FromArray(node.matrix);
  1921. matrix.decompose(scaling, rotation, position);
  1922. }
  1923. else {
  1924. if (node.translation) {
  1925. position = babylonjs_1.Vector3.FromArray(node.translation);
  1926. }
  1927. if (node.rotation) {
  1928. rotation = babylonjs_1.Quaternion.FromArray(node.rotation);
  1929. }
  1930. if (node.scale) {
  1931. scaling = babylonjs_1.Vector3.FromArray(node.scale);
  1932. }
  1933. }
  1934. babylonNode.position = position;
  1935. babylonNode.rotationQuaternion = rotation;
  1936. babylonNode.scaling = scaling;
  1937. };
  1938. GLTFLoaderV2.prototype._loadSkinAsync = function (context, node, skin) {
  1939. var _this = this;
  1940. var assignSkeleton = function (skeleton) {
  1941. _this._forEachPrimitive(node, function (babylonMesh) {
  1942. babylonMesh.skeleton = skeleton;
  1943. });
  1944. // Ignore the TRS of skinned nodes.
  1945. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  1946. node._babylonMesh.position = babylonjs_1.Vector3.Zero();
  1947. node._babylonMesh.rotationQuaternion = babylonjs_1.Quaternion.Identity();
  1948. node._babylonMesh.scaling = babylonjs_1.Vector3.One();
  1949. };
  1950. if (skin._promise) {
  1951. return skin._promise.then(function () {
  1952. assignSkeleton(skin._babylonSkeleton);
  1953. });
  1954. }
  1955. var skeletonId = "skeleton" + skin.index;
  1956. var babylonSkeleton = new babylonjs_1.Skeleton(skin.name || skeletonId, skeletonId, this.babylonScene);
  1957. skin._babylonSkeleton = babylonSkeleton;
  1958. this._loadBones(context, skin);
  1959. assignSkeleton(babylonSkeleton);
  1960. return (skin._promise = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  1961. _this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData);
  1962. }));
  1963. };
  1964. GLTFLoaderV2.prototype._loadBones = function (context, skin) {
  1965. var babylonBones = {};
  1966. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  1967. var index = _a[_i];
  1968. var node = ArrayItem.Get(context + "/joints/" + index, this.gltf.nodes, index);
  1969. this._loadBone(node, skin, babylonBones);
  1970. }
  1971. };
  1972. GLTFLoaderV2.prototype._loadBone = function (node, skin, babylonBones) {
  1973. var babylonBone = babylonBones[node.index];
  1974. if (babylonBone) {
  1975. return babylonBone;
  1976. }
  1977. var babylonParentBone = null;
  1978. if (node.parent && node.parent._babylonMesh !== this._rootBabylonMesh) {
  1979. babylonParentBone = this._loadBone(node.parent, skin, babylonBones);
  1980. }
  1981. var boneIndex = skin.joints.indexOf(node.index);
  1982. babylonBone = new babylonjs_1.Bone(node.name || "joint" + node.index, skin._babylonSkeleton, babylonParentBone, this._getNodeMatrix(node), null, null, boneIndex);
  1983. babylonBones[node.index] = babylonBone;
  1984. node._babylonBones = node._babylonBones || [];
  1985. node._babylonBones.push(babylonBone);
  1986. return babylonBone;
  1987. };
  1988. GLTFLoaderV2.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  1989. if (skin.inverseBindMatrices == undefined) {
  1990. return Promise.resolve(null);
  1991. }
  1992. var accessor = ArrayItem.Get(context + "/inverseBindMatrices", this.gltf.accessors, skin.inverseBindMatrices);
  1993. return this._loadFloatAccessorAsync("#/accessors/" + accessor.index, accessor);
  1994. };
  1995. GLTFLoaderV2.prototype._updateBoneMatrices = function (babylonSkeleton, inverseBindMatricesData) {
  1996. for (var _i = 0, _a = babylonSkeleton.bones; _i < _a.length; _i++) {
  1997. var babylonBone = _a[_i];
  1998. var baseMatrix = babylonjs_1.Matrix.Identity();
  1999. var boneIndex = babylonBone._index;
  2000. if (inverseBindMatricesData && boneIndex !== -1) {
  2001. babylonjs_1.Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix);
  2002. baseMatrix.invertToRef(baseMatrix);
  2003. }
  2004. var babylonParentBone = babylonBone.getParent();
  2005. if (babylonParentBone) {
  2006. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  2007. }
  2008. babylonBone.updateMatrix(baseMatrix, false, false);
  2009. babylonBone._updateDifferenceMatrix(undefined, false);
  2010. }
  2011. };
  2012. GLTFLoaderV2.prototype._getNodeMatrix = function (node) {
  2013. return node.matrix ?
  2014. babylonjs_1.Matrix.FromArray(node.matrix) :
  2015. babylonjs_1.Matrix.Compose(node.scale ? babylonjs_1.Vector3.FromArray(node.scale) : babylonjs_1.Vector3.One(), node.rotation ? babylonjs_1.Quaternion.FromArray(node.rotation) : babylonjs_1.Quaternion.Identity(), node.translation ? babylonjs_1.Vector3.FromArray(node.translation) : babylonjs_1.Vector3.Zero());
  2016. };
  2017. /**
  2018. * Loads a glTF camera.
  2019. * @param context The context when loading the asset
  2020. * @param camera The glTF camera property
  2021. * @param assign A function called synchronously after parsing the glTF properties
  2022. * @returns A promise that resolves with the loaded Babylon camera when the load is complete
  2023. */
  2024. GLTFLoaderV2.prototype.loadCameraAsync = function (context, camera, assign) {
  2025. if (assign === void 0) { assign = function () { }; }
  2026. var extensionPromise = this._extensionsLoadCameraAsync(context, camera, assign);
  2027. if (extensionPromise) {
  2028. return extensionPromise;
  2029. }
  2030. var promises = new Array();
  2031. this.logOpen(context + " " + (camera.name || ""));
  2032. var babylonCamera = new babylonjs_1.FreeCamera(camera.name || "camera" + camera.index, babylonjs_1.Vector3.Zero(), this.babylonScene, false);
  2033. babylonCamera.rotation = new babylonjs_1.Vector3(0, Math.PI, 0);
  2034. switch (camera.type) {
  2035. case "perspective" /* PERSPECTIVE */: {
  2036. var perspective = camera.perspective;
  2037. if (!perspective) {
  2038. throw new Error(context + ": Camera perspective properties are missing");
  2039. }
  2040. babylonCamera.fov = perspective.yfov;
  2041. babylonCamera.minZ = perspective.znear;
  2042. babylonCamera.maxZ = perspective.zfar || Number.MAX_VALUE;
  2043. break;
  2044. }
  2045. case "orthographic" /* ORTHOGRAPHIC */: {
  2046. if (!camera.orthographic) {
  2047. throw new Error(context + ": Camera orthographic properties are missing");
  2048. }
  2049. babylonCamera.mode = babylonjs_1.Camera.ORTHOGRAPHIC_CAMERA;
  2050. babylonCamera.orthoLeft = -camera.orthographic.xmag;
  2051. babylonCamera.orthoRight = camera.orthographic.xmag;
  2052. babylonCamera.orthoBottom = -camera.orthographic.ymag;
  2053. babylonCamera.orthoTop = camera.orthographic.ymag;
  2054. babylonCamera.minZ = camera.orthographic.znear;
  2055. babylonCamera.maxZ = camera.orthographic.zfar;
  2056. break;
  2057. }
  2058. default: {
  2059. throw new Error(context + ": Invalid camera type (" + camera.type + ")");
  2060. }
  2061. }
  2062. assign(babylonCamera);
  2063. this._parent.onCameraLoadedObservable.notifyObservers(babylonCamera);
  2064. return Promise.all(promises).then(function () {
  2065. return babylonCamera;
  2066. });
  2067. };
  2068. GLTFLoaderV2.prototype._loadAnimationsAsync = function () {
  2069. var animations = this.gltf.animations;
  2070. if (!animations) {
  2071. return Promise.resolve();
  2072. }
  2073. var promises = new Array();
  2074. for (var index = 0; index < animations.length; index++) {
  2075. var animation = animations[index];
  2076. promises.push(this.loadAnimationAsync("#/animations/" + animation.index, animation));
  2077. }
  2078. return Promise.all(promises).then(function () { });
  2079. };
  2080. /**
  2081. * Loads a glTF animation.
  2082. * @param context The context when loading the asset
  2083. * @param animation The glTF animation property
  2084. * @returns A promise that resolves with the loaded Babylon animation group when the load is complete
  2085. */
  2086. GLTFLoaderV2.prototype.loadAnimationAsync = function (context, animation) {
  2087. var promise = this._extensionsLoadAnimationAsync(context, animation);
  2088. if (promise) {
  2089. return promise;
  2090. }
  2091. var babylonAnimationGroup = new babylonjs_1.AnimationGroup(animation.name || "animation" + animation.index, this.babylonScene);
  2092. animation._babylonAnimationGroup = babylonAnimationGroup;
  2093. var promises = new Array();
  2094. ArrayItem.Assign(animation.channels);
  2095. ArrayItem.Assign(animation.samplers);
  2096. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  2097. var channel = _a[_i];
  2098. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel.index, context, animation, channel, babylonAnimationGroup));
  2099. }
  2100. return Promise.all(promises).then(function () {
  2101. babylonAnimationGroup.normalize(0);
  2102. return babylonAnimationGroup;
  2103. });
  2104. };
  2105. GLTFLoaderV2.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  2106. var _this = this;
  2107. var targetNode = ArrayItem.Get(context + "/target/node", this.gltf.nodes, channel.target.node);
  2108. // Ignore animations that have no animation targets.
  2109. if ((channel.target.path === "weights" /* WEIGHTS */ && !targetNode._numMorphTargets) ||
  2110. (channel.target.path !== "weights" /* WEIGHTS */ && !targetNode._babylonMesh)) {
  2111. return Promise.resolve();
  2112. }
  2113. // Ignore animations targeting TRS of skinned nodes.
  2114. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  2115. if (targetNode.skin != undefined && channel.target.path !== "weights" /* WEIGHTS */) {
  2116. return Promise.resolve();
  2117. }
  2118. var sampler = ArrayItem.Get(context + "/sampler", animation.samplers, channel.sampler);
  2119. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  2120. var targetPath;
  2121. var animationType;
  2122. switch (channel.target.path) {
  2123. case "translation" /* TRANSLATION */: {
  2124. targetPath = "position";
  2125. animationType = babylonjs_1.Animation.ANIMATIONTYPE_VECTOR3;
  2126. break;
  2127. }
  2128. case "rotation" /* ROTATION */: {
  2129. targetPath = "rotationQuaternion";
  2130. animationType = babylonjs_1.Animation.ANIMATIONTYPE_QUATERNION;
  2131. break;
  2132. }
  2133. case "scale" /* SCALE */: {
  2134. targetPath = "scaling";
  2135. animationType = babylonjs_1.Animation.ANIMATIONTYPE_VECTOR3;
  2136. break;
  2137. }
  2138. case "weights" /* WEIGHTS */: {
  2139. targetPath = "influence";
  2140. animationType = babylonjs_1.Animation.ANIMATIONTYPE_FLOAT;
  2141. break;
  2142. }
  2143. default: {
  2144. throw new Error(context + "/target/path: Invalid value (" + channel.target.path + ")");
  2145. }
  2146. }
  2147. var outputBufferOffset = 0;
  2148. var getNextOutputValue;
  2149. switch (targetPath) {
  2150. case "position": {
  2151. getNextOutputValue = function () {
  2152. var value = babylonjs_1.Vector3.FromArray(data.output, outputBufferOffset);
  2153. outputBufferOffset += 3;
  2154. return value;
  2155. };
  2156. break;
  2157. }
  2158. case "rotationQuaternion": {
  2159. getNextOutputValue = function () {
  2160. var value = babylonjs_1.Quaternion.FromArray(data.output, outputBufferOffset);
  2161. outputBufferOffset += 4;
  2162. return value;
  2163. };
  2164. break;
  2165. }
  2166. case "scaling": {
  2167. getNextOutputValue = function () {
  2168. var value = babylonjs_1.Vector3.FromArray(data.output, outputBufferOffset);
  2169. outputBufferOffset += 3;
  2170. return value;
  2171. };
  2172. break;
  2173. }
  2174. case "influence": {
  2175. getNextOutputValue = function () {
  2176. var value = new Array(targetNode._numMorphTargets);
  2177. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  2178. value[i] = data.output[outputBufferOffset++];
  2179. }
  2180. return value;
  2181. };
  2182. break;
  2183. }
  2184. }
  2185. var getNextKey;
  2186. switch (data.interpolation) {
  2187. case "STEP" /* STEP */: {
  2188. getNextKey = function (frameIndex) { return ({
  2189. frame: data.input[frameIndex],
  2190. value: getNextOutputValue(),
  2191. interpolation: babylonjs_1.AnimationKeyInterpolation.STEP
  2192. }); };
  2193. break;
  2194. }
  2195. case "LINEAR" /* LINEAR */: {
  2196. getNextKey = function (frameIndex) { return ({
  2197. frame: data.input[frameIndex],
  2198. value: getNextOutputValue()
  2199. }); };
  2200. break;
  2201. }
  2202. case "CUBICSPLINE" /* CUBICSPLINE */: {
  2203. getNextKey = function (frameIndex) { return ({
  2204. frame: data.input[frameIndex],
  2205. inTangent: getNextOutputValue(),
  2206. value: getNextOutputValue(),
  2207. outTangent: getNextOutputValue()
  2208. }); };
  2209. break;
  2210. }
  2211. }
  2212. var keys = new Array(data.input.length);
  2213. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  2214. keys[frameIndex] = getNextKey(frameIndex);
  2215. }
  2216. if (targetPath === "influence") {
  2217. var _loop_2 = function (targetIndex) {
  2218. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  2219. var babylonAnimation = new babylonjs_1.Animation(animationName, targetPath, 1, animationType);
  2220. babylonAnimation.setKeys(keys.map(function (key) { return ({
  2221. frame: key.frame,
  2222. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  2223. value: key.value[targetIndex],
  2224. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  2225. }); }));
  2226. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  2227. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  2228. var babylonAnimationClone = babylonAnimation.clone();
  2229. morphTarget.animations.push(babylonAnimationClone);
  2230. babylonAnimationGroup.addTargetedAnimation(babylonAnimationClone, morphTarget);
  2231. });
  2232. };
  2233. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  2234. _loop_2(targetIndex);
  2235. }
  2236. }
  2237. else {
  2238. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  2239. var babylonAnimation = new babylonjs_1.Animation(animationName, targetPath, 1, animationType);
  2240. babylonAnimation.setKeys(keys);
  2241. if (targetNode._babylonBones) {
  2242. var babylonAnimationTargets = [targetNode._babylonMesh].concat(targetNode._babylonBones);
  2243. for (var _i = 0, babylonAnimationTargets_1 = babylonAnimationTargets; _i < babylonAnimationTargets_1.length; _i++) {
  2244. var babylonAnimationTarget = babylonAnimationTargets_1[_i];
  2245. babylonAnimationTarget.animations.push(babylonAnimation);
  2246. }
  2247. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, babylonAnimationTargets);
  2248. }
  2249. else {
  2250. targetNode._babylonMesh.animations.push(babylonAnimation);
  2251. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonMesh);
  2252. }
  2253. }
  2254. });
  2255. };
  2256. GLTFLoaderV2.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  2257. if (sampler._data) {
  2258. return sampler._data;
  2259. }
  2260. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  2261. switch (interpolation) {
  2262. case "STEP" /* STEP */:
  2263. case "LINEAR" /* LINEAR */:
  2264. case "CUBICSPLINE" /* CUBICSPLINE */: {
  2265. break;
  2266. }
  2267. default: {
  2268. throw new Error(context + "/interpolation: Invalid value (" + sampler.interpolation + ")");
  2269. }
  2270. }
  2271. var inputAccessor = ArrayItem.Get(context + "/input", this.gltf.accessors, sampler.input);
  2272. var outputAccessor = ArrayItem.Get(context + "/output", this.gltf.accessors, sampler.output);
  2273. sampler._data = Promise.all([
  2274. this._loadFloatAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor),
  2275. this._loadFloatAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor)
  2276. ]).then(function (_a) {
  2277. var inputData = _a[0], outputData = _a[1];
  2278. return {
  2279. input: inputData,
  2280. interpolation: interpolation,
  2281. output: outputData,
  2282. };
  2283. });
  2284. return sampler._data;
  2285. };
  2286. GLTFLoaderV2.prototype._loadBufferAsync = function (context, buffer) {
  2287. if (buffer._data) {
  2288. return buffer._data;
  2289. }
  2290. if (!buffer.uri) {
  2291. throw new Error(context + "/uri: Value is missing");
  2292. }
  2293. buffer._data = this.loadUriAsync(context + "/uri", buffer.uri);
  2294. return buffer._data;
  2295. };
  2296. /**
  2297. * Loads a glTF buffer view.
  2298. * @param context The context when loading the asset
  2299. * @param bufferView The glTF buffer view property
  2300. * @returns A promise that resolves with the loaded data when the load is complete
  2301. */
  2302. GLTFLoaderV2.prototype.loadBufferViewAsync = function (context, bufferView) {
  2303. if (bufferView._data) {
  2304. return bufferView._data;
  2305. }
  2306. var buffer = ArrayItem.Get(context + "/buffer", this.gltf.buffers, bufferView.buffer);
  2307. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer.index, buffer).then(function (data) {
  2308. try {
  2309. return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  2310. }
  2311. catch (e) {
  2312. throw new Error(context + ": " + e.message);
  2313. }
  2314. });
  2315. return bufferView._data;
  2316. };
  2317. GLTFLoaderV2.prototype._loadIndicesAccessorAsync = function (context, accessor) {
  2318. if (accessor.type !== "SCALAR" /* SCALAR */) {
  2319. throw new Error(context + "/type: Invalid value " + accessor.type);
  2320. }
  2321. if (accessor.componentType !== 5121 /* UNSIGNED_BYTE */ &&
  2322. accessor.componentType !== 5123 /* UNSIGNED_SHORT */ &&
  2323. accessor.componentType !== 5125 /* UNSIGNED_INT */) {
  2324. throw new Error(context + "/componentType: Invalid value " + accessor.componentType);
  2325. }
  2326. if (accessor._data) {
  2327. return accessor._data;
  2328. }
  2329. var bufferView = ArrayItem.Get(context + "/bufferView", this.gltf.bufferViews, accessor.bufferView);
  2330. accessor._data = this.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView).then(function (data) {
  2331. return GLTFLoaderV2._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, accessor.count);
  2332. });
  2333. return accessor._data;
  2334. };
  2335. GLTFLoaderV2.prototype._loadFloatAccessorAsync = function (context, accessor) {
  2336. // TODO: support normalized and stride
  2337. var _this = this;
  2338. if (accessor.componentType !== 5126 /* FLOAT */) {
  2339. throw new Error("Invalid component type " + accessor.componentType);
  2340. }
  2341. if (accessor._data) {
  2342. return accessor._data;
  2343. }
  2344. var numComponents = GLTFLoaderV2._GetNumComponents(context, accessor.type);
  2345. var length = numComponents * accessor.count;
  2346. if (accessor.bufferView == undefined) {
  2347. accessor._data = Promise.resolve(new Float32Array(length));
  2348. }
  2349. else {
  2350. var bufferView = ArrayItem.Get(context + "/bufferView", this.gltf.bufferViews, accessor.bufferView);
  2351. accessor._data = this.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView).then(function (data) {
  2352. return GLTFLoaderV2._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, length);
  2353. });
  2354. }
  2355. if (accessor.sparse) {
  2356. var sparse_1 = accessor.sparse;
  2357. accessor._data = accessor._data.then(function (data) {
  2358. var indicesBufferView = ArrayItem.Get(context + "/sparse/indices/bufferView", _this.gltf.bufferViews, sparse_1.indices.bufferView);
  2359. var valuesBufferView = ArrayItem.Get(context + "/sparse/values/bufferView", _this.gltf.bufferViews, sparse_1.values.bufferView);
  2360. return Promise.all([
  2361. _this.loadBufferViewAsync("#/bufferViews/" + indicesBufferView.index, indicesBufferView),
  2362. _this.loadBufferViewAsync("#/bufferViews/" + valuesBufferView.index, valuesBufferView)
  2363. ]).then(function (_a) {
  2364. var indicesData = _a[0], valuesData = _a[1];
  2365. var indices = GLTFLoaderV2._GetTypedArray(context + "/sparse/indices", sparse_1.indices.componentType, indicesData, sparse_1.indices.byteOffset, sparse_1.count);
  2366. var values = GLTFLoaderV2._GetTypedArray(context + "/sparse/values", accessor.componentType, valuesData, sparse_1.values.byteOffset, numComponents * sparse_1.count);
  2367. var valuesIndex = 0;
  2368. for (var indicesIndex = 0; indicesIndex < indices.length; indicesIndex++) {
  2369. var dataIndex = indices[indicesIndex] * numComponents;
  2370. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  2371. data[dataIndex++] = values[valuesIndex++];
  2372. }
  2373. }
  2374. return data;
  2375. });
  2376. });
  2377. }
  2378. return accessor._data;
  2379. };
  2380. GLTFLoaderV2.prototype._loadVertexBufferViewAsync = function (bufferView, kind) {
  2381. var _this = this;
  2382. if (bufferView._babylonBuffer) {
  2383. return bufferView._babylonBuffer;
  2384. }
  2385. bufferView._babylonBuffer = this.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView).then(function (data) {
  2386. return new babylonjs_1.Buffer(_this.babylonScene.getEngine(), data, false);
  2387. });
  2388. return bufferView._babylonBuffer;
  2389. };
  2390. GLTFLoaderV2.prototype._loadVertexAccessorAsync = function (context, accessor, kind) {
  2391. var _this = this;
  2392. if (accessor._babylonVertexBuffer) {
  2393. return accessor._babylonVertexBuffer;
  2394. }
  2395. if (accessor.sparse) {
  2396. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync("#/accessors/" + accessor.index, accessor).then(function (data) {
  2397. return new babylonjs_1.VertexBuffer(_this.babylonScene.getEngine(), data, kind, false);
  2398. });
  2399. }
  2400. // HACK: If byte offset is not a multiple of component type byte length then load as a float array instead of using Babylon buffers.
  2401. else if (accessor.byteOffset && accessor.byteOffset % babylonjs_1.VertexBuffer.GetTypeByteLength(accessor.componentType) !== 0) {
  2402. babylonjs_1.Tools.Warn("Accessor byte offset is not a multiple of component type byte length");
  2403. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync("#/accessors/" + accessor.index, accessor).then(function (data) {
  2404. return new babylonjs_1.VertexBuffer(_this.babylonScene.getEngine(), data, kind, false);
  2405. });
  2406. }
  2407. else {
  2408. var bufferView_1 = ArrayItem.Get(context + "/bufferView", this.gltf.bufferViews, accessor.bufferView);
  2409. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync(bufferView_1, kind).then(function (babylonBuffer) {
  2410. var size = GLTFLoaderV2._GetNumComponents(context, accessor.type);
  2411. return new babylonjs_1.VertexBuffer(_this.babylonScene.getEngine(), babylonBuffer, kind, false, false, bufferView_1.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
  2412. });
  2413. }
  2414. return accessor._babylonVertexBuffer;
  2415. };
  2416. GLTFLoaderV2.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, properties, babylonMaterial) {
  2417. if (!(babylonMaterial instanceof babylonjs_1.PBRMaterial)) {
  2418. throw new Error(context + ": Material type not supported");
  2419. }
  2420. var promises = new Array();
  2421. if (properties) {
  2422. if (properties.baseColorFactor) {
  2423. babylonMaterial.albedoColor = babylonjs_1.Color3.FromArray(properties.baseColorFactor);
  2424. babylonMaterial.alpha = properties.baseColorFactor[3];
  2425. }
  2426. else {
  2427. babylonMaterial.albedoColor = babylonjs_1.Color3.White();
  2428. }
  2429. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  2430. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  2431. if (properties.baseColorTexture) {
  2432. promises.push(this.loadTextureInfoAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  2433. babylonMaterial.albedoTexture = texture;
  2434. }));
  2435. }
  2436. if (properties.metallicRoughnessTexture) {
  2437. promises.push(this.loadTextureInfoAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  2438. babylonMaterial.metallicTexture = texture;
  2439. }));
  2440. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  2441. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  2442. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  2443. }
  2444. }
  2445. return Promise.all(promises).then(function () { });
  2446. };
  2447. /** @hidden */
  2448. GLTFLoaderV2.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  2449. if (assign === void 0) { assign = function () { }; }
  2450. var extensionPromise = this._extensionsLoadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign);
  2451. if (extensionPromise) {
  2452. return extensionPromise;
  2453. }
  2454. material._babylonData = material._babylonData || {};
  2455. var babylonData = material._babylonData[babylonDrawMode];
  2456. if (!babylonData) {
  2457. this.logOpen(context + " " + (material.name || ""));
  2458. var babylonMaterial = this.createMaterial(context, material, babylonDrawMode);
  2459. babylonData = {
  2460. material: babylonMaterial,
  2461. meshes: [],
  2462. promise: this.loadMaterialPropertiesAsync(context, material, babylonMaterial)
  2463. };
  2464. material._babylonData[babylonDrawMode] = babylonData;
  2465. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  2466. this.logClose();
  2467. }
  2468. babylonData.meshes.push(babylonMesh);
  2469. babylonMesh.onDisposeObservable.addOnce(function () {
  2470. var index = babylonData.meshes.indexOf(babylonMesh);
  2471. if (index !== -1) {
  2472. babylonData.meshes.splice(index, 1);
  2473. }
  2474. });
  2475. assign(babylonData.material);
  2476. return babylonData.promise.then(function () {
  2477. return babylonData.material;
  2478. });
  2479. };
  2480. GLTFLoaderV2.prototype._createDefaultMaterial = function (name, babylonDrawMode) {
  2481. var babylonMaterial = new babylonjs_1.PBRMaterial(name, this.babylonScene);
  2482. babylonMaterial.sideOrientation = this.babylonScene.useRightHandedSystem ? babylonjs_1.Material.CounterClockWiseSideOrientation : babylonjs_1.Material.ClockWiseSideOrientation;
  2483. babylonMaterial.fillMode = babylonDrawMode;
  2484. babylonMaterial.enableSpecularAntiAliasing = true;
  2485. babylonMaterial.useRadianceOverAlpha = !this._parent.transparencyAsCoverage;
  2486. babylonMaterial.useSpecularOverAlpha = !this._parent.transparencyAsCoverage;
  2487. babylonMaterial.transparencyMode = babylonjs_1.PBRMaterial.PBRMATERIAL_OPAQUE;
  2488. babylonMaterial.metallic = 1;
  2489. babylonMaterial.roughness = 1;
  2490. return babylonMaterial;
  2491. };
  2492. /**
  2493. * Creates a Babylon material from a glTF material.
  2494. * @param context The context when loading the asset
  2495. * @param material The glTF material property
  2496. * @param babylonDrawMode The draw mode for the Babylon material
  2497. * @returns The Babylon material
  2498. */
  2499. GLTFLoaderV2.prototype.createMaterial = function (context, material, babylonDrawMode) {
  2500. var extensionPromise = this._extensionsCreateMaterial(context, material, babylonDrawMode);
  2501. if (extensionPromise) {
  2502. return extensionPromise;
  2503. }
  2504. var name = material.name || "material" + material.index;
  2505. return this._createDefaultMaterial(name, babylonDrawMode);
  2506. };
  2507. /**
  2508. * Loads properties from a glTF material into a Babylon material.
  2509. * @param context The context when loading the asset
  2510. * @param material The glTF material property
  2511. * @param babylonMaterial The Babylon material
  2512. * @returns A promise that resolves when the load is complete
  2513. */
  2514. GLTFLoaderV2.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  2515. var extensionPromise = this._extensionsLoadMaterialPropertiesAsync(context, material, babylonMaterial);
  2516. if (extensionPromise) {
  2517. return extensionPromise;
  2518. }
  2519. var promises = new Array();
  2520. promises.push(this.loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  2521. if (material.pbrMetallicRoughness) {
  2522. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context + "/pbrMetallicRoughness", material.pbrMetallicRoughness, babylonMaterial));
  2523. }
  2524. this.loadMaterialAlphaProperties(context, material, babylonMaterial);
  2525. return Promise.all(promises).then(function () { });
  2526. };
  2527. /**
  2528. * Loads the normal, occlusion, and emissive properties from a glTF material into a Babylon material.
  2529. * @param context The context when loading the asset
  2530. * @param material The glTF material property
  2531. * @param babylonMaterial The Babylon material
  2532. * @returns A promise that resolves when the load is complete
  2533. */
  2534. GLTFLoaderV2.prototype.loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  2535. if (!(babylonMaterial instanceof babylonjs_1.PBRMaterial)) {
  2536. throw new Error(context + ": Material type not supported");
  2537. }
  2538. var promises = new Array();
  2539. babylonMaterial.emissiveColor = material.emissiveFactor ? babylonjs_1.Color3.FromArray(material.emissiveFactor) : new babylonjs_1.Color3(0, 0, 0);
  2540. if (material.doubleSided) {
  2541. babylonMaterial.backFaceCulling = false;
  2542. babylonMaterial.twoSidedLighting = true;
  2543. }
  2544. if (material.normalTexture) {
  2545. promises.push(this.loadTextureInfoAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  2546. babylonMaterial.bumpTexture = texture;
  2547. }));
  2548. babylonMaterial.invertNormalMapX = !this.babylonScene.useRightHandedSystem;
  2549. babylonMaterial.invertNormalMapY = this.babylonScene.useRightHandedSystem;
  2550. if (material.normalTexture.scale != undefined) {
  2551. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  2552. }
  2553. }
  2554. if (material.occlusionTexture) {
  2555. promises.push(this.loadTextureInfoAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  2556. babylonMaterial.ambientTexture = texture;
  2557. }));
  2558. babylonMaterial.useAmbientInGrayScale = true;
  2559. if (material.occlusionTexture.strength != undefined) {
  2560. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  2561. }
  2562. }
  2563. if (material.emissiveTexture) {
  2564. promises.push(this.loadTextureInfoAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  2565. babylonMaterial.emissiveTexture = texture;
  2566. }));
  2567. }
  2568. return Promise.all(promises).then(function () { });
  2569. };
  2570. /**
  2571. * Loads the alpha properties from a glTF material into a Babylon material.
  2572. * Must be called after the setting the albedo texture of the Babylon material when the material has an albedo texture.
  2573. * @param context The context when loading the asset
  2574. * @param material The glTF material property
  2575. * @param babylonMaterial The Babylon material
  2576. */
  2577. GLTFLoaderV2.prototype.loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  2578. if (!(babylonMaterial instanceof babylonjs_1.PBRMaterial)) {
  2579. throw new Error(context + ": Material type not supported");
  2580. }
  2581. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  2582. switch (alphaMode) {
  2583. case "OPAQUE" /* OPAQUE */: {
  2584. babylonMaterial.transparencyMode = babylonjs_1.PBRMaterial.PBRMATERIAL_OPAQUE;
  2585. break;
  2586. }
  2587. case "MASK" /* MASK */: {
  2588. babylonMaterial.transparencyMode = babylonjs_1.PBRMaterial.PBRMATERIAL_ALPHATEST;
  2589. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  2590. if (babylonMaterial.albedoTexture) {
  2591. babylonMaterial.albedoTexture.hasAlpha = true;
  2592. }
  2593. break;
  2594. }
  2595. case "BLEND" /* BLEND */: {
  2596. babylonMaterial.transparencyMode = babylonjs_1.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  2597. if (babylonMaterial.albedoTexture) {
  2598. babylonMaterial.albedoTexture.hasAlpha = true;
  2599. babylonMaterial.useAlphaFromAlbedoTexture = true;
  2600. }
  2601. break;
  2602. }
  2603. default: {
  2604. throw new Error(context + "/alphaMode: Invalid value (" + material.alphaMode + ")");
  2605. }
  2606. }
  2607. };
  2608. /**
  2609. * Loads a glTF texture info.
  2610. * @param context The context when loading the asset
  2611. * @param textureInfo The glTF texture info property
  2612. * @param assign A function called synchronously after parsing the glTF properties
  2613. * @returns A promise that resolves with the loaded Babylon texture when the load is complete
  2614. */
  2615. GLTFLoaderV2.prototype.loadTextureInfoAsync = function (context, textureInfo, assign) {
  2616. if (assign === void 0) { assign = function () { }; }
  2617. var extensionPromise = this._extensionsLoadTextureInfoAsync(context, textureInfo, assign);
  2618. if (extensionPromise) {
  2619. return extensionPromise;
  2620. }
  2621. this.logOpen("" + context);
  2622. var texture = ArrayItem.Get(context + "/index", this.gltf.textures, textureInfo.index);
  2623. var promise = this._loadTextureAsync("#/textures/" + textureInfo.index, texture, function (babylonTexture) {
  2624. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  2625. assign(babylonTexture);
  2626. });
  2627. this.logClose();
  2628. return promise;
  2629. };
  2630. GLTFLoaderV2.prototype._loadTextureAsync = function (context, texture, assign) {
  2631. var _this = this;
  2632. if (assign === void 0) { assign = function () { }; }
  2633. var promises = new Array();
  2634. this.logOpen(context + " " + (texture.name || ""));
  2635. var sampler = (texture.sampler == undefined ? GLTFLoaderV2._DefaultSampler : ArrayItem.Get(context + "/sampler", this.gltf.samplers, texture.sampler));
  2636. var samplerData = this._loadSampler("#/samplers/" + sampler.index, sampler);
  2637. var deferred = new babylonjs_1.Deferred();
  2638. var babylonTexture = new babylonjs_1.Texture(null, this.babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  2639. if (!_this._disposed) {
  2640. deferred.resolve();
  2641. }
  2642. }, function (message, exception) {
  2643. if (!_this._disposed) {
  2644. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  2645. }
  2646. });
  2647. promises.push(deferred.promise);
  2648. babylonTexture.name = texture.name || "texture" + texture.index;
  2649. babylonTexture.wrapU = samplerData.wrapU;
  2650. babylonTexture.wrapV = samplerData.wrapV;
  2651. var image = ArrayItem.Get(context + "/source", this.gltf.images, texture.source);
  2652. promises.push(this.loadImageAsync("#/images/" + image.index, image).then(function (data) {
  2653. var name = image.uri || _this._fileName + "#image" + image.index;
  2654. var dataUrl = "data:" + _this._uniqueRootUrl + name;
  2655. babylonTexture.updateURL(dataUrl, new Blob([data], { type: image.mimeType }));
  2656. }));
  2657. assign(babylonTexture);
  2658. this._parent.onTextureLoadedObservable.notifyObservers(babylonTexture);
  2659. this.logClose();
  2660. return Promise.all(promises).then(function () {
  2661. return babylonTexture;
  2662. });
  2663. };
  2664. GLTFLoaderV2.prototype._loadSampler = function (context, sampler) {
  2665. if (!sampler._data) {
  2666. sampler._data = {
  2667. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  2668. samplingMode: GLTFLoaderV2._GetTextureSamplingMode(context, sampler),
  2669. wrapU: GLTFLoaderV2._GetTextureWrapMode(context + "/wrapS", sampler.wrapS),
  2670. wrapV: GLTFLoaderV2._GetTextureWrapMode(context + "/wrapT", sampler.wrapT)
  2671. };
  2672. }
  2673. return sampler._data;
  2674. };
  2675. /**
  2676. * Loads a glTF image.
  2677. * @param context The context when loading the asset
  2678. * @param image The glTF image property
  2679. * @returns A promise that resolves with the loaded data when the load is complete
  2680. */
  2681. GLTFLoaderV2.prototype.loadImageAsync = function (context, image) {
  2682. if (!image._data) {
  2683. this.logOpen(context + " " + (image.name || ""));
  2684. if (image.uri) {
  2685. image._data = this.loadUriAsync(context + "/uri", image.uri);
  2686. }
  2687. else {
  2688. var bufferView = ArrayItem.Get(context + "/bufferView", this.gltf.bufferViews, image.bufferView);
  2689. image._data = this.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView);
  2690. }
  2691. this.logClose();
  2692. }
  2693. return image._data;
  2694. };
  2695. /**
  2696. * Loads a glTF uri.
  2697. * @param context The context when loading the asset
  2698. * @param uri The base64 or relative uri
  2699. * @returns A promise that resolves with the loaded data when the load is complete
  2700. */
  2701. GLTFLoaderV2.prototype.loadUriAsync = function (context, uri) {
  2702. var _this = this;
  2703. var extensionPromise = this._extensionsLoadUriAsync(context, uri);
  2704. if (extensionPromise) {
  2705. return extensionPromise;
  2706. }
  2707. if (!GLTFLoaderV2._ValidateUri(uri)) {
  2708. throw new Error(context + ": '" + uri + "' is invalid");
  2709. }
  2710. if (babylonjs_1.Tools.IsBase64(uri)) {
  2711. var data = new Uint8Array(babylonjs_1.Tools.DecodeBase64(uri));
  2712. this.log("Decoded " + uri.substr(0, 64) + "... (" + data.length + " bytes)");
  2713. return Promise.resolve(data);
  2714. }
  2715. this.log("Loading " + uri);
  2716. return this._parent.preprocessUrlAsync(this._rootUrl + uri).then(function (url) {
  2717. return new Promise(function (resolve, reject) {
  2718. if (!_this._disposed) {
  2719. var request_1 = babylonjs_1.Tools.LoadFile(url, function (fileData) {
  2720. if (!_this._disposed) {
  2721. var data = new Uint8Array(fileData);
  2722. _this.log("Loaded " + uri + " (" + data.length + " bytes)");
  2723. resolve(data);
  2724. }
  2725. }, function (event) {
  2726. if (!_this._disposed) {
  2727. if (request_1) {
  2728. request_1._lengthComputable = event.lengthComputable;
  2729. request_1._loaded = event.loaded;
  2730. request_1._total = event.total;
  2731. }
  2732. if (_this._state === glTFFileLoader_1.GLTFLoaderState.LOADING) {
  2733. try {
  2734. _this._onProgress();
  2735. }
  2736. catch (e) {
  2737. reject(e);
  2738. }
  2739. }
  2740. }
  2741. }, _this.babylonScene.offlineProvider, true, function (request, exception) {
  2742. if (!_this._disposed) {
  2743. reject(new babylonjs_1.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  2744. }
  2745. });
  2746. _this._requests.push(request_1);
  2747. }
  2748. });
  2749. });
  2750. };
  2751. GLTFLoaderV2.prototype._onProgress = function () {
  2752. if (!this._progressCallback) {
  2753. return;
  2754. }
  2755. var lengthComputable = true;
  2756. var loaded = 0;
  2757. var total = 0;
  2758. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  2759. var request = _a[_i];
  2760. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  2761. return;
  2762. }
  2763. lengthComputable = lengthComputable && request._lengthComputable;
  2764. loaded += request._loaded;
  2765. total += request._total;
  2766. }
  2767. this._progressCallback(new babylonjs_1.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  2768. };
  2769. GLTFLoaderV2._GetTextureWrapMode = function (context, mode) {
  2770. // Set defaults if undefined
  2771. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  2772. switch (mode) {
  2773. case 33071 /* CLAMP_TO_EDGE */: return babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  2774. case 33648 /* MIRRORED_REPEAT */: return babylonjs_1.Texture.MIRROR_ADDRESSMODE;
  2775. case 10497 /* REPEAT */: return babylonjs_1.Texture.WRAP_ADDRESSMODE;
  2776. default:
  2777. babylonjs_1.Tools.Warn(context + ": Invalid value (" + mode + ")");
  2778. return babylonjs_1.Texture.WRAP_ADDRESSMODE;
  2779. }
  2780. };
  2781. GLTFLoaderV2._GetTextureSamplingMode = function (context, sampler) {
  2782. // Set defaults if undefined
  2783. var magFilter = sampler.magFilter == undefined ? 9729 /* LINEAR */ : sampler.magFilter;
  2784. var minFilter = sampler.minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : sampler.minFilter;
  2785. if (magFilter === 9729 /* LINEAR */) {
  2786. switch (minFilter) {
  2787. case 9728 /* NEAREST */: return babylonjs_1.Texture.LINEAR_NEAREST;
  2788. case 9729 /* LINEAR */: return babylonjs_1.Texture.LINEAR_LINEAR;
  2789. case 9984 /* NEAREST_MIPMAP_NEAREST */: return babylonjs_1.Texture.LINEAR_NEAREST_MIPNEAREST;
  2790. case 9985 /* LINEAR_MIPMAP_NEAREST */: return babylonjs_1.Texture.LINEAR_LINEAR_MIPNEAREST;
  2791. case 9986 /* NEAREST_MIPMAP_LINEAR */: return babylonjs_1.Texture.LINEAR_NEAREST_MIPLINEAR;
  2792. case 9987 /* LINEAR_MIPMAP_LINEAR */: return babylonjs_1.Texture.LINEAR_LINEAR_MIPLINEAR;
  2793. default:
  2794. babylonjs_1.Tools.Warn(context + "/minFilter: Invalid value (" + minFilter + ")");
  2795. return babylonjs_1.Texture.LINEAR_LINEAR_MIPLINEAR;
  2796. }
  2797. }
  2798. else {
  2799. if (magFilter !== 9728 /* NEAREST */) {
  2800. babylonjs_1.Tools.Warn(context + "/magFilter: Invalid value (" + magFilter + ")");
  2801. }
  2802. switch (minFilter) {
  2803. case 9728 /* NEAREST */: return babylonjs_1.Texture.NEAREST_NEAREST;
  2804. case 9729 /* LINEAR */: return babylonjs_1.Texture.NEAREST_LINEAR;
  2805. case 9984 /* NEAREST_MIPMAP_NEAREST */: return babylonjs_1.Texture.NEAREST_NEAREST_MIPNEAREST;
  2806. case 9985 /* LINEAR_MIPMAP_NEAREST */: return babylonjs_1.Texture.NEAREST_LINEAR_MIPNEAREST;
  2807. case 9986 /* NEAREST_MIPMAP_LINEAR */: return babylonjs_1.Texture.NEAREST_NEAREST_MIPLINEAR;
  2808. case 9987 /* LINEAR_MIPMAP_LINEAR */: return babylonjs_1.Texture.NEAREST_LINEAR_MIPLINEAR;
  2809. default:
  2810. babylonjs_1.Tools.Warn(context + "/minFilter: Invalid value (" + minFilter + ")");
  2811. return babylonjs_1.Texture.NEAREST_NEAREST_MIPNEAREST;
  2812. }
  2813. }
  2814. };
  2815. GLTFLoaderV2._GetTypedArray = function (context, componentType, bufferView, byteOffset, length) {
  2816. var buffer = bufferView.buffer;
  2817. byteOffset = bufferView.byteOffset + (byteOffset || 0);
  2818. try {
  2819. switch (componentType) {
  2820. case 5120 /* BYTE */: return new Int8Array(buffer, byteOffset, length);
  2821. case 5121 /* UNSIGNED_BYTE */: return new Uint8Array(buffer, byteOffset, length);
  2822. case 5122 /* SHORT */: return new Int16Array(buffer, byteOffset, length);
  2823. case 5123 /* UNSIGNED_SHORT */: return new Uint16Array(buffer, byteOffset, length);
  2824. case 5125 /* UNSIGNED_INT */: return new Uint32Array(buffer, byteOffset, length);
  2825. case 5126 /* FLOAT */: return new Float32Array(buffer, byteOffset, length);
  2826. default: throw new Error("Invalid component type " + componentType);
  2827. }
  2828. }
  2829. catch (e) {
  2830. throw new Error(context + ": " + e);
  2831. }
  2832. };
  2833. GLTFLoaderV2._GetNumComponents = function (context, type) {
  2834. switch (type) {
  2835. case "SCALAR": return 1;
  2836. case "VEC2": return 2;
  2837. case "VEC3": return 3;
  2838. case "VEC4": return 4;
  2839. case "MAT2": return 4;
  2840. case "MAT3": return 9;
  2841. case "MAT4": return 16;
  2842. }
  2843. throw new Error(context + ": Invalid type (" + type + ")");
  2844. };
  2845. GLTFLoaderV2._ValidateUri = function (uri) {
  2846. return (babylonjs_1.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  2847. };
  2848. GLTFLoaderV2._GetDrawMode = function (context, mode) {
  2849. if (mode == undefined) {
  2850. mode = 4 /* TRIANGLES */;
  2851. }
  2852. switch (mode) {
  2853. case 0 /* POINTS */: return babylonjs_1.Material.PointListDrawMode;
  2854. case 1 /* LINES */: return babylonjs_1.Material.LineListDrawMode;
  2855. case 2 /* LINE_LOOP */: return babylonjs_1.Material.LineLoopDrawMode;
  2856. case 3 /* LINE_STRIP */: return babylonjs_1.Material.LineStripDrawMode;
  2857. case 4 /* TRIANGLES */: return babylonjs_1.Material.TriangleFillMode;
  2858. case 5 /* TRIANGLE_STRIP */: return babylonjs_1.Material.TriangleStripDrawMode;
  2859. case 6 /* TRIANGLE_FAN */: return babylonjs_1.Material.TriangleFanDrawMode;
  2860. }
  2861. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  2862. };
  2863. GLTFLoaderV2.prototype._compileMaterialsAsync = function () {
  2864. var _this = this;
  2865. this._parent._startPerformanceCounter("Compile materials");
  2866. var promises = new Array();
  2867. if (this.gltf.materials) {
  2868. for (var _i = 0, _a = this.gltf.materials; _i < _a.length; _i++) {
  2869. var material = _a[_i];
  2870. if (material._babylonData) {
  2871. for (var babylonDrawMode in material._babylonData) {
  2872. var babylonData = material._babylonData[babylonDrawMode];
  2873. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  2874. var babylonMesh = _c[_b];
  2875. // Ensure nonUniformScaling is set if necessary.
  2876. babylonMesh.computeWorldMatrix(true);
  2877. var babylonMaterial = babylonData.material;
  2878. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  2879. if (this._parent.useClipPlane) {
  2880. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  2881. }
  2882. }
  2883. }
  2884. }
  2885. }
  2886. }
  2887. return Promise.all(promises).then(function () {
  2888. _this._parent._endPerformanceCounter("Compile materials");
  2889. });
  2890. };
  2891. GLTFLoaderV2.prototype._compileShadowGeneratorsAsync = function () {
  2892. var _this = this;
  2893. this._parent._startPerformanceCounter("Compile shadow generators");
  2894. var promises = new Array();
  2895. var lights = this.babylonScene.lights;
  2896. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  2897. var light = lights_1[_i];
  2898. var generator = light.getShadowGenerator();
  2899. if (generator) {
  2900. promises.push(generator.forceCompilationAsync());
  2901. }
  2902. }
  2903. return Promise.all(promises).then(function () {
  2904. _this._parent._endPerformanceCounter("Compile shadow generators");
  2905. });
  2906. };
  2907. GLTFLoaderV2.prototype._forEachExtensions = function (action) {
  2908. for (var _i = 0, _a = GLTFLoaderV2._ExtensionNames; _i < _a.length; _i++) {
  2909. var name_4 = _a[_i];
  2910. var extension = this._extensions[name_4];
  2911. if (extension.enabled) {
  2912. action(extension);
  2913. }
  2914. }
  2915. };
  2916. GLTFLoaderV2.prototype._applyExtensions = function (property, actionAsync) {
  2917. for (var _i = 0, _a = GLTFLoaderV2._ExtensionNames; _i < _a.length; _i++) {
  2918. var name_5 = _a[_i];
  2919. var extension = this._extensions[name_5];
  2920. if (extension.enabled) {
  2921. var loaderProperty = property;
  2922. loaderProperty._activeLoaderExtensions = loaderProperty._activeLoaderExtensions || {};
  2923. var activeLoaderExtensions = loaderProperty._activeLoaderExtensions;
  2924. if (!activeLoaderExtensions[name_5]) {
  2925. activeLoaderExtensions[name_5] = true;
  2926. try {
  2927. var result = actionAsync(extension);
  2928. if (result) {
  2929. return result;
  2930. }
  2931. }
  2932. finally {
  2933. delete activeLoaderExtensions[name_5];
  2934. }
  2935. }
  2936. }
  2937. }
  2938. return null;
  2939. };
  2940. GLTFLoaderV2.prototype._extensionsOnLoading = function () {
  2941. this._forEachExtensions(function (extension) { return extension.onLoading && extension.onLoading(); });
  2942. };
  2943. GLTFLoaderV2.prototype._extensionsOnReady = function () {
  2944. this._forEachExtensions(function (extension) { return extension.onReady && extension.onReady(); });
  2945. };
  2946. GLTFLoaderV2.prototype._extensionsLoadSceneAsync = function (context, scene) {
  2947. return this._applyExtensions(scene, function (extension) { return extension.loadSceneAsync && extension.loadSceneAsync(context, scene); });
  2948. };
  2949. GLTFLoaderV2.prototype._extensionsLoadNodeAsync = function (context, node, assign) {
  2950. return this._applyExtensions(node, function (extension) { return extension.loadNodeAsync && extension.loadNodeAsync(context, node, assign); });
  2951. };
  2952. GLTFLoaderV2.prototype._extensionsLoadCameraAsync = function (context, camera, assign) {
  2953. return this._applyExtensions(camera, function (extension) { return extension.loadCameraAsync && extension.loadCameraAsync(context, camera, assign); });
  2954. };
  2955. GLTFLoaderV2.prototype._extensionsLoadVertexDataAsync = function (context, primitive, babylonMesh) {
  2956. return this._applyExtensions(primitive, function (extension) { return extension._loadVertexDataAsync && extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  2957. };
  2958. GLTFLoaderV2.prototype._extensionsLoadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  2959. return this._applyExtensions(material, function (extension) { return extension._loadMaterialAsync && extension._loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign); });
  2960. };
  2961. GLTFLoaderV2.prototype._extensionsCreateMaterial = function (context, material, babylonDrawMode) {
  2962. return this._applyExtensions({}, function (extension) { return extension.createMaterial && extension.createMaterial(context, material, babylonDrawMode); });
  2963. };
  2964. GLTFLoaderV2.prototype._extensionsLoadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  2965. return this._applyExtensions(material, function (extension) { return extension.loadMaterialPropertiesAsync && extension.loadMaterialPropertiesAsync(context, material, babylonMaterial); });
  2966. };
  2967. GLTFLoaderV2.prototype._extensionsLoadTextureInfoAsync = function (context, textureInfo, assign) {
  2968. return this._applyExtensions(textureInfo, function (extension) { return extension.loadTextureInfoAsync && extension.loadTextureInfoAsync(context, textureInfo, assign); });
  2969. };
  2970. GLTFLoaderV2.prototype._extensionsLoadAnimationAsync = function (context, animation) {
  2971. return this._applyExtensions(animation, function (extension) { return extension.loadAnimationAsync && extension.loadAnimationAsync(context, animation); });
  2972. };
  2973. GLTFLoaderV2.prototype._extensionsLoadUriAsync = function (context, uri) {
  2974. return this._applyExtensions({}, function (extension) { return extension._loadUriAsync && extension._loadUriAsync(context, uri); });
  2975. };
  2976. /**
  2977. * Helper method called by a loader extension to load an glTF extension.
  2978. * @param context The context when loading the asset
  2979. * @param property The glTF property to load the extension from
  2980. * @param extensionName The name of the extension to load
  2981. * @param actionAsync The action to run
  2982. * @returns The promise returned by actionAsync or null if the extension does not exist
  2983. */
  2984. GLTFLoaderV2.LoadExtensionAsync = function (context, property, extensionName, actionAsync) {
  2985. if (!property.extensions) {
  2986. return null;
  2987. }
  2988. var extensions = property.extensions;
  2989. var extension = extensions[extensionName];
  2990. if (!extension) {
  2991. return null;
  2992. }
  2993. return actionAsync(context + "/extensions/" + extensionName, extension);
  2994. };
  2995. /**
  2996. * Helper method called by a loader extension to load a glTF extra.
  2997. * @param context The context when loading the asset
  2998. * @param property The glTF property to load the extra from
  2999. * @param extensionName The name of the extension to load
  3000. * @param actionAsync The action to run
  3001. * @returns The promise returned by actionAsync or null if the extra does not exist
  3002. */
  3003. GLTFLoaderV2.LoadExtraAsync = function (context, property, extensionName, actionAsync) {
  3004. if (!property.extras) {
  3005. return null;
  3006. }
  3007. var extras = property.extras;
  3008. var extra = extras[extensionName];
  3009. if (!extra) {
  3010. return null;
  3011. }
  3012. return actionAsync(context + "/extras/" + extensionName, extra);
  3013. };
  3014. /**
  3015. * Increments the indentation level and logs a message.
  3016. * @param message The message to log
  3017. */
  3018. GLTFLoaderV2.prototype.logOpen = function (message) {
  3019. this._parent._logOpen(message);
  3020. };
  3021. /**
  3022. * Decrements the indentation level.
  3023. */
  3024. GLTFLoaderV2.prototype.logClose = function () {
  3025. this._parent._logClose();
  3026. };
  3027. /**
  3028. * Logs a message
  3029. * @param message The message to log
  3030. */
  3031. GLTFLoaderV2.prototype.log = function (message) {
  3032. this._parent._log(message);
  3033. };
  3034. /**
  3035. * Starts a performance counter.
  3036. * @param counterName The name of the performance counter
  3037. */
  3038. GLTFLoaderV2.prototype.startPerformanceCounter = function (counterName) {
  3039. this._parent._startPerformanceCounter(counterName);
  3040. };
  3041. /**
  3042. * Ends a performance counter.
  3043. * @param counterName The name of the performance counter
  3044. */
  3045. GLTFLoaderV2.prototype.endPerformanceCounter = function (counterName) {
  3046. this._parent._endPerformanceCounter(counterName);
  3047. };
  3048. GLTFLoaderV2._DefaultSampler = { index: -1 };
  3049. GLTFLoaderV2._ExtensionNames = new Array();
  3050. GLTFLoaderV2._ExtensionFactories = {};
  3051. return GLTFLoaderV2;
  3052. }());
  3053. exports.GLTFLoaderV2 = GLTFLoaderV2;
  3054. glTFFileLoader_1.GLTFFileLoader._CreateGLTFLoaderV2 = function (parent) { return new GLTFLoaderV2(parent); };
  3055. /***/ }),
  3056. /***/ "./src/glTF/2.0/glTFLoaderExtension.ts":
  3057. /*!*********************************************!*\
  3058. !*** ./src/glTF/2.0/glTFLoaderExtension.ts ***!
  3059. \*********************************************/
  3060. /*! no static exports found */
  3061. /***/ (function(module, exports, __webpack_require__) {
  3062. "use strict";
  3063. Object.defineProperty(exports, "__esModule", { value: true });
  3064. /** @hidden */
  3065. exports.__IGLTFLoaderExtensionV2 = 0; // I am here to allow dts to be created
  3066. /***/ }),
  3067. /***/ "./src/glTF/2.0/glTFLoaderInterfaces.ts":
  3068. /*!**********************************************!*\
  3069. !*** ./src/glTF/2.0/glTFLoaderInterfaces.ts ***!
  3070. \**********************************************/
  3071. /*! no static exports found */
  3072. /***/ (function(module, exports, __webpack_require__) {
  3073. "use strict";
  3074. Object.defineProperty(exports, "__esModule", { value: true });
  3075. /** @hidden */
  3076. exports.__IGLTFLoaderInterfacesV2 = 0; // I am here to allow dts to be created
  3077. /***/ }),
  3078. /***/ "./src/glTF/2.0/index.ts":
  3079. /*!*******************************!*\
  3080. !*** ./src/glTF/2.0/index.ts ***!
  3081. \*******************************/
  3082. /*! no static exports found */
  3083. /***/ (function(module, exports, __webpack_require__) {
  3084. "use strict";
  3085. function __export(m) {
  3086. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  3087. }
  3088. Object.defineProperty(exports, "__esModule", { value: true });
  3089. __export(__webpack_require__(/*! ./glTFLoader */ "./src/glTF/2.0/glTFLoader.ts"));
  3090. __export(__webpack_require__(/*! ./glTFLoaderExtension */ "./src/glTF/2.0/glTFLoaderExtension.ts"));
  3091. __export(__webpack_require__(/*! ./glTFLoaderInterfaces */ "./src/glTF/2.0/glTFLoaderInterfaces.ts"));
  3092. __export(__webpack_require__(/*! ./Extensions */ "./src/glTF/2.0/Extensions/index.ts"));
  3093. /***/ }),
  3094. /***/ "./src/glTF/glTFFileLoader.ts":
  3095. /*!************************************!*\
  3096. !*** ./src/glTF/glTFFileLoader.ts ***!
  3097. \************************************/
  3098. /*! no static exports found */
  3099. /***/ (function(module, exports, __webpack_require__) {
  3100. "use strict";
  3101. Object.defineProperty(exports, "__esModule", { value: true });
  3102. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  3103. /**
  3104. * Mode that determines the coordinate system to use.
  3105. */
  3106. var GLTFLoaderCoordinateSystemMode;
  3107. (function (GLTFLoaderCoordinateSystemMode) {
  3108. /**
  3109. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  3110. */
  3111. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  3112. /**
  3113. * Sets the useRightHandedSystem flag on the scene.
  3114. */
  3115. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  3116. })(GLTFLoaderCoordinateSystemMode = exports.GLTFLoaderCoordinateSystemMode || (exports.GLTFLoaderCoordinateSystemMode = {}));
  3117. /**
  3118. * Mode that determines what animations will start.
  3119. */
  3120. var GLTFLoaderAnimationStartMode;
  3121. (function (GLTFLoaderAnimationStartMode) {
  3122. /**
  3123. * No animation will start.
  3124. */
  3125. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  3126. /**
  3127. * The first animation will start.
  3128. */
  3129. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  3130. /**
  3131. * All animations will start.
  3132. */
  3133. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  3134. })(GLTFLoaderAnimationStartMode = exports.GLTFLoaderAnimationStartMode || (exports.GLTFLoaderAnimationStartMode = {}));
  3135. /**
  3136. * Loader state.
  3137. */
  3138. var GLTFLoaderState;
  3139. (function (GLTFLoaderState) {
  3140. /**
  3141. * The asset is loading.
  3142. */
  3143. GLTFLoaderState[GLTFLoaderState["LOADING"] = 0] = "LOADING";
  3144. /**
  3145. * The asset is ready for rendering.
  3146. */
  3147. GLTFLoaderState[GLTFLoaderState["READY"] = 1] = "READY";
  3148. /**
  3149. * The asset is completely loaded.
  3150. */
  3151. GLTFLoaderState[GLTFLoaderState["COMPLETE"] = 2] = "COMPLETE";
  3152. })(GLTFLoaderState = exports.GLTFLoaderState || (exports.GLTFLoaderState = {}));
  3153. /**
  3154. * File loader for loading glTF files into a scene.
  3155. */
  3156. var GLTFFileLoader = /** @class */ (function () {
  3157. function GLTFFileLoader() {
  3158. // --------------
  3159. // Common options
  3160. // --------------
  3161. /**
  3162. * Raised when the asset has been parsed
  3163. */
  3164. this.onParsedObservable = new babylonjs_1.Observable();
  3165. // ----------
  3166. // V2 options
  3167. // ----------
  3168. /**
  3169. * The coordinate system mode. Defaults to AUTO.
  3170. */
  3171. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  3172. /**
  3173. * The animation start mode. Defaults to FIRST.
  3174. */
  3175. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  3176. /**
  3177. * Defines if the loader should compile materials before raising the success callback. Defaults to false.
  3178. */
  3179. this.compileMaterials = false;
  3180. /**
  3181. * Defines if the loader should also compile materials with clip planes. Defaults to false.
  3182. */
  3183. this.useClipPlane = false;
  3184. /**
  3185. * Defines if the loader should compile shadow generators before raising the success callback. Defaults to false.
  3186. */
  3187. this.compileShadowGenerators = false;
  3188. /**
  3189. * Defines if the Alpha blended materials are only applied as coverage.
  3190. * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials.
  3191. * If true, no extra effects are applied to transparent pixels.
  3192. */
  3193. this.transparencyAsCoverage = false;
  3194. /**
  3195. * Function called before loading a url referenced by the asset.
  3196. */
  3197. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  3198. /**
  3199. * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  3200. */
  3201. this.onMeshLoadedObservable = new babylonjs_1.Observable();
  3202. /**
  3203. * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.
  3204. */
  3205. this.onTextureLoadedObservable = new babylonjs_1.Observable();
  3206. /**
  3207. * Observable raised when the loader creates a material after parsing the glTF properties of the material.
  3208. */
  3209. this.onMaterialLoadedObservable = new babylonjs_1.Observable();
  3210. /**
  3211. * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.
  3212. */
  3213. this.onCameraLoadedObservable = new babylonjs_1.Observable();
  3214. /**
  3215. * Observable raised when the asset is completely loaded, immediately before the loader is disposed.
  3216. * For assets with LODs, raised when all of the LODs are complete.
  3217. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  3218. */
  3219. this.onCompleteObservable = new babylonjs_1.Observable();
  3220. /**
  3221. * Observable raised when an error occurs.
  3222. */
  3223. this.onErrorObservable = new babylonjs_1.Observable();
  3224. /**
  3225. * Observable raised after the loader is disposed.
  3226. */
  3227. this.onDisposeObservable = new babylonjs_1.Observable();
  3228. /**
  3229. * Observable raised after a loader extension is created.
  3230. * Set additional options for a loader extension in this event.
  3231. */
  3232. this.onExtensionLoadedObservable = new babylonjs_1.Observable();
  3233. /**
  3234. * Defines if the loader should validate the asset.
  3235. */
  3236. this.validate = false;
  3237. /**
  3238. * Observable raised after validation when validate is set to true. The event data is the result of the validation.
  3239. */
  3240. this.onValidatedObservable = new babylonjs_1.Observable();
  3241. this._loader = null;
  3242. /**
  3243. * Name of the loader ("gltf")
  3244. */
  3245. this.name = "gltf";
  3246. /**
  3247. * Supported file extensions of the loader (.gltf, .glb)
  3248. */
  3249. this.extensions = {
  3250. ".gltf": { isBinary: false },
  3251. ".glb": { isBinary: true }
  3252. };
  3253. this._logIndentLevel = 0;
  3254. this._loggingEnabled = false;
  3255. /** @hidden */
  3256. this._log = this._logDisabled;
  3257. this._capturePerformanceCounters = false;
  3258. /** @hidden */
  3259. this._startPerformanceCounter = this._startPerformanceCounterDisabled;
  3260. /** @hidden */
  3261. this._endPerformanceCounter = this._endPerformanceCounterDisabled;
  3262. }
  3263. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  3264. /**
  3265. * Raised when the asset has been parsed
  3266. */
  3267. set: function (callback) {
  3268. if (this._onParsedObserver) {
  3269. this.onParsedObservable.remove(this._onParsedObserver);
  3270. }
  3271. this._onParsedObserver = this.onParsedObservable.add(callback);
  3272. },
  3273. enumerable: true,
  3274. configurable: true
  3275. });
  3276. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  3277. /**
  3278. * Callback raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  3279. */
  3280. set: function (callback) {
  3281. if (this._onMeshLoadedObserver) {
  3282. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  3283. }
  3284. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  3285. },
  3286. enumerable: true,
  3287. configurable: true
  3288. });
  3289. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  3290. /**
  3291. * Callback raised when the loader creates a texture after parsing the glTF properties of the texture.
  3292. */
  3293. set: function (callback) {
  3294. if (this._onTextureLoadedObserver) {
  3295. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  3296. }
  3297. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  3298. },
  3299. enumerable: true,
  3300. configurable: true
  3301. });
  3302. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  3303. /**
  3304. * Callback raised when the loader creates a material after parsing the glTF properties of the material.
  3305. */
  3306. set: function (callback) {
  3307. if (this._onMaterialLoadedObserver) {
  3308. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  3309. }
  3310. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  3311. },
  3312. enumerable: true,
  3313. configurable: true
  3314. });
  3315. Object.defineProperty(GLTFFileLoader.prototype, "onCameraLoaded", {
  3316. /**
  3317. * Callback raised when the loader creates a camera after parsing the glTF properties of the camera.
  3318. */
  3319. set: function (callback) {
  3320. if (this._onCameraLoadedObserver) {
  3321. this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver);
  3322. }
  3323. this._onCameraLoadedObserver = this.onCameraLoadedObservable.add(callback);
  3324. },
  3325. enumerable: true,
  3326. configurable: true
  3327. });
  3328. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  3329. /**
  3330. * Callback raised when the asset is completely loaded, immediately before the loader is disposed.
  3331. * For assets with LODs, raised when all of the LODs are complete.
  3332. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  3333. */
  3334. set: function (callback) {
  3335. if (this._onCompleteObserver) {
  3336. this.onCompleteObservable.remove(this._onCompleteObserver);
  3337. }
  3338. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  3339. },
  3340. enumerable: true,
  3341. configurable: true
  3342. });
  3343. Object.defineProperty(GLTFFileLoader.prototype, "onError", {
  3344. /**
  3345. * Callback raised when an error occurs.
  3346. */
  3347. set: function (callback) {
  3348. if (this._onErrorObserver) {
  3349. this.onErrorObservable.remove(this._onErrorObserver);
  3350. }
  3351. this._onErrorObserver = this.onErrorObservable.add(callback);
  3352. },
  3353. enumerable: true,
  3354. configurable: true
  3355. });
  3356. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  3357. /**
  3358. * Callback raised after the loader is disposed.
  3359. */
  3360. set: function (callback) {
  3361. if (this._onDisposeObserver) {
  3362. this.onDisposeObservable.remove(this._onDisposeObserver);
  3363. }
  3364. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  3365. },
  3366. enumerable: true,
  3367. configurable: true
  3368. });
  3369. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  3370. /**
  3371. * Callback raised after a loader extension is created.
  3372. */
  3373. set: function (callback) {
  3374. if (this._onExtensionLoadedObserver) {
  3375. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  3376. }
  3377. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  3378. },
  3379. enumerable: true,
  3380. configurable: true
  3381. });
  3382. Object.defineProperty(GLTFFileLoader.prototype, "loggingEnabled", {
  3383. /**
  3384. * Defines if the loader logging is enabled.
  3385. */
  3386. get: function () {
  3387. return this._loggingEnabled;
  3388. },
  3389. set: function (value) {
  3390. if (this._loggingEnabled === value) {
  3391. return;
  3392. }
  3393. this._loggingEnabled = value;
  3394. if (this._loggingEnabled) {
  3395. this._log = this._logEnabled;
  3396. }
  3397. else {
  3398. this._log = this._logDisabled;
  3399. }
  3400. },
  3401. enumerable: true,
  3402. configurable: true
  3403. });
  3404. Object.defineProperty(GLTFFileLoader.prototype, "capturePerformanceCounters", {
  3405. /**
  3406. * Defines if the loader should capture performance counters.
  3407. */
  3408. get: function () {
  3409. return this._capturePerformanceCounters;
  3410. },
  3411. set: function (value) {
  3412. if (this._capturePerformanceCounters === value) {
  3413. return;
  3414. }
  3415. this._capturePerformanceCounters = value;
  3416. if (this._capturePerformanceCounters) {
  3417. this._startPerformanceCounter = this._startPerformanceCounterEnabled;
  3418. this._endPerformanceCounter = this._endPerformanceCounterEnabled;
  3419. }
  3420. else {
  3421. this._startPerformanceCounter = this._startPerformanceCounterDisabled;
  3422. this._endPerformanceCounter = this._endPerformanceCounterDisabled;
  3423. }
  3424. },
  3425. enumerable: true,
  3426. configurable: true
  3427. });
  3428. Object.defineProperty(GLTFFileLoader.prototype, "onValidated", {
  3429. /**
  3430. * Callback raised after a loader extension is created.
  3431. */
  3432. set: function (callback) {
  3433. if (this._onValidatedObserver) {
  3434. this.onValidatedObservable.remove(this._onValidatedObserver);
  3435. }
  3436. this._onValidatedObserver = this.onValidatedObservable.add(callback);
  3437. },
  3438. enumerable: true,
  3439. configurable: true
  3440. });
  3441. /**
  3442. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  3443. */
  3444. GLTFFileLoader.prototype.dispose = function () {
  3445. if (this._loader) {
  3446. this._loader.dispose();
  3447. this._loader = null;
  3448. }
  3449. this._clear();
  3450. this.onDisposeObservable.notifyObservers(undefined);
  3451. this.onDisposeObservable.clear();
  3452. };
  3453. /** @hidden */
  3454. GLTFFileLoader.prototype._clear = function () {
  3455. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  3456. this.onMeshLoadedObservable.clear();
  3457. this.onTextureLoadedObservable.clear();
  3458. this.onMaterialLoadedObservable.clear();
  3459. this.onCameraLoadedObservable.clear();
  3460. this.onCompleteObservable.clear();
  3461. this.onExtensionLoadedObservable.clear();
  3462. };
  3463. /**
  3464. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  3465. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  3466. * @param scene the scene the meshes should be added to
  3467. * @param data the glTF data to load
  3468. * @param rootUrl root url to load from
  3469. * @param onProgress event that fires when loading progress has occured
  3470. * @param fileName Defines the name of the file to load
  3471. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  3472. */
  3473. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress, fileName) {
  3474. var _this = this;
  3475. return this._parseAsync(scene, data, rootUrl, fileName).then(function (loaderData) {
  3476. _this._log("Loading " + (fileName || ""));
  3477. _this._loader = _this._getLoader(loaderData);
  3478. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress, fileName);
  3479. });
  3480. };
  3481. /**
  3482. * Imports all objects from the loaded glTF data and adds them to the scene
  3483. * @param scene the scene the objects should be added to
  3484. * @param data the glTF data to load
  3485. * @param rootUrl root url to load from
  3486. * @param onProgress event that fires when loading progress has occured
  3487. * @param fileName Defines the name of the file to load
  3488. * @returns a promise which completes when objects have been loaded to the scene
  3489. */
  3490. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress, fileName) {
  3491. var _this = this;
  3492. return this._parseAsync(scene, data, rootUrl, fileName).then(function (loaderData) {
  3493. _this._log("Loading " + (fileName || ""));
  3494. _this._loader = _this._getLoader(loaderData);
  3495. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress, fileName);
  3496. });
  3497. };
  3498. /**
  3499. * Load into an asset container.
  3500. * @param scene The scene to load into
  3501. * @param data The data to import
  3502. * @param rootUrl The root url for scene and resources
  3503. * @param onProgress The callback when the load progresses
  3504. * @param fileName Defines the name of the file to load
  3505. * @returns The loaded asset container
  3506. */
  3507. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress, fileName) {
  3508. var _this = this;
  3509. return this._parseAsync(scene, data, rootUrl, fileName).then(function (loaderData) {
  3510. _this._log("Loading " + (fileName || ""));
  3511. _this._loader = _this._getLoader(loaderData);
  3512. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress, fileName).then(function (result) {
  3513. var container = new babylonjs_1.AssetContainer(scene);
  3514. Array.prototype.push.apply(container.meshes, result.meshes);
  3515. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  3516. Array.prototype.push.apply(container.skeletons, result.skeletons);
  3517. Array.prototype.push.apply(container.animationGroups, result.animationGroups);
  3518. container.removeAllFromScene();
  3519. return container;
  3520. });
  3521. });
  3522. };
  3523. /**
  3524. * If the data string can be loaded directly.
  3525. * @param data string contianing the file data
  3526. * @returns if the data can be loaded directly
  3527. */
  3528. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  3529. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  3530. };
  3531. /**
  3532. * Instantiates a glTF file loader plugin.
  3533. * @returns the created plugin
  3534. */
  3535. GLTFFileLoader.prototype.createPlugin = function () {
  3536. return new GLTFFileLoader();
  3537. };
  3538. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  3539. /**
  3540. * The loader state or null if the loader is not active.
  3541. */
  3542. get: function () {
  3543. return this._loader ? this._loader.state : null;
  3544. },
  3545. enumerable: true,
  3546. configurable: true
  3547. });
  3548. /**
  3549. * Returns a promise that resolves when the asset is completely loaded.
  3550. * @returns a promise that resolves when the asset is completely loaded.
  3551. */
  3552. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  3553. var _this = this;
  3554. return new Promise(function (resolve, reject) {
  3555. _this.onCompleteObservable.addOnce(function () {
  3556. resolve();
  3557. });
  3558. _this.onErrorObservable.addOnce(function (reason) {
  3559. reject(reason);
  3560. });
  3561. });
  3562. };
  3563. GLTFFileLoader.prototype._parseAsync = function (scene, data, rootUrl, fileName) {
  3564. var _this = this;
  3565. return Promise.resolve().then(function () {
  3566. var unpacked = (data instanceof ArrayBuffer) ? _this._unpackBinary(data) : { json: data, bin: null };
  3567. return _this._validateAsync(scene, unpacked.json, rootUrl, fileName).then(function () {
  3568. _this._startPerformanceCounter("Parse JSON");
  3569. _this._log("JSON length: " + unpacked.json.length);
  3570. var loaderData = {
  3571. json: JSON.parse(unpacked.json),
  3572. bin: unpacked.bin
  3573. };
  3574. _this._endPerformanceCounter("Parse JSON");
  3575. _this.onParsedObservable.notifyObservers(loaderData);
  3576. _this.onParsedObservable.clear();
  3577. return loaderData;
  3578. });
  3579. });
  3580. };
  3581. GLTFFileLoader.prototype._validateAsync = function (scene, json, rootUrl, fileName) {
  3582. var _this = this;
  3583. if (!this.validate || typeof GLTFValidator === "undefined") {
  3584. return Promise.resolve();
  3585. }
  3586. this._startPerformanceCounter("Validate JSON");
  3587. var options = {
  3588. externalResourceFunction: function (uri) {
  3589. return _this.preprocessUrlAsync(rootUrl + uri)
  3590. .then(function (url) { return scene._loadFileAsync(url, true, true); })
  3591. .then(function (data) { return new Uint8Array(data); });
  3592. }
  3593. };
  3594. if (fileName && fileName.substr(0, 5) !== "data:") {
  3595. options.uri = (rootUrl === "file:" ? fileName : "" + rootUrl + fileName);
  3596. }
  3597. return GLTFValidator.validateString(json, options).then(function (result) {
  3598. _this._endPerformanceCounter("Validate JSON");
  3599. _this.onValidatedObservable.notifyObservers(result);
  3600. _this.onValidatedObservable.clear();
  3601. }, function (reason) {
  3602. _this._endPerformanceCounter("Validate JSON");
  3603. babylonjs_1.Tools.Warn("Failed to validate: " + reason);
  3604. _this.onValidatedObservable.clear();
  3605. });
  3606. };
  3607. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  3608. var asset = loaderData.json.asset || {};
  3609. this._log("Asset version: " + asset.version);
  3610. asset.minVersion && this._log("Asset minimum version: " + asset.minVersion);
  3611. asset.generator && this._log("Asset generator: " + asset.generator);
  3612. var version = GLTFFileLoader._parseVersion(asset.version);
  3613. if (!version) {
  3614. throw new Error("Invalid version: " + asset.version);
  3615. }
  3616. if (asset.minVersion !== undefined) {
  3617. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  3618. if (!minVersion) {
  3619. throw new Error("Invalid minimum version: " + asset.minVersion);
  3620. }
  3621. if (GLTFFileLoader._compareVersion(minVersion, { major: 2, minor: 0 }) > 0) {
  3622. throw new Error("Incompatible minimum version: " + asset.minVersion);
  3623. }
  3624. }
  3625. var createLoaders = {
  3626. 1: GLTFFileLoader._CreateGLTFLoaderV1,
  3627. 2: GLTFFileLoader._CreateGLTFLoaderV2
  3628. };
  3629. var createLoader = createLoaders[version.major];
  3630. if (!createLoader) {
  3631. throw new Error("Unsupported version: " + asset.version);
  3632. }
  3633. return createLoader(this);
  3634. };
  3635. GLTFFileLoader.prototype._unpackBinary = function (data) {
  3636. this._startPerformanceCounter("Unpack binary");
  3637. this._log("Binary length: " + data.byteLength);
  3638. var Binary = {
  3639. Magic: 0x46546C67
  3640. };
  3641. var binaryReader = new BinaryReader(data);
  3642. var magic = binaryReader.readUint32();
  3643. if (magic !== Binary.Magic) {
  3644. throw new Error("Unexpected magic: " + magic);
  3645. }
  3646. var version = binaryReader.readUint32();
  3647. if (this.loggingEnabled) {
  3648. this._log("Binary version: " + version);
  3649. }
  3650. var unpacked;
  3651. switch (version) {
  3652. case 1: {
  3653. unpacked = this._unpackBinaryV1(binaryReader);
  3654. break;
  3655. }
  3656. case 2: {
  3657. unpacked = this._unpackBinaryV2(binaryReader);
  3658. break;
  3659. }
  3660. default: {
  3661. throw new Error("Unsupported version: " + version);
  3662. }
  3663. }
  3664. this._endPerformanceCounter("Unpack binary");
  3665. return unpacked;
  3666. };
  3667. GLTFFileLoader.prototype._unpackBinaryV1 = function (binaryReader) {
  3668. var ContentFormat = {
  3669. JSON: 0
  3670. };
  3671. var length = binaryReader.readUint32();
  3672. if (length != binaryReader.getLength()) {
  3673. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  3674. }
  3675. var contentLength = binaryReader.readUint32();
  3676. var contentFormat = binaryReader.readUint32();
  3677. var content;
  3678. switch (contentFormat) {
  3679. case ContentFormat.JSON: {
  3680. content = GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength));
  3681. break;
  3682. }
  3683. default: {
  3684. throw new Error("Unexpected content format: " + contentFormat);
  3685. }
  3686. }
  3687. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  3688. var body = binaryReader.readUint8Array(bytesRemaining);
  3689. return {
  3690. json: content,
  3691. bin: body
  3692. };
  3693. };
  3694. GLTFFileLoader.prototype._unpackBinaryV2 = function (binaryReader) {
  3695. var ChunkFormat = {
  3696. JSON: 0x4E4F534A,
  3697. BIN: 0x004E4942
  3698. };
  3699. var length = binaryReader.readUint32();
  3700. if (length !== binaryReader.getLength()) {
  3701. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  3702. }
  3703. // JSON chunk
  3704. var chunkLength = binaryReader.readUint32();
  3705. var chunkFormat = binaryReader.readUint32();
  3706. if (chunkFormat !== ChunkFormat.JSON) {
  3707. throw new Error("First chunk format is not JSON");
  3708. }
  3709. var json = GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength));
  3710. // Look for BIN chunk
  3711. var bin = null;
  3712. while (binaryReader.getPosition() < binaryReader.getLength()) {
  3713. var chunkLength_1 = binaryReader.readUint32();
  3714. var chunkFormat_1 = binaryReader.readUint32();
  3715. switch (chunkFormat_1) {
  3716. case ChunkFormat.JSON: {
  3717. throw new Error("Unexpected JSON chunk");
  3718. }
  3719. case ChunkFormat.BIN: {
  3720. bin = binaryReader.readUint8Array(chunkLength_1);
  3721. break;
  3722. }
  3723. default: {
  3724. // ignore unrecognized chunkFormat
  3725. binaryReader.skipBytes(chunkLength_1);
  3726. break;
  3727. }
  3728. }
  3729. }
  3730. return {
  3731. json: json,
  3732. bin: bin
  3733. };
  3734. };
  3735. GLTFFileLoader._parseVersion = function (version) {
  3736. if (version === "1.0" || version === "1.0.1") {
  3737. return {
  3738. major: 1,
  3739. minor: 0
  3740. };
  3741. }
  3742. var match = (version + "").match(/^(\d+)\.(\d+)/);
  3743. if (!match) {
  3744. return null;
  3745. }
  3746. return {
  3747. major: parseInt(match[1]),
  3748. minor: parseInt(match[2])
  3749. };
  3750. };
  3751. GLTFFileLoader._compareVersion = function (a, b) {
  3752. if (a.major > b.major) {
  3753. return 1;
  3754. }
  3755. if (a.major < b.major) {
  3756. return -1;
  3757. }
  3758. if (a.minor > b.minor) {
  3759. return 1;
  3760. }
  3761. if (a.minor < b.minor) {
  3762. return -1;
  3763. }
  3764. return 0;
  3765. };
  3766. GLTFFileLoader._decodeBufferToText = function (buffer) {
  3767. var result = "";
  3768. var length = buffer.byteLength;
  3769. for (var i = 0; i < length; i++) {
  3770. result += String.fromCharCode(buffer[i]);
  3771. }
  3772. return result;
  3773. };
  3774. /** @hidden */
  3775. GLTFFileLoader.prototype._logOpen = function (message) {
  3776. this._log(message);
  3777. this._logIndentLevel++;
  3778. };
  3779. /** @hidden */
  3780. GLTFFileLoader.prototype._logClose = function () {
  3781. --this._logIndentLevel;
  3782. };
  3783. GLTFFileLoader.prototype._logEnabled = function (message) {
  3784. var spaces = GLTFFileLoader._logSpaces.substr(0, this._logIndentLevel * 2);
  3785. babylonjs_1.Tools.Log("" + spaces + message);
  3786. };
  3787. GLTFFileLoader.prototype._logDisabled = function (message) {
  3788. };
  3789. GLTFFileLoader.prototype._startPerformanceCounterEnabled = function (counterName) {
  3790. babylonjs_1.Tools.StartPerformanceCounter(counterName);
  3791. };
  3792. GLTFFileLoader.prototype._startPerformanceCounterDisabled = function (counterName) {
  3793. };
  3794. GLTFFileLoader.prototype._endPerformanceCounterEnabled = function (counterName) {
  3795. babylonjs_1.Tools.EndPerformanceCounter(counterName);
  3796. };
  3797. GLTFFileLoader.prototype._endPerformanceCounterDisabled = function (counterName) {
  3798. };
  3799. // ----------
  3800. // V1 options
  3801. // ----------
  3802. /**
  3803. * Set this property to false to disable incremental loading which delays the loader from calling the success callback until after loading the meshes and shaders.
  3804. * Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled.
  3805. * Defaults to true.
  3806. * @hidden
  3807. */
  3808. GLTFFileLoader.IncrementalLoading = true;
  3809. /**
  3810. * Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters.
  3811. * Defaults to false. See https://en.wikipedia.org/wiki/Homogeneous_coordinates.
  3812. * @hidden
  3813. */
  3814. GLTFFileLoader.HomogeneousCoordinates = false;
  3815. GLTFFileLoader._logSpaces = " ";
  3816. return GLTFFileLoader;
  3817. }());
  3818. exports.GLTFFileLoader = GLTFFileLoader;
  3819. var BinaryReader = /** @class */ (function () {
  3820. function BinaryReader(arrayBuffer) {
  3821. this._arrayBuffer = arrayBuffer;
  3822. this._dataView = new DataView(arrayBuffer);
  3823. this._byteOffset = 0;
  3824. }
  3825. BinaryReader.prototype.getPosition = function () {
  3826. return this._byteOffset;
  3827. };
  3828. BinaryReader.prototype.getLength = function () {
  3829. return this._arrayBuffer.byteLength;
  3830. };
  3831. BinaryReader.prototype.readUint32 = function () {
  3832. var value = this._dataView.getUint32(this._byteOffset, true);
  3833. this._byteOffset += 4;
  3834. return value;
  3835. };
  3836. BinaryReader.prototype.readUint8Array = function (length) {
  3837. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  3838. this._byteOffset += length;
  3839. return value;
  3840. };
  3841. BinaryReader.prototype.skipBytes = function (length) {
  3842. this._byteOffset += length;
  3843. };
  3844. return BinaryReader;
  3845. }());
  3846. if (babylonjs_1.SceneLoader) {
  3847. babylonjs_1.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  3848. }
  3849. /***/ }),
  3850. /***/ "babylonjs":
  3851. /*!****************************************************************************************************!*\
  3852. !*** external {"root":"BABYLON","commonjs":"babylonjs","commonjs2":"babylonjs","amd":"babylonjs"} ***!
  3853. \****************************************************************************************************/
  3854. /*! no static exports found */
  3855. /***/ (function(module, exports) {
  3856. module.exports = __WEBPACK_EXTERNAL_MODULE_babylonjs__;
  3857. /***/ })
  3858. /******/ });
  3859. });
  3860. //# sourceMappingURL=babylon.glTF2FileLoader.js.map