本人在学习opengl做项目时,需要设计三维人脸模型。于是寻找多种方案。求得用opengl读取OBJ模型文件,并进行纹理修饰这一解决方案。在使用中用到了glm.c的库。主要用到如下几个函数,并进行了分析。希望能给大家有所帮助,如果分析中有不恰当的地方,望批评指正。建议花点时间看看
(1)obj文件的读取函数
GLMmodel*
glmReadOBJ(char* filename)
{
GLMmodel* model;
FILE* file;
/* open the file */
file = fopen(filename, "r");
if (!file) {
fprintf(stderr, "glmReadOBJ() failed: can't open data file \"%s\".\n",
filename);
exit(1);
}
/* allocate a new model */
model = (GLMmodel*)malloc(sizeof(GLMmodel));
model->pathname = strdup(filename);//模型文件和材质库的路径
model->mtllibname = NULL;//材质库名
model->numvertices = 0;//顶点数
model->vertices = NULL;//储存顶点的向量
model->numnormals = 0;//模型法向数
model->normals = NULL;//储存法向的向量
model->numtexcoords = 0;//纹理坐标数
model->texcoords = NULL;//储存纹理坐标的向量
model->numfacetnorms = 0;//规则平面数
model->facetnorms = NULL;//储存规则平面的向量
model->numtriangles = 0;//三角形数
model->triangles = NULL;//储存三角形的向量
model->nummaterials = 0;//材质数
model->materials = NULL;//储存材质的向量
model->numgroups = 0;//图元组数
model->groups = NULL;//储存图元组的向量
model->position[0] = 0.0;//模型的位置
model->position[1] = 0.0;
model->position[2] = 0.0;
/* make a first pass through the file to get a count of the number
of vertices, normals, texcoords & triangles */
glmFirstPass(model, file);//只是获得v(顶点)、vt(贴图坐标)、vn(法线)、f(面)等数量
/* allocate memory 开辟数据空间*/
model->vertices = (GLfloat*)malloc(sizeof(GLfloat) *
3 * (model->numvertices + 1));
model->triangles = (GLMtriangle*)malloc(sizeof(GLMtriangle) *
model->numtriangles);
if (model->numnormals) {
model->normals = (GLfloat*)malloc(sizeof(GLfloat) *
3 * (model->numnormals + 1));
}
if (model->numtexcoords) {
model->texcoords = (GLfloat*)malloc(sizeof(GLfloat) *
2 * (model->numtexcoords + 1));
}
/* rewind to beginning of file and read in the data this pass */
rewind(file);//将文件内部的位置指针重新指向一个流(数据流/文件)的开头
glmSecondPass(model, file);//读取v(顶点)、vt(贴图坐标)、vn(法线)、f(面)等的数据值
/* close the file */
fclose(file);
return model;
}
(2)/按mode指定模式使用当前的OPENGL绘制上下文(context)绘制模型函数
//mode指定写入方式,此参数为取或(“|”)的位联合:
//GLM_NONE - 只按顶点处理
//GLM_FLAT - 按面计算法向