babylon.objFileLoader.ts 40 KB

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