babylon.objFileLoader.ts 40 KB

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