babylon.objFileLoader.ts 41 KB

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