我有一个 obj 文件,它以这种方式存储数据:
v value1 value2 value3
f value1 value2 value3
首先,我计算面部的法线,然后为该面部的每个顶点分配:
for(int i = 0; i < verticesInd.size(); i+=3)
{
glm::vec3 normal = glm::normalize(glm::cross(glm::vec3(vertices[verticesInd[i + 1]]) - glm::vec3(vertices[verticesInd[i]]), glm::vec3(vertices[verticesInd[i + 2]]) - glm::vec3(vertices[verticesInd[i]])));
out_Normals[i] = normal;
out_Normals[i + 1] = normal;
out_Normals[i + 2] = normal;
}
为了实现平面着色,我可以复制顶点:
for(int i = 0; i < verticesInd.size(); i++)
{
out_Vertices.push_back(vertices[verticesInd[i]]);
}
然后使用 glDrawArrays 绘制对象:
glDrawArrays(GL_TRIANGLES, 0, out_Vertices.size());
为了获得平滑的阴影,我需要平均每个顶点的法线,但我不知道如何找到相邻的面。
Edit1:我没有注意到 f 之前的单个 s 参数:
v value1 value2 value3
s 1
f value1 value2 value3
Edit2:法线平均
glm::vec3 tNormal;
for(int i = 0; i < vertices.size(); i++)
{
for(int j = 0; j < verticesInd.size(); j++)
{
if(verticesInd[j] == i)
{
tNormal += faceNormals[j / 3];
}
}
aNormals.push_back(glm::normalize(tNormal));
tNormal = glm::vec3(0,0,0);
}
编辑 3面法线:
for(int i = 0; i < verticesInd.size(); i+=3)
{
glm::vec3 normal = glm::normalize(glm::cross(glm::vec3(vertices[verticesInd[i + 1]]) - glm::vec3(vertices[verticesInd[i]]), glm::vec3(vertices[verticesInd[i + 2]]) - glm::vec3(vertices[verticesInd[i]])));
faceNormals.push_back(normal);
}