babylon.objFileLoader.js 35 KB

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