I have trouble understanding the following Javascript code.
It calculates, given a mesh described by its vertices vs
and indices ind
, the normals for each vertex. The mesh faces are a triangle list, and are oriented counterclockwise.
utilsObject.prototype.calculateNormals = function(vs, ind) {
var x = 0;
var y = 1;
var z = 2;
var ns = [];
// for each vertex, initialize normal x, normal y, normal z
for (var i = 0; i < vs.length; i++) {
ns[i] = 0.0;
}
// we work on triads of vertices to calculate normals so
// i = i+3 (i = indices index)
for (var i = 0; i < ind.length; i = i + 3) {
var v1 = [];
var v2 = [];
var normal = [];
// p1 - p0
v1[x] = vs[3 * ind[i + 1] + x] - vs[3 * ind[i] + x];
v1[y] = vs[3 * ind[i + 1] + y] - vs[3 * ind[i] + y];
v1[z] = vs[3 * ind[i + 1] + z] - vs[3 * ind[i] + z];
// p0 - p1
v2[x] = vs[3 * ind[i + 2] + x] - vs[3 * ind[i + 1] + x];
v2[y] = vs[3 * ind[i + 2] + y] - vs[3 * ind[i + 1] + y];
v2[z] = vs[3 * ind[i + 2] + z] - vs[3 * ind[i + 1] + z];
// cross product by Sarrus Rule
normal[x] = v1[y] * v2[z] - v1[z] * v2[y];
normal[y] = v1[z] * v2[x] - v1[x] * v2[z];
normal[z] = v1[x] * v2[y] - v1[y] * v2[x];
// update the normals of that triangle: sum of vectors
for (j = 0; j < 3; j++) {
ns[3 * ind[i + j] + x] = ns[3 * ind[i + j] + x] + normal[x];
ns[3 * ind[i + j] + y] = ns[3 * ind[i + j] + y] + normal[y];
ns[3 * ind[i + j] + z] = ns[3 * ind[i + j] + z] + normal[z];
}
}
}
How does this function work? For example, could you explain the use of indices in the instruction:
v1[x] = vs[3*ind[i+1]+x] - vs[3*ind[i]+x];
Rather than a high-level explanation, I am interested in the logic of the implementation details.
vs
is a vertex array andns
a corresponding normal array. Both are raw float arrays so they are indexed withi*3+0
(i*3+x
in the code) for x component of vector number i,i*3+1
for y,i*3+2
for z.ind
is an indirection array which contains vertex (and thus normal too) indices. It defines the triangle strips (the topology) within the arbitrary set of vertices.v1
andv2
are two edges of the triangle. $\endgroup$