babylon.objFileLoader.js 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  1. var BABYLON;
  2. (function (BABYLON) {
  3. /**
  4. * Class reading and parsing the MTL file bundled with the obj file.
  5. */
  6. var MTLFileLoader = (function () {
  7. function MTLFileLoader() {
  8. // All material loaded from the mtl will be set here
  9. this.materials = [];
  10. /**
  11. * This function will read the mtl file and create each material described inside
  12. * This function could be improve by adding :
  13. * -some component missing (Ni, Tf...)
  14. * -including the specific options available
  15. *
  16. * @param scene
  17. * @param data
  18. * @param rootUrl
  19. */
  20. this.parseMTL = function (scene, data, rootUrl) {
  21. //Split the lines from the file
  22. var lines = data.split('\n');
  23. //Space char
  24. var delimiter_pattern = /\s+/;
  25. //Array with RGB colors
  26. var color;
  27. //New material
  28. var material;
  29. //Look at each line
  30. for (var i = 0; i < lines.length; i++) {
  31. var line = lines[i].trim();
  32. // Blank line or comment
  33. if (line.length === 0 || line.charAt(0) === '#') {
  34. continue;
  35. }
  36. //Get the first parameter (keyword)
  37. var pos = line.indexOf(' ');
  38. var key = (pos >= 0) ? line.substring(0, pos) : line;
  39. key = key.toLowerCase();
  40. //Get the data following the key
  41. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  42. //This mtl keyword will create the new material
  43. if (key === "newmtl") {
  44. //Check if it is the first material.
  45. // Materials specifications are described after this keyword.
  46. if (material) {
  47. //Add the previous material in the material array.
  48. this.materials.push(material);
  49. }
  50. //Create a new material.
  51. // value is the name of the material read in the mtl file
  52. material = new BABYLON.StandardMaterial(value, scene);
  53. }
  54. else if (key === "kd") {
  55. // Diffuse color (color under white light) using RGB values
  56. //value = "r g b"
  57. color = value.split(delimiter_pattern, 3);
  58. //color = [r,g,b]
  59. //Set tghe color into the material
  60. material.diffuseColor = BABYLON.Color3.FromArray(color);
  61. }
  62. else if (key === "ka") {
  63. // Ambient color (color under shadow) using RGB values
  64. //value = "r g b"
  65. color = value.split(delimiter_pattern, 3);
  66. //color = [r,g,b]
  67. //Set tghe color into the material
  68. material.ambientColor = BABYLON.Color3.FromArray(color);
  69. }
  70. else if (key === "ks") {
  71. // Specular color (color when light is reflected from shiny surface) using RGB values
  72. //value = "r g b"
  73. color = value.split(delimiter_pattern, 3);
  74. //color = [r,g,b]
  75. //Set the color into the material
  76. material.specularColor = BABYLON.Color3.FromArray(color);
  77. }
  78. else if (key === "ns") {
  79. //value = "Integer"
  80. material.specularPower = value;
  81. }
  82. else if (key === "d") {
  83. //d is dissolve for current material. It mean alpha for BABYLON
  84. material.alpha = value;
  85. }
  86. else if (key === "map_ka") {
  87. // ambient texture map with a loaded image
  88. //We must first get the folder of the image
  89. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  90. }
  91. else if (key === "map_kd") {
  92. // Diffuse texture map with a loaded image
  93. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  94. }
  95. else if (key === "map_ks") {
  96. // Specular texture map with a loaded image
  97. //We must first get the folder of the image
  98. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  99. }
  100. else if (key === "map_ns") {
  101. }
  102. else if (key === "map_bump") {
  103. //The bump texture
  104. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  105. }
  106. else if (key === "map_d") {
  107. // The dissolve of the material
  108. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  109. }
  110. else if (key === "illum") {
  111. //Illumination
  112. if (value === "0") {
  113. }
  114. else if (value === "1") {
  115. }
  116. else if (value === "2") {
  117. }
  118. else if (value === "3") {
  119. }
  120. else if (value === "4") {
  121. }
  122. else if (value === "5") {
  123. }
  124. else if (value === "6") {
  125. }
  126. else if (value === "7") {
  127. }
  128. else if (value === "8") {
  129. }
  130. else if (value === "9") {
  131. }
  132. else if (value === "10") {
  133. }
  134. }
  135. else {
  136. }
  137. }
  138. //At the end of the file, add the last material
  139. this.materials.push(material);
  140. };
  141. }
  142. /**
  143. * Gets the texture for the material.
  144. *
  145. * If the material is imported from input file,
  146. * We sanitize the url to ensure it takes the textre from aside the material.
  147. *
  148. * @param rootUrl The root url to load from
  149. * @param value The value stored in the mtl
  150. * @return The Texture
  151. */
  152. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  153. var url = rootUrl;
  154. // Load from input file.
  155. if (rootUrl === "file:") {
  156. var lastDelimiter = value.lastIndexOf("\\");
  157. if (lastDelimiter === -1) {
  158. lastDelimiter = value.lastIndexOf("/");
  159. }
  160. if (lastDelimiter > -1) {
  161. url += value.substr(lastDelimiter + 1);
  162. }
  163. else {
  164. url += value;
  165. }
  166. }
  167. else {
  168. url += value;
  169. }
  170. return new BABYLON.Texture(url, scene);
  171. };
  172. return MTLFileLoader;
  173. }());
  174. BABYLON.MTLFileLoader = MTLFileLoader;
  175. var OBJFileLoader = (function () {
  176. function OBJFileLoader() {
  177. this.extensions = ".obj";
  178. this.obj = /^o/;
  179. this.group = /^g/;
  180. this.mtllib = /^mtllib /;
  181. this.usemtl = /^usemtl /;
  182. this.smooth = /^s /;
  183. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  184. // vn float float float
  185. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  186. // vt float float
  187. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  188. // f vertex vertex vertex ...
  189. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  190. // f vertex/uvs vertex/uvs vertex/uvs ...
  191. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  192. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  193. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  194. // f vertex//normal vertex//normal vertex//normal ...
  195. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  196. }
  197. /**
  198. * Calls synchronously the MTL file attached to this obj.
  199. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  200. * Without this function materials are not displayed in the first frame (but displayed after).
  201. * In consequence it is impossible to get material information in your HTML file
  202. *
  203. * @param url The URL of the MTL file
  204. * @param rootUrl
  205. * @param onSuccess Callback function to be called when the MTL file is loaded
  206. * @private
  207. */
  208. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  209. //The complete path to the mtl file
  210. var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
  211. // Loads through the babylon tools to allow fileInput search.
  212. BABYLON.Tools.LoadFile(pathOfFile, onSuccess, null, null, false, function () { console.warn("Error - Unable to load " + pathOfFile); }, true /* synchronous call */);
  213. };
  214. OBJFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  215. //get the meshes from OBJ file
  216. var loadedMeshes = this._parseSolid(meshesNames, scene, data, rootUrl);
  217. //Push meshes from OBJ file into the variable mesh of this function
  218. if (meshes) {
  219. loadedMeshes.forEach(function (mesh) {
  220. meshes.push(mesh);
  221. });
  222. }
  223. return true;
  224. };
  225. OBJFileLoader.prototype.load = function (scene, data, rootUrl) {
  226. //Get the 3D model
  227. return this.importMesh(null, scene, data, rootUrl, null, null, null);
  228. };
  229. /**
  230. * Read the OBJ file and create an Array of meshes.
  231. * Each mesh contains all information given by the OBJ and the MTL file.
  232. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  233. *
  234. * @param meshesNames
  235. * @param scene BABYLON.Scene The scene where are displayed the data
  236. * @param data String The content of the obj file
  237. * @param rootUrl String The path to the folder
  238. * @returns Array<AbstractMesh>
  239. * @private
  240. */
  241. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  242. var positions = []; //values for the positions of vertices
  243. var normals = []; //Values for the normals
  244. var uvs = []; //Values for the textures
  245. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  246. var handledMesh; //The current mesh of meshes array
  247. var indicesForBabylon = []; //The list of indices for VertexData
  248. var wrappedPositionForBabylon = []; //The list of position in vectors
  249. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  250. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  251. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  252. var curPositionInIndices = 0;
  253. var hasMeshes = false; //Meshes are defined in the file
  254. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  255. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  256. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  257. var triangles = []; //Indices from new triangles coming from polygons
  258. var materialNameFromObj = ""; //The name of the current material
  259. var fileToLoad = ""; //The name of the mtlFile to load
  260. var materialsFromMTLFile = new MTLFileLoader();
  261. var objMeshName = ""; //The name of the current obj mesh
  262. var increment = 1; //Id for meshes created by the multimaterial
  263. var isFirstMaterial = true;
  264. /**
  265. * Search for obj in the given array.
  266. * This function is called to check if a couple of data already exists in an array.
  267. *
  268. * If found, returns the index of the founded tuple index. Returns -1 if not found
  269. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  270. * @param obj Array<number>
  271. * @returns {boolean}
  272. */
  273. var isInArray = function (arr, obj) {
  274. if (!arr[obj[0]])
  275. arr[obj[0]] = { normals: [], idx: [] };
  276. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  277. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  278. };
  279. var isInArrayUV = function (arr, obj) {
  280. if (!arr[obj[0]])
  281. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  282. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  283. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  284. return arr[obj[0]].idx[idx];
  285. }
  286. return -1;
  287. };
  288. /**
  289. * This function set the data for each triangle.
  290. * Data are position, normals and uvs
  291. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  292. * If the tuple already exist, add only their indice
  293. *
  294. * @param indicePositionFromObj Integer The index in positions array
  295. * @param indiceUvsFromObj Integer The index in uvs array
  296. * @param indiceNormalFromObj Integer The index in normals array
  297. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  298. * @param textureVectorFromOBJ Vector3 The value of uvs
  299. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  300. */
  301. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  302. //Check if this tuple already exists in the list of tuples
  303. var _index;
  304. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  305. _index = isInArrayUV(tuplePosNorm, [
  306. indicePositionFromObj,
  307. indiceNormalFromObj,
  308. indiceUvsFromObj
  309. ]);
  310. }
  311. else {
  312. _index = isInArray(tuplePosNorm, [
  313. indicePositionFromObj,
  314. indiceNormalFromObj
  315. ]);
  316. }
  317. //If it not exists
  318. if (_index == -1) {
  319. //Add an new indice.
  320. //The array of indices is only an array with his length equal to the number of triangles - 1.
  321. //We add vertices data in this order
  322. indicesForBabylon.push(wrappedPositionForBabylon.length);
  323. //Push the position of vertice for Babylon
  324. //Each element is a BABYLON.Vector3(x,y,z)
  325. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  326. //Push the uvs for Babylon
  327. //Each element is a BABYLON.Vector3(u,v)
  328. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  329. //Push the normals for Babylon
  330. //Each element is a BABYLON.Vector3(x,y,z)
  331. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  332. //Add the tuple in the comparison list
  333. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  334. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  335. if (OBJFileLoader.OPTIMIZE_WITH_UV)
  336. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  337. }
  338. else {
  339. //The tuple already exists
  340. //Add the index of the already existing tuple
  341. //At this index we can get the value of position, normal and uvs of vertex
  342. indicesForBabylon.push(_index);
  343. }
  344. };
  345. /**
  346. * Transform BABYLON.Vector() object onto 3 digits in an array
  347. */
  348. var unwrapData = function () {
  349. //Every array has the same length
  350. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  351. //Push the x, y, z values of each element in the unwrapped array
  352. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  353. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  354. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  355. }
  356. // Reset arrays for the next new meshes
  357. wrappedPositionForBabylon = [];
  358. wrappedNormalsForBabylon = [];
  359. wrappedUvsForBabylon = [];
  360. tuplePosNorm = [];
  361. curPositionInIndices = 0;
  362. };
  363. /**
  364. * Create triangles from polygons by recursion
  365. * The best to understand how it works is to draw it in the same time you get the recursion.
  366. * It is important to notice that a triangle is a polygon
  367. * We get 4 patterns of face defined in OBJ File :
  368. * facePattern1 = ["1","2","3","4","5","6"]
  369. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  370. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  371. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  372. * Each pattern is divided by the same method
  373. * @param face Array[String] The indices of elements
  374. * @param v Integer The variable to increment
  375. */
  376. var getTriangles = function (face, v) {
  377. //Work for each element of the array
  378. if (v + 1 < face.length) {
  379. //Add on the triangle variable the indexes to obtain triangles
  380. triangles.push(face[0], face[v], face[v + 1]);
  381. //Incrementation for recursion
  382. v += 1;
  383. //Recursion
  384. getTriangles(face, v);
  385. }
  386. //Result obtained after 2 iterations:
  387. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  388. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  389. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  390. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  391. };
  392. /**
  393. * Create triangles and push the data for each polygon for the pattern 1
  394. * In this pattern we get vertice positions
  395. * @param face
  396. * @param v
  397. */
  398. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  399. //Get the indices of triangles for each polygon
  400. getTriangles(face, v);
  401. //For each element in the triangles array.
  402. //This var could contains 1 to an infinity of triangles
  403. for (var k = 0; k < triangles.length; k++) {
  404. // Set position indice
  405. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  406. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  407. positions[indicePositionFromObj], //Get the vectors data
  408. BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
  409. );
  410. }
  411. //Reset variable for the next line
  412. triangles = [];
  413. };
  414. /**
  415. * Create triangles and push the data for each polygon for the pattern 2
  416. * In this pattern we get vertice positions and uvsu
  417. * @param face
  418. * @param v
  419. */
  420. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  421. //Get the indices of triangles for each polygon
  422. getTriangles(face, v);
  423. for (var k = 0; k < triangles.length; k++) {
  424. //triangle[k] = "1/1"
  425. //Split the data for getting position and uv
  426. var point = triangles[k].split("/"); // ["1", "1"]
  427. //Set position indice
  428. var indicePositionFromObj = parseInt(point[0]) - 1;
  429. //Set uv indice
  430. var indiceUvsFromObj = parseInt(point[1]) - 1;
  431. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  432. positions[indicePositionFromObj], //Get the values for each element
  433. uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
  434. );
  435. }
  436. //Reset variable for the next line
  437. triangles = [];
  438. };
  439. /**
  440. * Create triangles and push the data for each polygon for the pattern 3
  441. * In this pattern we get vertice positions, uvs and normals
  442. * @param face
  443. * @param v
  444. */
  445. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  446. //Get the indices of triangles for each polygon
  447. getTriangles(face, v);
  448. for (var k = 0; k < triangles.length; k++) {
  449. //triangle[k] = "1/1/1"
  450. //Split the data for getting position, uv, and normals
  451. var point = triangles[k].split("/"); // ["1", "1", "1"]
  452. // Set position indice
  453. var indicePositionFromObj = parseInt(point[0]) - 1;
  454. // Set uv indice
  455. var indiceUvsFromObj = parseInt(point[1]) - 1;
  456. // Set normal indice
  457. var indiceNormalFromObj = parseInt(point[2]) - 1;
  458. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  459. );
  460. }
  461. //Reset variable for the next line
  462. triangles = [];
  463. };
  464. /**
  465. * Create triangles and push the data for each polygon for the pattern 4
  466. * In this pattern we get vertice positions and normals
  467. * @param face
  468. * @param v
  469. */
  470. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  471. getTriangles(face, v);
  472. for (var k = 0; k < triangles.length; k++) {
  473. //triangle[k] = "1//1"
  474. //Split the data for getting position and normals
  475. var point = triangles[k].split("//"); // ["1", "1"]
  476. // We check indices, and normals
  477. var indicePositionFromObj = parseInt(point[0]) - 1;
  478. var indiceNormalFromObj = parseInt(point[1]) - 1;
  479. setData(indicePositionFromObj, 1, //Default value for uv
  480. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  481. BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
  482. }
  483. //Reset variable for the next line
  484. triangles = [];
  485. };
  486. var addPreviousObjMesh = function () {
  487. //Check if it is not the first mesh. Otherwise we don't have data.
  488. if (meshesFromObj.length > 0) {
  489. //Get the previous mesh for applying the data about the faces
  490. //=> in obj file, faces definition append after the name of the mesh
  491. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  492. //Set the data into Array for the mesh
  493. unwrapData();
  494. // Reverse tab. Otherwise face are displayed in the wrong sens
  495. indicesForBabylon.reverse();
  496. //Set the information for the mesh
  497. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  498. handledMesh.indices = indicesForBabylon.slice();
  499. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  500. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  501. handledMesh.uvs = unwrappedUVForBabylon.slice();
  502. //Reset the array for the next mesh
  503. indicesForBabylon = [];
  504. unwrappedPositionsForBabylon = [];
  505. unwrappedNormalsForBabylon = [];
  506. unwrappedUVForBabylon = [];
  507. }
  508. };
  509. //Main function
  510. //Split the file into lines
  511. var lines = data.split('\n');
  512. //Look at each line
  513. for (var i = 0; i < lines.length; i++) {
  514. var line = lines[i].trim();
  515. var result;
  516. //Comment or newLine
  517. if (line.length === 0 || line.charAt(0) === '#') {
  518. continue;
  519. }
  520. else if ((result = this.vertexPattern.exec(line)) !== null) {
  521. //Create a Vector3 with the position x, y, z
  522. //Value of result:
  523. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  524. //Add the Vector in the list of positions
  525. positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  526. }
  527. else if ((result = this.normalPattern.exec(line)) !== null) {
  528. //Create a Vector3 with the normals x, y, z
  529. //Value of result
  530. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  531. //Add the Vector in the list of normals
  532. normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  533. }
  534. else if ((result = this.uvPattern.exec(line)) !== null) {
  535. //Create a Vector2 with the normals u, v
  536. //Value of result
  537. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  538. //Add the Vector in the list of uvs
  539. uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  540. }
  541. else if ((result = this.facePattern3.exec(line)) !== null) {
  542. //Value of result:
  543. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  544. //Set the data for this face
  545. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  546. 1);
  547. }
  548. else if ((result = this.facePattern4.exec(line)) !== null) {
  549. //Value of result:
  550. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  551. //Set the data for this face
  552. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  553. 1);
  554. }
  555. else if ((result = this.facePattern2.exec(line)) !== null) {
  556. //Value of result:
  557. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  558. //Set the data for this face
  559. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  560. 1);
  561. }
  562. else if ((result = this.facePattern1.exec(line)) !== null) {
  563. //Value of result
  564. //["f 1 2 3", "1 2 3"...]
  565. //Set the data for this face
  566. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  567. 1);
  568. }
  569. else if (this.group.test(line) || this.obj.test(line)) {
  570. //Create a new mesh corresponding to the name of the group.
  571. //Definition of the mesh
  572. var objMesh =
  573. //Set the name of the current obj mesh
  574. {
  575. name: line.substring(2).trim(),
  576. indices: undefined,
  577. positions: undefined,
  578. normals: undefined,
  579. uvs: undefined,
  580. materialName: ""
  581. };
  582. addPreviousObjMesh();
  583. //Push the last mesh created with only the name
  584. meshesFromObj.push(objMesh);
  585. //Set this variable to indicate that now meshesFromObj has objects defined inside
  586. hasMeshes = true;
  587. isFirstMaterial = true;
  588. increment = 1;
  589. }
  590. else if (this.usemtl.test(line)) {
  591. //Get the name of the material
  592. materialNameFromObj = line.substring(7).trim();
  593. //If this new material is in the same mesh
  594. if (!isFirstMaterial) {
  595. //Set the data for the previous mesh
  596. addPreviousObjMesh();
  597. //Create a new mesh
  598. var objMesh =
  599. //Set the name of the current obj mesh
  600. {
  601. name: objMeshName + "_mm" + increment.toString(),
  602. indices: undefined,
  603. positions: undefined,
  604. normals: undefined,
  605. uvs: undefined,
  606. materialName: materialNameFromObj
  607. };
  608. increment++;
  609. //If meshes are already defined
  610. meshesFromObj.push(objMesh);
  611. }
  612. //Set the material name if the previous line define a mesh
  613. if (hasMeshes && isFirstMaterial) {
  614. //Set the material name to the previous mesh (1 material per mesh)
  615. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  616. isFirstMaterial = false;
  617. }
  618. }
  619. else if (this.mtllib.test(line)) {
  620. //Get the name of mtl file
  621. fileToLoad = line.substring(7).trim();
  622. }
  623. else if (this.smooth.test(line)) {
  624. }
  625. else {
  626. //If there is another possibility
  627. console.log("Unhandled expression at line : " + line);
  628. }
  629. }
  630. //At the end of the file, add the last mesh into the meshesFromObj array
  631. if (hasMeshes) {
  632. //Set the data for the last mesh
  633. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  634. //Reverse indices for displaying faces in the good sens
  635. indicesForBabylon.reverse();
  636. //Get the good array
  637. unwrapData();
  638. //Set array
  639. handledMesh.indices = indicesForBabylon;
  640. handledMesh.positions = unwrappedPositionsForBabylon;
  641. handledMesh.normals = unwrappedNormalsForBabylon;
  642. handledMesh.uvs = unwrappedUVForBabylon;
  643. }
  644. //If any o or g keyword found, create a mesj with a random id
  645. if (!hasMeshes) {
  646. // reverse tab of indices
  647. indicesForBabylon.reverse();
  648. //Get positions normals uvs
  649. unwrapData();
  650. //Set data for one mesh
  651. meshesFromObj.push({
  652. name: BABYLON.Geometry.RandomId(),
  653. indices: indicesForBabylon,
  654. positions: unwrappedPositionsForBabylon,
  655. normals: unwrappedNormalsForBabylon,
  656. uvs: unwrappedUVForBabylon,
  657. materialName: materialNameFromObj
  658. });
  659. }
  660. //Create a BABYLON.Mesh list
  661. var babylonMeshesArray = []; //The mesh for babylon
  662. var materialToUse = [];
  663. //Set data for each mesh
  664. for (var j = 0; j < meshesFromObj.length; j++) {
  665. //check meshesNames (stlFileLoader)
  666. if (meshesNames && meshesFromObj[j].name) {
  667. if (meshesNames instanceof Array) {
  668. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  669. continue;
  670. }
  671. }
  672. else {
  673. if (meshesFromObj[j].name !== meshesNames) {
  674. continue;
  675. }
  676. }
  677. }
  678. //Get the current mesh
  679. //Set the data with VertexBuffer for each mesh
  680. handledMesh = meshesFromObj[j];
  681. //Create a BABYLON.Mesh with the name of the obj mesh
  682. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  683. //Push the name of the material to an array
  684. //This is indispensable for the importMesh function
  685. materialToUse.push(meshesFromObj[j].materialName);
  686. //Set the data for the babylonMesh
  687. var vertexData = new BABYLON.VertexData(); //The container for the values
  688. vertexData.positions = handledMesh.positions;
  689. vertexData.normals = handledMesh.normals;
  690. vertexData.uvs = handledMesh.uvs;
  691. vertexData.indices = handledMesh.indices;
  692. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  693. vertexData.applyToMesh(babylonMesh);
  694. //Push the mesh into an array
  695. babylonMeshesArray.push(babylonMesh);
  696. }
  697. //load the materials
  698. //Check if we have a file to load
  699. if (fileToLoad !== "") {
  700. //Load the file synchronously
  701. this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  702. //Create materials thanks MTLLoader function
  703. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  704. //Look at each material loaded in the mtl file
  705. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  706. //Three variables to get all meshes with the same material
  707. var startIndex = 0;
  708. var _indices = [];
  709. var _index;
  710. //The material from MTL file is used in the meshes loaded
  711. //Push the indice in an array
  712. //Check if the material is not used for another mesh
  713. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  714. _indices.push(_index);
  715. startIndex = _index + 1;
  716. }
  717. //If the material is not used dispose it
  718. if (_index == -1 && _indices.length == 0) {
  719. //If the material is not needed, remove it
  720. materialsFromMTLFile.materials[n].dispose();
  721. }
  722. else {
  723. for (var o = 0; o < _indices.length; o++) {
  724. //Apply the material to the BABYLON.Mesh for each mesh with the material
  725. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  726. }
  727. }
  728. }
  729. });
  730. }
  731. //Return an array with all BABYLON.Mesh
  732. return babylonMeshesArray;
  733. };
  734. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  735. return OBJFileLoader;
  736. }());
  737. BABYLON.OBJFileLoader = OBJFileLoader;
  738. //Add this loader into the register plugin
  739. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  740. })(BABYLON || (BABYLON = {}));