我有一个 Wavefront OBJ Parser 正在运行,但是在花了无数小时试图弄清楚我如何在 OpenGL 中加载数据之后,我最终不得不放弃。
这是代码的构建方式:
struct ObjMeshVertex{
Vector3f pos;
Vector2f texcoord;
Vector3f normal;
};
struct ObjMeshFace{
ObjMeshVertex vertices[3];
};
struct ObjMesh{
std::vector<ObjMeshFace> faces;
};
ObjMesh myMesh;
for(size_t i = 0; i < faces.size(); ++i){
ObjMeshFace face;
for(size_t j = 0; j < 3; ++j){
face.vertices[j].pos = positions[faces[i].pos_index[j] - 1];
face.vertices[j].texcoord = texcoords[faces[i].tex_index[j] - 1];
face.vertices[j].normal = normals[faces[i].nor_index[j] - 1];
}
myMesh.faces.push_back(face);
}
通常当我创建一个简单的多维数据集时,数组看起来像这样{posX, posY, posZ, normX, normY, normZ}
:
并且通过使用偏移量glVertexAttribPointer
来加载数据非常简单。
但我不知道这是怎么做到的?
编辑设置:
glGenVertexArraysOES(1, &_boxVAO);
glBindVertexArrayOES(_boxVAO);
int sizeOfFaces = myMesh.faces.size() * sizeof(ObjMeshFace);
glGenBuffers(1, &_boxBuffer);
glBindBuffer(GL_ARRAY_BUFFER, _boxBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeOfFaces, &(myMesh.faces[0]), GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(ObjMeshVertex), 0);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(ObjMeshVertex), (void*)offsetof(ObjMeshVertex, texcoord));
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE ,sizeof(ObjMeshVertex), (void*)offsetof(ObjMeshVertex, normal));
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
glBindVertexArrayOES(0);
画:
glBindVertexArrayOES(_boxVAO);
glDrawArrays(GL_TRIANGLES, 0, indicesize);
其中 indexize = myMesh.faces.size()