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 LoadersV1 = __webpack_require__(/*! ../src/glTF/1.0 */ "./src/glTF/1.0/index.ts");
  135. /**
  136. * This is the entry point for the UMD module.
  137. * The entry point for a future ESM package should be index.ts
  138. */
  139. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : undefined);
  140. if (typeof globalObject !== "undefined") {
  141. globalObject.BABYLON = globalObject.BABYLON || {};
  142. for (var key in FileLoader) {
  143. globalObject.BABYLON[key] = FileLoader[key];
  144. }
  145. globalObject.BABYLON.GLTF1 = globalObject.BABYLON.GLTF1 || {};
  146. for (var key in LoadersV1) {
  147. globalObject.BABYLON.GLTF1[key] = LoadersV1[key];
  148. }
  149. }
  150. __export(__webpack_require__(/*! ../src/glTF/glTFFileLoader */ "./src/glTF/glTFFileLoader.ts"));
  151. __export(__webpack_require__(/*! ../src/glTF/1.0 */ "./src/glTF/1.0/index.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/glTF1Loader.ts":
  155. /*!*************************************!*\
  156. !*** ./src/glTF/1.0/glTF1Loader.ts ***!
  157. \*************************************/
  158. /*! no static exports found */
  159. /***/ (function(module, exports, __webpack_require__) {
  160. "use strict";
  161. Object.defineProperty(exports, "__esModule", { value: true });
  162. var glTFLoaderInterfaces_1 = __webpack_require__(/*! ./glTFLoaderInterfaces */ "./src/glTF/1.0/glTFLoaderInterfaces.ts");
  163. var glTFLoaderUtils_1 = __webpack_require__(/*! ./glTFLoaderUtils */ "./src/glTF/1.0/glTFLoaderUtils.ts");
  164. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  165. var glTFFileLoader_1 = __webpack_require__(/*! ../glTFFileLoader */ "./src/glTF/glTFFileLoader.ts");
  166. var glTFLoaderExtension_1 = __webpack_require__(/*! ./glTFLoaderExtension */ "./src/glTF/1.0/glTFLoaderExtension.ts");
  167. /**
  168. * Tokenizer. Used for shaders compatibility
  169. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  170. */
  171. var ETokenType;
  172. (function (ETokenType) {
  173. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  174. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  175. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  176. })(ETokenType || (ETokenType = {}));
  177. var Tokenizer = /** @class */ (function () {
  178. function Tokenizer(toParse) {
  179. this._pos = 0;
  180. this.currentToken = ETokenType.UNKNOWN;
  181. this.currentIdentifier = "";
  182. this.currentString = "";
  183. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  184. this._toParse = toParse;
  185. this._maxPos = toParse.length;
  186. }
  187. Tokenizer.prototype.getNextToken = function () {
  188. if (this.isEnd()) {
  189. return ETokenType.END_OF_INPUT;
  190. }
  191. this.currentString = this.read();
  192. this.currentToken = ETokenType.UNKNOWN;
  193. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  194. this.currentToken = ETokenType.IDENTIFIER;
  195. this.currentIdentifier = this.currentString;
  196. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  197. this.currentIdentifier += this.currentString;
  198. this.forward();
  199. }
  200. }
  201. return this.currentToken;
  202. };
  203. Tokenizer.prototype.peek = function () {
  204. return this._toParse[this._pos];
  205. };
  206. Tokenizer.prototype.read = function () {
  207. return this._toParse[this._pos++];
  208. };
  209. Tokenizer.prototype.forward = function () {
  210. this._pos++;
  211. };
  212. Tokenizer.prototype.isEnd = function () {
  213. return this._pos >= this._maxPos;
  214. };
  215. return Tokenizer;
  216. }());
  217. /**
  218. * Values
  219. */
  220. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  221. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  222. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  223. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  224. /**
  225. * Parse
  226. */
  227. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  228. for (var buf in parsedBuffers) {
  229. var parsedBuffer = parsedBuffers[buf];
  230. gltfRuntime.buffers[buf] = parsedBuffer;
  231. gltfRuntime.buffersCount++;
  232. }
  233. };
  234. var parseShaders = function (parsedShaders, gltfRuntime) {
  235. for (var sha in parsedShaders) {
  236. var parsedShader = parsedShaders[sha];
  237. gltfRuntime.shaders[sha] = parsedShader;
  238. gltfRuntime.shaderscount++;
  239. }
  240. };
  241. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  242. for (var object in parsedObjects) {
  243. var parsedObject = parsedObjects[object];
  244. gltfRuntime[runtimeProperty][object] = parsedObject;
  245. }
  246. };
  247. /**
  248. * Utils
  249. */
  250. var normalizeUVs = function (buffer) {
  251. if (!buffer) {
  252. return;
  253. }
  254. for (var i = 0; i < buffer.length / 2; i++) {
  255. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  256. }
  257. };
  258. var getAttribute = function (attributeParameter) {
  259. if (attributeParameter.semantic === "NORMAL") {
  260. return "normal";
  261. }
  262. else if (attributeParameter.semantic === "POSITION") {
  263. return "position";
  264. }
  265. else if (attributeParameter.semantic === "JOINT") {
  266. return "matricesIndices";
  267. }
  268. else if (attributeParameter.semantic === "WEIGHT") {
  269. return "matricesWeights";
  270. }
  271. else if (attributeParameter.semantic === "COLOR") {
  272. return "color";
  273. }
  274. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  275. var channel = Number(attributeParameter.semantic.split("_")[1]);
  276. return "uv" + (channel === 0 ? "" : channel + 1);
  277. }
  278. return null;
  279. };
  280. /**
  281. * Loads and creates animations
  282. */
  283. var loadAnimations = function (gltfRuntime) {
  284. for (var anim in gltfRuntime.animations) {
  285. var animation = gltfRuntime.animations[anim];
  286. if (!animation.channels || !animation.samplers) {
  287. continue;
  288. }
  289. var lastAnimation = null;
  290. for (var i = 0; i < animation.channels.length; i++) {
  291. // Get parameters and load buffers
  292. var channel = animation.channels[i];
  293. var sampler = animation.samplers[channel.sampler];
  294. if (!sampler) {
  295. continue;
  296. }
  297. var inputData = null;
  298. var outputData = null;
  299. if (animation.parameters) {
  300. inputData = animation.parameters[sampler.input];
  301. outputData = animation.parameters[sampler.output];
  302. }
  303. else {
  304. inputData = sampler.input;
  305. outputData = sampler.output;
  306. }
  307. var bufferInput = glTFLoaderUtils_1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  308. var bufferOutput = glTFLoaderUtils_1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  309. var targetID = channel.target.id;
  310. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  311. if (targetNode === null) {
  312. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  313. }
  314. if (targetNode === null) {
  315. babylonjs_1.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  316. continue;
  317. }
  318. var isBone = targetNode instanceof babylonjs_1.Bone;
  319. // Get target path (position, rotation or scaling)
  320. var targetPath = channel.target.path;
  321. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  322. if (targetPathIndex !== -1) {
  323. targetPath = babylonAnimationPaths[targetPathIndex];
  324. }
  325. // Determine animation type
  326. var animationType = babylonjs_1.Animation.ANIMATIONTYPE_MATRIX;
  327. if (!isBone) {
  328. if (targetPath === "rotationQuaternion") {
  329. animationType = babylonjs_1.Animation.ANIMATIONTYPE_QUATERNION;
  330. targetNode.rotationQuaternion = new babylonjs_1.Quaternion();
  331. }
  332. else {
  333. animationType = babylonjs_1.Animation.ANIMATIONTYPE_VECTOR3;
  334. }
  335. }
  336. // Create animation and key frames
  337. var babylonAnimation = null;
  338. var keys = [];
  339. var arrayOffset = 0;
  340. var modifyKey = false;
  341. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  342. babylonAnimation = lastAnimation;
  343. modifyKey = true;
  344. }
  345. if (!modifyKey) {
  346. babylonAnimation = new babylonjs_1.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, babylonjs_1.Animation.ANIMATIONLOOPMODE_CYCLE);
  347. }
  348. // For each frame
  349. for (var j = 0; j < bufferInput.length; j++) {
  350. var value = null;
  351. if (targetPath === "rotationQuaternion") { // VEC4
  352. value = babylonjs_1.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  353. arrayOffset += 4;
  354. }
  355. else { // Position and scaling are VEC3
  356. value = babylonjs_1.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  357. arrayOffset += 3;
  358. }
  359. if (isBone) {
  360. var bone = targetNode;
  361. var translation = babylonjs_1.Vector3.Zero();
  362. var rotationQuaternion = new babylonjs_1.Quaternion();
  363. var scaling = babylonjs_1.Vector3.Zero();
  364. // Warning on decompose
  365. var mat = bone.getBaseMatrix();
  366. if (modifyKey && lastAnimation) {
  367. mat = lastAnimation.getKeys()[j].value;
  368. }
  369. mat.decompose(scaling, rotationQuaternion, translation);
  370. if (targetPath === "position") {
  371. translation = value;
  372. }
  373. else if (targetPath === "rotationQuaternion") {
  374. rotationQuaternion = value;
  375. }
  376. else {
  377. scaling = value;
  378. }
  379. value = babylonjs_1.Matrix.Compose(scaling, rotationQuaternion, translation);
  380. }
  381. if (!modifyKey) {
  382. keys.push({
  383. frame: bufferInput[j],
  384. value: value
  385. });
  386. }
  387. else if (lastAnimation) {
  388. lastAnimation.getKeys()[j].value = value;
  389. }
  390. }
  391. // Finish
  392. if (!modifyKey && babylonAnimation) {
  393. babylonAnimation.setKeys(keys);
  394. targetNode.animations.push(babylonAnimation);
  395. }
  396. lastAnimation = babylonAnimation;
  397. gltfRuntime.scene.stopAnimation(targetNode);
  398. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  399. }
  400. }
  401. };
  402. /**
  403. * Returns the bones transformation matrix
  404. */
  405. var configureBoneTransformation = function (node) {
  406. var mat = null;
  407. if (node.translation || node.rotation || node.scale) {
  408. var scale = babylonjs_1.Vector3.FromArray(node.scale || [1, 1, 1]);
  409. var rotation = babylonjs_1.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  410. var position = babylonjs_1.Vector3.FromArray(node.translation || [0, 0, 0]);
  411. mat = babylonjs_1.Matrix.Compose(scale, rotation, position);
  412. }
  413. else {
  414. mat = babylonjs_1.Matrix.FromArray(node.matrix);
  415. }
  416. return mat;
  417. };
  418. /**
  419. * Returns the parent bone
  420. */
  421. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  422. // Try to find
  423. for (var i = 0; i < newSkeleton.bones.length; i++) {
  424. if (newSkeleton.bones[i].name === jointName) {
  425. return newSkeleton.bones[i];
  426. }
  427. }
  428. // Not found, search in gltf nodes
  429. var nodes = gltfRuntime.nodes;
  430. for (var nde in nodes) {
  431. var node = nodes[nde];
  432. if (!node.jointName) {
  433. continue;
  434. }
  435. var children = node.children;
  436. for (var i = 0; i < children.length; i++) {
  437. var child = gltfRuntime.nodes[children[i]];
  438. if (!child.jointName) {
  439. continue;
  440. }
  441. if (child.jointName === jointName) {
  442. var mat = configureBoneTransformation(node);
  443. var bone = new babylonjs_1.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  444. bone.id = nde;
  445. return bone;
  446. }
  447. }
  448. }
  449. return null;
  450. };
  451. /**
  452. * Returns the appropriate root node
  453. */
  454. var getNodeToRoot = function (nodesToRoot, id) {
  455. for (var i = 0; i < nodesToRoot.length; i++) {
  456. var nodeToRoot = nodesToRoot[i];
  457. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  458. var child = nodeToRoot.node.children[j];
  459. if (child === id) {
  460. return nodeToRoot.bone;
  461. }
  462. }
  463. }
  464. return null;
  465. };
  466. /**
  467. * Returns the node with the joint name
  468. */
  469. var getJointNode = function (gltfRuntime, jointName) {
  470. var nodes = gltfRuntime.nodes;
  471. var node = nodes[jointName];
  472. if (node) {
  473. return {
  474. node: node,
  475. id: jointName
  476. };
  477. }
  478. for (var nde in nodes) {
  479. node = nodes[nde];
  480. if (node.jointName === jointName) {
  481. return {
  482. node: node,
  483. id: nde
  484. };
  485. }
  486. }
  487. return null;
  488. };
  489. /**
  490. * Checks if a nodes is in joints
  491. */
  492. var nodeIsInJoints = function (skins, id) {
  493. for (var i = 0; i < skins.jointNames.length; i++) {
  494. if (skins.jointNames[i] === id) {
  495. return true;
  496. }
  497. }
  498. return false;
  499. };
  500. /**
  501. * Fills the nodes to root for bones and builds hierarchy
  502. */
  503. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  504. // Creates nodes for root
  505. for (var nde in gltfRuntime.nodes) {
  506. var node = gltfRuntime.nodes[nde];
  507. var id = nde;
  508. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  509. continue;
  510. }
  511. // Create node to root bone
  512. var mat = configureBoneTransformation(node);
  513. var bone = new babylonjs_1.Bone(node.name || "", newSkeleton, null, mat);
  514. bone.id = id;
  515. nodesToRoot.push({ bone: bone, node: node, id: id });
  516. }
  517. // Parenting
  518. for (var i = 0; i < nodesToRoot.length; i++) {
  519. var nodeToRoot = nodesToRoot[i];
  520. var children = nodeToRoot.node.children;
  521. for (var j = 0; j < children.length; j++) {
  522. var child = null;
  523. for (var k = 0; k < nodesToRoot.length; k++) {
  524. if (nodesToRoot[k].id === children[j]) {
  525. child = nodesToRoot[k];
  526. break;
  527. }
  528. }
  529. if (child) {
  530. child.bone._parent = nodeToRoot.bone;
  531. nodeToRoot.bone.children.push(child.bone);
  532. }
  533. }
  534. }
  535. };
  536. /**
  537. * Imports a skeleton
  538. */
  539. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  540. if (!newSkeleton) {
  541. newSkeleton = new babylonjs_1.Skeleton(skins.name || "", "", gltfRuntime.scene);
  542. }
  543. if (!skins.babylonSkeleton) {
  544. return newSkeleton;
  545. }
  546. // Find the root bones
  547. var nodesToRoot = [];
  548. var nodesToRootToAdd = [];
  549. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  550. newSkeleton.bones = [];
  551. // Joints
  552. for (var i = 0; i < skins.jointNames.length; i++) {
  553. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  554. if (!jointNode) {
  555. continue;
  556. }
  557. var node = jointNode.node;
  558. if (!node) {
  559. babylonjs_1.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  560. continue;
  561. }
  562. var id = jointNode.id;
  563. // Optimize, if the bone already exists...
  564. var existingBone = gltfRuntime.scene.getBoneByID(id);
  565. if (existingBone) {
  566. newSkeleton.bones.push(existingBone);
  567. continue;
  568. }
  569. // Search for parent bone
  570. var foundBone = false;
  571. var parentBone = null;
  572. for (var j = 0; j < i; j++) {
  573. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  574. if (!jointNode_1) {
  575. continue;
  576. }
  577. var joint = jointNode_1.node;
  578. if (!joint) {
  579. babylonjs_1.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  580. continue;
  581. }
  582. var children = joint.children;
  583. if (!children) {
  584. continue;
  585. }
  586. foundBone = false;
  587. for (var k = 0; k < children.length; k++) {
  588. if (children[k] === id) {
  589. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  590. foundBone = true;
  591. break;
  592. }
  593. }
  594. if (foundBone) {
  595. break;
  596. }
  597. }
  598. // Create bone
  599. var mat = configureBoneTransformation(node);
  600. if (!parentBone && nodesToRoot.length > 0) {
  601. parentBone = getNodeToRoot(nodesToRoot, id);
  602. if (parentBone) {
  603. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  604. nodesToRootToAdd.push(parentBone);
  605. }
  606. }
  607. }
  608. var bone = new babylonjs_1.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  609. bone.id = id;
  610. }
  611. // Polish
  612. var bones = newSkeleton.bones;
  613. newSkeleton.bones = [];
  614. for (var i = 0; i < skins.jointNames.length; i++) {
  615. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  616. if (!jointNode) {
  617. continue;
  618. }
  619. for (var j = 0; j < bones.length; j++) {
  620. if (bones[j].id === jointNode.id) {
  621. newSkeleton.bones.push(bones[j]);
  622. break;
  623. }
  624. }
  625. }
  626. newSkeleton.prepare();
  627. // Finish
  628. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  629. newSkeleton.bones.push(nodesToRootToAdd[i]);
  630. }
  631. return newSkeleton;
  632. };
  633. /**
  634. * Imports a mesh and its geometries
  635. */
  636. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  637. if (!newMesh) {
  638. newMesh = new babylonjs_1.Mesh(node.name || "", gltfRuntime.scene);
  639. newMesh.id = id;
  640. }
  641. if (!node.babylonNode) {
  642. return newMesh;
  643. }
  644. var subMaterials = [];
  645. var vertexData = null;
  646. var verticesStarts = new Array();
  647. var verticesCounts = new Array();
  648. var indexStarts = new Array();
  649. var indexCounts = new Array();
  650. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  651. var meshID = meshes[meshIndex];
  652. var mesh = gltfRuntime.meshes[meshID];
  653. if (!mesh) {
  654. continue;
  655. }
  656. // Positions, normals and UVs
  657. for (var i = 0; i < mesh.primitives.length; i++) {
  658. // Temporary vertex data
  659. var tempVertexData = new babylonjs_1.VertexData();
  660. var primitive = mesh.primitives[i];
  661. if (primitive.mode !== 4) {
  662. // continue;
  663. }
  664. var attributes = primitive.attributes;
  665. var accessor = null;
  666. var buffer = null;
  667. // Set positions, normal and uvs
  668. for (var semantic in attributes) {
  669. // Link accessor and buffer view
  670. accessor = gltfRuntime.accessors[attributes[semantic]];
  671. buffer = glTFLoaderUtils_1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  672. if (semantic === "NORMAL") {
  673. tempVertexData.normals = new Float32Array(buffer.length);
  674. tempVertexData.normals.set(buffer);
  675. }
  676. else if (semantic === "POSITION") {
  677. if (glTFFileLoader_1.GLTFFileLoader.HomogeneousCoordinates) {
  678. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  679. for (var j = 0; j < buffer.length; j += 4) {
  680. tempVertexData.positions[j] = buffer[j];
  681. tempVertexData.positions[j + 1] = buffer[j + 1];
  682. tempVertexData.positions[j + 2] = buffer[j + 2];
  683. }
  684. }
  685. else {
  686. tempVertexData.positions = new Float32Array(buffer.length);
  687. tempVertexData.positions.set(buffer);
  688. }
  689. verticesCounts.push(tempVertexData.positions.length);
  690. }
  691. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  692. var channel = Number(semantic.split("_")[1]);
  693. var uvKind = babylonjs_1.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  694. var uvs = new Float32Array(buffer.length);
  695. uvs.set(buffer);
  696. normalizeUVs(uvs);
  697. tempVertexData.set(uvs, uvKind);
  698. }
  699. else if (semantic === "JOINT") {
  700. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  701. tempVertexData.matricesIndices.set(buffer);
  702. }
  703. else if (semantic === "WEIGHT") {
  704. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  705. tempVertexData.matricesWeights.set(buffer);
  706. }
  707. else if (semantic === "COLOR") {
  708. tempVertexData.colors = new Float32Array(buffer.length);
  709. tempVertexData.colors.set(buffer);
  710. }
  711. }
  712. // Indices
  713. accessor = gltfRuntime.accessors[primitive.indices];
  714. if (accessor) {
  715. buffer = glTFLoaderUtils_1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  716. tempVertexData.indices = new Int32Array(buffer.length);
  717. tempVertexData.indices.set(buffer);
  718. indexCounts.push(tempVertexData.indices.length);
  719. }
  720. else {
  721. // Set indices on the fly
  722. var indices = [];
  723. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  724. indices.push(j);
  725. }
  726. tempVertexData.indices = new Int32Array(indices);
  727. indexCounts.push(tempVertexData.indices.length);
  728. }
  729. if (!vertexData) {
  730. vertexData = tempVertexData;
  731. }
  732. else {
  733. vertexData.merge(tempVertexData);
  734. }
  735. // Sub material
  736. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  737. subMaterials.push(material_1 === null ? glTFLoaderUtils_1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  738. // Update vertices start and index start
  739. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  740. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  741. }
  742. }
  743. var material;
  744. if (subMaterials.length > 1) {
  745. material = new babylonjs_1.MultiMaterial("multimat" + id, gltfRuntime.scene);
  746. material.subMaterials = subMaterials;
  747. }
  748. else {
  749. material = new babylonjs_1.StandardMaterial("multimat" + id, gltfRuntime.scene);
  750. }
  751. if (subMaterials.length === 1) {
  752. material = subMaterials[0];
  753. }
  754. if (!newMesh.material) {
  755. newMesh.material = material;
  756. }
  757. // Apply geometry
  758. new babylonjs_1.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  759. newMesh.computeWorldMatrix(true);
  760. // Apply submeshes
  761. newMesh.subMeshes = [];
  762. var index = 0;
  763. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  764. var meshID = meshes[meshIndex];
  765. var mesh = gltfRuntime.meshes[meshID];
  766. if (!mesh) {
  767. continue;
  768. }
  769. for (var i = 0; i < mesh.primitives.length; i++) {
  770. if (mesh.primitives[i].mode !== 4) {
  771. //continue;
  772. }
  773. babylonjs_1.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  774. index++;
  775. }
  776. }
  777. // Finish
  778. return newMesh;
  779. };
  780. /**
  781. * Configure node transformation from position, rotation and scaling
  782. */
  783. var configureNode = function (newNode, position, rotation, scaling) {
  784. if (newNode.position) {
  785. newNode.position = position;
  786. }
  787. if (newNode.rotationQuaternion || newNode.rotation) {
  788. newNode.rotationQuaternion = rotation;
  789. }
  790. if (newNode.scaling) {
  791. newNode.scaling = scaling;
  792. }
  793. };
  794. /**
  795. * Configures node from transformation matrix
  796. */
  797. var configureNodeFromMatrix = function (newNode, node, parent) {
  798. if (node.matrix) {
  799. var position = new babylonjs_1.Vector3(0, 0, 0);
  800. var rotation = new babylonjs_1.Quaternion();
  801. var scaling = new babylonjs_1.Vector3(0, 0, 0);
  802. var mat = babylonjs_1.Matrix.FromArray(node.matrix);
  803. mat.decompose(scaling, rotation, position);
  804. configureNode(newNode, position, rotation, scaling);
  805. }
  806. else if (node.translation && node.rotation && node.scale) {
  807. configureNode(newNode, babylonjs_1.Vector3.FromArray(node.translation), babylonjs_1.Quaternion.FromArray(node.rotation), babylonjs_1.Vector3.FromArray(node.scale));
  808. }
  809. newNode.computeWorldMatrix(true);
  810. };
  811. /**
  812. * Imports a node
  813. */
  814. var importNode = function (gltfRuntime, node, id, parent) {
  815. var lastNode = null;
  816. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  817. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  818. return null;
  819. }
  820. }
  821. // Meshes
  822. if (node.skin) {
  823. if (node.meshes) {
  824. var skin = gltfRuntime.skins[node.skin];
  825. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  826. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  827. if (newMesh.skeleton === null) {
  828. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  829. if (!skin.babylonSkeleton) {
  830. skin.babylonSkeleton = newMesh.skeleton;
  831. }
  832. }
  833. lastNode = newMesh;
  834. }
  835. }
  836. else if (node.meshes) {
  837. /**
  838. * Improve meshes property
  839. */
  840. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  841. lastNode = newMesh;
  842. }
  843. // Lights
  844. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  845. var light = gltfRuntime.lights[node.light];
  846. if (light) {
  847. if (light.type === "ambient") {
  848. var ambienLight = light[light.type];
  849. var hemiLight = new babylonjs_1.HemisphericLight(node.light, babylonjs_1.Vector3.Zero(), gltfRuntime.scene);
  850. hemiLight.name = node.name || "";
  851. if (ambienLight.color) {
  852. hemiLight.diffuse = babylonjs_1.Color3.FromArray(ambienLight.color);
  853. }
  854. lastNode = hemiLight;
  855. }
  856. else if (light.type === "directional") {
  857. var directionalLight = light[light.type];
  858. var dirLight = new babylonjs_1.DirectionalLight(node.light, babylonjs_1.Vector3.Zero(), gltfRuntime.scene);
  859. dirLight.name = node.name || "";
  860. if (directionalLight.color) {
  861. dirLight.diffuse = babylonjs_1.Color3.FromArray(directionalLight.color);
  862. }
  863. lastNode = dirLight;
  864. }
  865. else if (light.type === "point") {
  866. var pointLight = light[light.type];
  867. var ptLight = new babylonjs_1.PointLight(node.light, babylonjs_1.Vector3.Zero(), gltfRuntime.scene);
  868. ptLight.name = node.name || "";
  869. if (pointLight.color) {
  870. ptLight.diffuse = babylonjs_1.Color3.FromArray(pointLight.color);
  871. }
  872. lastNode = ptLight;
  873. }
  874. else if (light.type === "spot") {
  875. var spotLight = light[light.type];
  876. var spLight = new babylonjs_1.SpotLight(node.light, babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  877. spLight.name = node.name || "";
  878. if (spotLight.color) {
  879. spLight.diffuse = babylonjs_1.Color3.FromArray(spotLight.color);
  880. }
  881. if (spotLight.fallOfAngle) {
  882. spLight.angle = spotLight.fallOfAngle;
  883. }
  884. if (spotLight.fallOffExponent) {
  885. spLight.exponent = spotLight.fallOffExponent;
  886. }
  887. lastNode = spLight;
  888. }
  889. }
  890. }
  891. // Cameras
  892. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  893. var camera = gltfRuntime.cameras[node.camera];
  894. if (camera) {
  895. if (camera.type === "orthographic") {
  896. var orthoCamera = new babylonjs_1.FreeCamera(node.camera, babylonjs_1.Vector3.Zero(), gltfRuntime.scene, false);
  897. orthoCamera.name = node.name || "";
  898. orthoCamera.mode = babylonjs_1.Camera.ORTHOGRAPHIC_CAMERA;
  899. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  900. lastNode = orthoCamera;
  901. }
  902. else if (camera.type === "perspective") {
  903. var perspectiveCamera = camera[camera.type];
  904. var persCamera = new babylonjs_1.FreeCamera(node.camera, babylonjs_1.Vector3.Zero(), gltfRuntime.scene, false);
  905. persCamera.name = node.name || "";
  906. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  907. if (!perspectiveCamera.aspectRatio) {
  908. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  909. }
  910. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  911. persCamera.maxZ = perspectiveCamera.zfar;
  912. persCamera.minZ = perspectiveCamera.znear;
  913. }
  914. lastNode = persCamera;
  915. }
  916. }
  917. }
  918. // Empty node
  919. if (!node.jointName) {
  920. if (node.babylonNode) {
  921. return node.babylonNode;
  922. }
  923. else if (lastNode === null) {
  924. var dummy = new babylonjs_1.Mesh(node.name || "", gltfRuntime.scene);
  925. node.babylonNode = dummy;
  926. lastNode = dummy;
  927. }
  928. }
  929. if (lastNode !== null) {
  930. if (node.matrix && lastNode instanceof babylonjs_1.Mesh) {
  931. configureNodeFromMatrix(lastNode, node, parent);
  932. }
  933. else {
  934. var translation = node.translation || [0, 0, 0];
  935. var rotation = node.rotation || [0, 0, 0, 1];
  936. var scale = node.scale || [1, 1, 1];
  937. configureNode(lastNode, babylonjs_1.Vector3.FromArray(translation), babylonjs_1.Quaternion.FromArray(rotation), babylonjs_1.Vector3.FromArray(scale));
  938. }
  939. lastNode.updateCache(true);
  940. node.babylonNode = lastNode;
  941. }
  942. return lastNode;
  943. };
  944. /**
  945. * Traverses nodes and creates them
  946. */
  947. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  948. if (meshIncluded === void 0) { meshIncluded = false; }
  949. var node = gltfRuntime.nodes[id];
  950. var newNode = null;
  951. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  952. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  953. meshIncluded = true;
  954. }
  955. else {
  956. meshIncluded = false;
  957. }
  958. }
  959. else {
  960. meshIncluded = true;
  961. }
  962. if (!node.jointName && meshIncluded) {
  963. newNode = importNode(gltfRuntime, node, id, parent);
  964. if (newNode !== null) {
  965. newNode.id = id;
  966. newNode.parent = parent;
  967. }
  968. }
  969. if (node.children) {
  970. for (var i = 0; i < node.children.length; i++) {
  971. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  972. }
  973. }
  974. };
  975. /**
  976. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  977. */
  978. var postLoad = function (gltfRuntime) {
  979. // Nodes
  980. var currentScene = gltfRuntime.currentScene;
  981. if (currentScene) {
  982. for (var i = 0; i < currentScene.nodes.length; i++) {
  983. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  984. }
  985. }
  986. else {
  987. for (var thing in gltfRuntime.scenes) {
  988. currentScene = gltfRuntime.scenes[thing];
  989. for (var i = 0; i < currentScene.nodes.length; i++) {
  990. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  991. }
  992. }
  993. }
  994. // Set animations
  995. loadAnimations(gltfRuntime);
  996. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  997. var skeleton = gltfRuntime.scene.skeletons[i];
  998. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  999. }
  1000. };
  1001. /**
  1002. * onBind shaderrs callback to set uniforms and matrices
  1003. */
  1004. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  1005. var materialValues = material.values || technique.parameters;
  1006. for (var unif in unTreatedUniforms) {
  1007. var uniform = unTreatedUniforms[unif];
  1008. var type = uniform.type;
  1009. if (type === glTFLoaderInterfaces_1.EParameterType.FLOAT_MAT2 || type === glTFLoaderInterfaces_1.EParameterType.FLOAT_MAT3 || type === glTFLoaderInterfaces_1.EParameterType.FLOAT_MAT4) {
  1010. if (uniform.semantic && !uniform.source && !uniform.node) {
  1011. glTFLoaderUtils_1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  1012. }
  1013. else if (uniform.semantic && (uniform.source || uniform.node)) {
  1014. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  1015. if (source === null) {
  1016. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  1017. }
  1018. if (source === null) {
  1019. continue;
  1020. }
  1021. glTFLoaderUtils_1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  1022. }
  1023. }
  1024. else {
  1025. var value = materialValues[technique.uniforms[unif]];
  1026. if (!value) {
  1027. continue;
  1028. }
  1029. if (type === glTFLoaderInterfaces_1.EParameterType.SAMPLER_2D) {
  1030. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  1031. if (texture === null || texture === undefined) {
  1032. continue;
  1033. }
  1034. shaderMaterial.getEffect().setTexture(unif, texture);
  1035. }
  1036. else {
  1037. glTFLoaderUtils_1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  1038. }
  1039. }
  1040. }
  1041. onSuccess(shaderMaterial);
  1042. };
  1043. /**
  1044. * Prepare uniforms to send the only one time
  1045. * Loads the appropriate textures
  1046. */
  1047. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  1048. var materialValues = material.values || technique.parameters;
  1049. var techniqueUniforms = technique.uniforms;
  1050. /**
  1051. * Prepare values here (not matrices)
  1052. */
  1053. for (var unif in unTreatedUniforms) {
  1054. var uniform = unTreatedUniforms[unif];
  1055. var type = uniform.type;
  1056. var value = materialValues[techniqueUniforms[unif]];
  1057. if (value === undefined) {
  1058. // In case the value is the same for all materials
  1059. value = uniform.value;
  1060. }
  1061. if (!value) {
  1062. continue;
  1063. }
  1064. var onLoadTexture = function (uniformName) {
  1065. return function (texture) {
  1066. if (uniform.value && uniformName) {
  1067. // Static uniform
  1068. shaderMaterial.setTexture(uniformName, texture);
  1069. delete unTreatedUniforms[uniformName];
  1070. }
  1071. };
  1072. };
  1073. // Texture (sampler2D)
  1074. if (type === glTFLoaderInterfaces_1.EParameterType.SAMPLER_2D) {
  1075. glTFLoaderExtension_1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  1076. }
  1077. // Others
  1078. else {
  1079. if (uniform.value && glTFLoaderUtils_1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  1080. // Static uniform
  1081. delete unTreatedUniforms[unif];
  1082. }
  1083. }
  1084. }
  1085. };
  1086. /**
  1087. * Shader compilation failed
  1088. */
  1089. var onShaderCompileError = function (program, shaderMaterial, onError) {
  1090. return function (effect, error) {
  1091. shaderMaterial.dispose(true);
  1092. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  1093. };
  1094. };
  1095. /**
  1096. * Shader compilation success
  1097. */
  1098. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  1099. return function (_) {
  1100. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  1101. shaderMaterial.onBind = function (mesh) {
  1102. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  1103. };
  1104. };
  1105. };
  1106. /**
  1107. * Returns the appropriate uniform if already handled by babylon
  1108. */
  1109. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  1110. for (var unif in technique.uniforms) {
  1111. var uniform = technique.uniforms[unif];
  1112. var uniformParameter = technique.parameters[uniform];
  1113. if (tokenizer.currentIdentifier === unif) {
  1114. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  1115. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1116. if (transformIndex !== -1) {
  1117. delete unTreatedUniforms[unif];
  1118. return babylonTransforms[transformIndex];
  1119. }
  1120. }
  1121. }
  1122. }
  1123. return tokenizer.currentIdentifier;
  1124. };
  1125. /**
  1126. * All shaders loaded. Create materials one by one
  1127. */
  1128. var importMaterials = function (gltfRuntime) {
  1129. // Create materials
  1130. for (var mat in gltfRuntime.materials) {
  1131. glTFLoaderExtension_1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  1132. }
  1133. };
  1134. /**
  1135. * Implementation of the base glTF spec
  1136. * @hidden
  1137. */
  1138. var GLTFLoaderBase = /** @class */ (function () {
  1139. function GLTFLoaderBase() {
  1140. }
  1141. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  1142. var gltfRuntime = {
  1143. extensions: {},
  1144. accessors: {},
  1145. buffers: {},
  1146. bufferViews: {},
  1147. meshes: {},
  1148. lights: {},
  1149. cameras: {},
  1150. nodes: {},
  1151. images: {},
  1152. textures: {},
  1153. shaders: {},
  1154. programs: {},
  1155. samplers: {},
  1156. techniques: {},
  1157. materials: {},
  1158. animations: {},
  1159. skins: {},
  1160. extensionsUsed: [],
  1161. scenes: {},
  1162. buffersCount: 0,
  1163. shaderscount: 0,
  1164. scene: scene,
  1165. rootUrl: rootUrl,
  1166. loadedBufferCount: 0,
  1167. loadedBufferViews: {},
  1168. loadedShaderCount: 0,
  1169. importOnlyMeshes: false,
  1170. dummyNodes: []
  1171. };
  1172. // Parse
  1173. if (parsedData.extensions) {
  1174. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  1175. }
  1176. if (parsedData.extensionsUsed) {
  1177. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  1178. }
  1179. if (parsedData.buffers) {
  1180. parseBuffers(parsedData.buffers, gltfRuntime);
  1181. }
  1182. if (parsedData.bufferViews) {
  1183. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  1184. }
  1185. if (parsedData.accessors) {
  1186. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  1187. }
  1188. if (parsedData.meshes) {
  1189. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  1190. }
  1191. if (parsedData.lights) {
  1192. parseObject(parsedData.lights, "lights", gltfRuntime);
  1193. }
  1194. if (parsedData.cameras) {
  1195. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  1196. }
  1197. if (parsedData.nodes) {
  1198. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  1199. }
  1200. if (parsedData.images) {
  1201. parseObject(parsedData.images, "images", gltfRuntime);
  1202. }
  1203. if (parsedData.textures) {
  1204. parseObject(parsedData.textures, "textures", gltfRuntime);
  1205. }
  1206. if (parsedData.shaders) {
  1207. parseShaders(parsedData.shaders, gltfRuntime);
  1208. }
  1209. if (parsedData.programs) {
  1210. parseObject(parsedData.programs, "programs", gltfRuntime);
  1211. }
  1212. if (parsedData.samplers) {
  1213. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  1214. }
  1215. if (parsedData.techniques) {
  1216. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  1217. }
  1218. if (parsedData.materials) {
  1219. parseObject(parsedData.materials, "materials", gltfRuntime);
  1220. }
  1221. if (parsedData.animations) {
  1222. parseObject(parsedData.animations, "animations", gltfRuntime);
  1223. }
  1224. if (parsedData.skins) {
  1225. parseObject(parsedData.skins, "skins", gltfRuntime);
  1226. }
  1227. if (parsedData.scenes) {
  1228. gltfRuntime.scenes = parsedData.scenes;
  1229. }
  1230. if (parsedData.scene && parsedData.scenes) {
  1231. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  1232. }
  1233. return gltfRuntime;
  1234. };
  1235. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  1236. var buffer = gltfRuntime.buffers[id];
  1237. if (babylonjs_1.Tools.IsBase64(buffer.uri)) {
  1238. setTimeout(function () { return onSuccess(new Uint8Array(babylonjs_1.Tools.DecodeBase64(buffer.uri))); });
  1239. }
  1240. else {
  1241. babylonjs_1.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  1242. if (request) {
  1243. onError(request.status + " " + request.statusText);
  1244. }
  1245. });
  1246. }
  1247. };
  1248. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1249. var texture = gltfRuntime.textures[id];
  1250. if (!texture || !texture.source) {
  1251. onError("");
  1252. return;
  1253. }
  1254. if (texture.babylonTexture) {
  1255. onSuccess(null);
  1256. return;
  1257. }
  1258. var source = gltfRuntime.images[texture.source];
  1259. if (babylonjs_1.Tools.IsBase64(source.uri)) {
  1260. setTimeout(function () { return onSuccess(new Uint8Array(babylonjs_1.Tools.DecodeBase64(source.uri))); });
  1261. }
  1262. else {
  1263. babylonjs_1.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  1264. if (request) {
  1265. onError(request.status + " " + request.statusText);
  1266. }
  1267. });
  1268. }
  1269. };
  1270. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1271. var texture = gltfRuntime.textures[id];
  1272. if (texture.babylonTexture) {
  1273. onSuccess(texture.babylonTexture);
  1274. return;
  1275. }
  1276. var sampler = gltfRuntime.samplers[texture.sampler];
  1277. var createMipMaps = (sampler.minFilter === glTFLoaderInterfaces_1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  1278. (sampler.minFilter === glTFLoaderInterfaces_1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  1279. (sampler.minFilter === glTFLoaderInterfaces_1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  1280. (sampler.minFilter === glTFLoaderInterfaces_1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  1281. var samplingMode = babylonjs_1.Texture.BILINEAR_SAMPLINGMODE;
  1282. var blob = buffer == null ? new Blob() : new Blob([buffer]);
  1283. var blobURL = URL.createObjectURL(blob);
  1284. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  1285. var newTexture = new babylonjs_1.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  1286. if (sampler.wrapS !== undefined) {
  1287. newTexture.wrapU = glTFLoaderUtils_1.GLTFUtils.GetWrapMode(sampler.wrapS);
  1288. }
  1289. if (sampler.wrapT !== undefined) {
  1290. newTexture.wrapV = glTFLoaderUtils_1.GLTFUtils.GetWrapMode(sampler.wrapT);
  1291. }
  1292. newTexture.name = id;
  1293. texture.babylonTexture = newTexture;
  1294. onSuccess(newTexture);
  1295. };
  1296. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1297. var shader = gltfRuntime.shaders[id];
  1298. if (babylonjs_1.Tools.IsBase64(shader.uri)) {
  1299. var shaderString = atob(shader.uri.split(",")[1]);
  1300. if (onSuccess) {
  1301. onSuccess(shaderString);
  1302. }
  1303. }
  1304. else {
  1305. babylonjs_1.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  1306. if (request && onError) {
  1307. onError(request.status + " " + request.statusText);
  1308. }
  1309. });
  1310. }
  1311. };
  1312. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1313. var material = gltfRuntime.materials[id];
  1314. if (!material.technique) {
  1315. if (onError) {
  1316. onError("No technique found.");
  1317. }
  1318. return;
  1319. }
  1320. var technique = gltfRuntime.techniques[material.technique];
  1321. if (!technique) {
  1322. var defaultMaterial = new babylonjs_1.StandardMaterial(id, gltfRuntime.scene);
  1323. defaultMaterial.diffuseColor = new babylonjs_1.Color3(0.5, 0.5, 0.5);
  1324. defaultMaterial.sideOrientation = babylonjs_1.Material.CounterClockWiseSideOrientation;
  1325. onSuccess(defaultMaterial);
  1326. return;
  1327. }
  1328. var program = gltfRuntime.programs[technique.program];
  1329. var states = technique.states;
  1330. var vertexShader = babylonjs_1.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  1331. var pixelShader = babylonjs_1.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  1332. var newVertexShader = "";
  1333. var newPixelShader = "";
  1334. var vertexTokenizer = new Tokenizer(vertexShader);
  1335. var pixelTokenizer = new Tokenizer(pixelShader);
  1336. var unTreatedUniforms = {};
  1337. var uniforms = [];
  1338. var attributes = [];
  1339. var samplers = [];
  1340. // Fill uniform, sampler2D and attributes
  1341. for (var unif in technique.uniforms) {
  1342. var uniform = technique.uniforms[unif];
  1343. var uniformParameter = technique.parameters[uniform];
  1344. unTreatedUniforms[unif] = uniformParameter;
  1345. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  1346. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1347. if (transformIndex !== -1) {
  1348. uniforms.push(babylonTransforms[transformIndex]);
  1349. delete unTreatedUniforms[unif];
  1350. }
  1351. else {
  1352. uniforms.push(unif);
  1353. }
  1354. }
  1355. else if (uniformParameter.type === glTFLoaderInterfaces_1.EParameterType.SAMPLER_2D) {
  1356. samplers.push(unif);
  1357. }
  1358. else {
  1359. uniforms.push(unif);
  1360. }
  1361. }
  1362. for (var attr in technique.attributes) {
  1363. var attribute = technique.attributes[attr];
  1364. var attributeParameter = technique.parameters[attribute];
  1365. if (attributeParameter.semantic) {
  1366. var name_1 = getAttribute(attributeParameter);
  1367. if (name_1) {
  1368. attributes.push(name_1);
  1369. }
  1370. }
  1371. }
  1372. // Configure vertex shader
  1373. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  1374. var tokenType = vertexTokenizer.currentToken;
  1375. if (tokenType !== ETokenType.IDENTIFIER) {
  1376. newVertexShader += vertexTokenizer.currentString;
  1377. continue;
  1378. }
  1379. var foundAttribute = false;
  1380. for (var attr in technique.attributes) {
  1381. var attribute = technique.attributes[attr];
  1382. var attributeParameter = technique.parameters[attribute];
  1383. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  1384. newVertexShader += getAttribute(attributeParameter);
  1385. foundAttribute = true;
  1386. break;
  1387. }
  1388. }
  1389. if (foundAttribute) {
  1390. continue;
  1391. }
  1392. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  1393. }
  1394. // Configure pixel shader
  1395. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  1396. var tokenType = pixelTokenizer.currentToken;
  1397. if (tokenType !== ETokenType.IDENTIFIER) {
  1398. newPixelShader += pixelTokenizer.currentString;
  1399. continue;
  1400. }
  1401. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  1402. }
  1403. // Create shader material
  1404. var shaderPath = {
  1405. vertex: program.vertexShader + id,
  1406. fragment: program.fragmentShader + id
  1407. };
  1408. var options = {
  1409. attributes: attributes,
  1410. uniforms: uniforms,
  1411. samplers: samplers,
  1412. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  1413. };
  1414. babylonjs_1.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  1415. babylonjs_1.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  1416. var shaderMaterial = new babylonjs_1.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  1417. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  1418. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  1419. shaderMaterial.sideOrientation = babylonjs_1.Material.CounterClockWiseSideOrientation;
  1420. if (states && states.functions) {
  1421. var functions = states.functions;
  1422. if (functions.cullFace && functions.cullFace[0] !== glTFLoaderInterfaces_1.ECullingType.BACK) {
  1423. shaderMaterial.backFaceCulling = false;
  1424. }
  1425. var blendFunc = functions.blendFuncSeparate;
  1426. if (blendFunc) {
  1427. 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) {
  1428. shaderMaterial.alphaMode = babylonjs_1.Engine.ALPHA_COMBINE;
  1429. }
  1430. 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) {
  1431. shaderMaterial.alphaMode = babylonjs_1.Engine.ALPHA_ONEONE;
  1432. }
  1433. 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) {
  1434. shaderMaterial.alphaMode = babylonjs_1.Engine.ALPHA_ADD;
  1435. }
  1436. 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) {
  1437. shaderMaterial.alphaMode = babylonjs_1.Engine.ALPHA_SUBTRACT;
  1438. }
  1439. 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) {
  1440. shaderMaterial.alphaMode = babylonjs_1.Engine.ALPHA_MULTIPLY;
  1441. }
  1442. 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) {
  1443. shaderMaterial.alphaMode = babylonjs_1.Engine.ALPHA_MAXIMIZED;
  1444. }
  1445. }
  1446. }
  1447. };
  1448. return GLTFLoaderBase;
  1449. }());
  1450. exports.GLTFLoaderBase = GLTFLoaderBase;
  1451. /**
  1452. * glTF V1 Loader
  1453. * @hidden
  1454. */
  1455. var GLTF1Loader = /** @class */ (function () {
  1456. function GLTF1Loader() {
  1457. this.state = null;
  1458. }
  1459. GLTF1Loader.RegisterExtension = function (extension) {
  1460. if (GLTF1Loader.Extensions[extension.name]) {
  1461. babylonjs_1.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  1462. return;
  1463. }
  1464. GLTF1Loader.Extensions[extension.name] = extension;
  1465. };
  1466. GLTF1Loader.prototype.dispose = function () {
  1467. // do nothing
  1468. };
  1469. GLTF1Loader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  1470. var _this = this;
  1471. scene.useRightHandedSystem = true;
  1472. glTFLoaderExtension_1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1473. gltfRuntime.importOnlyMeshes = true;
  1474. if (meshesNames === "") {
  1475. gltfRuntime.importMeshesNames = [];
  1476. }
  1477. else if (typeof meshesNames === "string") {
  1478. gltfRuntime.importMeshesNames = [meshesNames];
  1479. }
  1480. else if (meshesNames && !(meshesNames instanceof Array)) {
  1481. gltfRuntime.importMeshesNames = [meshesNames];
  1482. }
  1483. else {
  1484. gltfRuntime.importMeshesNames = [];
  1485. babylonjs_1.Tools.Warn("Argument meshesNames must be of type string or string[]");
  1486. }
  1487. // Create nodes
  1488. _this._createNodes(gltfRuntime);
  1489. var meshes = new Array();
  1490. var skeletons = new Array();
  1491. // Fill arrays of meshes and skeletons
  1492. for (var nde in gltfRuntime.nodes) {
  1493. var node = gltfRuntime.nodes[nde];
  1494. if (node.babylonNode instanceof babylonjs_1.AbstractMesh) {
  1495. meshes.push(node.babylonNode);
  1496. }
  1497. }
  1498. for (var skl in gltfRuntime.skins) {
  1499. var skin = gltfRuntime.skins[skl];
  1500. if (skin.babylonSkeleton instanceof babylonjs_1.Skeleton) {
  1501. skeletons.push(skin.babylonSkeleton);
  1502. }
  1503. }
  1504. // Load buffers, shaders, materials, etc.
  1505. _this._loadBuffersAsync(gltfRuntime, function () {
  1506. _this._loadShadersAsync(gltfRuntime, function () {
  1507. importMaterials(gltfRuntime);
  1508. postLoad(gltfRuntime);
  1509. if (!glTFFileLoader_1.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1510. onSuccess(meshes, skeletons);
  1511. }
  1512. });
  1513. }, onProgress);
  1514. if (glTFFileLoader_1.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1515. onSuccess(meshes, skeletons);
  1516. }
  1517. }, onError);
  1518. return true;
  1519. };
  1520. /**
  1521. * Imports one or more meshes from a loaded gltf file and adds them to the scene
  1522. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  1523. * @param scene the scene the meshes should be added to
  1524. * @param data gltf data containing information of the meshes in a loaded file
  1525. * @param rootUrl root url to load from
  1526. * @param onProgress event that fires when loading progress has occured
  1527. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  1528. */
  1529. GLTF1Loader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  1530. var _this = this;
  1531. return new Promise(function (resolve, reject) {
  1532. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, skeletons) {
  1533. resolve({
  1534. meshes: meshes,
  1535. particleSystems: [],
  1536. skeletons: skeletons,
  1537. animationGroups: []
  1538. });
  1539. }, onProgress, function (message) {
  1540. reject(new Error(message));
  1541. });
  1542. });
  1543. };
  1544. GLTF1Loader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  1545. var _this = this;
  1546. scene.useRightHandedSystem = true;
  1547. glTFLoaderExtension_1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1548. // Load runtime extensios
  1549. glTFLoaderExtension_1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  1550. // Create nodes
  1551. _this._createNodes(gltfRuntime);
  1552. // Load buffers, shaders, materials, etc.
  1553. _this._loadBuffersAsync(gltfRuntime, function () {
  1554. _this._loadShadersAsync(gltfRuntime, function () {
  1555. importMaterials(gltfRuntime);
  1556. postLoad(gltfRuntime);
  1557. if (!glTFFileLoader_1.GLTFFileLoader.IncrementalLoading) {
  1558. onSuccess();
  1559. }
  1560. });
  1561. });
  1562. if (glTFFileLoader_1.GLTFFileLoader.IncrementalLoading) {
  1563. onSuccess();
  1564. }
  1565. }, onError);
  1566. }, onError);
  1567. };
  1568. /**
  1569. * Imports all objects from a loaded gltf file and adds them to the scene
  1570. * @param scene the scene the objects should be added to
  1571. * @param data gltf data containing information of the meshes in a loaded file
  1572. * @param rootUrl root url to load from
  1573. * @param onProgress event that fires when loading progress has occured
  1574. * @returns a promise which completes when objects have been loaded to the scene
  1575. */
  1576. GLTF1Loader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  1577. var _this = this;
  1578. return new Promise(function (resolve, reject) {
  1579. _this._loadAsync(scene, data, rootUrl, function () {
  1580. resolve();
  1581. }, onProgress, function (message) {
  1582. reject(new Error(message));
  1583. });
  1584. });
  1585. };
  1586. GLTF1Loader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  1587. var hasShaders = false;
  1588. var processShader = function (sha, shader) {
  1589. glTFLoaderExtension_1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  1590. if (shaderString instanceof ArrayBuffer) {
  1591. return;
  1592. }
  1593. gltfRuntime.loadedShaderCount++;
  1594. if (shaderString) {
  1595. babylonjs_1.Effect.ShadersStore[sha + (shader.type === glTFLoaderInterfaces_1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  1596. }
  1597. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  1598. onload();
  1599. }
  1600. }, function () {
  1601. babylonjs_1.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  1602. });
  1603. };
  1604. for (var sha in gltfRuntime.shaders) {
  1605. hasShaders = true;
  1606. var shader = gltfRuntime.shaders[sha];
  1607. if (shader) {
  1608. processShader.bind(this, sha, shader)();
  1609. }
  1610. else {
  1611. babylonjs_1.Tools.Error("No shader named: " + sha);
  1612. }
  1613. }
  1614. if (!hasShaders) {
  1615. onload();
  1616. }
  1617. };
  1618. GLTF1Loader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  1619. var hasBuffers = false;
  1620. var processBuffer = function (buf, buffer) {
  1621. glTFLoaderExtension_1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  1622. gltfRuntime.loadedBufferCount++;
  1623. if (bufferView) {
  1624. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  1625. babylonjs_1.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  1626. }
  1627. gltfRuntime.loadedBufferViews[buf] = bufferView;
  1628. }
  1629. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  1630. onLoad();
  1631. }
  1632. }, function () {
  1633. babylonjs_1.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  1634. });
  1635. };
  1636. for (var buf in gltfRuntime.buffers) {
  1637. hasBuffers = true;
  1638. var buffer = gltfRuntime.buffers[buf];
  1639. if (buffer) {
  1640. processBuffer.bind(this, buf, buffer)();
  1641. }
  1642. else {
  1643. babylonjs_1.Tools.Error("No buffer named: " + buf);
  1644. }
  1645. }
  1646. if (!hasBuffers) {
  1647. onLoad();
  1648. }
  1649. };
  1650. GLTF1Loader.prototype._createNodes = function (gltfRuntime) {
  1651. var currentScene = gltfRuntime.currentScene;
  1652. if (currentScene) {
  1653. // Only one scene even if multiple scenes are defined
  1654. for (var i = 0; i < currentScene.nodes.length; i++) {
  1655. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1656. }
  1657. }
  1658. else {
  1659. // Load all scenes
  1660. for (var thing in gltfRuntime.scenes) {
  1661. currentScene = gltfRuntime.scenes[thing];
  1662. for (var i = 0; i < currentScene.nodes.length; i++) {
  1663. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1664. }
  1665. }
  1666. }
  1667. };
  1668. GLTF1Loader.Extensions = {};
  1669. return GLTF1Loader;
  1670. }());
  1671. exports.GLTF1Loader = GLTF1Loader;
  1672. glTFFileLoader_1.GLTFFileLoader._CreateGLTF1Loader = function () { return new GLTF1Loader(); };
  1673. /***/ }),
  1674. /***/ "./src/glTF/1.0/glTFBinaryExtension.ts":
  1675. /*!*********************************************!*\
  1676. !*** ./src/glTF/1.0/glTFBinaryExtension.ts ***!
  1677. \*********************************************/
  1678. /*! no static exports found */
  1679. /***/ (function(module, exports, __webpack_require__) {
  1680. "use strict";
  1681. var __extends = (this && this.__extends) || (function () {
  1682. var extendStatics = function (d, b) {
  1683. extendStatics = Object.setPrototypeOf ||
  1684. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  1685. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  1686. return extendStatics(d, b);
  1687. }
  1688. return function (d, b) {
  1689. extendStatics(d, b);
  1690. function __() { this.constructor = d; }
  1691. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1692. };
  1693. })();
  1694. Object.defineProperty(exports, "__esModule", { value: true });
  1695. var glTFLoaderExtension_1 = __webpack_require__(/*! ./glTFLoaderExtension */ "./src/glTF/1.0/glTFLoaderExtension.ts");
  1696. var glTFLoaderUtils_1 = __webpack_require__(/*! ./glTFLoaderUtils */ "./src/glTF/1.0/glTFLoaderUtils.ts");
  1697. var glTFLoaderInterfaces_1 = __webpack_require__(/*! ./glTFLoaderInterfaces */ "./src/glTF/1.0/glTFLoaderInterfaces.ts");
  1698. var glTF1Loader_1 = __webpack_require__(/*! ./glTF1Loader */ "./src/glTF/1.0/glTF1Loader.ts");
  1699. var BinaryExtensionBufferName = "binary_glTF";
  1700. /** @hidden */
  1701. var GLTFBinaryExtension = /** @class */ (function (_super) {
  1702. __extends(GLTFBinaryExtension, _super);
  1703. function GLTFBinaryExtension() {
  1704. return _super.call(this, "KHR_binary_glTF") || this;
  1705. }
  1706. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  1707. var extensionsUsed = data.json.extensionsUsed;
  1708. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  1709. return false;
  1710. }
  1711. this._bin = data.bin;
  1712. onSuccess(glTF1Loader_1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  1713. return true;
  1714. };
  1715. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1716. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  1717. return false;
  1718. }
  1719. if (id !== BinaryExtensionBufferName) {
  1720. return false;
  1721. }
  1722. onSuccess(this._bin);
  1723. return true;
  1724. };
  1725. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1726. var texture = gltfRuntime.textures[id];
  1727. var source = gltfRuntime.images[texture.source];
  1728. if (!source.extensions || !(this.name in source.extensions)) {
  1729. return false;
  1730. }
  1731. var sourceExt = source.extensions[this.name];
  1732. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  1733. var buffer = glTFLoaderUtils_1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, glTFLoaderInterfaces_1.EComponentType.UNSIGNED_BYTE);
  1734. onSuccess(buffer);
  1735. return true;
  1736. };
  1737. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1738. var shader = gltfRuntime.shaders[id];
  1739. if (!shader.extensions || !(this.name in shader.extensions)) {
  1740. return false;
  1741. }
  1742. var binaryExtensionShader = shader.extensions[this.name];
  1743. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  1744. var shaderBytes = glTFLoaderUtils_1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, glTFLoaderInterfaces_1.EComponentType.UNSIGNED_BYTE);
  1745. setTimeout(function () {
  1746. var shaderString = glTFLoaderUtils_1.GLTFUtils.DecodeBufferToText(shaderBytes);
  1747. onSuccess(shaderString);
  1748. });
  1749. return true;
  1750. };
  1751. return GLTFBinaryExtension;
  1752. }(glTFLoaderExtension_1.GLTFLoaderExtension));
  1753. exports.GLTFBinaryExtension = GLTFBinaryExtension;
  1754. glTF1Loader_1.GLTF1Loader.RegisterExtension(new GLTFBinaryExtension());
  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 glTF1Loader_1 = __webpack_require__(/*! ./glTF1Loader */ "./src/glTF/1.0/glTF1Loader.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(glTF1Loader_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. glTF1Loader_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. glTF1Loader_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. glTF1Loader_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. glTF1Loader_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. glTF1Loader_1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  1890. });
  1891. };
  1892. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  1893. for (var extensionName in glTF1Loader_1.GLTF1Loader.Extensions) {
  1894. var loaderExtension = glTF1Loader_1.GLTF1Loader.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 glTF1Loader_1 = __webpack_require__(/*! ./glTF1Loader */ "./src/glTF/1.0/glTF1Loader.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. glTF1Loader_1.GLTF1Loader.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__(/*! ./glTF1Loader */ "./src/glTF/1.0/glTF1Loader.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