babylon.glTF1FileLoader.js 137 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225
  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-glTF1FileLoader.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-glTF1FileLoader.ts":
  122. /*!******************************************!*\
  123. !*** ./legacy/legacy-glTF1FileLoader.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 GLTF1 = __webpack_require__(/*! ../src/glTF/1.0 */ "./src/glTF/1.0/index.ts");
  135. exports.GLTF1 = GLTF1;
  136. /**
  137. * This is the entry point for the UMD module.
  138. * The entry point for a future ESM package should be index.ts
  139. */
  140. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : undefined);
  141. if (typeof globalObject !== "undefined") {
  142. globalObject.BABYLON = globalObject.BABYLON || {};
  143. for (var key in FileLoader) {
  144. globalObject.BABYLON[key] = FileLoader[key];
  145. }
  146. globalObject.BABYLON.GLTF1 = globalObject.BABYLON.GLTF1 || {};
  147. for (var key in GLTF1) {
  148. globalObject.BABYLON.GLTF1[key] = GLTF1[key];
  149. }
  150. }
  151. __export(__webpack_require__(/*! ../src/glTF/glTFFileLoader */ "./src/glTF/glTFFileLoader.ts"));
  152. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../node_modules/webpack/buildin/global.js */ "../node_modules/webpack/buildin/global.js")))
  153. /***/ }),
  154. /***/ "./src/glTF/1.0/glTFBinaryExtension.ts":
  155. /*!*********************************************!*\
  156. !*** ./src/glTF/1.0/glTFBinaryExtension.ts ***!
  157. \*********************************************/
  158. /*! no static exports found */
  159. /***/ (function(module, exports, __webpack_require__) {
  160. "use strict";
  161. var __extends = (this && this.__extends) || (function () {
  162. var extendStatics = function (d, b) {
  163. extendStatics = Object.setPrototypeOf ||
  164. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  165. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  166. return extendStatics(d, b);
  167. }
  168. return function (d, b) {
  169. extendStatics(d, b);
  170. function __() { this.constructor = d; }
  171. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  172. };
  173. })();
  174. Object.defineProperty(exports, "__esModule", { value: true });
  175. var glTFLoaderExtension_1 = __webpack_require__(/*! ./glTFLoaderExtension */ "./src/glTF/1.0/glTFLoaderExtension.ts");
  176. var glTFLoaderUtils_1 = __webpack_require__(/*! ./glTFLoaderUtils */ "./src/glTF/1.0/glTFLoaderUtils.ts");
  177. var glTFLoaderInterfaces_1 = __webpack_require__(/*! ./glTFLoaderInterfaces */ "./src/glTF/1.0/glTFLoaderInterfaces.ts");
  178. var glTFLoader_1 = __webpack_require__(/*! ./glTFLoader */ "./src/glTF/1.0/glTFLoader.ts");
  179. var BinaryExtensionBufferName = "binary_glTF";
  180. /** @hidden */
  181. var GLTFBinaryExtension = /** @class */ (function (_super) {
  182. __extends(GLTFBinaryExtension, _super);
  183. function GLTFBinaryExtension() {
  184. return _super.call(this, "KHR_binary_glTF") || this;
  185. }
  186. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  187. var extensionsUsed = data.json.extensionsUsed;
  188. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  189. return false;
  190. }
  191. this._bin = data.bin;
  192. onSuccess(glTFLoader_1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  193. return true;
  194. };
  195. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  196. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  197. return false;
  198. }
  199. if (id !== BinaryExtensionBufferName) {
  200. return false;
  201. }
  202. onSuccess(this._bin);
  203. return true;
  204. };
  205. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  206. var texture = gltfRuntime.textures[id];
  207. var source = gltfRuntime.images[texture.source];
  208. if (!source.extensions || !(this.name in source.extensions)) {
  209. return false;
  210. }
  211. var sourceExt = source.extensions[this.name];
  212. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  213. var buffer = glTFLoaderUtils_1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, glTFLoaderInterfaces_1.EComponentType.UNSIGNED_BYTE);
  214. onSuccess(buffer);
  215. return true;
  216. };
  217. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  218. var shader = gltfRuntime.shaders[id];
  219. if (!shader.extensions || !(this.name in shader.extensions)) {
  220. return false;
  221. }
  222. var binaryExtensionShader = shader.extensions[this.name];
  223. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  224. var shaderBytes = glTFLoaderUtils_1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, glTFLoaderInterfaces_1.EComponentType.UNSIGNED_BYTE);
  225. setTimeout(function () {
  226. var shaderString = glTFLoaderUtils_1.GLTFUtils.DecodeBufferToText(shaderBytes);
  227. onSuccess(shaderString);
  228. });
  229. return true;
  230. };
  231. return GLTFBinaryExtension;
  232. }(glTFLoaderExtension_1.GLTFLoaderExtension));
  233. exports.GLTFBinaryExtension = GLTFBinaryExtension;
  234. glTFLoader_1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  235. /***/ }),
  236. /***/ "./src/glTF/1.0/glTFLoader.ts":
  237. /*!************************************!*\
  238. !*** ./src/glTF/1.0/glTFLoader.ts ***!
  239. \************************************/
  240. /*! no static exports found */
  241. /***/ (function(module, exports, __webpack_require__) {
  242. "use strict";
  243. Object.defineProperty(exports, "__esModule", { value: true });
  244. var glTFLoaderInterfaces_1 = __webpack_require__(/*! ./glTFLoaderInterfaces */ "./src/glTF/1.0/glTFLoaderInterfaces.ts");
  245. var glTFLoaderUtils_1 = __webpack_require__(/*! ./glTFLoaderUtils */ "./src/glTF/1.0/glTFLoaderUtils.ts");
  246. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  247. var glTFFileLoader_1 = __webpack_require__(/*! ../glTFFileLoader */ "./src/glTF/glTFFileLoader.ts");
  248. var glTFLoaderExtension_1 = __webpack_require__(/*! ./glTFLoaderExtension */ "./src/glTF/1.0/glTFLoaderExtension.ts");
  249. /**
  250. * Tokenizer. Used for shaders compatibility
  251. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  252. */
  253. var ETokenType;
  254. (function (ETokenType) {
  255. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  256. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  257. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  258. })(ETokenType || (ETokenType = {}));
  259. var Tokenizer = /** @class */ (function () {
  260. function Tokenizer(toParse) {
  261. this._pos = 0;
  262. this.currentToken = ETokenType.UNKNOWN;
  263. this.currentIdentifier = "";
  264. this.currentString = "";
  265. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  266. this._toParse = toParse;
  267. this._maxPos = toParse.length;
  268. }
  269. Tokenizer.prototype.getNextToken = function () {
  270. if (this.isEnd()) {
  271. return ETokenType.END_OF_INPUT;
  272. }
  273. this.currentString = this.read();
  274. this.currentToken = ETokenType.UNKNOWN;
  275. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  276. this.currentToken = ETokenType.IDENTIFIER;
  277. this.currentIdentifier = this.currentString;
  278. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  279. this.currentIdentifier += this.currentString;
  280. this.forward();
  281. }
  282. }
  283. return this.currentToken;
  284. };
  285. Tokenizer.prototype.peek = function () {
  286. return this._toParse[this._pos];
  287. };
  288. Tokenizer.prototype.read = function () {
  289. return this._toParse[this._pos++];
  290. };
  291. Tokenizer.prototype.forward = function () {
  292. this._pos++;
  293. };
  294. Tokenizer.prototype.isEnd = function () {
  295. return this._pos >= this._maxPos;
  296. };
  297. return Tokenizer;
  298. }());
  299. /**
  300. * Values
  301. */
  302. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  303. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  304. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  305. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  306. /**
  307. * Parse
  308. */
  309. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  310. for (var buf in parsedBuffers) {
  311. var parsedBuffer = parsedBuffers[buf];
  312. gltfRuntime.buffers[buf] = parsedBuffer;
  313. gltfRuntime.buffersCount++;
  314. }
  315. };
  316. var parseShaders = function (parsedShaders, gltfRuntime) {
  317. for (var sha in parsedShaders) {
  318. var parsedShader = parsedShaders[sha];
  319. gltfRuntime.shaders[sha] = parsedShader;
  320. gltfRuntime.shaderscount++;
  321. }
  322. };
  323. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  324. for (var object in parsedObjects) {
  325. var parsedObject = parsedObjects[object];
  326. gltfRuntime[runtimeProperty][object] = parsedObject;
  327. }
  328. };
  329. /**
  330. * Utils
  331. */
  332. var normalizeUVs = function (buffer) {
  333. if (!buffer) {
  334. return;
  335. }
  336. for (var i = 0; i < buffer.length / 2; i++) {
  337. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  338. }
  339. };
  340. var getAttribute = function (attributeParameter) {
  341. if (attributeParameter.semantic === "NORMAL") {
  342. return "normal";
  343. }
  344. else if (attributeParameter.semantic === "POSITION") {
  345. return "position";
  346. }
  347. else if (attributeParameter.semantic === "JOINT") {
  348. return "matricesIndices";
  349. }
  350. else if (attributeParameter.semantic === "WEIGHT") {
  351. return "matricesWeights";
  352. }
  353. else if (attributeParameter.semantic === "COLOR") {
  354. return "color";
  355. }
  356. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  357. var channel = Number(attributeParameter.semantic.split("_")[1]);
  358. return "uv" + (channel === 0 ? "" : channel + 1);
  359. }
  360. return null;
  361. };
  362. /**
  363. * Loads and creates animations
  364. */
  365. var loadAnimations = function (gltfRuntime) {
  366. for (var anim in gltfRuntime.animations) {
  367. var animation = gltfRuntime.animations[anim];
  368. if (!animation.channels || !animation.samplers) {
  369. continue;
  370. }
  371. var lastAnimation = null;
  372. for (var i = 0; i < animation.channels.length; i++) {
  373. // Get parameters and load buffers
  374. var channel = animation.channels[i];
  375. var sampler = animation.samplers[channel.sampler];
  376. if (!sampler) {
  377. continue;
  378. }
  379. var inputData = null;
  380. var outputData = null;
  381. if (animation.parameters) {
  382. inputData = animation.parameters[sampler.input];
  383. outputData = animation.parameters[sampler.output];
  384. }
  385. else {
  386. inputData = sampler.input;
  387. outputData = sampler.output;
  388. }
  389. var bufferInput = glTFLoaderUtils_1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  390. var bufferOutput = glTFLoaderUtils_1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  391. var targetID = channel.target.id;
  392. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  393. if (targetNode === null) {
  394. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  395. }
  396. if (targetNode === null) {
  397. babylonjs_1.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  398. continue;
  399. }
  400. var isBone = targetNode instanceof babylonjs_1.Bone;
  401. // Get target path (position, rotation or scaling)
  402. var targetPath = channel.target.path;
  403. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  404. if (targetPathIndex !== -1) {
  405. targetPath = babylonAnimationPaths[targetPathIndex];
  406. }
  407. // Determine animation type
  408. var animationType = babylonjs_1.Animation.ANIMATIONTYPE_MATRIX;
  409. if (!isBone) {
  410. if (targetPath === "rotationQuaternion") {
  411. animationType = babylonjs_1.Animation.ANIMATIONTYPE_QUATERNION;
  412. targetNode.rotationQuaternion = new babylonjs_1.Quaternion();
  413. }
  414. else {
  415. animationType = babylonjs_1.Animation.ANIMATIONTYPE_VECTOR3;
  416. }
  417. }
  418. // Create animation and key frames
  419. var babylonAnimation = null;
  420. var keys = [];
  421. var arrayOffset = 0;
  422. var modifyKey = false;
  423. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  424. babylonAnimation = lastAnimation;
  425. modifyKey = true;
  426. }
  427. if (!modifyKey) {
  428. babylonAnimation = new babylonjs_1.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, babylonjs_1.Animation.ANIMATIONLOOPMODE_CYCLE);
  429. }
  430. // For each frame
  431. for (var j = 0; j < bufferInput.length; j++) {
  432. var value = null;
  433. if (targetPath === "rotationQuaternion") { // VEC4
  434. value = babylonjs_1.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  435. arrayOffset += 4;
  436. }
  437. else { // Position and scaling are VEC3
  438. value = babylonjs_1.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  439. arrayOffset += 3;
  440. }
  441. if (isBone) {
  442. var bone = targetNode;
  443. var translation = babylonjs_1.Vector3.Zero();
  444. var rotationQuaternion = new babylonjs_1.Quaternion();
  445. var scaling = babylonjs_1.Vector3.Zero();
  446. // Warning on decompose
  447. var mat = bone.getBaseMatrix();
  448. if (modifyKey && lastAnimation) {
  449. mat = lastAnimation.getKeys()[j].value;
  450. }
  451. mat.decompose(scaling, rotationQuaternion, translation);
  452. if (targetPath === "position") {
  453. translation = value;
  454. }
  455. else if (targetPath === "rotationQuaternion") {
  456. rotationQuaternion = value;
  457. }
  458. else {
  459. scaling = value;
  460. }
  461. value = babylonjs_1.Matrix.Compose(scaling, rotationQuaternion, translation);
  462. }
  463. if (!modifyKey) {
  464. keys.push({
  465. frame: bufferInput[j],
  466. value: value
  467. });
  468. }
  469. else if (lastAnimation) {
  470. lastAnimation.getKeys()[j].value = value;
  471. }
  472. }
  473. // Finish
  474. if (!modifyKey && babylonAnimation) {
  475. babylonAnimation.setKeys(keys);
  476. targetNode.animations.push(babylonAnimation);
  477. }
  478. lastAnimation = babylonAnimation;
  479. gltfRuntime.scene.stopAnimation(targetNode);
  480. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  481. }
  482. }
  483. };
  484. /**
  485. * Returns the bones transformation matrix
  486. */
  487. var configureBoneTransformation = function (node) {
  488. var mat = null;
  489. if (node.translation || node.rotation || node.scale) {
  490. var scale = babylonjs_1.Vector3.FromArray(node.scale || [1, 1, 1]);
  491. var rotation = babylonjs_1.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  492. var position = babylonjs_1.Vector3.FromArray(node.translation || [0, 0, 0]);
  493. mat = babylonjs_1.Matrix.Compose(scale, rotation, position);
  494. }
  495. else {
  496. mat = babylonjs_1.Matrix.FromArray(node.matrix);
  497. }
  498. return mat;
  499. };
  500. /**
  501. * Returns the parent bone
  502. */
  503. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  504. // Try to find
  505. for (var i = 0; i < newSkeleton.bones.length; i++) {
  506. if (newSkeleton.bones[i].name === jointName) {
  507. return newSkeleton.bones[i];
  508. }
  509. }
  510. // Not found, search in gltf nodes
  511. var nodes = gltfRuntime.nodes;
  512. for (var nde in nodes) {
  513. var node = nodes[nde];
  514. if (!node.jointName) {
  515. continue;
  516. }
  517. var children = node.children;
  518. for (var i = 0; i < children.length; i++) {
  519. var child = gltfRuntime.nodes[children[i]];
  520. if (!child.jointName) {
  521. continue;
  522. }
  523. if (child.jointName === jointName) {
  524. var mat = configureBoneTransformation(node);
  525. var bone = new babylonjs_1.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  526. bone.id = nde;
  527. return bone;
  528. }
  529. }
  530. }
  531. return null;
  532. };
  533. /**
  534. * Returns the appropriate root node
  535. */
  536. var getNodeToRoot = function (nodesToRoot, id) {
  537. for (var i = 0; i < nodesToRoot.length; i++) {
  538. var nodeToRoot = nodesToRoot[i];
  539. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  540. var child = nodeToRoot.node.children[j];
  541. if (child === id) {
  542. return nodeToRoot.bone;
  543. }
  544. }
  545. }
  546. return null;
  547. };
  548. /**
  549. * Returns the node with the joint name
  550. */
  551. var getJointNode = function (gltfRuntime, jointName) {
  552. var nodes = gltfRuntime.nodes;
  553. var node = nodes[jointName];
  554. if (node) {
  555. return {
  556. node: node,
  557. id: jointName
  558. };
  559. }
  560. for (var nde in nodes) {
  561. node = nodes[nde];
  562. if (node.jointName === jointName) {
  563. return {
  564. node: node,
  565. id: nde
  566. };
  567. }
  568. }
  569. return null;
  570. };
  571. /**
  572. * Checks if a nodes is in joints
  573. */
  574. var nodeIsInJoints = function (skins, id) {
  575. for (var i = 0; i < skins.jointNames.length; i++) {
  576. if (skins.jointNames[i] === id) {
  577. return true;
  578. }
  579. }
  580. return false;
  581. };
  582. /**
  583. * Fills the nodes to root for bones and builds hierarchy
  584. */
  585. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  586. // Creates nodes for root
  587. for (var nde in gltfRuntime.nodes) {
  588. var node = gltfRuntime.nodes[nde];
  589. var id = nde;
  590. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  591. continue;
  592. }
  593. // Create node to root bone
  594. var mat = configureBoneTransformation(node);
  595. var bone = new babylonjs_1.Bone(node.name || "", newSkeleton, null, mat);
  596. bone.id = id;
  597. nodesToRoot.push({ bone: bone, node: node, id: id });
  598. }
  599. // Parenting
  600. for (var i = 0; i < nodesToRoot.length; i++) {
  601. var nodeToRoot = nodesToRoot[i];
  602. var children = nodeToRoot.node.children;
  603. for (var j = 0; j < children.length; j++) {
  604. var child = null;
  605. for (var k = 0; k < nodesToRoot.length; k++) {
  606. if (nodesToRoot[k].id === children[j]) {
  607. child = nodesToRoot[k];
  608. break;
  609. }
  610. }
  611. if (child) {
  612. child.bone._parent = nodeToRoot.bone;
  613. nodeToRoot.bone.children.push(child.bone);
  614. }
  615. }
  616. }
  617. };
  618. /**
  619. * Imports a skeleton
  620. */
  621. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  622. if (!newSkeleton) {
  623. newSkeleton = new babylonjs_1.Skeleton(skins.name || "", "", gltfRuntime.scene);
  624. }
  625. if (!skins.babylonSkeleton) {
  626. return newSkeleton;
  627. }
  628. // Find the root bones
  629. var nodesToRoot = [];
  630. var nodesToRootToAdd = [];
  631. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  632. newSkeleton.bones = [];
  633. // Joints
  634. for (var i = 0; i < skins.jointNames.length; i++) {
  635. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  636. if (!jointNode) {
  637. continue;
  638. }
  639. var node = jointNode.node;
  640. if (!node) {
  641. babylonjs_1.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  642. continue;
  643. }
  644. var id = jointNode.id;
  645. // Optimize, if the bone already exists...
  646. var existingBone = gltfRuntime.scene.getBoneByID(id);
  647. if (existingBone) {
  648. newSkeleton.bones.push(existingBone);
  649. continue;
  650. }
  651. // Search for parent bone
  652. var foundBone = false;
  653. var parentBone = null;
  654. for (var j = 0; j < i; j++) {
  655. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  656. if (!jointNode_1) {
  657. continue;
  658. }
  659. var joint = jointNode_1.node;
  660. if (!joint) {
  661. babylonjs_1.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  662. continue;
  663. }
  664. var children = joint.children;
  665. if (!children) {
  666. continue;
  667. }
  668. foundBone = false;
  669. for (var k = 0; k < children.length; k++) {
  670. if (children[k] === id) {
  671. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  672. foundBone = true;
  673. break;
  674. }
  675. }
  676. if (foundBone) {
  677. break;
  678. }
  679. }
  680. // Create bone
  681. var mat = configureBoneTransformation(node);
  682. if (!parentBone && nodesToRoot.length > 0) {
  683. parentBone = getNodeToRoot(nodesToRoot, id);
  684. if (parentBone) {
  685. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  686. nodesToRootToAdd.push(parentBone);
  687. }
  688. }
  689. }
  690. var bone = new babylonjs_1.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  691. bone.id = id;
  692. }
  693. // Polish
  694. var bones = newSkeleton.bones;
  695. newSkeleton.bones = [];
  696. for (var i = 0; i < skins.jointNames.length; i++) {
  697. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  698. if (!jointNode) {
  699. continue;
  700. }
  701. for (var j = 0; j < bones.length; j++) {
  702. if (bones[j].id === jointNode.id) {
  703. newSkeleton.bones.push(bones[j]);
  704. break;
  705. }
  706. }
  707. }
  708. newSkeleton.prepare();
  709. // Finish
  710. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  711. newSkeleton.bones.push(nodesToRootToAdd[i]);
  712. }
  713. return newSkeleton;
  714. };
  715. /**
  716. * Imports a mesh and its geometries
  717. */
  718. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  719. if (!newMesh) {
  720. newMesh = new babylonjs_1.Mesh(node.name || "", gltfRuntime.scene);
  721. newMesh.id = id;
  722. }
  723. if (!node.babylonNode) {
  724. return newMesh;
  725. }
  726. var subMaterials = [];
  727. var vertexData = null;
  728. var verticesStarts = new Array();
  729. var verticesCounts = new Array();
  730. var indexStarts = new Array();
  731. var indexCounts = new Array();
  732. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  733. var meshID = meshes[meshIndex];
  734. var mesh = gltfRuntime.meshes[meshID];
  735. if (!mesh) {
  736. continue;
  737. }
  738. // Positions, normals and UVs
  739. for (var i = 0; i < mesh.primitives.length; i++) {
  740. // Temporary vertex data
  741. var tempVertexData = new babylonjs_1.VertexData();
  742. var primitive = mesh.primitives[i];
  743. if (primitive.mode !== 4) {
  744. // continue;
  745. }
  746. var attributes = primitive.attributes;
  747. var accessor = null;
  748. var buffer = null;
  749. // Set positions, normal and uvs
  750. for (var semantic in attributes) {
  751. // Link accessor and buffer view
  752. accessor = gltfRuntime.accessors[attributes[semantic]];
  753. buffer = glTFLoaderUtils_1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  754. if (semantic === "NORMAL") {
  755. tempVertexData.normals = new Float32Array(buffer.length);
  756. tempVertexData.normals.set(buffer);
  757. }
  758. else if (semantic === "POSITION") {
  759. if (glTFFileLoader_1.GLTFFileLoader.HomogeneousCoordinates) {
  760. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  761. for (var j = 0; j < buffer.length; j += 4) {
  762. tempVertexData.positions[j] = buffer[j];
  763. tempVertexData.positions[j + 1] = buffer[j + 1];
  764. tempVertexData.positions[j + 2] = buffer[j + 2];
  765. }
  766. }
  767. else {
  768. tempVertexData.positions = new Float32Array(buffer.length);
  769. tempVertexData.positions.set(buffer);
  770. }
  771. verticesCounts.push(tempVertexData.positions.length);
  772. }
  773. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  774. var channel = Number(semantic.split("_")[1]);
  775. var uvKind = babylonjs_1.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  776. var uvs = new Float32Array(buffer.length);
  777. uvs.set(buffer);
  778. normalizeUVs(uvs);
  779. tempVertexData.set(uvs, uvKind);
  780. }
  781. else if (semantic === "JOINT") {
  782. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  783. tempVertexData.matricesIndices.set(buffer);
  784. }
  785. else if (semantic === "WEIGHT") {
  786. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  787. tempVertexData.matricesWeights.set(buffer);
  788. }
  789. else if (semantic === "COLOR") {
  790. tempVertexData.colors = new Float32Array(buffer.length);
  791. tempVertexData.colors.set(buffer);
  792. }
  793. }
  794. // Indices
  795. accessor = gltfRuntime.accessors[primitive.indices];
  796. if (accessor) {
  797. buffer = glTFLoaderUtils_1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  798. tempVertexData.indices = new Int32Array(buffer.length);
  799. tempVertexData.indices.set(buffer);
  800. indexCounts.push(tempVertexData.indices.length);
  801. }
  802. else {
  803. // Set indices on the fly
  804. var indices = [];
  805. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  806. indices.push(j);
  807. }
  808. tempVertexData.indices = new Int32Array(indices);
  809. indexCounts.push(tempVertexData.indices.length);
  810. }
  811. if (!vertexData) {
  812. vertexData = tempVertexData;
  813. }
  814. else {
  815. vertexData.merge(tempVertexData);
  816. }
  817. // Sub material
  818. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  819. subMaterials.push(material_1 === null ? glTFLoaderUtils_1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  820. // Update vertices start and index start
  821. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  822. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  823. }
  824. }
  825. var material;
  826. if (subMaterials.length > 1) {
  827. material = new babylonjs_1.MultiMaterial("multimat" + id, gltfRuntime.scene);
  828. material.subMaterials = subMaterials;
  829. }
  830. else {
  831. material = new babylonjs_1.StandardMaterial("multimat" + id, gltfRuntime.scene);
  832. }
  833. if (subMaterials.length === 1) {
  834. material = subMaterials[0];
  835. }
  836. if (!newMesh.material) {
  837. newMesh.material = material;
  838. }
  839. // Apply geometry
  840. new babylonjs_1.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  841. newMesh.computeWorldMatrix(true);
  842. // Apply submeshes
  843. newMesh.subMeshes = [];
  844. var index = 0;
  845. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  846. var meshID = meshes[meshIndex];
  847. var mesh = gltfRuntime.meshes[meshID];
  848. if (!mesh) {
  849. continue;
  850. }
  851. for (var i = 0; i < mesh.primitives.length; i++) {
  852. if (mesh.primitives[i].mode !== 4) {
  853. //continue;
  854. }
  855. babylonjs_1.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  856. index++;
  857. }
  858. }
  859. // Finish
  860. return newMesh;
  861. };
  862. /**
  863. * Configure node transformation from position, rotation and scaling
  864. */
  865. var configureNode = function (newNode, position, rotation, scaling) {
  866. if (newNode.position) {
  867. newNode.position = position;
  868. }
  869. if (newNode.rotationQuaternion || newNode.rotation) {
  870. newNode.rotationQuaternion = rotation;
  871. }
  872. if (newNode.scaling) {
  873. newNode.scaling = scaling;
  874. }
  875. };
  876. /**
  877. * Configures node from transformation matrix
  878. */
  879. var configureNodeFromMatrix = function (newNode, node, parent) {
  880. if (node.matrix) {
  881. var position = new babylonjs_1.Vector3(0, 0, 0);
  882. var rotation = new babylonjs_1.Quaternion();
  883. var scaling = new babylonjs_1.Vector3(0, 0, 0);
  884. var mat = babylonjs_1.Matrix.FromArray(node.matrix);
  885. mat.decompose(scaling, rotation, position);
  886. configureNode(newNode, position, rotation, scaling);
  887. }
  888. else if (node.translation && node.rotation && node.scale) {
  889. configureNode(newNode, babylonjs_1.Vector3.FromArray(node.translation), babylonjs_1.Quaternion.FromArray(node.rotation), babylonjs_1.Vector3.FromArray(node.scale));
  890. }
  891. newNode.computeWorldMatrix(true);
  892. };
  893. /**
  894. * Imports a node
  895. */
  896. var importNode = function (gltfRuntime, node, id, parent) {
  897. var lastNode = null;
  898. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  899. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  900. return null;
  901. }
  902. }
  903. // Meshes
  904. if (node.skin) {
  905. if (node.meshes) {
  906. var skin = gltfRuntime.skins[node.skin];
  907. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  908. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  909. if (newMesh.skeleton === null) {
  910. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  911. if (!skin.babylonSkeleton) {
  912. skin.babylonSkeleton = newMesh.skeleton;
  913. }
  914. }
  915. lastNode = newMesh;
  916. }
  917. }
  918. else if (node.meshes) {
  919. /**
  920. * Improve meshes property
  921. */
  922. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  923. lastNode = newMesh;
  924. }
  925. // Lights
  926. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  927. var light = gltfRuntime.lights[node.light];
  928. if (light) {
  929. if (light.type === "ambient") {
  930. var ambienLight = light[light.type];
  931. var hemiLight = new babylonjs_1.HemisphericLight(node.light, babylonjs_1.Vector3.Zero(), gltfRuntime.scene);
  932. hemiLight.name = node.name || "";
  933. if (ambienLight.color) {
  934. hemiLight.diffuse = babylonjs_1.Color3.FromArray(ambienLight.color);
  935. }
  936. lastNode = hemiLight;
  937. }
  938. else if (light.type === "directional") {
  939. var directionalLight = light[light.type];
  940. var dirLight = new babylonjs_1.DirectionalLight(node.light, babylonjs_1.Vector3.Zero(), gltfRuntime.scene);
  941. dirLight.name = node.name || "";
  942. if (directionalLight.color) {
  943. dirLight.diffuse = babylonjs_1.Color3.FromArray(directionalLight.color);
  944. }
  945. lastNode = dirLight;
  946. }
  947. else if (light.type === "point") {
  948. var pointLight = light[light.type];
  949. var ptLight = new babylonjs_1.PointLight(node.light, babylonjs_1.Vector3.Zero(), gltfRuntime.scene);
  950. ptLight.name = node.name || "";
  951. if (pointLight.color) {
  952. ptLight.diffuse = babylonjs_1.Color3.FromArray(pointLight.color);
  953. }
  954. lastNode = ptLight;
  955. }
  956. else if (light.type === "spot") {
  957. var spotLight = light[light.type];
  958. var spLight = new babylonjs_1.SpotLight(node.light, babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  959. spLight.name = node.name || "";
  960. if (spotLight.color) {
  961. spLight.diffuse = babylonjs_1.Color3.FromArray(spotLight.color);
  962. }
  963. if (spotLight.fallOfAngle) {
  964. spLight.angle = spotLight.fallOfAngle;
  965. }
  966. if (spotLight.fallOffExponent) {
  967. spLight.exponent = spotLight.fallOffExponent;
  968. }
  969. lastNode = spLight;
  970. }
  971. }
  972. }
  973. // Cameras
  974. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  975. var camera = gltfRuntime.cameras[node.camera];
  976. if (camera) {
  977. if (camera.type === "orthographic") {
  978. var orthoCamera = new babylonjs_1.FreeCamera(node.camera, babylonjs_1.Vector3.Zero(), gltfRuntime.scene, false);
  979. orthoCamera.name = node.name || "";
  980. orthoCamera.mode = babylonjs_1.Camera.ORTHOGRAPHIC_CAMERA;
  981. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  982. lastNode = orthoCamera;
  983. }
  984. else if (camera.type === "perspective") {
  985. var perspectiveCamera = camera[camera.type];
  986. var persCamera = new babylonjs_1.FreeCamera(node.camera, babylonjs_1.Vector3.Zero(), gltfRuntime.scene, false);
  987. persCamera.name = node.name || "";
  988. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  989. if (!perspectiveCamera.aspectRatio) {
  990. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  991. }
  992. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  993. persCamera.maxZ = perspectiveCamera.zfar;
  994. persCamera.minZ = perspectiveCamera.znear;
  995. }
  996. lastNode = persCamera;
  997. }
  998. }
  999. }
  1000. // Empty node
  1001. if (!node.jointName) {
  1002. if (node.babylonNode) {
  1003. return node.babylonNode;
  1004. }
  1005. else if (lastNode === null) {
  1006. var dummy = new babylonjs_1.Mesh(node.name || "", gltfRuntime.scene);
  1007. node.babylonNode = dummy;
  1008. lastNode = dummy;
  1009. }
  1010. }
  1011. if (lastNode !== null) {
  1012. if (node.matrix && lastNode instanceof babylonjs_1.Mesh) {
  1013. configureNodeFromMatrix(lastNode, node, parent);
  1014. }
  1015. else {
  1016. var translation = node.translation || [0, 0, 0];
  1017. var rotation = node.rotation || [0, 0, 0, 1];
  1018. var scale = node.scale || [1, 1, 1];
  1019. configureNode(lastNode, babylonjs_1.Vector3.FromArray(translation), babylonjs_1.Quaternion.FromArray(rotation), babylonjs_1.Vector3.FromArray(scale));
  1020. }
  1021. lastNode.updateCache(true);
  1022. node.babylonNode = lastNode;
  1023. }
  1024. return lastNode;
  1025. };
  1026. /**
  1027. * Traverses nodes and creates them
  1028. */
  1029. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  1030. if (meshIncluded === void 0) { meshIncluded = false; }
  1031. var node = gltfRuntime.nodes[id];
  1032. var newNode = null;
  1033. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  1034. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  1035. meshIncluded = true;
  1036. }
  1037. else {
  1038. meshIncluded = false;
  1039. }
  1040. }
  1041. else {
  1042. meshIncluded = true;
  1043. }
  1044. if (!node.jointName && meshIncluded) {
  1045. newNode = importNode(gltfRuntime, node, id, parent);
  1046. if (newNode !== null) {
  1047. newNode.id = id;
  1048. newNode.parent = parent;
  1049. }
  1050. }
  1051. if (node.children) {
  1052. for (var i = 0; i < node.children.length; i++) {
  1053. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  1054. }
  1055. }
  1056. };
  1057. /**
  1058. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  1059. */
  1060. var postLoad = function (gltfRuntime) {
  1061. // Nodes
  1062. var currentScene = gltfRuntime.currentScene;
  1063. if (currentScene) {
  1064. for (var i = 0; i < currentScene.nodes.length; i++) {
  1065. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1066. }
  1067. }
  1068. else {
  1069. for (var thing in gltfRuntime.scenes) {
  1070. currentScene = gltfRuntime.scenes[thing];
  1071. for (var i = 0; i < currentScene.nodes.length; i++) {
  1072. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1073. }
  1074. }
  1075. }
  1076. // Set animations
  1077. loadAnimations(gltfRuntime);
  1078. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  1079. var skeleton = gltfRuntime.scene.skeletons[i];
  1080. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  1081. }
  1082. };
  1083. /**
  1084. * onBind shaderrs callback to set uniforms and matrices
  1085. */
  1086. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  1087. var materialValues = material.values || technique.parameters;
  1088. for (var unif in unTreatedUniforms) {
  1089. var uniform = unTreatedUniforms[unif];
  1090. var type = uniform.type;
  1091. if (type === glTFLoaderInterfaces_1.EParameterType.FLOAT_MAT2 || type === glTFLoaderInterfaces_1.EParameterType.FLOAT_MAT3 || type === glTFLoaderInterfaces_1.EParameterType.FLOAT_MAT4) {
  1092. if (uniform.semantic && !uniform.source && !uniform.node) {
  1093. glTFLoaderUtils_1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  1094. }
  1095. else if (uniform.semantic && (uniform.source || uniform.node)) {
  1096. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  1097. if (source === null) {
  1098. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  1099. }
  1100. if (source === null) {
  1101. continue;
  1102. }
  1103. glTFLoaderUtils_1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  1104. }
  1105. }
  1106. else {
  1107. var value = materialValues[technique.uniforms[unif]];
  1108. if (!value) {
  1109. continue;
  1110. }
  1111. if (type === glTFLoaderInterfaces_1.EParameterType.SAMPLER_2D) {
  1112. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  1113. if (texture === null || texture === undefined) {
  1114. continue;
  1115. }
  1116. shaderMaterial.getEffect().setTexture(unif, texture);
  1117. }
  1118. else {
  1119. glTFLoaderUtils_1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  1120. }
  1121. }
  1122. }
  1123. onSuccess(shaderMaterial);
  1124. };
  1125. /**
  1126. * Prepare uniforms to send the only one time
  1127. * Loads the appropriate textures
  1128. */
  1129. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  1130. var materialValues = material.values || technique.parameters;
  1131. var techniqueUniforms = technique.uniforms;
  1132. /**
  1133. * Prepare values here (not matrices)
  1134. */
  1135. for (var unif in unTreatedUniforms) {
  1136. var uniform = unTreatedUniforms[unif];
  1137. var type = uniform.type;
  1138. var value = materialValues[techniqueUniforms[unif]];
  1139. if (value === undefined) {
  1140. // In case the value is the same for all materials
  1141. value = uniform.value;
  1142. }
  1143. if (!value) {
  1144. continue;
  1145. }
  1146. var onLoadTexture = function (uniformName) {
  1147. return function (texture) {
  1148. if (uniform.value && uniformName) {
  1149. // Static uniform
  1150. shaderMaterial.setTexture(uniformName, texture);
  1151. delete unTreatedUniforms[uniformName];
  1152. }
  1153. };
  1154. };
  1155. // Texture (sampler2D)
  1156. if (type === glTFLoaderInterfaces_1.EParameterType.SAMPLER_2D) {
  1157. glTFLoaderExtension_1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  1158. }
  1159. // Others
  1160. else {
  1161. if (uniform.value && glTFLoaderUtils_1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  1162. // Static uniform
  1163. delete unTreatedUniforms[unif];
  1164. }
  1165. }
  1166. }
  1167. };
  1168. /**
  1169. * Shader compilation failed
  1170. */
  1171. var onShaderCompileError = function (program, shaderMaterial, onError) {
  1172. return function (effect, error) {
  1173. shaderMaterial.dispose(true);
  1174. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  1175. };
  1176. };
  1177. /**
  1178. * Shader compilation success
  1179. */
  1180. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  1181. return function (_) {
  1182. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  1183. shaderMaterial.onBind = function (mesh) {
  1184. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  1185. };
  1186. };
  1187. };
  1188. /**
  1189. * Returns the appropriate uniform if already handled by babylon
  1190. */
  1191. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  1192. for (var unif in technique.uniforms) {
  1193. var uniform = technique.uniforms[unif];
  1194. var uniformParameter = technique.parameters[uniform];
  1195. if (tokenizer.currentIdentifier === unif) {
  1196. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  1197. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1198. if (transformIndex !== -1) {
  1199. delete unTreatedUniforms[unif];
  1200. return babylonTransforms[transformIndex];
  1201. }
  1202. }
  1203. }
  1204. }
  1205. return tokenizer.currentIdentifier;
  1206. };
  1207. /**
  1208. * All shaders loaded. Create materials one by one
  1209. */
  1210. var importMaterials = function (gltfRuntime) {
  1211. // Create materials
  1212. for (var mat in gltfRuntime.materials) {
  1213. glTFLoaderExtension_1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  1214. }
  1215. };
  1216. /**
  1217. * Implementation of the base glTF spec
  1218. * @hidden
  1219. */
  1220. var GLTFLoaderBase = /** @class */ (function () {
  1221. function GLTFLoaderBase() {
  1222. }
  1223. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  1224. var gltfRuntime = {
  1225. extensions: {},
  1226. accessors: {},
  1227. buffers: {},
  1228. bufferViews: {},
  1229. meshes: {},
  1230. lights: {},
  1231. cameras: {},
  1232. nodes: {},
  1233. images: {},
  1234. textures: {},
  1235. shaders: {},
  1236. programs: {},
  1237. samplers: {},
  1238. techniques: {},
  1239. materials: {},
  1240. animations: {},
  1241. skins: {},
  1242. extensionsUsed: [],
  1243. scenes: {},
  1244. buffersCount: 0,
  1245. shaderscount: 0,
  1246. scene: scene,
  1247. rootUrl: rootUrl,
  1248. loadedBufferCount: 0,
  1249. loadedBufferViews: {},
  1250. loadedShaderCount: 0,
  1251. importOnlyMeshes: false,
  1252. dummyNodes: []
  1253. };
  1254. // Parse
  1255. if (parsedData.extensions) {
  1256. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  1257. }
  1258. if (parsedData.extensionsUsed) {
  1259. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  1260. }
  1261. if (parsedData.buffers) {
  1262. parseBuffers(parsedData.buffers, gltfRuntime);
  1263. }
  1264. if (parsedData.bufferViews) {
  1265. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  1266. }
  1267. if (parsedData.accessors) {
  1268. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  1269. }
  1270. if (parsedData.meshes) {
  1271. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  1272. }
  1273. if (parsedData.lights) {
  1274. parseObject(parsedData.lights, "lights", gltfRuntime);
  1275. }
  1276. if (parsedData.cameras) {
  1277. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  1278. }
  1279. if (parsedData.nodes) {
  1280. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  1281. }
  1282. if (parsedData.images) {
  1283. parseObject(parsedData.images, "images", gltfRuntime);
  1284. }
  1285. if (parsedData.textures) {
  1286. parseObject(parsedData.textures, "textures", gltfRuntime);
  1287. }
  1288. if (parsedData.shaders) {
  1289. parseShaders(parsedData.shaders, gltfRuntime);
  1290. }
  1291. if (parsedData.programs) {
  1292. parseObject(parsedData.programs, "programs", gltfRuntime);
  1293. }
  1294. if (parsedData.samplers) {
  1295. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  1296. }
  1297. if (parsedData.techniques) {
  1298. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  1299. }
  1300. if (parsedData.materials) {
  1301. parseObject(parsedData.materials, "materials", gltfRuntime);
  1302. }
  1303. if (parsedData.animations) {
  1304. parseObject(parsedData.animations, "animations", gltfRuntime);
  1305. }
  1306. if (parsedData.skins) {
  1307. parseObject(parsedData.skins, "skins", gltfRuntime);
  1308. }
  1309. if (parsedData.scenes) {
  1310. gltfRuntime.scenes = parsedData.scenes;
  1311. }
  1312. if (parsedData.scene && parsedData.scenes) {
  1313. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  1314. }
  1315. return gltfRuntime;
  1316. };
  1317. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  1318. var buffer = gltfRuntime.buffers[id];
  1319. if (babylonjs_1.Tools.IsBase64(buffer.uri)) {
  1320. setTimeout(function () { return onSuccess(new Uint8Array(babylonjs_1.Tools.DecodeBase64(buffer.uri))); });
  1321. }
  1322. else {
  1323. babylonjs_1.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  1324. if (request) {
  1325. onError(request.status + " " + request.statusText);
  1326. }
  1327. });
  1328. }
  1329. };
  1330. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1331. var texture = gltfRuntime.textures[id];
  1332. if (!texture || !texture.source) {
  1333. onError("");
  1334. return;
  1335. }
  1336. if (texture.babylonTexture) {
  1337. onSuccess(null);
  1338. return;
  1339. }
  1340. var source = gltfRuntime.images[texture.source];
  1341. if (babylonjs_1.Tools.IsBase64(source.uri)) {
  1342. setTimeout(function () { return onSuccess(new Uint8Array(babylonjs_1.Tools.DecodeBase64(source.uri))); });
  1343. }
  1344. else {
  1345. babylonjs_1.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  1346. if (request) {
  1347. onError(request.status + " " + request.statusText);
  1348. }
  1349. });
  1350. }
  1351. };
  1352. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1353. var texture = gltfRuntime.textures[id];
  1354. if (texture.babylonTexture) {
  1355. onSuccess(texture.babylonTexture);
  1356. return;
  1357. }
  1358. var sampler = gltfRuntime.samplers[texture.sampler];
  1359. var createMipMaps = (sampler.minFilter === glTFLoaderInterfaces_1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  1360. (sampler.minFilter === glTFLoaderInterfaces_1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  1361. (sampler.minFilter === glTFLoaderInterfaces_1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  1362. (sampler.minFilter === glTFLoaderInterfaces_1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  1363. var samplingMode = babylonjs_1.Texture.BILINEAR_SAMPLINGMODE;
  1364. var blob = buffer == null ? new Blob() : new Blob([buffer]);
  1365. var blobURL = URL.createObjectURL(blob);
  1366. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  1367. var newTexture = new babylonjs_1.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  1368. if (sampler.wrapS !== undefined) {
  1369. newTexture.wrapU = glTFLoaderUtils_1.GLTFUtils.GetWrapMode(sampler.wrapS);
  1370. }
  1371. if (sampler.wrapT !== undefined) {
  1372. newTexture.wrapV = glTFLoaderUtils_1.GLTFUtils.GetWrapMode(sampler.wrapT);
  1373. }
  1374. newTexture.name = id;
  1375. texture.babylonTexture = newTexture;
  1376. onSuccess(newTexture);
  1377. };
  1378. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1379. var shader = gltfRuntime.shaders[id];
  1380. if (babylonjs_1.Tools.IsBase64(shader.uri)) {
  1381. var shaderString = atob(shader.uri.split(",")[1]);
  1382. if (onSuccess) {
  1383. onSuccess(shaderString);
  1384. }
  1385. }
  1386. else {
  1387. babylonjs_1.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  1388. if (request && onError) {
  1389. onError(request.status + " " + request.statusText);
  1390. }
  1391. });
  1392. }
  1393. };
  1394. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1395. var material = gltfRuntime.materials[id];
  1396. if (!material.technique) {
  1397. if (onError) {
  1398. onError("No technique found.");
  1399. }
  1400. return;
  1401. }
  1402. var technique = gltfRuntime.techniques[material.technique];
  1403. if (!technique) {
  1404. var defaultMaterial = new babylonjs_1.StandardMaterial(id, gltfRuntime.scene);
  1405. defaultMaterial.diffuseColor = new babylonjs_1.Color3(0.5, 0.5, 0.5);
  1406. defaultMaterial.sideOrientation = babylonjs_1.Material.CounterClockWiseSideOrientation;
  1407. onSuccess(defaultMaterial);
  1408. return;
  1409. }
  1410. var program = gltfRuntime.programs[technique.program];
  1411. var states = technique.states;
  1412. var vertexShader = babylonjs_1.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  1413. var pixelShader = babylonjs_1.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  1414. var newVertexShader = "";
  1415. var newPixelShader = "";
  1416. var vertexTokenizer = new Tokenizer(vertexShader);
  1417. var pixelTokenizer = new Tokenizer(pixelShader);
  1418. var unTreatedUniforms = {};
  1419. var uniforms = [];
  1420. var attributes = [];
  1421. var samplers = [];
  1422. // Fill uniform, sampler2D and attributes
  1423. for (var unif in technique.uniforms) {
  1424. var uniform = technique.uniforms[unif];
  1425. var uniformParameter = technique.parameters[uniform];
  1426. unTreatedUniforms[unif] = uniformParameter;
  1427. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  1428. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1429. if (transformIndex !== -1) {
  1430. uniforms.push(babylonTransforms[transformIndex]);
  1431. delete unTreatedUniforms[unif];
  1432. }
  1433. else {
  1434. uniforms.push(unif);
  1435. }
  1436. }
  1437. else if (uniformParameter.type === glTFLoaderInterfaces_1.EParameterType.SAMPLER_2D) {
  1438. samplers.push(unif);
  1439. }
  1440. else {
  1441. uniforms.push(unif);
  1442. }
  1443. }
  1444. for (var attr in technique.attributes) {
  1445. var attribute = technique.attributes[attr];
  1446. var attributeParameter = technique.parameters[attribute];
  1447. if (attributeParameter.semantic) {
  1448. var name_1 = getAttribute(attributeParameter);
  1449. if (name_1) {
  1450. attributes.push(name_1);
  1451. }
  1452. }
  1453. }
  1454. // Configure vertex shader
  1455. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  1456. var tokenType = vertexTokenizer.currentToken;
  1457. if (tokenType !== ETokenType.IDENTIFIER) {
  1458. newVertexShader += vertexTokenizer.currentString;
  1459. continue;
  1460. }
  1461. var foundAttribute = false;
  1462. for (var attr in technique.attributes) {
  1463. var attribute = technique.attributes[attr];
  1464. var attributeParameter = technique.parameters[attribute];
  1465. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  1466. newVertexShader += getAttribute(attributeParameter);
  1467. foundAttribute = true;
  1468. break;
  1469. }
  1470. }
  1471. if (foundAttribute) {
  1472. continue;
  1473. }
  1474. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  1475. }
  1476. // Configure pixel shader
  1477. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  1478. var tokenType = pixelTokenizer.currentToken;
  1479. if (tokenType !== ETokenType.IDENTIFIER) {
  1480. newPixelShader += pixelTokenizer.currentString;
  1481. continue;
  1482. }
  1483. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  1484. }
  1485. // Create shader material
  1486. var shaderPath = {
  1487. vertex: program.vertexShader + id,
  1488. fragment: program.fragmentShader + id
  1489. };
  1490. var options = {
  1491. attributes: attributes,
  1492. uniforms: uniforms,
  1493. samplers: samplers,
  1494. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  1495. };
  1496. babylonjs_1.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  1497. babylonjs_1.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  1498. var shaderMaterial = new babylonjs_1.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  1499. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  1500. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  1501. shaderMaterial.sideOrientation = babylonjs_1.Material.CounterClockWiseSideOrientation;
  1502. if (states && states.functions) {
  1503. var functions = states.functions;
  1504. if (functions.cullFace && functions.cullFace[0] !== glTFLoaderInterfaces_1.ECullingType.BACK) {
  1505. shaderMaterial.backFaceCulling = false;
  1506. }
  1507. var blendFunc = functions.blendFuncSeparate;
  1508. if (blendFunc) {
  1509. if (blendFunc[0] === glTFLoaderInterfaces_1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === glTFLoaderInterfaces_1.EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === glTFLoaderInterfaces_1.EBlendingFunction.ONE && blendFunc[3] === glTFLoaderInterfaces_1.EBlendingFunction.ONE) {
  1510. shaderMaterial.alphaMode = babylonjs_1.Engine.ALPHA_COMBINE;
  1511. }
  1512. else if (blendFunc[0] === glTFLoaderInterfaces_1.EBlendingFunction.ONE && blendFunc[1] === glTFLoaderInterfaces_1.EBlendingFunction.ONE && blendFunc[2] === glTFLoaderInterfaces_1.EBlendingFunction.ZERO && blendFunc[3] === glTFLoaderInterfaces_1.EBlendingFunction.ONE) {
  1513. shaderMaterial.alphaMode = babylonjs_1.Engine.ALPHA_ONEONE;
  1514. }
  1515. else if (blendFunc[0] === glTFLoaderInterfaces_1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === glTFLoaderInterfaces_1.EBlendingFunction.ONE && blendFunc[2] === glTFLoaderInterfaces_1.EBlendingFunction.ZERO && blendFunc[3] === glTFLoaderInterfaces_1.EBlendingFunction.ONE) {
  1516. shaderMaterial.alphaMode = babylonjs_1.Engine.ALPHA_ADD;
  1517. }
  1518. else if (blendFunc[0] === glTFLoaderInterfaces_1.EBlendingFunction.ZERO && blendFunc[1] === glTFLoaderInterfaces_1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === glTFLoaderInterfaces_1.EBlendingFunction.ONE && blendFunc[3] === glTFLoaderInterfaces_1.EBlendingFunction.ONE) {
  1519. shaderMaterial.alphaMode = babylonjs_1.Engine.ALPHA_SUBTRACT;
  1520. }
  1521. else if (blendFunc[0] === glTFLoaderInterfaces_1.EBlendingFunction.DST_COLOR && blendFunc[1] === glTFLoaderInterfaces_1.EBlendingFunction.ZERO && blendFunc[2] === glTFLoaderInterfaces_1.EBlendingFunction.ONE && blendFunc[3] === glTFLoaderInterfaces_1.EBlendingFunction.ONE) {
  1522. shaderMaterial.alphaMode = babylonjs_1.Engine.ALPHA_MULTIPLY;
  1523. }
  1524. else if (blendFunc[0] === glTFLoaderInterfaces_1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === glTFLoaderInterfaces_1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === glTFLoaderInterfaces_1.EBlendingFunction.ONE && blendFunc[3] === glTFLoaderInterfaces_1.EBlendingFunction.ONE) {
  1525. shaderMaterial.alphaMode = babylonjs_1.Engine.ALPHA_MAXIMIZED;
  1526. }
  1527. }
  1528. }
  1529. };
  1530. return GLTFLoaderBase;
  1531. }());
  1532. exports.GLTFLoaderBase = GLTFLoaderBase;
  1533. /**
  1534. * glTF V1 Loader
  1535. * @hidden
  1536. */
  1537. var GLTFLoader = /** @class */ (function () {
  1538. function GLTFLoader() {
  1539. this.state = null;
  1540. }
  1541. GLTFLoader.RegisterExtension = function (extension) {
  1542. if (GLTFLoader.Extensions[extension.name]) {
  1543. babylonjs_1.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  1544. return;
  1545. }
  1546. GLTFLoader.Extensions[extension.name] = extension;
  1547. };
  1548. GLTFLoader.prototype.dispose = function () {
  1549. // do nothing
  1550. };
  1551. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  1552. var _this = this;
  1553. scene.useRightHandedSystem = true;
  1554. glTFLoaderExtension_1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1555. gltfRuntime.importOnlyMeshes = true;
  1556. if (meshesNames === "") {
  1557. gltfRuntime.importMeshesNames = [];
  1558. }
  1559. else if (typeof meshesNames === "string") {
  1560. gltfRuntime.importMeshesNames = [meshesNames];
  1561. }
  1562. else if (meshesNames && !(meshesNames instanceof Array)) {
  1563. gltfRuntime.importMeshesNames = [meshesNames];
  1564. }
  1565. else {
  1566. gltfRuntime.importMeshesNames = [];
  1567. babylonjs_1.Tools.Warn("Argument meshesNames must be of type string or string[]");
  1568. }
  1569. // Create nodes
  1570. _this._createNodes(gltfRuntime);
  1571. var meshes = new Array();
  1572. var skeletons = new Array();
  1573. // Fill arrays of meshes and skeletons
  1574. for (var nde in gltfRuntime.nodes) {
  1575. var node = gltfRuntime.nodes[nde];
  1576. if (node.babylonNode instanceof babylonjs_1.AbstractMesh) {
  1577. meshes.push(node.babylonNode);
  1578. }
  1579. }
  1580. for (var skl in gltfRuntime.skins) {
  1581. var skin = gltfRuntime.skins[skl];
  1582. if (skin.babylonSkeleton instanceof babylonjs_1.Skeleton) {
  1583. skeletons.push(skin.babylonSkeleton);
  1584. }
  1585. }
  1586. // Load buffers, shaders, materials, etc.
  1587. _this._loadBuffersAsync(gltfRuntime, function () {
  1588. _this._loadShadersAsync(gltfRuntime, function () {
  1589. importMaterials(gltfRuntime);
  1590. postLoad(gltfRuntime);
  1591. if (!glTFFileLoader_1.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1592. onSuccess(meshes, skeletons);
  1593. }
  1594. });
  1595. }, onProgress);
  1596. if (glTFFileLoader_1.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1597. onSuccess(meshes, skeletons);
  1598. }
  1599. }, onError);
  1600. return true;
  1601. };
  1602. /**
  1603. * Imports one or more meshes from a loaded gltf file and adds them to the scene
  1604. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  1605. * @param scene the scene the meshes should be added to
  1606. * @param data gltf data containing information of the meshes in a loaded file
  1607. * @param rootUrl root url to load from
  1608. * @param onProgress event that fires when loading progress has occured
  1609. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  1610. */
  1611. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  1612. var _this = this;
  1613. return new Promise(function (resolve, reject) {
  1614. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, skeletons) {
  1615. resolve({
  1616. meshes: meshes,
  1617. particleSystems: [],
  1618. skeletons: skeletons,
  1619. animationGroups: []
  1620. });
  1621. }, onProgress, function (message) {
  1622. reject(new Error(message));
  1623. });
  1624. });
  1625. };
  1626. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  1627. var _this = this;
  1628. scene.useRightHandedSystem = true;
  1629. glTFLoaderExtension_1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1630. // Load runtime extensios
  1631. glTFLoaderExtension_1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  1632. // Create nodes
  1633. _this._createNodes(gltfRuntime);
  1634. // Load buffers, shaders, materials, etc.
  1635. _this._loadBuffersAsync(gltfRuntime, function () {
  1636. _this._loadShadersAsync(gltfRuntime, function () {
  1637. importMaterials(gltfRuntime);
  1638. postLoad(gltfRuntime);
  1639. if (!glTFFileLoader_1.GLTFFileLoader.IncrementalLoading) {
  1640. onSuccess();
  1641. }
  1642. });
  1643. });
  1644. if (glTFFileLoader_1.GLTFFileLoader.IncrementalLoading) {
  1645. onSuccess();
  1646. }
  1647. }, onError);
  1648. }, onError);
  1649. };
  1650. /**
  1651. * Imports all objects from a loaded gltf file and adds them to the scene
  1652. * @param scene the scene the objects should be added to
  1653. * @param data gltf data containing information of the meshes in a loaded file
  1654. * @param rootUrl root url to load from
  1655. * @param onProgress event that fires when loading progress has occured
  1656. * @returns a promise which completes when objects have been loaded to the scene
  1657. */
  1658. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  1659. var _this = this;
  1660. return new Promise(function (resolve, reject) {
  1661. _this._loadAsync(scene, data, rootUrl, function () {
  1662. resolve();
  1663. }, onProgress, function (message) {
  1664. reject(new Error(message));
  1665. });
  1666. });
  1667. };
  1668. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  1669. var hasShaders = false;
  1670. var processShader = function (sha, shader) {
  1671. glTFLoaderExtension_1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  1672. if (shaderString instanceof ArrayBuffer) {
  1673. return;
  1674. }
  1675. gltfRuntime.loadedShaderCount++;
  1676. if (shaderString) {
  1677. babylonjs_1.Effect.ShadersStore[sha + (shader.type === glTFLoaderInterfaces_1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  1678. }
  1679. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  1680. onload();
  1681. }
  1682. }, function () {
  1683. babylonjs_1.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  1684. });
  1685. };
  1686. for (var sha in gltfRuntime.shaders) {
  1687. hasShaders = true;
  1688. var shader = gltfRuntime.shaders[sha];
  1689. if (shader) {
  1690. processShader.bind(this, sha, shader)();
  1691. }
  1692. else {
  1693. babylonjs_1.Tools.Error("No shader named: " + sha);
  1694. }
  1695. }
  1696. if (!hasShaders) {
  1697. onload();
  1698. }
  1699. };
  1700. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  1701. var hasBuffers = false;
  1702. var processBuffer = function (buf, buffer) {
  1703. glTFLoaderExtension_1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  1704. gltfRuntime.loadedBufferCount++;
  1705. if (bufferView) {
  1706. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  1707. babylonjs_1.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  1708. }
  1709. gltfRuntime.loadedBufferViews[buf] = bufferView;
  1710. }
  1711. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  1712. onLoad();
  1713. }
  1714. }, function () {
  1715. babylonjs_1.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  1716. });
  1717. };
  1718. for (var buf in gltfRuntime.buffers) {
  1719. hasBuffers = true;
  1720. var buffer = gltfRuntime.buffers[buf];
  1721. if (buffer) {
  1722. processBuffer.bind(this, buf, buffer)();
  1723. }
  1724. else {
  1725. babylonjs_1.Tools.Error("No buffer named: " + buf);
  1726. }
  1727. }
  1728. if (!hasBuffers) {
  1729. onLoad();
  1730. }
  1731. };
  1732. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  1733. var currentScene = gltfRuntime.currentScene;
  1734. if (currentScene) {
  1735. // Only one scene even if multiple scenes are defined
  1736. for (var i = 0; i < currentScene.nodes.length; i++) {
  1737. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1738. }
  1739. }
  1740. else {
  1741. // Load all scenes
  1742. for (var thing in gltfRuntime.scenes) {
  1743. currentScene = gltfRuntime.scenes[thing];
  1744. for (var i = 0; i < currentScene.nodes.length; i++) {
  1745. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1746. }
  1747. }
  1748. }
  1749. };
  1750. GLTFLoader.Extensions = {};
  1751. return GLTFLoader;
  1752. }());
  1753. exports.GLTFLoader = GLTFLoader;
  1754. glTFFileLoader_1.GLTFFileLoader._CreateGLTF1Loader = function () { return new GLTFLoader(); };
  1755. /***/ }),
  1756. /***/ "./src/glTF/1.0/glTFLoaderExtension.ts":
  1757. /*!*********************************************!*\
  1758. !*** ./src/glTF/1.0/glTFLoaderExtension.ts ***!
  1759. \*********************************************/
  1760. /*! no static exports found */
  1761. /***/ (function(module, exports, __webpack_require__) {
  1762. "use strict";
  1763. Object.defineProperty(exports, "__esModule", { value: true });
  1764. var glTFLoader_1 = __webpack_require__(/*! ./glTFLoader */ "./src/glTF/1.0/glTFLoader.ts");
  1765. /** @hidden */
  1766. var GLTFLoaderExtension = /** @class */ (function () {
  1767. function GLTFLoaderExtension(name) {
  1768. this._name = name;
  1769. }
  1770. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  1771. get: function () {
  1772. return this._name;
  1773. },
  1774. enumerable: true,
  1775. configurable: true
  1776. });
  1777. /**
  1778. * Defines an override for loading the runtime
  1779. * Return true to stop further extensions from loading the runtime
  1780. */
  1781. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  1782. return false;
  1783. };
  1784. /**
  1785. * Defines an onverride for creating gltf runtime
  1786. * Return true to stop further extensions from creating the runtime
  1787. */
  1788. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  1789. return false;
  1790. };
  1791. /**
  1792. * Defines an override for loading buffers
  1793. * Return true to stop further extensions from loading this buffer
  1794. */
  1795. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  1796. return false;
  1797. };
  1798. /**
  1799. * Defines an override for loading texture buffers
  1800. * Return true to stop further extensions from loading this texture data
  1801. */
  1802. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1803. return false;
  1804. };
  1805. /**
  1806. * Defines an override for creating textures
  1807. * Return true to stop further extensions from loading this texture
  1808. */
  1809. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1810. return false;
  1811. };
  1812. /**
  1813. * Defines an override for loading shader strings
  1814. * Return true to stop further extensions from loading this shader data
  1815. */
  1816. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1817. return false;
  1818. };
  1819. /**
  1820. * Defines an override for loading materials
  1821. * Return true to stop further extensions from loading this material
  1822. */
  1823. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1824. return false;
  1825. };
  1826. // ---------
  1827. // Utilities
  1828. // ---------
  1829. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  1830. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1831. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  1832. }, function () {
  1833. setTimeout(function () {
  1834. if (!onSuccess) {
  1835. return;
  1836. }
  1837. onSuccess(glTFLoader_1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  1838. });
  1839. });
  1840. };
  1841. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  1842. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1843. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  1844. }, function () {
  1845. setTimeout(function () {
  1846. onSuccess();
  1847. });
  1848. });
  1849. };
  1850. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  1851. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1852. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  1853. }, function () {
  1854. glTFLoader_1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  1855. });
  1856. };
  1857. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  1858. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  1859. if (buffer) {
  1860. GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  1861. }
  1862. }, onError);
  1863. };
  1864. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1865. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1866. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  1867. }, function () {
  1868. glTFLoader_1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  1869. });
  1870. };
  1871. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1872. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1873. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  1874. }, function () {
  1875. glTFLoader_1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  1876. });
  1877. };
  1878. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1879. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1880. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  1881. }, function () {
  1882. glTFLoader_1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  1883. });
  1884. };
  1885. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1886. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1887. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  1888. }, function () {
  1889. glTFLoader_1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  1890. });
  1891. };
  1892. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  1893. for (var extensionName in glTFLoader_1.GLTFLoader.Extensions) {
  1894. var loaderExtension = glTFLoader_1.GLTFLoader.Extensions[extensionName];
  1895. if (func(loaderExtension)) {
  1896. return;
  1897. }
  1898. }
  1899. defaultFunc();
  1900. };
  1901. return GLTFLoaderExtension;
  1902. }());
  1903. exports.GLTFLoaderExtension = GLTFLoaderExtension;
  1904. /***/ }),
  1905. /***/ "./src/glTF/1.0/glTFLoaderInterfaces.ts":
  1906. /*!**********************************************!*\
  1907. !*** ./src/glTF/1.0/glTFLoaderInterfaces.ts ***!
  1908. \**********************************************/
  1909. /*! no static exports found */
  1910. /***/ (function(module, exports, __webpack_require__) {
  1911. "use strict";
  1912. Object.defineProperty(exports, "__esModule", { value: true });
  1913. /**
  1914. * Enums
  1915. * @hidden
  1916. */
  1917. var EComponentType;
  1918. (function (EComponentType) {
  1919. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  1920. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  1921. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  1922. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  1923. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  1924. })(EComponentType = exports.EComponentType || (exports.EComponentType = {}));
  1925. /** @hidden */
  1926. var EShaderType;
  1927. (function (EShaderType) {
  1928. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  1929. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  1930. })(EShaderType = exports.EShaderType || (exports.EShaderType = {}));
  1931. /** @hidden */
  1932. var EParameterType;
  1933. (function (EParameterType) {
  1934. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  1935. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  1936. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  1937. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  1938. EParameterType[EParameterType["INT"] = 5124] = "INT";
  1939. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  1940. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  1941. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  1942. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  1943. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  1944. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  1945. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  1946. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  1947. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  1948. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  1949. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  1950. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  1951. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  1952. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  1953. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  1954. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  1955. })(EParameterType = exports.EParameterType || (exports.EParameterType = {}));
  1956. /** @hidden */
  1957. var ETextureWrapMode;
  1958. (function (ETextureWrapMode) {
  1959. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  1960. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  1961. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  1962. })(ETextureWrapMode = exports.ETextureWrapMode || (exports.ETextureWrapMode = {}));
  1963. /** @hidden */
  1964. var ETextureFilterType;
  1965. (function (ETextureFilterType) {
  1966. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  1967. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  1968. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  1969. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  1970. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  1971. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  1972. })(ETextureFilterType = exports.ETextureFilterType || (exports.ETextureFilterType = {}));
  1973. /** @hidden */
  1974. var ETextureFormat;
  1975. (function (ETextureFormat) {
  1976. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  1977. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  1978. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  1979. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  1980. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  1981. })(ETextureFormat = exports.ETextureFormat || (exports.ETextureFormat = {}));
  1982. /** @hidden */
  1983. var ECullingType;
  1984. (function (ECullingType) {
  1985. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  1986. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  1987. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  1988. })(ECullingType = exports.ECullingType || (exports.ECullingType = {}));
  1989. /** @hidden */
  1990. var EBlendingFunction;
  1991. (function (EBlendingFunction) {
  1992. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  1993. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  1994. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  1995. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  1996. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  1997. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  1998. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  1999. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  2000. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  2001. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  2002. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  2003. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  2004. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  2005. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  2006. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  2007. })(EBlendingFunction = exports.EBlendingFunction || (exports.EBlendingFunction = {}));
  2008. /***/ }),
  2009. /***/ "./src/glTF/1.0/glTFLoaderUtils.ts":
  2010. /*!*****************************************!*\
  2011. !*** ./src/glTF/1.0/glTFLoaderUtils.ts ***!
  2012. \*****************************************/
  2013. /*! no static exports found */
  2014. /***/ (function(module, exports, __webpack_require__) {
  2015. "use strict";
  2016. Object.defineProperty(exports, "__esModule", { value: true });
  2017. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  2018. var glTFLoaderInterfaces_1 = __webpack_require__(/*! ./glTFLoaderInterfaces */ "./src/glTF/1.0/glTFLoaderInterfaces.ts");
  2019. /**
  2020. * Utils functions for GLTF
  2021. * @hidden
  2022. */
  2023. var GLTFUtils = /** @class */ (function () {
  2024. function GLTFUtils() {
  2025. }
  2026. /**
  2027. * Sets the given "parameter" matrix
  2028. * @param scene: the Scene object
  2029. * @param source: the source node where to pick the matrix
  2030. * @param parameter: the GLTF technique parameter
  2031. * @param uniformName: the name of the shader's uniform
  2032. * @param shaderMaterial: the shader material
  2033. */
  2034. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  2035. var mat = null;
  2036. if (parameter.semantic === "MODEL") {
  2037. mat = source.getWorldMatrix();
  2038. }
  2039. else if (parameter.semantic === "PROJECTION") {
  2040. mat = scene.getProjectionMatrix();
  2041. }
  2042. else if (parameter.semantic === "VIEW") {
  2043. mat = scene.getViewMatrix();
  2044. }
  2045. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  2046. mat = babylonjs_1.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  2047. }
  2048. else if (parameter.semantic === "MODELVIEW") {
  2049. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  2050. }
  2051. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  2052. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  2053. }
  2054. else if (parameter.semantic === "MODELINVERSE") {
  2055. mat = source.getWorldMatrix().invert();
  2056. }
  2057. else if (parameter.semantic === "VIEWINVERSE") {
  2058. mat = scene.getViewMatrix().invert();
  2059. }
  2060. else if (parameter.semantic === "PROJECTIONINVERSE") {
  2061. mat = scene.getProjectionMatrix().invert();
  2062. }
  2063. else if (parameter.semantic === "MODELVIEWINVERSE") {
  2064. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  2065. }
  2066. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  2067. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  2068. }
  2069. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  2070. mat = babylonjs_1.Matrix.Transpose(source.getWorldMatrix().invert());
  2071. }
  2072. else {
  2073. debugger;
  2074. }
  2075. if (mat) {
  2076. switch (parameter.type) {
  2077. case glTFLoaderInterfaces_1.EParameterType.FLOAT_MAT2:
  2078. shaderMaterial.setMatrix2x2(uniformName, babylonjs_1.Matrix.GetAsMatrix2x2(mat));
  2079. break;
  2080. case glTFLoaderInterfaces_1.EParameterType.FLOAT_MAT3:
  2081. shaderMaterial.setMatrix3x3(uniformName, babylonjs_1.Matrix.GetAsMatrix3x3(mat));
  2082. break;
  2083. case glTFLoaderInterfaces_1.EParameterType.FLOAT_MAT4:
  2084. shaderMaterial.setMatrix(uniformName, mat);
  2085. break;
  2086. default: break;
  2087. }
  2088. }
  2089. };
  2090. /**
  2091. * Sets the given "parameter" matrix
  2092. * @param shaderMaterial: the shader material
  2093. * @param uniform: the name of the shader's uniform
  2094. * @param value: the value of the uniform
  2095. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  2096. */
  2097. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  2098. switch (type) {
  2099. case glTFLoaderInterfaces_1.EParameterType.FLOAT:
  2100. shaderMaterial.setFloat(uniform, value);
  2101. return true;
  2102. case glTFLoaderInterfaces_1.EParameterType.FLOAT_VEC2:
  2103. shaderMaterial.setVector2(uniform, babylonjs_1.Vector2.FromArray(value));
  2104. return true;
  2105. case glTFLoaderInterfaces_1.EParameterType.FLOAT_VEC3:
  2106. shaderMaterial.setVector3(uniform, babylonjs_1.Vector3.FromArray(value));
  2107. return true;
  2108. case glTFLoaderInterfaces_1.EParameterType.FLOAT_VEC4:
  2109. shaderMaterial.setVector4(uniform, babylonjs_1.Vector4.FromArray(value));
  2110. return true;
  2111. default: return false;
  2112. }
  2113. };
  2114. /**
  2115. * Returns the wrap mode of the texture
  2116. * @param mode: the mode value
  2117. */
  2118. GLTFUtils.GetWrapMode = function (mode) {
  2119. switch (mode) {
  2120. case glTFLoaderInterfaces_1.ETextureWrapMode.CLAMP_TO_EDGE: return babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  2121. case glTFLoaderInterfaces_1.ETextureWrapMode.MIRRORED_REPEAT: return babylonjs_1.Texture.MIRROR_ADDRESSMODE;
  2122. case glTFLoaderInterfaces_1.ETextureWrapMode.REPEAT: return babylonjs_1.Texture.WRAP_ADDRESSMODE;
  2123. default: return babylonjs_1.Texture.WRAP_ADDRESSMODE;
  2124. }
  2125. };
  2126. /**
  2127. * Returns the byte stride giving an accessor
  2128. * @param accessor: the GLTF accessor objet
  2129. */
  2130. GLTFUtils.GetByteStrideFromType = function (accessor) {
  2131. // Needs this function since "byteStride" isn't requiered in glTF format
  2132. var type = accessor.type;
  2133. switch (type) {
  2134. case "VEC2": return 2;
  2135. case "VEC3": return 3;
  2136. case "VEC4": return 4;
  2137. case "MAT2": return 4;
  2138. case "MAT3": return 9;
  2139. case "MAT4": return 16;
  2140. default: return 1;
  2141. }
  2142. };
  2143. /**
  2144. * Returns the texture filter mode giving a mode value
  2145. * @param mode: the filter mode value
  2146. */
  2147. GLTFUtils.GetTextureFilterMode = function (mode) {
  2148. switch (mode) {
  2149. case glTFLoaderInterfaces_1.ETextureFilterType.LINEAR:
  2150. case glTFLoaderInterfaces_1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  2151. case glTFLoaderInterfaces_1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return babylonjs_1.Texture.TRILINEAR_SAMPLINGMODE;
  2152. case glTFLoaderInterfaces_1.ETextureFilterType.NEAREST:
  2153. case glTFLoaderInterfaces_1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return babylonjs_1.Texture.NEAREST_SAMPLINGMODE;
  2154. default: return babylonjs_1.Texture.BILINEAR_SAMPLINGMODE;
  2155. }
  2156. };
  2157. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  2158. var byteOffset = bufferView.byteOffset + byteOffset;
  2159. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  2160. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  2161. throw new Error("Buffer access is out of range");
  2162. }
  2163. var buffer = loadedBufferView.buffer;
  2164. byteOffset += loadedBufferView.byteOffset;
  2165. switch (componentType) {
  2166. case glTFLoaderInterfaces_1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  2167. case glTFLoaderInterfaces_1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  2168. case glTFLoaderInterfaces_1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  2169. case glTFLoaderInterfaces_1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  2170. default: return new Float32Array(buffer, byteOffset, byteLength);
  2171. }
  2172. };
  2173. /**
  2174. * Returns a buffer from its accessor
  2175. * @param gltfRuntime: the GLTF runtime
  2176. * @param accessor: the GLTF accessor
  2177. */
  2178. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  2179. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  2180. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  2181. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  2182. };
  2183. /**
  2184. * Decodes a buffer view into a string
  2185. * @param view: the buffer view
  2186. */
  2187. GLTFUtils.DecodeBufferToText = function (view) {
  2188. var result = "";
  2189. var length = view.byteLength;
  2190. for (var i = 0; i < length; ++i) {
  2191. result += String.fromCharCode(view[i]);
  2192. }
  2193. return result;
  2194. };
  2195. /**
  2196. * Returns the default material of gltf. Related to
  2197. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  2198. * @param scene: the Babylon.js scene
  2199. */
  2200. GLTFUtils.GetDefaultMaterial = function (scene) {
  2201. if (!GLTFUtils._DefaultMaterial) {
  2202. babylonjs_1.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  2203. "precision highp float;",
  2204. "",
  2205. "uniform mat4 worldView;",
  2206. "uniform mat4 projection;",
  2207. "",
  2208. "attribute vec3 position;",
  2209. "",
  2210. "void main(void)",
  2211. "{",
  2212. " gl_Position = projection * worldView * vec4(position, 1.0);",
  2213. "}"
  2214. ].join("\n");
  2215. babylonjs_1.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  2216. "precision highp float;",
  2217. "",
  2218. "uniform vec4 u_emission;",
  2219. "",
  2220. "void main(void)",
  2221. "{",
  2222. " gl_FragColor = u_emission;",
  2223. "}"
  2224. ].join("\n");
  2225. var shaderPath = {
  2226. vertex: "GLTFDefaultMaterial",
  2227. fragment: "GLTFDefaultMaterial"
  2228. };
  2229. var options = {
  2230. attributes: ["position"],
  2231. uniforms: ["worldView", "projection", "u_emission"],
  2232. samplers: new Array(),
  2233. needAlphaBlending: false
  2234. };
  2235. GLTFUtils._DefaultMaterial = new babylonjs_1.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  2236. GLTFUtils._DefaultMaterial.setColor4("u_emission", new babylonjs_1.Color4(0.5, 0.5, 0.5, 1.0));
  2237. }
  2238. return GLTFUtils._DefaultMaterial;
  2239. };
  2240. // The GLTF default material
  2241. GLTFUtils._DefaultMaterial = null;
  2242. return GLTFUtils;
  2243. }());
  2244. exports.GLTFUtils = GLTFUtils;
  2245. /***/ }),
  2246. /***/ "./src/glTF/1.0/glTFMaterialsCommonExtension.ts":
  2247. /*!******************************************************!*\
  2248. !*** ./src/glTF/1.0/glTFMaterialsCommonExtension.ts ***!
  2249. \******************************************************/
  2250. /*! no static exports found */
  2251. /***/ (function(module, exports, __webpack_require__) {
  2252. "use strict";
  2253. var __extends = (this && this.__extends) || (function () {
  2254. var extendStatics = function (d, b) {
  2255. extendStatics = Object.setPrototypeOf ||
  2256. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2257. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2258. return extendStatics(d, b);
  2259. }
  2260. return function (d, b) {
  2261. extendStatics(d, b);
  2262. function __() { this.constructor = d; }
  2263. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2264. };
  2265. })();
  2266. Object.defineProperty(exports, "__esModule", { value: true });
  2267. var _1 = __webpack_require__(/*! . */ "./src/glTF/1.0/index.ts");
  2268. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  2269. var glTFLoader_1 = __webpack_require__(/*! ./glTFLoader */ "./src/glTF/1.0/glTFLoader.ts");
  2270. /** @hidden */
  2271. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  2272. __extends(GLTFMaterialsCommonExtension, _super);
  2273. function GLTFMaterialsCommonExtension() {
  2274. return _super.call(this, "KHR_materials_common") || this;
  2275. }
  2276. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2277. if (!gltfRuntime.extensions) {
  2278. return false;
  2279. }
  2280. var extension = gltfRuntime.extensions[this.name];
  2281. if (!extension) {
  2282. return false;
  2283. }
  2284. // Create lights
  2285. var lights = extension.lights;
  2286. if (lights) {
  2287. for (var thing in lights) {
  2288. var light = lights[thing];
  2289. switch (light.type) {
  2290. case "ambient":
  2291. var ambientLight = new babylonjs_1.HemisphericLight(light.name, new babylonjs_1.Vector3(0, 1, 0), gltfRuntime.scene);
  2292. var ambient = light.ambient;
  2293. if (ambient) {
  2294. ambientLight.diffuse = babylonjs_1.Color3.FromArray(ambient.color || [1, 1, 1]);
  2295. }
  2296. break;
  2297. case "point":
  2298. var pointLight = new babylonjs_1.PointLight(light.name, new babylonjs_1.Vector3(10, 10, 10), gltfRuntime.scene);
  2299. var point = light.point;
  2300. if (point) {
  2301. pointLight.diffuse = babylonjs_1.Color3.FromArray(point.color || [1, 1, 1]);
  2302. }
  2303. break;
  2304. case "directional":
  2305. var dirLight = new babylonjs_1.DirectionalLight(light.name, new babylonjs_1.Vector3(0, -1, 0), gltfRuntime.scene);
  2306. var directional = light.directional;
  2307. if (directional) {
  2308. dirLight.diffuse = babylonjs_1.Color3.FromArray(directional.color || [1, 1, 1]);
  2309. }
  2310. break;
  2311. case "spot":
  2312. var spot = light.spot;
  2313. if (spot) {
  2314. var spotLight = new babylonjs_1.SpotLight(light.name, new babylonjs_1.Vector3(0, 10, 0), new babylonjs_1.Vector3(0, -1, 0), spot.fallOffAngle || Math.PI, spot.fallOffExponent || 0.0, gltfRuntime.scene);
  2315. spotLight.diffuse = babylonjs_1.Color3.FromArray(spot.color || [1, 1, 1]);
  2316. }
  2317. break;
  2318. default:
  2319. babylonjs_1.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  2320. break;
  2321. }
  2322. }
  2323. }
  2324. return false;
  2325. };
  2326. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2327. var material = gltfRuntime.materials[id];
  2328. if (!material || !material.extensions) {
  2329. return false;
  2330. }
  2331. var extension = material.extensions[this.name];
  2332. if (!extension) {
  2333. return false;
  2334. }
  2335. var standardMaterial = new babylonjs_1.StandardMaterial(id, gltfRuntime.scene);
  2336. standardMaterial.sideOrientation = babylonjs_1.Material.CounterClockWiseSideOrientation;
  2337. if (extension.technique === "CONSTANT") {
  2338. standardMaterial.disableLighting = true;
  2339. }
  2340. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  2341. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  2342. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  2343. // Ambient
  2344. if (typeof extension.values.ambient === "string") {
  2345. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  2346. }
  2347. else {
  2348. standardMaterial.ambientColor = babylonjs_1.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  2349. }
  2350. // Diffuse
  2351. if (typeof extension.values.diffuse === "string") {
  2352. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  2353. }
  2354. else {
  2355. standardMaterial.diffuseColor = babylonjs_1.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  2356. }
  2357. // Emission
  2358. if (typeof extension.values.emission === "string") {
  2359. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  2360. }
  2361. else {
  2362. standardMaterial.emissiveColor = babylonjs_1.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  2363. }
  2364. // Specular
  2365. if (typeof extension.values.specular === "string") {
  2366. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  2367. }
  2368. else {
  2369. standardMaterial.specularColor = babylonjs_1.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  2370. }
  2371. return true;
  2372. };
  2373. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  2374. // Create buffer from texture url
  2375. _1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  2376. // Create texture from buffer
  2377. _1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  2378. }, onError);
  2379. };
  2380. return GLTFMaterialsCommonExtension;
  2381. }(_1.GLTFLoaderExtension));
  2382. exports.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  2383. glTFLoader_1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  2384. /***/ }),
  2385. /***/ "./src/glTF/1.0/index.ts":
  2386. /*!*******************************!*\
  2387. !*** ./src/glTF/1.0/index.ts ***!
  2388. \*******************************/
  2389. /*! no static exports found */
  2390. /***/ (function(module, exports, __webpack_require__) {
  2391. "use strict";
  2392. function __export(m) {
  2393. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  2394. }
  2395. Object.defineProperty(exports, "__esModule", { value: true });
  2396. __export(__webpack_require__(/*! ./glTFBinaryExtension */ "./src/glTF/1.0/glTFBinaryExtension.ts"));
  2397. __export(__webpack_require__(/*! ./glTFLoader */ "./src/glTF/1.0/glTFLoader.ts"));
  2398. __export(__webpack_require__(/*! ./glTFLoaderExtension */ "./src/glTF/1.0/glTFLoaderExtension.ts"));
  2399. __export(__webpack_require__(/*! ./glTFLoaderInterfaces */ "./src/glTF/1.0/glTFLoaderInterfaces.ts"));
  2400. __export(__webpack_require__(/*! ./glTFLoaderUtils */ "./src/glTF/1.0/glTFLoaderUtils.ts"));
  2401. __export(__webpack_require__(/*! ./glTFMaterialsCommonExtension */ "./src/glTF/1.0/glTFMaterialsCommonExtension.ts"));
  2402. /***/ }),
  2403. /***/ "./src/glTF/glTFFileLoader.ts":
  2404. /*!************************************!*\
  2405. !*** ./src/glTF/glTFFileLoader.ts ***!
  2406. \************************************/
  2407. /*! no static exports found */
  2408. /***/ (function(module, exports, __webpack_require__) {
  2409. "use strict";
  2410. Object.defineProperty(exports, "__esModule", { value: true });
  2411. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  2412. /**
  2413. * Mode that determines the coordinate system to use.
  2414. */
  2415. var GLTFLoaderCoordinateSystemMode;
  2416. (function (GLTFLoaderCoordinateSystemMode) {
  2417. /**
  2418. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  2419. */
  2420. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  2421. /**
  2422. * Sets the useRightHandedSystem flag on the scene.
  2423. */
  2424. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  2425. })(GLTFLoaderCoordinateSystemMode = exports.GLTFLoaderCoordinateSystemMode || (exports.GLTFLoaderCoordinateSystemMode = {}));
  2426. /**
  2427. * Mode that determines what animations will start.
  2428. */
  2429. var GLTFLoaderAnimationStartMode;
  2430. (function (GLTFLoaderAnimationStartMode) {
  2431. /**
  2432. * No animation will start.
  2433. */
  2434. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  2435. /**
  2436. * The first animation will start.
  2437. */
  2438. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  2439. /**
  2440. * All animations will start.
  2441. */
  2442. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  2443. })(GLTFLoaderAnimationStartMode = exports.GLTFLoaderAnimationStartMode || (exports.GLTFLoaderAnimationStartMode = {}));
  2444. /**
  2445. * Loader state.
  2446. */
  2447. var GLTFLoaderState;
  2448. (function (GLTFLoaderState) {
  2449. /**
  2450. * The asset is loading.
  2451. */
  2452. GLTFLoaderState[GLTFLoaderState["LOADING"] = 0] = "LOADING";
  2453. /**
  2454. * The asset is ready for rendering.
  2455. */
  2456. GLTFLoaderState[GLTFLoaderState["READY"] = 1] = "READY";
  2457. /**
  2458. * The asset is completely loaded.
  2459. */
  2460. GLTFLoaderState[GLTFLoaderState["COMPLETE"] = 2] = "COMPLETE";
  2461. })(GLTFLoaderState = exports.GLTFLoaderState || (exports.GLTFLoaderState = {}));
  2462. /**
  2463. * File loader for loading glTF files into a scene.
  2464. */
  2465. var GLTFFileLoader = /** @class */ (function () {
  2466. function GLTFFileLoader() {
  2467. // --------------
  2468. // Common options
  2469. // --------------
  2470. /**
  2471. * Raised when the asset has been parsed
  2472. */
  2473. this.onParsedObservable = new babylonjs_1.Observable();
  2474. // ----------
  2475. // V2 options
  2476. // ----------
  2477. /**
  2478. * The coordinate system mode. Defaults to AUTO.
  2479. */
  2480. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  2481. /**
  2482. * The animation start mode. Defaults to FIRST.
  2483. */
  2484. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  2485. /**
  2486. * Defines if the loader should compile materials before raising the success callback. Defaults to false.
  2487. */
  2488. this.compileMaterials = false;
  2489. /**
  2490. * Defines if the loader should also compile materials with clip planes. Defaults to false.
  2491. */
  2492. this.useClipPlane = false;
  2493. /**
  2494. * Defines if the loader should compile shadow generators before raising the success callback. Defaults to false.
  2495. */
  2496. this.compileShadowGenerators = false;
  2497. /**
  2498. * Defines if the Alpha blended materials are only applied as coverage.
  2499. * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials.
  2500. * If true, no extra effects are applied to transparent pixels.
  2501. */
  2502. this.transparencyAsCoverage = false;
  2503. /**
  2504. * Function called before loading a url referenced by the asset.
  2505. */
  2506. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  2507. /**
  2508. * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  2509. */
  2510. this.onMeshLoadedObservable = new babylonjs_1.Observable();
  2511. /**
  2512. * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.
  2513. */
  2514. this.onTextureLoadedObservable = new babylonjs_1.Observable();
  2515. /**
  2516. * Observable raised when the loader creates a material after parsing the glTF properties of the material.
  2517. */
  2518. this.onMaterialLoadedObservable = new babylonjs_1.Observable();
  2519. /**
  2520. * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.
  2521. */
  2522. this.onCameraLoadedObservable = new babylonjs_1.Observable();
  2523. /**
  2524. * Observable raised when the asset is completely loaded, immediately before the loader is disposed.
  2525. * For assets with LODs, raised when all of the LODs are complete.
  2526. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  2527. */
  2528. this.onCompleteObservable = new babylonjs_1.Observable();
  2529. /**
  2530. * Observable raised when an error occurs.
  2531. */
  2532. this.onErrorObservable = new babylonjs_1.Observable();
  2533. /**
  2534. * Observable raised after the loader is disposed.
  2535. */
  2536. this.onDisposeObservable = new babylonjs_1.Observable();
  2537. /**
  2538. * Observable raised after a loader extension is created.
  2539. * Set additional options for a loader extension in this event.
  2540. */
  2541. this.onExtensionLoadedObservable = new babylonjs_1.Observable();
  2542. /**
  2543. * Defines if the loader should validate the asset.
  2544. */
  2545. this.validate = false;
  2546. /**
  2547. * Observable raised after validation when validate is set to true. The event data is the result of the validation.
  2548. */
  2549. this.onValidatedObservable = new babylonjs_1.Observable();
  2550. this._loader = null;
  2551. /**
  2552. * Name of the loader ("gltf")
  2553. */
  2554. this.name = "gltf";
  2555. /**
  2556. * Supported file extensions of the loader (.gltf, .glb)
  2557. */
  2558. this.extensions = {
  2559. ".gltf": { isBinary: false },
  2560. ".glb": { isBinary: true }
  2561. };
  2562. this._logIndentLevel = 0;
  2563. this._loggingEnabled = false;
  2564. /** @hidden */
  2565. this._log = this._logDisabled;
  2566. this._capturePerformanceCounters = false;
  2567. /** @hidden */
  2568. this._startPerformanceCounter = this._startPerformanceCounterDisabled;
  2569. /** @hidden */
  2570. this._endPerformanceCounter = this._endPerformanceCounterDisabled;
  2571. }
  2572. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  2573. /**
  2574. * Raised when the asset has been parsed
  2575. */
  2576. set: function (callback) {
  2577. if (this._onParsedObserver) {
  2578. this.onParsedObservable.remove(this._onParsedObserver);
  2579. }
  2580. this._onParsedObserver = this.onParsedObservable.add(callback);
  2581. },
  2582. enumerable: true,
  2583. configurable: true
  2584. });
  2585. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  2586. /**
  2587. * Callback raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  2588. */
  2589. set: function (callback) {
  2590. if (this._onMeshLoadedObserver) {
  2591. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  2592. }
  2593. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  2594. },
  2595. enumerable: true,
  2596. configurable: true
  2597. });
  2598. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  2599. /**
  2600. * Callback raised when the loader creates a texture after parsing the glTF properties of the texture.
  2601. */
  2602. set: function (callback) {
  2603. if (this._onTextureLoadedObserver) {
  2604. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  2605. }
  2606. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  2607. },
  2608. enumerable: true,
  2609. configurable: true
  2610. });
  2611. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  2612. /**
  2613. * Callback raised when the loader creates a material after parsing the glTF properties of the material.
  2614. */
  2615. set: function (callback) {
  2616. if (this._onMaterialLoadedObserver) {
  2617. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  2618. }
  2619. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  2620. },
  2621. enumerable: true,
  2622. configurable: true
  2623. });
  2624. Object.defineProperty(GLTFFileLoader.prototype, "onCameraLoaded", {
  2625. /**
  2626. * Callback raised when the loader creates a camera after parsing the glTF properties of the camera.
  2627. */
  2628. set: function (callback) {
  2629. if (this._onCameraLoadedObserver) {
  2630. this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver);
  2631. }
  2632. this._onCameraLoadedObserver = this.onCameraLoadedObservable.add(callback);
  2633. },
  2634. enumerable: true,
  2635. configurable: true
  2636. });
  2637. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  2638. /**
  2639. * Callback raised when the asset is completely loaded, immediately before the loader is disposed.
  2640. * For assets with LODs, raised when all of the LODs are complete.
  2641. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  2642. */
  2643. set: function (callback) {
  2644. if (this._onCompleteObserver) {
  2645. this.onCompleteObservable.remove(this._onCompleteObserver);
  2646. }
  2647. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  2648. },
  2649. enumerable: true,
  2650. configurable: true
  2651. });
  2652. Object.defineProperty(GLTFFileLoader.prototype, "onError", {
  2653. /**
  2654. * Callback raised when an error occurs.
  2655. */
  2656. set: function (callback) {
  2657. if (this._onErrorObserver) {
  2658. this.onErrorObservable.remove(this._onErrorObserver);
  2659. }
  2660. this._onErrorObserver = this.onErrorObservable.add(callback);
  2661. },
  2662. enumerable: true,
  2663. configurable: true
  2664. });
  2665. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  2666. /**
  2667. * Callback raised after the loader is disposed.
  2668. */
  2669. set: function (callback) {
  2670. if (this._onDisposeObserver) {
  2671. this.onDisposeObservable.remove(this._onDisposeObserver);
  2672. }
  2673. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  2674. },
  2675. enumerable: true,
  2676. configurable: true
  2677. });
  2678. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  2679. /**
  2680. * Callback raised after a loader extension is created.
  2681. */
  2682. set: function (callback) {
  2683. if (this._onExtensionLoadedObserver) {
  2684. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  2685. }
  2686. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  2687. },
  2688. enumerable: true,
  2689. configurable: true
  2690. });
  2691. Object.defineProperty(GLTFFileLoader.prototype, "loggingEnabled", {
  2692. /**
  2693. * Defines if the loader logging is enabled.
  2694. */
  2695. get: function () {
  2696. return this._loggingEnabled;
  2697. },
  2698. set: function (value) {
  2699. if (this._loggingEnabled === value) {
  2700. return;
  2701. }
  2702. this._loggingEnabled = value;
  2703. if (this._loggingEnabled) {
  2704. this._log = this._logEnabled;
  2705. }
  2706. else {
  2707. this._log = this._logDisabled;
  2708. }
  2709. },
  2710. enumerable: true,
  2711. configurable: true
  2712. });
  2713. Object.defineProperty(GLTFFileLoader.prototype, "capturePerformanceCounters", {
  2714. /**
  2715. * Defines if the loader should capture performance counters.
  2716. */
  2717. get: function () {
  2718. return this._capturePerformanceCounters;
  2719. },
  2720. set: function (value) {
  2721. if (this._capturePerformanceCounters === value) {
  2722. return;
  2723. }
  2724. this._capturePerformanceCounters = value;
  2725. if (this._capturePerformanceCounters) {
  2726. this._startPerformanceCounter = this._startPerformanceCounterEnabled;
  2727. this._endPerformanceCounter = this._endPerformanceCounterEnabled;
  2728. }
  2729. else {
  2730. this._startPerformanceCounter = this._startPerformanceCounterDisabled;
  2731. this._endPerformanceCounter = this._endPerformanceCounterDisabled;
  2732. }
  2733. },
  2734. enumerable: true,
  2735. configurable: true
  2736. });
  2737. Object.defineProperty(GLTFFileLoader.prototype, "onValidated", {
  2738. /**
  2739. * Callback raised after a loader extension is created.
  2740. */
  2741. set: function (callback) {
  2742. if (this._onValidatedObserver) {
  2743. this.onValidatedObservable.remove(this._onValidatedObserver);
  2744. }
  2745. this._onValidatedObserver = this.onValidatedObservable.add(callback);
  2746. },
  2747. enumerable: true,
  2748. configurable: true
  2749. });
  2750. /**
  2751. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  2752. */
  2753. GLTFFileLoader.prototype.dispose = function () {
  2754. if (this._loader) {
  2755. this._loader.dispose();
  2756. this._loader = null;
  2757. }
  2758. this._clear();
  2759. this.onDisposeObservable.notifyObservers(undefined);
  2760. this.onDisposeObservable.clear();
  2761. };
  2762. /** @hidden */
  2763. GLTFFileLoader.prototype._clear = function () {
  2764. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  2765. this.onMeshLoadedObservable.clear();
  2766. this.onTextureLoadedObservable.clear();
  2767. this.onMaterialLoadedObservable.clear();
  2768. this.onCameraLoadedObservable.clear();
  2769. this.onCompleteObservable.clear();
  2770. this.onExtensionLoadedObservable.clear();
  2771. };
  2772. /**
  2773. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  2774. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  2775. * @param scene the scene the meshes should be added to
  2776. * @param data the glTF data to load
  2777. * @param rootUrl root url to load from
  2778. * @param onProgress event that fires when loading progress has occured
  2779. * @param fileName Defines the name of the file to load
  2780. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  2781. */
  2782. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress, fileName) {
  2783. var _this = this;
  2784. return this._parseAsync(scene, data, rootUrl, fileName).then(function (loaderData) {
  2785. _this._log("Loading " + (fileName || ""));
  2786. _this._loader = _this._getLoader(loaderData);
  2787. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress, fileName);
  2788. });
  2789. };
  2790. /**
  2791. * Imports all objects from the loaded glTF data and adds them to the scene
  2792. * @param scene the scene the objects should be added to
  2793. * @param data the glTF data to load
  2794. * @param rootUrl root url to load from
  2795. * @param onProgress event that fires when loading progress has occured
  2796. * @param fileName Defines the name of the file to load
  2797. * @returns a promise which completes when objects have been loaded to the scene
  2798. */
  2799. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress, fileName) {
  2800. var _this = this;
  2801. return this._parseAsync(scene, data, rootUrl, fileName).then(function (loaderData) {
  2802. _this._log("Loading " + (fileName || ""));
  2803. _this._loader = _this._getLoader(loaderData);
  2804. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress, fileName);
  2805. });
  2806. };
  2807. /**
  2808. * Load into an asset container.
  2809. * @param scene The scene to load into
  2810. * @param data The data to import
  2811. * @param rootUrl The root url for scene and resources
  2812. * @param onProgress The callback when the load progresses
  2813. * @param fileName Defines the name of the file to load
  2814. * @returns The loaded asset container
  2815. */
  2816. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress, fileName) {
  2817. var _this = this;
  2818. return this._parseAsync(scene, data, rootUrl, fileName).then(function (loaderData) {
  2819. _this._log("Loading " + (fileName || ""));
  2820. _this._loader = _this._getLoader(loaderData);
  2821. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress, fileName).then(function (result) {
  2822. var container = new babylonjs_1.AssetContainer(scene);
  2823. Array.prototype.push.apply(container.meshes, result.meshes);
  2824. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  2825. Array.prototype.push.apply(container.skeletons, result.skeletons);
  2826. Array.prototype.push.apply(container.animationGroups, result.animationGroups);
  2827. container.removeAllFromScene();
  2828. return container;
  2829. });
  2830. });
  2831. };
  2832. /**
  2833. * If the data string can be loaded directly.
  2834. * @param data string contianing the file data
  2835. * @returns if the data can be loaded directly
  2836. */
  2837. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  2838. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  2839. };
  2840. /**
  2841. * Instantiates a glTF file loader plugin.
  2842. * @returns the created plugin
  2843. */
  2844. GLTFFileLoader.prototype.createPlugin = function () {
  2845. return new GLTFFileLoader();
  2846. };
  2847. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  2848. /**
  2849. * The loader state or null if the loader is not active.
  2850. */
  2851. get: function () {
  2852. return this._loader ? this._loader.state : null;
  2853. },
  2854. enumerable: true,
  2855. configurable: true
  2856. });
  2857. /**
  2858. * Returns a promise that resolves when the asset is completely loaded.
  2859. * @returns a promise that resolves when the asset is completely loaded.
  2860. */
  2861. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  2862. var _this = this;
  2863. return new Promise(function (resolve, reject) {
  2864. _this.onCompleteObservable.addOnce(function () {
  2865. resolve();
  2866. });
  2867. _this.onErrorObservable.addOnce(function (reason) {
  2868. reject(reason);
  2869. });
  2870. });
  2871. };
  2872. GLTFFileLoader.prototype._parseAsync = function (scene, data, rootUrl, fileName) {
  2873. var _this = this;
  2874. return Promise.resolve().then(function () {
  2875. var unpacked = (data instanceof ArrayBuffer) ? _this._unpackBinary(data) : { json: data, bin: null };
  2876. return _this._validateAsync(scene, unpacked.json, rootUrl, fileName).then(function () {
  2877. _this._startPerformanceCounter("Parse JSON");
  2878. _this._log("JSON length: " + unpacked.json.length);
  2879. var loaderData = {
  2880. json: JSON.parse(unpacked.json),
  2881. bin: unpacked.bin
  2882. };
  2883. _this._endPerformanceCounter("Parse JSON");
  2884. _this.onParsedObservable.notifyObservers(loaderData);
  2885. _this.onParsedObservable.clear();
  2886. return loaderData;
  2887. });
  2888. });
  2889. };
  2890. GLTFFileLoader.prototype._validateAsync = function (scene, json, rootUrl, fileName) {
  2891. var _this = this;
  2892. if (!this.validate || typeof GLTFValidator === "undefined") {
  2893. return Promise.resolve();
  2894. }
  2895. this._startPerformanceCounter("Validate JSON");
  2896. var options = {
  2897. externalResourceFunction: function (uri) {
  2898. return _this.preprocessUrlAsync(rootUrl + uri)
  2899. .then(function (url) { return scene._loadFileAsync(url, true, true); })
  2900. .then(function (data) { return new Uint8Array(data); });
  2901. }
  2902. };
  2903. if (fileName && fileName.substr(0, 5) !== "data:") {
  2904. options.uri = (rootUrl === "file:" ? fileName : "" + rootUrl + fileName);
  2905. }
  2906. return GLTFValidator.validateString(json, options).then(function (result) {
  2907. _this._endPerformanceCounter("Validate JSON");
  2908. _this.onValidatedObservable.notifyObservers(result);
  2909. _this.onValidatedObservable.clear();
  2910. }, function (reason) {
  2911. _this._endPerformanceCounter("Validate JSON");
  2912. babylonjs_1.Tools.Warn("Failed to validate: " + reason);
  2913. _this.onValidatedObservable.clear();
  2914. });
  2915. };
  2916. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  2917. var asset = loaderData.json.asset || {};
  2918. this._log("Asset version: " + asset.version);
  2919. asset.minVersion && this._log("Asset minimum version: " + asset.minVersion);
  2920. asset.generator && this._log("Asset generator: " + asset.generator);
  2921. var version = GLTFFileLoader._parseVersion(asset.version);
  2922. if (!version) {
  2923. throw new Error("Invalid version: " + asset.version);
  2924. }
  2925. if (asset.minVersion !== undefined) {
  2926. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  2927. if (!minVersion) {
  2928. throw new Error("Invalid minimum version: " + asset.minVersion);
  2929. }
  2930. if (GLTFFileLoader._compareVersion(minVersion, { major: 2, minor: 0 }) > 0) {
  2931. throw new Error("Incompatible minimum version: " + asset.minVersion);
  2932. }
  2933. }
  2934. var createLoaders = {
  2935. 1: GLTFFileLoader._CreateGLTF1Loader,
  2936. 2: GLTFFileLoader._CreateGLTF2Loader
  2937. };
  2938. var createLoader = createLoaders[version.major];
  2939. if (!createLoader) {
  2940. throw new Error("Unsupported version: " + asset.version);
  2941. }
  2942. return createLoader(this);
  2943. };
  2944. GLTFFileLoader.prototype._unpackBinary = function (data) {
  2945. this._startPerformanceCounter("Unpack binary");
  2946. this._log("Binary length: " + data.byteLength);
  2947. var Binary = {
  2948. Magic: 0x46546C67
  2949. };
  2950. var binaryReader = new BinaryReader(data);
  2951. var magic = binaryReader.readUint32();
  2952. if (magic !== Binary.Magic) {
  2953. throw new Error("Unexpected magic: " + magic);
  2954. }
  2955. var version = binaryReader.readUint32();
  2956. if (this.loggingEnabled) {
  2957. this._log("Binary version: " + version);
  2958. }
  2959. var unpacked;
  2960. switch (version) {
  2961. case 1: {
  2962. unpacked = this._unpackBinaryV1(binaryReader);
  2963. break;
  2964. }
  2965. case 2: {
  2966. unpacked = this._unpackBinaryV2(binaryReader);
  2967. break;
  2968. }
  2969. default: {
  2970. throw new Error("Unsupported version: " + version);
  2971. }
  2972. }
  2973. this._endPerformanceCounter("Unpack binary");
  2974. return unpacked;
  2975. };
  2976. GLTFFileLoader.prototype._unpackBinaryV1 = function (binaryReader) {
  2977. var ContentFormat = {
  2978. JSON: 0
  2979. };
  2980. var length = binaryReader.readUint32();
  2981. if (length != binaryReader.getLength()) {
  2982. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  2983. }
  2984. var contentLength = binaryReader.readUint32();
  2985. var contentFormat = binaryReader.readUint32();
  2986. var content;
  2987. switch (contentFormat) {
  2988. case ContentFormat.JSON: {
  2989. content = GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength));
  2990. break;
  2991. }
  2992. default: {
  2993. throw new Error("Unexpected content format: " + contentFormat);
  2994. }
  2995. }
  2996. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  2997. var body = binaryReader.readUint8Array(bytesRemaining);
  2998. return {
  2999. json: content,
  3000. bin: body
  3001. };
  3002. };
  3003. GLTFFileLoader.prototype._unpackBinaryV2 = function (binaryReader) {
  3004. var ChunkFormat = {
  3005. JSON: 0x4E4F534A,
  3006. BIN: 0x004E4942
  3007. };
  3008. var length = binaryReader.readUint32();
  3009. if (length !== binaryReader.getLength()) {
  3010. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  3011. }
  3012. // JSON chunk
  3013. var chunkLength = binaryReader.readUint32();
  3014. var chunkFormat = binaryReader.readUint32();
  3015. if (chunkFormat !== ChunkFormat.JSON) {
  3016. throw new Error("First chunk format is not JSON");
  3017. }
  3018. var json = GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength));
  3019. // Look for BIN chunk
  3020. var bin = null;
  3021. while (binaryReader.getPosition() < binaryReader.getLength()) {
  3022. var chunkLength_1 = binaryReader.readUint32();
  3023. var chunkFormat_1 = binaryReader.readUint32();
  3024. switch (chunkFormat_1) {
  3025. case ChunkFormat.JSON: {
  3026. throw new Error("Unexpected JSON chunk");
  3027. }
  3028. case ChunkFormat.BIN: {
  3029. bin = binaryReader.readUint8Array(chunkLength_1);
  3030. break;
  3031. }
  3032. default: {
  3033. // ignore unrecognized chunkFormat
  3034. binaryReader.skipBytes(chunkLength_1);
  3035. break;
  3036. }
  3037. }
  3038. }
  3039. return {
  3040. json: json,
  3041. bin: bin
  3042. };
  3043. };
  3044. GLTFFileLoader._parseVersion = function (version) {
  3045. if (version === "1.0" || version === "1.0.1") {
  3046. return {
  3047. major: 1,
  3048. minor: 0
  3049. };
  3050. }
  3051. var match = (version + "").match(/^(\d+)\.(\d+)/);
  3052. if (!match) {
  3053. return null;
  3054. }
  3055. return {
  3056. major: parseInt(match[1]),
  3057. minor: parseInt(match[2])
  3058. };
  3059. };
  3060. GLTFFileLoader._compareVersion = function (a, b) {
  3061. if (a.major > b.major) {
  3062. return 1;
  3063. }
  3064. if (a.major < b.major) {
  3065. return -1;
  3066. }
  3067. if (a.minor > b.minor) {
  3068. return 1;
  3069. }
  3070. if (a.minor < b.minor) {
  3071. return -1;
  3072. }
  3073. return 0;
  3074. };
  3075. GLTFFileLoader._decodeBufferToText = function (buffer) {
  3076. var result = "";
  3077. var length = buffer.byteLength;
  3078. for (var i = 0; i < length; i++) {
  3079. result += String.fromCharCode(buffer[i]);
  3080. }
  3081. return result;
  3082. };
  3083. /** @hidden */
  3084. GLTFFileLoader.prototype._logOpen = function (message) {
  3085. this._log(message);
  3086. this._logIndentLevel++;
  3087. };
  3088. /** @hidden */
  3089. GLTFFileLoader.prototype._logClose = function () {
  3090. --this._logIndentLevel;
  3091. };
  3092. GLTFFileLoader.prototype._logEnabled = function (message) {
  3093. var spaces = GLTFFileLoader._logSpaces.substr(0, this._logIndentLevel * 2);
  3094. babylonjs_1.Tools.Log("" + spaces + message);
  3095. };
  3096. GLTFFileLoader.prototype._logDisabled = function (message) {
  3097. };
  3098. GLTFFileLoader.prototype._startPerformanceCounterEnabled = function (counterName) {
  3099. babylonjs_1.Tools.StartPerformanceCounter(counterName);
  3100. };
  3101. GLTFFileLoader.prototype._startPerformanceCounterDisabled = function (counterName) {
  3102. };
  3103. GLTFFileLoader.prototype._endPerformanceCounterEnabled = function (counterName) {
  3104. babylonjs_1.Tools.EndPerformanceCounter(counterName);
  3105. };
  3106. GLTFFileLoader.prototype._endPerformanceCounterDisabled = function (counterName) {
  3107. };
  3108. // ----------
  3109. // V1 options
  3110. // ----------
  3111. /**
  3112. * 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.
  3113. * Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled.
  3114. * Defaults to true.
  3115. * @hidden
  3116. */
  3117. GLTFFileLoader.IncrementalLoading = true;
  3118. /**
  3119. * Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters.
  3120. * Defaults to false. See https://en.wikipedia.org/wiki/Homogeneous_coordinates.
  3121. * @hidden
  3122. */
  3123. GLTFFileLoader.HomogeneousCoordinates = false;
  3124. GLTFFileLoader._logSpaces = " ";
  3125. return GLTFFileLoader;
  3126. }());
  3127. exports.GLTFFileLoader = GLTFFileLoader;
  3128. var BinaryReader = /** @class */ (function () {
  3129. function BinaryReader(arrayBuffer) {
  3130. this._arrayBuffer = arrayBuffer;
  3131. this._dataView = new DataView(arrayBuffer);
  3132. this._byteOffset = 0;
  3133. }
  3134. BinaryReader.prototype.getPosition = function () {
  3135. return this._byteOffset;
  3136. };
  3137. BinaryReader.prototype.getLength = function () {
  3138. return this._arrayBuffer.byteLength;
  3139. };
  3140. BinaryReader.prototype.readUint32 = function () {
  3141. var value = this._dataView.getUint32(this._byteOffset, true);
  3142. this._byteOffset += 4;
  3143. return value;
  3144. };
  3145. BinaryReader.prototype.readUint8Array = function (length) {
  3146. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  3147. this._byteOffset += length;
  3148. return value;
  3149. };
  3150. BinaryReader.prototype.skipBytes = function (length) {
  3151. this._byteOffset += length;
  3152. };
  3153. return BinaryReader;
  3154. }());
  3155. if (babylonjs_1.SceneLoader) {
  3156. babylonjs_1.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  3157. }
  3158. /***/ }),
  3159. /***/ "babylonjs":
  3160. /*!****************************************************************************************************!*\
  3161. !*** external {"root":"BABYLON","commonjs":"babylonjs","commonjs2":"babylonjs","amd":"babylonjs"} ***!
  3162. \****************************************************************************************************/
  3163. /*! no static exports found */
  3164. /***/ (function(module, exports) {
  3165. module.exports = __WEBPACK_EXTERNAL_MODULE_babylonjs__;
  3166. /***/ })
  3167. /******/ });
  3168. });
  3169. //# sourceMappingURL=babylon.glTF1FileLoader.js.map