|
1 #include <iostream> |
|
2 #include <fstream> |
|
3 #include <iomanip> |
|
4 |
|
5 void load_ply(Raytracer &rt, const char *filename, Material *mat, Vector3 scale, Vector3 transp) |
|
6 { |
|
7 vector<NormalVertex*> vertices; |
|
8 vector<Vector3> normals; |
|
9 vector<int> vertex_face_num; |
|
10 ifstream f(filename); |
|
11 string token = "a"; |
|
12 if (!f.is_open()) |
|
13 { |
|
14 cout << "File not found: " << filename <<endl; |
|
15 exit(1); |
|
16 } |
|
17 // read header |
|
18 int vertex_num, face_num; |
|
19 while (token != "end_header") |
|
20 { |
|
21 f >> token; |
|
22 if (token == "element") |
|
23 { |
|
24 f >> token; |
|
25 if (token == "vertex") |
|
26 f >> vertex_num; |
|
27 if (token == "face") |
|
28 f >> face_num; |
|
29 } |
|
30 f.ignore(1000,'\n'); |
|
31 } |
|
32 |
|
33 // read vertices |
|
34 Vector3 P; |
|
35 int num = vertex_num; |
|
36 while (num--) |
|
37 { |
|
38 f >> P.x >> P.y >> P.z; |
|
39 P.x = scale.x*P.x + transp.x; |
|
40 P.y = scale.y*P.y + transp.y; |
|
41 P.z = scale.z*P.z + transp.z; |
|
42 vertices.push_back(new NormalVertex(P)); |
|
43 normals.push_back(Vector3()); |
|
44 vertex_face_num.push_back(0); |
|
45 f.ignore(1000,'\n'); |
|
46 } |
|
47 |
|
48 // read faces |
|
49 Triangle *face; |
|
50 int v1, v2, v3; |
|
51 while (face_num--) |
|
52 { |
|
53 f >> num; |
|
54 if (num != 3) |
|
55 { |
|
56 printf("ply error: faces of %d vertices not supported", num); |
|
57 continue; |
|
58 } |
|
59 f >> v1 >> v2 >> v3; |
|
60 face = new Triangle(vertices.at(v1), vertices.at(v3), vertices.at(v2), mat); |
|
61 rt.addshape(face); |
|
62 face->setSmooth(); |
|
63 |
|
64 normals.at(v1) += face->getNormal(); |
|
65 vertex_face_num.at(v1)++; |
|
66 normals.at(v2) += face->getNormal(); |
|
67 vertex_face_num.at(v2)++; |
|
68 normals.at(v3) += face->getNormal(); |
|
69 vertex_face_num.at(v3)++; |
|
70 f.ignore(1000,'\n'); |
|
71 } |
|
72 |
|
73 for (int i = 0; i < vertex_num; i++) |
|
74 { |
|
75 normals.at(i) /= vertex_face_num.at(i); |
|
76 normals.at(i).normalize(); |
|
77 vertices.at(i)->N = normals.at(i); |
|
78 } |
|
79 |
|
80 f.close(); |
|
81 } |