babylon.objFileLoader.js 59 KB

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