babylon.objFileLoader.ts 41 KB

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