これが数回静かに尋ねられたことは知っていますが、私の問題はそれを行う方法ではありません。私はこれがどのように機能するかを知っています (少なくとも私はそう思います ^^) が、実装に何か問題があるようで、後戻りできません。手続き的に生成された地形メッシュがあり、この頂点が接続されているすべての三角形の法線を平均して、各頂点の法線を計算しようとしています。通常の xyz を RGB 頂点カラーに設定すると、黒 (0, 0, 0) または青 (0, 0, 1) のいずれかがランダムに表示されます。
void CalculateVertexNormal(int index){ //index of the vertex in the mesh's vertex array
std::vector<int> indices; //indices of triangles the vertex is a part of
Vector normals = Vector(0.0f, 0.0f, 0.0f, 0.0f); //sum of all the face normals
for(int i = 0; i < triangles.size(); i += 3){ //iterate over the triangle array in order
if(triangles[i] == index) //to find the triangle indices
indices.push_back(triangles[i]);
else if(triangles[i + 1] == index)
indices.push_back(triangles[i]);
else if(triangles[i + 2] == index)
indices.push_back(triangles[i]);
}
for(int i = 0; i < indices.size(); i++){ //iterate over the indices to calculate the normal for each tri
int vertex = indices[i];
Vector v1 = vertices[vertex + 1].GetLocation() - vertices[vertex].GetLocation(); //p1->p2
Vector v2 = vertices[vertex + 2].GetLocation() - vertices[vertex].GetLocation(); //p1->p3
normals += v1.Cross(v2); //cross product with two edges to receive face normal
}
vertices[index].SetNormals(normals.Normalize()); //normalize the sum of face normals and set to vertex
}
たぶん、誰かが見て、私が間違っていることを教えてくれるかもしれません。ありがとうございました。
編集: molbdnilo のコメントのおかげで、何が問題なのかがようやくわかりました。これは配列のインデックス作成の問題であり、私の 2 つのループも同様にややこしいものでした。少し休む必要があるかもしれません ;) 最終的にこれを思いつき、ループを 1 つに減らしました。
for(int i = 0; i < triangles.size(); i += 3){
if(triangles[i] == index || triangles[i + 1] == index || triangles[i + 2] == index){
Vector v1 = vertices[triangles[i + 1]].GetLocation() - vertices[index].GetLocation();
Vector v2 = vertices[triangles[i + 2]].GetLocation() - vertices[index].GetLocation();
faceNormals += v1.Cross(v2);
}
}
vertices[index].SetNormals(faceNormals.Normalize());