babylon.objFileLoader.ts 40 KB

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