1 #include "stdafx.h"
2
3 #include "Scene.hxx"
4 #include "EyeLightShader.hxx"
5
6 Vec3f vec3fFromStream(std::istream &aStream, Vec3f offset = Vec3f(0,0,0))
7 {
8 float x, y, z;
9 aStream >> x >> y >> z;
10 return Vec3f(x, y, z) + offset;
11 }
12
13 struct FaceIdcs
14 {
15 int v[3];
16 int t[3];
17 int n[3];
18
19 FaceIdcs()
20 {
21 memset(this, -1, sizeof(*this));
22 }
23
24 FaceIdcs(std::istream &aStream)
25 {
26 memset(this, -1, sizeof(*this));
27 char c;
28
29 for(int i = 0; i < 3; i++)
30 {
31 aStream >> v[i] >> c;
32
33 t[i] = 0;
34 if (aStream.peek() != '/')
35 aStream >> t[i] >> c;
36 else
37 aStream >> c;
38
39 n[i] = 0;
40 aStream >> n[i] >> std::ws;
41 }
42
43 std::string s;
44 aStream >> s >> std::ws; //Read any other crap...
45 }
46 };
47
48
49 void Scene::ParseOBJ(char *fileName, PrimitiveFactory *aFactory, Vec3f offset)
50 {
51 cout << "Parsing OBJFile : " << fileName << endl;
52
53 std::ifstream ifile(fileName);
54
55 if (ifile.fail())
56 {
57 cerr << "File cannot be opened!" << endl;
58 exit(0);
59 }
60
61 std::vector<FaceIdcs> faces;
62 std::vector<Vec3f> vert;
63 std::vector<Vec3f> vertn;
64 std::vector<Vec3f> vertt;
65
66 int count = 0;
67 while(!ifile.eof())
68 {
69 std::string curLine;
70 std::getline(ifile, curLine);
71
72 std::istringstream issLine(curLine);
73 std::string lineType;
74 issLine >> std::ws >> lineType;
75
76 if(lineType == "v")
77 vert.push_back(vec3fFromStream(issLine, offset));
78 else if (lineType == "f")
79 {
80 ++count;
81 faces.push_back(issLine);
82 }
83 else if (lineType == "vn")
84 vertn.push_back(vec3fFromStream(issLine));
85 else if (lineType == "vt")
86 vertt.push_back(vec3fFromStream(issLine));
87 else if (lineType == "usemtl" && aFactory->mFactory)
88 aFactory->mFactory->SetMaterial(issLine, count);
89 }
90
91 count = 0;
92 for(std::vector<FaceIdcs>::iterator itFace = faces.begin(); itFace != faces.end(); itFace++)
93 {
94 Vec3f v[3], vn[3], vt[3];
95 for(int i = 0; i < 3; i++)
96 {
97 v[i] = vert[itFace->v[i] - 1];
98
99 if (itFace->n[i])
100 vn[i] = vertn[itFace->n[i] - 1];
101
102 if (itFace->t[i])
103 vt[i] = vertt[itFace->t[i] - 1];
104 }
105
106 primitive.push_back(aFactory->createPrimitive(
107 count, v[0], v[1], v[2], vn[0], vn[1], vn[2], vt[0], vt[1], vt[2]
108 ));
109
110 ++count;
111 }
112
113 cout << "Number of Vertices: " << vert.size() << endl;
114 cout << "Number of Triangles: " << primitive.size() << endl;
115
116 cout << "Finished Parsing" << endl;
117 }
syntax highlighted by Code2HTML, v. 0.9.1