I'm trying to implement a ray caster and I'm starting out with simple .obj files (utah-teapot) and currently I only made classes for Spheres and Triangles, I basically have all the functions for the intersections, generating view rays, etc.. all ready but I just can't seem to be able to parse the .obj file into triangles (three vectors each) so I can have the ray casting possible on custom .obj files instead of just spheres.
This is my current .obj file parser (didn't include the full working code here)
char lineHeader[512];
// read the first word of the line
int res = fscanf(file, "%s", lineHeader);
if (res == EOF)
break; // EOF
// else : parse lineHeader
if (strcmp(lineHeader, "v") == 0) {
glm::vec3 vertex;
fscanf(file, "%f %f %f\n", &vertex.x, &vertex.y, &vertex.z);
vertex.x *= scale;
vertex.y *= scale;
vertex.z *= scale;
temp_vertices.push_back(vertex);
}
else if (strcmp(lineHeader, "vt") == 0) {
glm::vec2 uv;
fscanf(file, "%f %f\n", &uv.x, &uv.y);
uv.y = -uv.y; // Invert V coordinate since we will only use DDS texture, which are inverted. Remove if you want to use TGA or BMP loaders.
temp_uvs.push_back(uv);
}
else if (strcmp(lineHeader, "vn") == 0) {
glm::vec3 normal;
fscanf(file, "%f %f %f\n", &normal.x, &normal.y, &normal.z);
temp_normals.push_back(normal);
}
else if (strcmp(lineHeader, "f") == 0) {
std::string vertex1, vertex2, vertex3;
unsigned int vertexIndex[3] = { 0 }, uvIndex[3] = { 0 }, normalIndex[3] = { 0 };
char stupidBuffer[1024];
fgets(stupidBuffer, 1024, file);
int matches = sscanf(stupidBuffer, "%d/%d/%d %d/%d/%d %d/%d/%d\n", &vertexIndex[0], &uvIndex[0], &normalIndex[0], &vertexIndex[1], &uvIndex[1], &normalIndex[1], &vertexIndex[2], &uvIndex[2], &normalIndex[2]);
if (matches != 9) {
vertexIndex[3] = { 0 }, uvIndex[3] = { 0 }, normalIndex[3] = { 0 };
matches = sscanf(stupidBuffer, "%d//%d %d//%d %d//%d\n", &vertexIndex[0], &normalIndex[0], &vertexIndex[1], &normalIndex[1], &vertexIndex[2], &normalIndex[2]);
if (matches != 6) {
vertexIndex[3] = { 0 }, uvIndex[3] = { 0 }, normalIndex[3] = { 0 };
matches = sscanf(stupidBuffer, "%d %d %d\n", &vertexIndex[0], &vertexIndex[1], &vertexIndex[2]);
if (matches != 3) {
printf("File can't be read \n");
fclose(file);
return false;
}
}
}
}
This is my triangle class
class Triangle {
public:
Vector p0, p1, p2;
Vector color;
Vector normal(void);
};
I can't figure out how to parse the info from the .obj file into triangles that consist of three 3d vectors (points). I don't need code, I just need to understand how (if possible?) to parse all that info into triangles. Any other ideas are welcome. I want to make a simple puzzle game on the long run but I'm just taking it a step at a time.