babylon.objFileLoader.js 37 KB

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