I am coding an assignment in computer graphics where I have to use different light models (ambient, diffusion, specular) for an object consisting of N triangles. Given the coordinates of the three vertices of each triangle in 3-D space, I want to calculate the normal vectors for each vertex.
I have tried the following code using some help I found searching online but I really am not sure if I am doing this correctly.
function Normals = findVertNormals(R, F)
number_of_triangles = length(F);
number_of_vertices = length(R);
A = zeros(3,number_of_triangles);
Normals = zeros(3,number_of_vertices);
for i = 1:number_of_triangles
first_vertex = R(:,F(i,1));
second_vertex = R(:,F(i,2));
third_vertex = R(:,F(i,3));
V = second_vertex - first_vertex ;
W = third_vertex - first_vertex;
N = cross(V,W);
A(:,i) = N ./ norm(N);
end
for i = 1:number_of_triangles
for j = 1:3
Normals(:,F(i,j)) = Normals(:,F(i,j)) + A(:,i);
end
end
Normals = Normals ./ norm(Normals);
end
where matrix F
describes which vertices form each triangle and matrix R
contains the coordinates of vertex in 3-D space.