babylon.objFileLoader.js 40 KB

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