我正在将一个由Blender创建的.obj文件解析到OpenGL的C++程序中,看起来已经接近成功了。它似乎可以正确地找到所需的顶点。我正在尝试创建一个可以移动的大写字母I方块。以下是我的解析代码:
bool loadObjectFile(const char * filepath, std::vector < glm::vec3 > & out_vertices, std::vector < glm::vec3 > & out_normals)
{
std::vector< unsigned int > vertexIndices;
std::vector< glm::vec3 > temp_vertices;
std::vector< glm::vec3 > temp_normals;
glm::vec3 tempFaceNormal;
FILE * file = fopen(filepath, "r");
if (file == NULL)
{
printf("Impossible to open the file !\n");
return false;
}
while (1)
{
char lineHeader[128];
// read the first word of the line
int res = fscanf(file, "%s", lineHeader);
if (res == EOF)
break; // EOF = End Of File. Quit the loop.
// else : parse lineHeader
if (strcmp(lineHeader, "v") == 0)
{
glm::vec3 vertex;
fscanf(file, "%f %f %f\n", &vertex.x, &vertex.y, &vertex.z);
temp_vertices.push_back(vertex);
glm::vec3 zeroface;
zeroface.x = 0, zeroface.y = 0, zeroface.z = 0;
temp_normals.push_back(zeroface);
}
else if (strcmp(lineHeader, "f") == 0)
{
unsigned int vertexIndex[3];
int matches = fscanf(file, "%d %d %d\n", &vertexIndex[0], &vertexIndex[1], &vertexIndex[2]);
if (matches != 3)
{
printf("File can't be read by our simple parser : ( Try exporting with other options\n");
return false;
}
vertexIndices.push_back(vertexIndex[0]);
vertexIndices.push_back(vertexIndex[1]);
vertexIndices.push_back(vertexIndex[2]);
tempFaceNormal = computeNormal(temp_vertices[vertexIndex[0] - 1], temp_vertices[vertexIndex[1] - 1], temp_vertices[vertexIndex[2] - 1]);
temp_normals[vertexIndex[0] - 1] += tempFaceNormal;
temp_normals[vertexIndex[1] - 1] += tempFaceNormal;
temp_normals[vertexIndex[2] - 1] += tempFaceNormal;
}
}
// For each vertex of each triangle
for (unsigned int i = 0; i < vertexIndices.size(); i++)
{
unsigned int vertexIndex = vertexIndices[i];
glm::vec3 vertex = temp_vertices[vertexIndex - 1];
out_vertices.push_back(vertex);
}
//For each vertex normal
for (unsigned int i = 0; i < temp_normals.size(); i++)
{
out_normals.push_back(glm::normalize(temp_normals[i]));
}
}
glm::vec3 computeNormal(glm::vec3 const & a, glm::vec3 const & b, glm::vec3 const & c)
{
//Returns the (not normalized) face normal of each triangle
return glm::cross(c - a, b - a);
}
这是我用来绘制解析顶点的代码:
glBegin(GL_QUADS);
glColor3f(0.2, 0.2, 0);
for (int i = 0; i < vertices.size(); i++)
{
glVertex3f(vertices[i].x, vertices[i].y, vertices[i].z);
glTexCoord3f(vertices[i].x, vertices[i].y, vertices[i].z);
}
for (int i = 0; i < normals.size(); i++)
{
glNormal3f(normals[i].x, normals[i].y, normals[i].z);
}
glEnd();
这将产生以下结果(截图):
https://drive.google.com/file/d/0B6qCowcn51DnQk1mT0hSUjZWc00/view?usp=sharing
https://drive.google.com/file/d/0B6qCowcn51DndTBJRFctV1lOQlk/view?usp=sharing
这里,顶点似乎是正确的,但面似乎被错误地绘制了。
GL_QUADS
。这段代码有很多问题,不确定这是否特定到足以适用于 StackOverflow 的格式。 - Reto Koradi