babylon.objFileLoader.js 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365
  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. })((typeof self !== "undefined" ? self : typeof global !== "undefined" ? global : this), function(__WEBPACK_EXTERNAL_MODULE_babylonjs_Misc_tools__) {
  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-objFileLoader.ts");
  95. /******/ })
  96. /************************************************************************/
  97. /******/ ({
  98. /***/ "../../node_modules/webpack/buildin/global.js":
  99. /*!***********************************!*\
  100. !*** (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 || new Function("return 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. /***/ "./OBJ/index.ts":
  122. /*!**********************!*\
  123. !*** ./OBJ/index.ts ***!
  124. \**********************/
  125. /*! exports provided: MTLFileLoader, OBJFileLoader */
  126. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  127. "use strict";
  128. __webpack_require__.r(__webpack_exports__);
  129. /* harmony import */ var _mtlFileLoader__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./mtlFileLoader */ "./OBJ/mtlFileLoader.ts");
  130. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MTLFileLoader", function() { return _mtlFileLoader__WEBPACK_IMPORTED_MODULE_0__["MTLFileLoader"]; });
  131. /* harmony import */ var _objFileLoader__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./objFileLoader */ "./OBJ/objFileLoader.ts");
  132. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OBJFileLoader", function() { return _objFileLoader__WEBPACK_IMPORTED_MODULE_1__["OBJFileLoader"]; });
  133. /***/ }),
  134. /***/ "./OBJ/mtlFileLoader.ts":
  135. /*!******************************!*\
  136. !*** ./OBJ/mtlFileLoader.ts ***!
  137. \******************************/
  138. /*! exports provided: MTLFileLoader */
  139. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  140. "use strict";
  141. __webpack_require__.r(__webpack_exports__);
  142. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MTLFileLoader", function() { return MTLFileLoader; });
  143. /* harmony import */ var babylonjs_Maths_math_color__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! babylonjs/Maths/math.color */ "babylonjs/Misc/tools");
  144. /* harmony import */ var babylonjs_Maths_math_color__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Maths_math_color__WEBPACK_IMPORTED_MODULE_0__);
  145. /**
  146. * Class reading and parsing the MTL file bundled with the obj file.
  147. */
  148. var MTLFileLoader = /** @class */ (function () {
  149. function MTLFileLoader() {
  150. /**
  151. * All material loaded from the mtl will be set here
  152. */
  153. this.materials = [];
  154. }
  155. /**
  156. * This function will read the mtl file and create each material described inside
  157. * This function could be improve by adding :
  158. * -some component missing (Ni, Tf...)
  159. * -including the specific options available
  160. *
  161. * @param scene defines the scene the material will be created in
  162. * @param data defines the mtl data to parse
  163. * @param rootUrl defines the rooturl to use in order to load relative dependencies
  164. * @param forAssetContainer defines if the material should be registered in the scene
  165. */
  166. MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl, forAssetContainer) {
  167. if (data instanceof ArrayBuffer) {
  168. return;
  169. }
  170. //Split the lines from the file
  171. var lines = data.split('\n');
  172. //Space char
  173. var delimiter_pattern = /\s+/;
  174. //Array with RGB colors
  175. var color;
  176. //New material
  177. var material = null;
  178. //Look at each line
  179. for (var i = 0; i < lines.length; i++) {
  180. var line = lines[i].trim();
  181. // Blank line or comment
  182. if (line.length === 0 || line.charAt(0) === '#') {
  183. continue;
  184. }
  185. //Get the first parameter (keyword)
  186. var pos = line.indexOf(' ');
  187. var key = (pos >= 0) ? line.substring(0, pos) : line;
  188. key = key.toLowerCase();
  189. //Get the data following the key
  190. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  191. //This mtl keyword will create the new material
  192. if (key === "newmtl") {
  193. //Check if it is the first material.
  194. // Materials specifications are described after this keyword.
  195. if (material) {
  196. //Add the previous material in the material array.
  197. this.materials.push(material);
  198. }
  199. //Create a new material.
  200. // value is the name of the material read in the mtl file
  201. scene._blockEntityCollection = forAssetContainer;
  202. material = new babylonjs_Maths_math_color__WEBPACK_IMPORTED_MODULE_0__["StandardMaterial"](value, scene);
  203. scene._blockEntityCollection = false;
  204. }
  205. else if (key === "kd" && material) {
  206. // Diffuse color (color under white light) using RGB values
  207. //value = "r g b"
  208. color = value.split(delimiter_pattern, 3).map(parseFloat);
  209. //color = [r,g,b]
  210. //Set tghe color into the material
  211. material.diffuseColor = babylonjs_Maths_math_color__WEBPACK_IMPORTED_MODULE_0__["Color3"].FromArray(color);
  212. }
  213. else if (key === "ka" && material) {
  214. // Ambient color (color under shadow) using RGB values
  215. //value = "r g b"
  216. color = value.split(delimiter_pattern, 3).map(parseFloat);
  217. //color = [r,g,b]
  218. //Set tghe color into the material
  219. material.ambientColor = babylonjs_Maths_math_color__WEBPACK_IMPORTED_MODULE_0__["Color3"].FromArray(color);
  220. }
  221. else if (key === "ks" && material) {
  222. // Specular color (color when light is reflected from shiny surface) using RGB values
  223. //value = "r g b"
  224. color = value.split(delimiter_pattern, 3).map(parseFloat);
  225. //color = [r,g,b]
  226. //Set the color into the material
  227. material.specularColor = babylonjs_Maths_math_color__WEBPACK_IMPORTED_MODULE_0__["Color3"].FromArray(color);
  228. }
  229. else if (key === "ke" && material) {
  230. // Emissive color using RGB values
  231. color = value.split(delimiter_pattern, 3).map(parseFloat);
  232. material.emissiveColor = babylonjs_Maths_math_color__WEBPACK_IMPORTED_MODULE_0__["Color3"].FromArray(color);
  233. }
  234. else if (key === "ns" && material) {
  235. //value = "Integer"
  236. material.specularPower = parseFloat(value);
  237. }
  238. else if (key === "d" && material) {
  239. //d is dissolve for current material. It mean alpha for BABYLON
  240. material.alpha = parseFloat(value);
  241. //Texture
  242. //This part can be improved by adding the possible options of texture
  243. }
  244. else if (key === "map_ka" && material) {
  245. // ambient texture map with a loaded image
  246. //We must first get the folder of the image
  247. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  248. }
  249. else if (key === "map_kd" && material) {
  250. // Diffuse texture map with a loaded image
  251. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  252. }
  253. else if (key === "map_ks" && material) {
  254. // Specular texture map with a loaded image
  255. //We must first get the folder of the image
  256. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  257. }
  258. else if (key === "map_ns") {
  259. //Specular
  260. //Specular highlight component
  261. //We must first get the folder of the image
  262. //
  263. //Not supported by BABYLON
  264. //
  265. // continue;
  266. }
  267. else if (key === "map_bump" && material) {
  268. //The bump texture
  269. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  270. }
  271. else if (key === "map_d" && material) {
  272. // The dissolve of the material
  273. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  274. //Options for illumination
  275. }
  276. else if (key === "illum") {
  277. //Illumination
  278. if (value === "0") {
  279. //That mean Kd == Kd
  280. }
  281. else if (value === "1") {
  282. //Color on and Ambient on
  283. }
  284. else if (value === "2") {
  285. //Highlight on
  286. }
  287. else if (value === "3") {
  288. //Reflection on and Ray trace on
  289. }
  290. else if (value === "4") {
  291. //Transparency: Glass on, Reflection: Ray trace on
  292. }
  293. else if (value === "5") {
  294. //Reflection: Fresnel on and Ray trace on
  295. }
  296. else if (value === "6") {
  297. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  298. }
  299. else if (value === "7") {
  300. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  301. }
  302. else if (value === "8") {
  303. //Reflection on and Ray trace off
  304. }
  305. else if (value === "9") {
  306. //Transparency: Glass on, Reflection: Ray trace off
  307. }
  308. else if (value === "10") {
  309. //Casts shadows onto invisible surfaces
  310. }
  311. }
  312. else {
  313. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  314. }
  315. }
  316. //At the end of the file, add the last material
  317. if (material) {
  318. this.materials.push(material);
  319. }
  320. };
  321. /**
  322. * Gets the texture for the material.
  323. *
  324. * If the material is imported from input file,
  325. * We sanitize the url to ensure it takes the textre from aside the material.
  326. *
  327. * @param rootUrl The root url to load from
  328. * @param value The value stored in the mtl
  329. * @return The Texture
  330. */
  331. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  332. if (!value) {
  333. return null;
  334. }
  335. var url = rootUrl;
  336. // Load from input file.
  337. if (rootUrl === "file:") {
  338. var lastDelimiter = value.lastIndexOf("\\");
  339. if (lastDelimiter === -1) {
  340. lastDelimiter = value.lastIndexOf("/");
  341. }
  342. if (lastDelimiter > -1) {
  343. url += value.substr(lastDelimiter + 1);
  344. }
  345. else {
  346. url += value;
  347. }
  348. }
  349. // Not from input file.
  350. else {
  351. url += value;
  352. }
  353. return new babylonjs_Maths_math_color__WEBPACK_IMPORTED_MODULE_0__["Texture"](url, scene, false, MTLFileLoader.INVERT_TEXTURE_Y);
  354. };
  355. /**
  356. * Invert Y-Axis of referenced textures on load
  357. */
  358. MTLFileLoader.INVERT_TEXTURE_Y = true;
  359. return MTLFileLoader;
  360. }());
  361. /***/ }),
  362. /***/ "./OBJ/objFileLoader.ts":
  363. /*!******************************!*\
  364. !*** ./OBJ/objFileLoader.ts ***!
  365. \******************************/
  366. /*! exports provided: OBJFileLoader */
  367. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  368. "use strict";
  369. __webpack_require__.r(__webpack_exports__);
  370. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OBJFileLoader", function() { return OBJFileLoader; });
  371. /* harmony import */ var babylonjs_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! babylonjs/Maths/math.vector */ "babylonjs/Misc/tools");
  372. /* harmony import */ var babylonjs_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__);
  373. /* harmony import */ var _mtlFileLoader__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./mtlFileLoader */ "./OBJ/mtlFileLoader.ts");
  374. /**
  375. * OBJ file type loader.
  376. * This is a babylon scene loader plugin.
  377. */
  378. var OBJFileLoader = /** @class */ (function () {
  379. /**
  380. * Creates loader for .OBJ files
  381. *
  382. * @param meshLoadOptions options for loading and parsing OBJ/MTL files.
  383. */
  384. function OBJFileLoader(meshLoadOptions) {
  385. /**
  386. * Defines the name of the plugin.
  387. */
  388. this.name = "obj";
  389. /**
  390. * Defines the extension the plugin is able to load.
  391. */
  392. this.extensions = ".obj";
  393. /** @hidden */
  394. this.obj = /^o/;
  395. /** @hidden */
  396. this.group = /^g/;
  397. /** @hidden */
  398. this.mtllib = /^mtllib /;
  399. /** @hidden */
  400. this.usemtl = /^usemtl /;
  401. /** @hidden */
  402. this.smooth = /^s /;
  403. /** @hidden */
  404. this.vertexPattern = /v(\s+[\d|\.|\+|\-|e|E]+){3,7}/;
  405. // vn float float float
  406. /** @hidden */
  407. this.normalPattern = /vn(\s+[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  408. // vt float float
  409. /** @hidden */
  410. this.uvPattern = /vt(\s+[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  411. // f vertex vertex vertex ...
  412. /** @hidden */
  413. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  414. // f vertex/uvs vertex/uvs vertex/uvs ...
  415. /** @hidden */
  416. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  417. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  418. /** @hidden */
  419. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  420. // f vertex//normal vertex//normal vertex//normal ...
  421. /** @hidden */
  422. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  423. // f -vertex/-uvs/-normal -vertex/-uvs/-normal -vertex/-uvs/-normal ...
  424. /** @hidden */
  425. this.facePattern5 = /f\s+(((-[\d]{1,}\/-[\d]{1,}\/-[\d]{1,}[\s]?){3,})+)/;
  426. this._forAssetContainer = false;
  427. this._meshLoadOptions = meshLoadOptions || OBJFileLoader.currentMeshLoadOptions;
  428. }
  429. Object.defineProperty(OBJFileLoader, "INVERT_TEXTURE_Y", {
  430. /**
  431. * Invert Y-Axis of referenced textures on load
  432. */
  433. get: function () {
  434. return _mtlFileLoader__WEBPACK_IMPORTED_MODULE_1__["MTLFileLoader"].INVERT_TEXTURE_Y;
  435. },
  436. set: function (value) {
  437. _mtlFileLoader__WEBPACK_IMPORTED_MODULE_1__["MTLFileLoader"].INVERT_TEXTURE_Y = value;
  438. },
  439. enumerable: false,
  440. configurable: true
  441. });
  442. Object.defineProperty(OBJFileLoader, "currentMeshLoadOptions", {
  443. get: function () {
  444. return {
  445. ComputeNormals: OBJFileLoader.COMPUTE_NORMALS,
  446. OptimizeNormals: OBJFileLoader.OPTIMIZE_NORMALS,
  447. ImportVertexColors: OBJFileLoader.IMPORT_VERTEX_COLORS,
  448. InvertY: OBJFileLoader.INVERT_Y,
  449. InvertTextureY: OBJFileLoader.INVERT_TEXTURE_Y,
  450. UVScaling: OBJFileLoader.UV_SCALING,
  451. MaterialLoadingFailsSilently: OBJFileLoader.MATERIAL_LOADING_FAILS_SILENTLY,
  452. OptimizeWithUV: OBJFileLoader.OPTIMIZE_WITH_UV,
  453. SkipMaterials: OBJFileLoader.SKIP_MATERIALS
  454. };
  455. },
  456. enumerable: false,
  457. configurable: true
  458. });
  459. /**
  460. * Calls synchronously the MTL file attached to this obj.
  461. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  462. * Without this function materials are not displayed in the first frame (but displayed after).
  463. * In consequence it is impossible to get material information in your HTML file
  464. *
  465. * @param url The URL of the MTL file
  466. * @param rootUrl
  467. * @param onSuccess Callback function to be called when the MTL file is loaded
  468. * @private
  469. */
  470. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess, onFailure) {
  471. //The complete path to the mtl file
  472. var pathOfFile = babylonjs_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Tools"].BaseUrl + rootUrl + url;
  473. // Loads through the babylon tools to allow fileInput search.
  474. babylonjs_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Tools"].LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function (request, exception) {
  475. onFailure(pathOfFile, exception);
  476. });
  477. };
  478. /**
  479. * Instantiates a OBJ file loader plugin.
  480. * @returns the created plugin
  481. */
  482. OBJFileLoader.prototype.createPlugin = function () {
  483. return new OBJFileLoader(OBJFileLoader.currentMeshLoadOptions);
  484. };
  485. /**
  486. * If the data string can be loaded directly.
  487. *
  488. * @param data string containing the file data
  489. * @returns if the data can be loaded directly
  490. */
  491. OBJFileLoader.prototype.canDirectLoad = function (data) {
  492. return false;
  493. };
  494. /**
  495. * Imports one or more meshes from the loaded OBJ data and adds them to the scene
  496. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  497. * @param scene the scene the meshes should be added to
  498. * @param data the OBJ data to load
  499. * @param rootUrl root url to load from
  500. * @param onProgress event that fires when loading progress has occured
  501. * @param fileName Defines the name of the file to load
  502. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  503. */
  504. OBJFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress, fileName) {
  505. //get the meshes from OBJ file
  506. return this._parseSolid(meshesNames, scene, data, rootUrl).then(function (meshes) {
  507. return {
  508. meshes: meshes,
  509. particleSystems: [],
  510. skeletons: [],
  511. animationGroups: [],
  512. transformNodes: [],
  513. geometries: [],
  514. lights: []
  515. };
  516. });
  517. };
  518. /**
  519. * Imports all objects from the loaded OBJ data and adds them to the scene
  520. * @param scene the scene the objects should be added to
  521. * @param data the OBJ data to load
  522. * @param rootUrl root url to load from
  523. * @param onProgress event that fires when loading progress has occured
  524. * @param fileName Defines the name of the file to load
  525. * @returns a promise which completes when objects have been loaded to the scene
  526. */
  527. OBJFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress, fileName) {
  528. //Get the 3D model
  529. return this.importMeshAsync(null, scene, data, rootUrl, onProgress).then(function () {
  530. // return void
  531. });
  532. };
  533. /**
  534. * Load into an asset container.
  535. * @param scene The scene to load into
  536. * @param data The data to import
  537. * @param rootUrl The root url for scene and resources
  538. * @param onProgress The callback when the load progresses
  539. * @param fileName Defines the name of the file to load
  540. * @returns The loaded asset container
  541. */
  542. OBJFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress, fileName) {
  543. var _this = this;
  544. this._forAssetContainer = true;
  545. return this.importMeshAsync(null, scene, data, rootUrl).then(function (result) {
  546. var container = new babylonjs_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["AssetContainer"](scene);
  547. result.meshes.forEach(function (mesh) { return container.meshes.push(mesh); });
  548. result.meshes.forEach(function (mesh) {
  549. var material = mesh.material;
  550. if (material) {
  551. // Materials
  552. if (container.materials.indexOf(material) == -1) {
  553. container.materials.push(material);
  554. // Textures
  555. var textures = material.getActiveTextures();
  556. textures.forEach(function (t) {
  557. if (container.textures.indexOf(t) == -1) {
  558. container.textures.push(t);
  559. }
  560. });
  561. }
  562. }
  563. });
  564. _this._forAssetContainer = false;
  565. return container;
  566. }).catch(function (ex) {
  567. _this._forAssetContainer = false;
  568. throw ex;
  569. });
  570. };
  571. OBJFileLoader.prototype._optimizeNormals = function (mesh) {
  572. var positions = mesh.getVerticesData(babylonjs_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].PositionKind);
  573. var normals = mesh.getVerticesData(babylonjs_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].NormalKind);
  574. var mapVertices = {};
  575. if (!positions || !normals) {
  576. return;
  577. }
  578. for (var i = 0; i < positions.length / 3; i++) {
  579. var x = positions[i * 3 + 0];
  580. var y = positions[i * 3 + 1];
  581. var z = positions[i * 3 + 2];
  582. var key = x + "_" + y + "_" + z;
  583. var lst = mapVertices[key];
  584. if (!lst) {
  585. lst = [];
  586. mapVertices[key] = lst;
  587. }
  588. lst.push(i);
  589. }
  590. var normal = new babylonjs_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"]();
  591. for (var key in mapVertices) {
  592. var lst = mapVertices[key];
  593. if (lst.length < 2) {
  594. continue;
  595. }
  596. var v0Idx = lst[0];
  597. for (var i = 1; i < lst.length; ++i) {
  598. var vIdx = lst[i];
  599. normals[v0Idx * 3 + 0] += normals[vIdx * 3 + 0];
  600. normals[v0Idx * 3 + 1] += normals[vIdx * 3 + 1];
  601. normals[v0Idx * 3 + 2] += normals[vIdx * 3 + 2];
  602. }
  603. normal.copyFromFloats(normals[v0Idx * 3 + 0], normals[v0Idx * 3 + 1], normals[v0Idx * 3 + 2]);
  604. normal.normalize();
  605. for (var i = 0; i < lst.length; ++i) {
  606. var vIdx = lst[i];
  607. normals[vIdx * 3 + 0] = normal.x;
  608. normals[vIdx * 3 + 1] = normal.y;
  609. normals[vIdx * 3 + 2] = normal.z;
  610. }
  611. }
  612. mesh.setVerticesData(babylonjs_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].NormalKind, normals);
  613. };
  614. /**
  615. * Read the OBJ file and create an Array of meshes.
  616. * Each mesh contains all information given by the OBJ and the MTL file.
  617. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  618. *
  619. * @param meshesNames
  620. * @param scene Scene The scene where are displayed the data
  621. * @param data String The content of the obj file
  622. * @param rootUrl String The path to the folder
  623. * @returns Array<AbstractMesh>
  624. * @private
  625. */
  626. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  627. var _this = this;
  628. var positions = []; //values for the positions of vertices
  629. var normals = []; //Values for the normals
  630. var uvs = []; //Values for the textures
  631. var colors = [];
  632. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  633. var handledMesh; //The current mesh of meshes array
  634. var indicesForBabylon = []; //The list of indices for VertexData
  635. var wrappedPositionForBabylon = []; //The list of position in vectors
  636. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  637. var wrappedColorsForBabylon = []; // Array with all color values to match with the indices
  638. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  639. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  640. var curPositionInIndices = 0;
  641. var hasMeshes = false; //Meshes are defined in the file
  642. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  643. var unwrappedColorsForBabylon = []; // Value of colorForBabylon w/o Color4() [r,g,b,a]
  644. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  645. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  646. var triangles = []; //Indices from new triangles coming from polygons
  647. var materialNameFromObj = ""; //The name of the current material
  648. var fileToLoad = ""; //The name of the mtlFile to load
  649. var materialsFromMTLFile = new _mtlFileLoader__WEBPACK_IMPORTED_MODULE_1__["MTLFileLoader"]();
  650. var objMeshName = ""; //The name of the current obj mesh
  651. var increment = 1; //Id for meshes created by the multimaterial
  652. var isFirstMaterial = true;
  653. var grayColor = new babylonjs_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Color4"](0.5, 0.5, 0.5, 1);
  654. /**
  655. * Search for obj in the given array.
  656. * This function is called to check if a couple of data already exists in an array.
  657. *
  658. * If found, returns the index of the founded tuple index. Returns -1 if not found
  659. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  660. * @param obj Array<number>
  661. * @returns {boolean}
  662. */
  663. var isInArray = function (arr, obj) {
  664. if (!arr[obj[0]]) {
  665. arr[obj[0]] = { normals: [], idx: [] };
  666. }
  667. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  668. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  669. };
  670. var isInArrayUV = function (arr, obj) {
  671. if (!arr[obj[0]]) {
  672. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  673. }
  674. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  675. if (idx != 1 && (obj[2] === arr[obj[0]].uv[idx])) {
  676. return arr[obj[0]].idx[idx];
  677. }
  678. return -1;
  679. };
  680. /**
  681. * This function set the data for each triangle.
  682. * Data are position, normals and uvs
  683. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  684. * If the tuple already exist, add only their indice
  685. *
  686. * @param indicePositionFromObj Integer The index in positions array
  687. * @param indiceUvsFromObj Integer The index in uvs array
  688. * @param indiceNormalFromObj Integer The index in normals array
  689. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  690. * @param textureVectorFromOBJ Vector3 The value of uvs
  691. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  692. */
  693. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ, positionColorsFromOBJ) {
  694. //Check if this tuple already exists in the list of tuples
  695. var _index;
  696. if (_this._meshLoadOptions.OptimizeWithUV) {
  697. _index = isInArrayUV(tuplePosNorm, [
  698. indicePositionFromObj,
  699. indiceNormalFromObj,
  700. indiceUvsFromObj
  701. ]);
  702. }
  703. else {
  704. _index = isInArray(tuplePosNorm, [
  705. indicePositionFromObj,
  706. indiceNormalFromObj
  707. ]);
  708. }
  709. //If it not exists
  710. if (_index === -1) {
  711. //Add an new indice.
  712. //The array of indices is only an array with his length equal to the number of triangles - 1.
  713. //We add vertices data in this order
  714. indicesForBabylon.push(wrappedPositionForBabylon.length);
  715. //Push the position of vertice for Babylon
  716. //Each element is a Vector3(x,y,z)
  717. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  718. //Push the uvs for Babylon
  719. //Each element is a Vector3(u,v)
  720. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  721. //Push the normals for Babylon
  722. //Each element is a Vector3(x,y,z)
  723. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  724. if (positionColorsFromOBJ !== undefined) {
  725. //Push the colors for Babylon
  726. //Each element is a BABYLON.Color4(r,g,b,a)
  727. wrappedColorsForBabylon.push(positionColorsFromOBJ);
  728. }
  729. //Add the tuple in the comparison list
  730. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  731. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  732. if (_this._meshLoadOptions.OptimizeWithUV) {
  733. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  734. }
  735. }
  736. else {
  737. //The tuple already exists
  738. //Add the index of the already existing tuple
  739. //At this index we can get the value of position, normal, color and uvs of vertex
  740. indicesForBabylon.push(_index);
  741. }
  742. };
  743. /**
  744. * Transform Vector() and BABYLON.Color() objects into numbers in an array
  745. */
  746. var unwrapData = function () {
  747. //Every array has the same length
  748. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  749. //Push the x, y, z values of each element in the unwrapped array
  750. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  751. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  752. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  753. if (_this._meshLoadOptions.ImportVertexColors === true) {
  754. //Push the r, g, b, a values of each element in the unwrapped array
  755. unwrappedColorsForBabylon.push(wrappedColorsForBabylon[l].r, wrappedColorsForBabylon[l].g, wrappedColorsForBabylon[l].b, wrappedColorsForBabylon[l].a);
  756. }
  757. }
  758. // Reset arrays for the next new meshes
  759. wrappedPositionForBabylon = [];
  760. wrappedNormalsForBabylon = [];
  761. wrappedUvsForBabylon = [];
  762. wrappedColorsForBabylon = [];
  763. tuplePosNorm = [];
  764. curPositionInIndices = 0;
  765. };
  766. /**
  767. * Create triangles from polygons
  768. * It is important to notice that a triangle is a polygon
  769. * We get 5 patterns of face defined in OBJ File :
  770. * facePattern1 = ["1","2","3","4","5","6"]
  771. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  772. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  773. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  774. * facePattern5 = ["-1/-1/-1","-2/-2/-2","-3/-3/-3","-4/-4/-4","-5/-5/-5","-6/-6/-6"]
  775. * Each pattern is divided by the same method
  776. * @param face Array[String] The indices of elements
  777. * @param v Integer The variable to increment
  778. */
  779. var getTriangles = function (faces, v) {
  780. //Work for each element of the array
  781. for (var faceIndex = v; faceIndex < faces.length - 1; faceIndex++) {
  782. //Add on the triangle variable the indexes to obtain triangles
  783. triangles.push(faces[0], faces[faceIndex], faces[faceIndex + 1]);
  784. }
  785. //Result obtained after 2 iterations:
  786. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  787. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  788. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  789. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  790. //Pattern5 => triangle = ["-1/-1/-1","-2/-2/-2","-3/-3/-3","-1/-1/-1","-3/-3/-3","-4/-4/-4"];
  791. };
  792. /**
  793. * Create triangles and push the data for each polygon for the pattern 1
  794. * In this pattern we get vertice positions
  795. * @param face
  796. * @param v
  797. */
  798. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  799. //Get the indices of triangles for each polygon
  800. getTriangles(face, v);
  801. //For each element in the triangles array.
  802. //This var could contains 1 to an infinity of triangles
  803. for (var k = 0; k < triangles.length; k++) {
  804. // Set position indice
  805. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  806. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  807. positions[indicePositionFromObj], //Get the vectors data
  808. babylonjs_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector2"].Zero(), babylonjs_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Up(), //Create default vectors
  809. _this._meshLoadOptions.ImportVertexColors === true ? colors[indicePositionFromObj] : undefined);
  810. }
  811. //Reset variable for the next line
  812. triangles = [];
  813. };
  814. /**
  815. * Create triangles and push the data for each polygon for the pattern 2
  816. * In this pattern we get vertice positions and uvsu
  817. * @param face
  818. * @param v
  819. */
  820. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  821. //Get the indices of triangles for each polygon
  822. getTriangles(face, v);
  823. for (var k = 0; k < triangles.length; k++) {
  824. //triangle[k] = "1/1"
  825. //Split the data for getting position and uv
  826. var point = triangles[k].split("/"); // ["1", "1"]
  827. //Set position indice
  828. var indicePositionFromObj = parseInt(point[0]) - 1;
  829. //Set uv indice
  830. var indiceUvsFromObj = parseInt(point[1]) - 1;
  831. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  832. positions[indicePositionFromObj], //Get the values for each element
  833. uvs[indiceUvsFromObj], babylonjs_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Up(), //Default value for normals
  834. _this._meshLoadOptions.ImportVertexColors === true ? colors[indicePositionFromObj] : undefined);
  835. }
  836. //Reset variable for the next line
  837. triangles = [];
  838. };
  839. /**
  840. * Create triangles and push the data for each polygon for the pattern 3
  841. * In this pattern we get vertice positions, uvs and normals
  842. * @param face
  843. * @param v
  844. */
  845. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  846. //Get the indices of triangles for each polygon
  847. getTriangles(face, v);
  848. for (var k = 0; k < triangles.length; k++) {
  849. //triangle[k] = "1/1/1"
  850. //Split the data for getting position, uv, and normals
  851. var point = triangles[k].split("/"); // ["1", "1", "1"]
  852. // Set position indice
  853. var indicePositionFromObj = parseInt(point[0]) - 1;
  854. // Set uv indice
  855. var indiceUvsFromObj = parseInt(point[1]) - 1;
  856. // Set normal indice
  857. var indiceNormalFromObj = parseInt(point[2]) - 1;
  858. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  859. );
  860. }
  861. //Reset variable for the next line
  862. triangles = [];
  863. };
  864. /**
  865. * Create triangles and push the data for each polygon for the pattern 4
  866. * In this pattern we get vertice positions and normals
  867. * @param face
  868. * @param v
  869. */
  870. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  871. getTriangles(face, v);
  872. for (var k = 0; k < triangles.length; k++) {
  873. //triangle[k] = "1//1"
  874. //Split the data for getting position and normals
  875. var point = triangles[k].split("//"); // ["1", "1"]
  876. // We check indices, and normals
  877. var indicePositionFromObj = parseInt(point[0]) - 1;
  878. var indiceNormalFromObj = parseInt(point[1]) - 1;
  879. setData(indicePositionFromObj, 1, //Default value for uv
  880. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  881. babylonjs_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector2"].Zero(), normals[indiceNormalFromObj], _this._meshLoadOptions.ImportVertexColors === true ? colors[indicePositionFromObj] : undefined);
  882. }
  883. //Reset variable for the next line
  884. triangles = [];
  885. };
  886. /**
  887. * Create triangles and push the data for each polygon for the pattern 3
  888. * In this pattern we get vertice positions, uvs and normals
  889. * @param face
  890. * @param v
  891. */
  892. var setDataForCurrentFaceWithPattern5 = function (face, v) {
  893. //Get the indices of triangles for each polygon
  894. getTriangles(face, v);
  895. for (var k = 0; k < triangles.length; k++) {
  896. //triangle[k] = "-1/-1/-1"
  897. //Split the data for getting position, uv, and normals
  898. var point = triangles[k].split("/"); // ["-1", "-1", "-1"]
  899. // Set position indice
  900. var indicePositionFromObj = positions.length + parseInt(point[0]);
  901. // Set uv indice
  902. var indiceUvsFromObj = uvs.length + parseInt(point[1]);
  903. // Set normal indice
  904. var indiceNormalFromObj = normals.length + parseInt(point[2]);
  905. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj], //Set the vector for each component
  906. _this._meshLoadOptions.ImportVertexColors === true ? colors[indicePositionFromObj] : undefined);
  907. }
  908. //Reset variable for the next line
  909. triangles = [];
  910. };
  911. var addPreviousObjMesh = function () {
  912. //Check if it is not the first mesh. Otherwise we don't have data.
  913. if (meshesFromObj.length > 0) {
  914. //Get the previous mesh for applying the data about the faces
  915. //=> in obj file, faces definition append after the name of the mesh
  916. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  917. //Set the data into Array for the mesh
  918. unwrapData();
  919. // Reverse tab. Otherwise face are displayed in the wrong sens
  920. indicesForBabylon.reverse();
  921. //Set the information for the mesh
  922. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  923. handledMesh.indices = indicesForBabylon.slice();
  924. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  925. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  926. handledMesh.uvs = unwrappedUVForBabylon.slice();
  927. if (_this._meshLoadOptions.ImportVertexColors === true) {
  928. handledMesh.colors = unwrappedColorsForBabylon.slice();
  929. }
  930. //Reset the array for the next mesh
  931. indicesForBabylon = [];
  932. unwrappedPositionsForBabylon = [];
  933. unwrappedColorsForBabylon = [];
  934. unwrappedNormalsForBabylon = [];
  935. unwrappedUVForBabylon = [];
  936. }
  937. };
  938. //Main function
  939. //Split the file into lines
  940. var lines = data.split('\n');
  941. //Look at each line
  942. for (var i = 0; i < lines.length; i++) {
  943. var line = lines[i].trim().replace(/\s\s/g, " ");
  944. var result;
  945. //Comment or newLine
  946. if (line.length === 0 || line.charAt(0) === '#') {
  947. continue;
  948. //Get information about one position possible for the vertices
  949. }
  950. else if (this.vertexPattern.test(line)) {
  951. result = line.match(/[^ ]+/g); // match will return non-null due to passing regex pattern
  952. // Value of result with line: "v 1.0 2.0 3.0"
  953. // ["v", "1.0", "2.0", "3.0"]
  954. // Create a Vector3 with the position x, y, z
  955. positions.push(new babylonjs_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"](parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  956. if (this._meshLoadOptions.ImportVertexColors === true) {
  957. if (result.length >= 7) {
  958. // TODO: if these numbers are > 1 we can use Color4.FromInts(r,g,b,a)
  959. colors.push(new babylonjs_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Color4"](parseFloat(result[4]), parseFloat(result[5]), parseFloat(result[6]), (result.length === 7 || result[7] === undefined) ? 1 : parseFloat(result[7])));
  960. }
  961. else {
  962. // TODO: maybe push NULL and if all are NULL to skip (and remove grayColor var).
  963. colors.push(grayColor);
  964. }
  965. }
  966. }
  967. else if ((result = this.normalPattern.exec(line)) !== null) {
  968. //Create a Vector3 with the normals x, y, z
  969. //Value of result
  970. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  971. //Add the Vector in the list of normals
  972. normals.push(new babylonjs_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"](parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  973. }
  974. else if ((result = this.uvPattern.exec(line)) !== null) {
  975. //Create a Vector2 with the normals u, v
  976. //Value of result
  977. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  978. //Add the Vector in the list of uvs
  979. uvs.push(new babylonjs_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector2"](parseFloat(result[1]) * OBJFileLoader.UV_SCALING.x, parseFloat(result[2]) * OBJFileLoader.UV_SCALING.y));
  980. //Identify patterns of faces
  981. //Face could be defined in different type of pattern
  982. }
  983. else if ((result = this.facePattern3.exec(line)) !== null) {
  984. //Value of result:
  985. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  986. //Set the data for this face
  987. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  988. 1);
  989. }
  990. else if ((result = this.facePattern4.exec(line)) !== null) {
  991. //Value of result:
  992. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  993. //Set the data for this face
  994. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  995. 1);
  996. }
  997. else if ((result = this.facePattern5.exec(line)) !== null) {
  998. //Value of result:
  999. //["f -1/-1/-1 -2/-2/-2 -3/-3/-3", "-1/-1/-1 -2/-2/-2 -3/-3/-3"...]
  1000. //Set the data for this face
  1001. setDataForCurrentFaceWithPattern5(result[1].trim().split(" "), // ["-1/-1/-1", "-2/-2/-2", "-3/-3/-3"]
  1002. 1);
  1003. }
  1004. else if ((result = this.facePattern2.exec(line)) !== null) {
  1005. //Value of result:
  1006. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  1007. //Set the data for this face
  1008. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  1009. 1);
  1010. }
  1011. else if ((result = this.facePattern1.exec(line)) !== null) {
  1012. //Value of result
  1013. //["f 1 2 3", "1 2 3"...]
  1014. //Set the data for this face
  1015. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  1016. 1);
  1017. //Define a mesh or an object
  1018. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  1019. }
  1020. else if (this.group.test(line) || this.obj.test(line)) {
  1021. //Create a new mesh corresponding to the name of the group.
  1022. //Definition of the mesh
  1023. var objMesh = {
  1024. name: line.substring(2).trim(),
  1025. indices: undefined,
  1026. positions: undefined,
  1027. normals: undefined,
  1028. uvs: undefined,
  1029. colors: undefined,
  1030. materialName: ""
  1031. };
  1032. addPreviousObjMesh();
  1033. //Push the last mesh created with only the name
  1034. meshesFromObj.push(objMesh);
  1035. //Set this variable to indicate that now meshesFromObj has objects defined inside
  1036. hasMeshes = true;
  1037. isFirstMaterial = true;
  1038. increment = 1;
  1039. //Keyword for applying a material
  1040. }
  1041. else if (this.usemtl.test(line)) {
  1042. //Get the name of the material
  1043. materialNameFromObj = line.substring(7).trim();
  1044. //If this new material is in the same mesh
  1045. if (!isFirstMaterial || !hasMeshes) {
  1046. //Set the data for the previous mesh
  1047. addPreviousObjMesh();
  1048. //Create a new mesh
  1049. var objMesh =
  1050. //Set the name of the current obj mesh
  1051. {
  1052. name: (objMeshName || "mesh") + "_mm" + increment.toString(),
  1053. indices: undefined,
  1054. positions: undefined,
  1055. normals: undefined,
  1056. uvs: undefined,
  1057. colors: undefined,
  1058. materialName: materialNameFromObj
  1059. };
  1060. increment++;
  1061. //If meshes are already defined
  1062. meshesFromObj.push(objMesh);
  1063. hasMeshes = true;
  1064. }
  1065. //Set the material name if the previous line define a mesh
  1066. if (hasMeshes && isFirstMaterial) {
  1067. //Set the material name to the previous mesh (1 material per mesh)
  1068. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  1069. isFirstMaterial = false;
  1070. }
  1071. //Keyword for loading the mtl file
  1072. }
  1073. else if (this.mtllib.test(line)) {
  1074. //Get the name of mtl file
  1075. fileToLoad = line.substring(7).trim();
  1076. //Apply smoothing
  1077. }
  1078. else if (this.smooth.test(line)) {
  1079. // smooth shading => apply smoothing
  1080. //Today I don't know it work with babylon and with obj.
  1081. //With the obj file an integer is set
  1082. }
  1083. else {
  1084. //If there is another possibility
  1085. console.log("Unhandled expression at line : " + line);
  1086. }
  1087. }
  1088. //At the end of the file, add the last mesh into the meshesFromObj array
  1089. if (hasMeshes) {
  1090. //Set the data for the last mesh
  1091. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  1092. //Reverse indices for displaying faces in the good sense
  1093. indicesForBabylon.reverse();
  1094. //Get the good array
  1095. unwrapData();
  1096. //Set array
  1097. handledMesh.indices = indicesForBabylon;
  1098. handledMesh.positions = unwrappedPositionsForBabylon;
  1099. handledMesh.normals = unwrappedNormalsForBabylon;
  1100. handledMesh.uvs = unwrappedUVForBabylon;
  1101. if (this._meshLoadOptions.ImportVertexColors === true) {
  1102. handledMesh.colors = unwrappedColorsForBabylon;
  1103. }
  1104. }
  1105. //If any o or g keyword found, create a mesh with a random id
  1106. if (!hasMeshes) {
  1107. // reverse tab of indices
  1108. indicesForBabylon.reverse();
  1109. //Get positions normals uvs
  1110. unwrapData();
  1111. //Set data for one mesh
  1112. meshesFromObj.push({
  1113. name: babylonjs_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Geometry"].RandomId(),
  1114. indices: indicesForBabylon,
  1115. positions: unwrappedPositionsForBabylon,
  1116. colors: unwrappedColorsForBabylon,
  1117. normals: unwrappedNormalsForBabylon,
  1118. uvs: unwrappedUVForBabylon,
  1119. materialName: materialNameFromObj
  1120. });
  1121. }
  1122. //Create a Mesh list
  1123. var babylonMeshesArray = []; //The mesh for babylon
  1124. var materialToUse = new Array();
  1125. //Set data for each mesh
  1126. for (var j = 0; j < meshesFromObj.length; j++) {
  1127. //check meshesNames (stlFileLoader)
  1128. if (meshesNames && meshesFromObj[j].name) {
  1129. if (meshesNames instanceof Array) {
  1130. if (meshesNames.indexOf(meshesFromObj[j].name) === -1) {
  1131. continue;
  1132. }
  1133. }
  1134. else {
  1135. if (meshesFromObj[j].name !== meshesNames) {
  1136. continue;
  1137. }
  1138. }
  1139. }
  1140. //Get the current mesh
  1141. //Set the data with VertexBuffer for each mesh
  1142. handledMesh = meshesFromObj[j];
  1143. //Create a Mesh with the name of the obj mesh
  1144. scene._blockEntityCollection = this._forAssetContainer;
  1145. var babylonMesh = new babylonjs_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Mesh"](meshesFromObj[j].name, scene);
  1146. scene._blockEntityCollection = false;
  1147. //Push the name of the material to an array
  1148. //This is indispensable for the importMesh function
  1149. materialToUse.push(meshesFromObj[j].materialName);
  1150. var vertexData = new babylonjs_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["VertexData"](); //The container for the values
  1151. //Set the data for the babylonMesh
  1152. vertexData.uvs = handledMesh.uvs;
  1153. vertexData.indices = handledMesh.indices;
  1154. vertexData.positions = handledMesh.positions;
  1155. if (this._meshLoadOptions.ComputeNormals === true) {
  1156. var normals_1 = new Array();
  1157. babylonjs_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["VertexData"].ComputeNormals(handledMesh.positions, handledMesh.indices, normals_1);
  1158. vertexData.normals = normals_1;
  1159. }
  1160. else {
  1161. vertexData.normals = handledMesh.normals;
  1162. }
  1163. if (this._meshLoadOptions.ImportVertexColors === true) {
  1164. vertexData.colors = handledMesh.colors;
  1165. }
  1166. //Set the data from the VertexBuffer to the current Mesh
  1167. vertexData.applyToMesh(babylonMesh);
  1168. if (this._meshLoadOptions.InvertY) {
  1169. babylonMesh.scaling.y *= -1;
  1170. }
  1171. if (this._meshLoadOptions.OptimizeNormals === true) {
  1172. this._optimizeNormals(babylonMesh);
  1173. }
  1174. //Push the mesh into an array
  1175. babylonMeshesArray.push(babylonMesh);
  1176. }
  1177. var mtlPromises = [];
  1178. //load the materials
  1179. //Check if we have a file to load
  1180. if (fileToLoad !== "" && this._meshLoadOptions.SkipMaterials === false) {
  1181. //Load the file synchronously
  1182. mtlPromises.push(new Promise(function (resolve, reject) {
  1183. _this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  1184. try {
  1185. //Create materials thanks MTLLoader function
  1186. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl, _this._forAssetContainer);
  1187. //Look at each material loaded in the mtl file
  1188. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  1189. //Three variables to get all meshes with the same material
  1190. var startIndex = 0;
  1191. var _indices = [];
  1192. var _index;
  1193. //The material from MTL file is used in the meshes loaded
  1194. //Push the indice in an array
  1195. //Check if the material is not used for another mesh
  1196. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  1197. _indices.push(_index);
  1198. startIndex = _index + 1;
  1199. }
  1200. //If the material is not used dispose it
  1201. if (_index === -1 && _indices.length === 0) {
  1202. //If the material is not needed, remove it
  1203. materialsFromMTLFile.materials[n].dispose();
  1204. }
  1205. else {
  1206. for (var o = 0; o < _indices.length; o++) {
  1207. //Apply the material to the Mesh for each mesh with the material
  1208. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  1209. }
  1210. }
  1211. }
  1212. resolve();
  1213. }
  1214. catch (e) {
  1215. babylonjs_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Tools"].Warn("Error processing MTL file: '" + fileToLoad + "'");
  1216. if (_this._meshLoadOptions.MaterialLoadingFailsSilently) {
  1217. resolve();
  1218. }
  1219. else {
  1220. reject(e);
  1221. }
  1222. }
  1223. }, function (pathOfFile, exception) {
  1224. babylonjs_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Tools"].Warn("Error downloading MTL file: '" + fileToLoad + "'");
  1225. if (_this._meshLoadOptions.MaterialLoadingFailsSilently) {
  1226. resolve();
  1227. }
  1228. else {
  1229. reject(exception);
  1230. }
  1231. });
  1232. }));
  1233. }
  1234. //Return an array with all Mesh
  1235. return Promise.all(mtlPromises).then(function () {
  1236. return babylonMeshesArray;
  1237. });
  1238. };
  1239. /**
  1240. * Defines if UVs are optimized by default during load.
  1241. */
  1242. OBJFileLoader.OPTIMIZE_WITH_UV = true;
  1243. /**
  1244. * Invert model on y-axis (does a model scaling inversion)
  1245. */
  1246. OBJFileLoader.INVERT_Y = false;
  1247. /**
  1248. * Include in meshes the vertex colors available in some OBJ files. This is not part of OBJ standard.
  1249. */
  1250. OBJFileLoader.IMPORT_VERTEX_COLORS = false;
  1251. /**
  1252. * Compute the normals for the model, even if normals are present in the file.
  1253. */
  1254. OBJFileLoader.COMPUTE_NORMALS = false;
  1255. /**
  1256. * Optimize the normals for the model. Lighting can be uneven if you use OptimizeWithUV = true because new vertices can be created for the same location if they pertain to different faces.
  1257. * Using OptimizehNormals = true will help smoothing the lighting by averaging the normals of those vertices.
  1258. */
  1259. OBJFileLoader.OPTIMIZE_NORMALS = false;
  1260. /**
  1261. * Defines custom scaling of UV coordinates of loaded meshes.
  1262. */
  1263. OBJFileLoader.UV_SCALING = new babylonjs_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector2"](1, 1);
  1264. /**
  1265. * Skip loading the materials even if defined in the OBJ file (materials are ignored).
  1266. */
  1267. OBJFileLoader.SKIP_MATERIALS = false;
  1268. /**
  1269. * When a material fails to load OBJ loader will silently fail and onSuccess() callback will be triggered.
  1270. *
  1271. * Defaults to true for backwards compatibility.
  1272. */
  1273. OBJFileLoader.MATERIAL_LOADING_FAILS_SILENTLY = true;
  1274. return OBJFileLoader;
  1275. }());
  1276. if (babylonjs_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["SceneLoader"]) {
  1277. //Add this loader into the register plugin
  1278. babylonjs_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["SceneLoader"].RegisterPlugin(new OBJFileLoader());
  1279. }
  1280. /***/ }),
  1281. /***/ "./legacy/legacy-objFileLoader.ts":
  1282. /*!****************************************!*\
  1283. !*** ./legacy/legacy-objFileLoader.ts ***!
  1284. \****************************************/
  1285. /*! exports provided: MTLFileLoader, OBJFileLoader */
  1286. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  1287. "use strict";
  1288. __webpack_require__.r(__webpack_exports__);
  1289. /* WEBPACK VAR INJECTION */(function(global) {/* harmony import */ var _OBJ__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../OBJ */ "./OBJ/index.ts");
  1290. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MTLFileLoader", function() { return _OBJ__WEBPACK_IMPORTED_MODULE_0__["MTLFileLoader"]; });
  1291. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OBJFileLoader", function() { return _OBJ__WEBPACK_IMPORTED_MODULE_0__["OBJFileLoader"]; });
  1292. /**
  1293. * This is the entry point for the UMD module.
  1294. * The entry point for a future ESM package should be index.ts
  1295. */
  1296. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : undefined);
  1297. if (typeof globalObject !== "undefined") {
  1298. for (var key in _OBJ__WEBPACK_IMPORTED_MODULE_0__) {
  1299. globalObject.BABYLON[key] = _OBJ__WEBPACK_IMPORTED_MODULE_0__[key];
  1300. }
  1301. }
  1302. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../node_modules/webpack/buildin/global.js */ "../../node_modules/webpack/buildin/global.js")))
  1303. /***/ }),
  1304. /***/ "babylonjs/Misc/tools":
  1305. /*!****************************************************************************************************!*\
  1306. !*** external {"root":"BABYLON","commonjs":"babylonjs","commonjs2":"babylonjs","amd":"babylonjs"} ***!
  1307. \****************************************************************************************************/
  1308. /*! no static exports found */
  1309. /***/ (function(module, exports) {
  1310. module.exports = __WEBPACK_EXTERNAL_MODULE_babylonjs_Misc_tools__;
  1311. /***/ })
  1312. /******/ });
  1313. });
  1314. //# sourceMappingURL=babylon.objFileLoader.js.map