matthew117

OBJ Parser

Feb 6th, 2012
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.35 KB | None | 0 0
  1. private static List<Face> parseFileBetter(String fileName) {
  2.   List<Face> faces = new ArrayList<Face>();
  3.   List<float[]> vertices = new ArrayList<float[]>();
  4.   List<float[]> textureVertices = new ArrayList<float[]>();
  5.   List<float[]> normals = new ArrayList<float[]>();
  6.   try
  7.   {
  8.     Texture defaultTexture = TextureIO.newTexture(new File("default.jpg"),false);
  9.     Texture textureState = defaultTexture;
  10.     Scanner sc = new Scanner(new File(fileName));
  11.     while (sc.hasNextLine())
  12.     {
  13.       String t = sc.nextLine();
  14.       if (t.startsWith("v "))
  15.       {
  16.         Scanner st = new Scanner(t.replaceAll("v", "").trim());
  17.         vertices.add(new float[] { st.nextFloat(), st.nextFloat(), st.nextFloat() });
  18.       }
  19.       if (t.startsWith("vt"))
  20.       {
  21.         Scanner st = new Scanner(t.replaceAll("vt", "").trim());
  22.         textureVertices.add(new float[] { st.nextFloat(), st.nextFloat() });
  23.       }
  24.       if (t.startsWith("vn"))
  25.       {
  26.         Scanner st = new Scanner(t.replaceAll("vn", "").trim());
  27.         normals.add(new float[] { st.nextFloat(), st.nextFloat(), st.nextFloat() });
  28.       }
  29.       if (t.startsWith("usemtl"))
  30.       {
  31.         String ss = t.replaceAll("usemtl", "").trim();
  32.         if (ss.equals("Material"))
  33.         {
  34.           textureState = defaultTexture;
  35.         }
  36.         else
  37.         {
  38.           ss = ss.replaceAll("Material_", "");
  39.           textureState = TextureIO.newTexture(new File(ss),false);
  40.         }
  41.  
  42.       }
  43.       if (t.startsWith("f"))
  44.       {
  45.         Scanner st = new Scanner(t.replaceAll("f", "").trim().replaceAll("/", " "));
  46.         int[] v1 = new int[] { st.nextInt(), st.nextInt(), st.nextInt() };
  47.         int[] v2 = new int[] { st.nextInt(), st.nextInt(), st.nextInt() };
  48.         int[] v3 = new int[] { st.nextInt(), st.nextInt(), st.nextInt() };
  49.         float[][] _v = new float[][] { vertices.get(v1[0] - 1),
  50.             vertices.get(v2[0] - 1), vertices.get(v3[0] - 1) };
  51.         float[][] _t = new float[][] { textureVertices.get(v1[1] - 1),
  52.             textureVertices.get(v2[1] - 1), textureVertices.get(v3[1] - 1) };
  53.         float[][] _n = new float[][] { normals.get(v1[2] - 1), normals.get(v2[2] - 1),
  54.             normals.get(v3[2] - 1) };
  55.         faces.add(new Face(_v, _n, _t, textureState));
  56.       }
  57.     }
  58.   } catch (IOException e)
  59.   {
  60.     e.printStackTrace();
  61.   }
  62.   return faces;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment