我在尝试从波前文件加载 3d 对象并将其保存到我预定义的结构中时遇到问题。我收到分段错误错误,我假设我的指针在某个地方出错了。以下是结构:
struct vertex
{
float x,y,z;
};
// the idea is to split each object into groups in order to animate
// them seperately
struct group
{
float xpos, ypos, zpos;
float xrot, yrot, zrot;
int numVertices;
int numFaces;
//all verteces
vertex vertices[MAX_NUM];
//faces-- a face is made up of one vertex from each of these arrays
vertex vertexOne[MAX_NUM];
vertex vertexTwo[MAX_NUM];
vertex vertexThree[MAX_NUM];
};
struct object
{
float xpos, ypos, zpos;
float xrot, yrot, zrot;
int numGroups;
group * groups[MAX_NUM];
};
这是应该加载对象的函数:
object * loadObject(char * path)
{
object * obj;
obj = new object;
char str[1];
obj->numGroups = 0;
FILE * file = fopen(path, "r");
while(fscanf(file, "%s", str) != EOF)
{
if(str[0] == 'o')
{
obj->numGroups++;
obj->groups[obj->numGroups-1] = new group;
obj->groups[obj->numGroups-1]->numVertices = 0;
obj->groups[obj->numGroups-1]->numFaces = 0;
}
else if(str[0] == 'v' && str[1] == ' ')
{
obj->groups[obj->numGroups-1]->numVertices++;
sscanf(str, "v %f %f %f",
&(obj->groups[obj->numGroups-1]->vertices[obj->groups[obj->numGroups-1]->numVertices-1].x),
&(obj->groups[obj->numGroups-1]->vertices[obj->groups[obj->numGroups-1]->numVertices-1].y),
&(obj->groups[obj->numGroups-1]->vertices[obj->groups[obj->numGroups-1]->numVertices-1].z));
}
else if(str[0] == 'f')
{
int one, two, three;
obj->groups[obj->numGroups-1]->numFaces++;
sscanf(str, "f %i/%*i/%*i %i/%*i/%*i %i/%*i/%*i", &one, &two, &three);
obj->groups[obj->numGroups-1]->vertexOne[obj->groups[obj->numGroups-1]->numFaces-1] = obj->groups[obj->numGroups-1]->vertices[one-1];
obj->groups[obj->numGroups-1]->vertexTwo[obj->groups[obj->numGroups-1]->numFaces-1] = obj->groups[obj->numGroups-1]->vertices[two-1];
obj->groups[obj->numGroups-1]->vertexThree[obj->groups[obj->numGroups-1]->numFaces-1] = obj->groups[obj->numGroups-1]->vertices[three-1];
}
}
fclose(file);
return obj;
}
我已经尝试了很长时间才能找到问题,但我根本没有得到有关错误的信息。我知道我分配顶点和面的方式有点乏味,非常欢迎任何关于更整洁代码的建议。如果需要任何其他信息,请告诉我,非常感谢您提前。