Reputation: 601
I try to render lights on some models. All models have some uniques options (scale, position, rotation). I create a matrix with all this options and change all model's vertices from this matrix.
I have a big problem when the model has a negative scale, the normal is reversed and don't looks like it should.
Here the code I use:
vec3.calcNormal = function( a, b, c, dest ) {
var v1 = dest || vec3.create(), v2 = vec3.create();
vec3.subtract( c, b, v1 );
vec3.subtract( a, b, v2 );
vec3.cross( v1, v2 );
return vec3.normalize(v1);
};
// Apply matrix on vertices
size = vertices.length;
vert = new Array(size);
for( i=0; i<size; ++i ) {
vert[i] = vec3.create();
mat4.multiplyVec3( matrix, vertices[i], vert[i] );
}
// Generate face normals
face_normal = new Array(faces.length);
for ( i=0, count=faces.length; i<count; ++i ) {
face = faces[i];
face_normal[i] = vec3.create();
vec3.calcNormal(
vert[ face.vertidx[0] ],
vert[ face.vertidx[1] ],
vert[ face.vertidx[2] ],
face_normal[i]
);
}
Does someone know how to fix this problem ? I tried to scale back the normal or don't scale it at all, but It didn't work.
Fixed with:
// Get normal matrix
mat3.transpose( mat4.toInverseMat3(matrix), normalMat );
// Apply matrix on vertices
size = vertices.length;
vert = new Array(size);
for( i=0; i<size; ++i ) {
vert[i] = vec3.create();
mat4.multiplyVec3( matrix, vertices[i], vert[i] );
}
// Generate face normals
face_normal = new Array(faces.length);
for ( i=0, count=faces.length; i<count; ++i ) {
face = faces[i];
face_normal[i] = vec3.create();
vec3.calcNormal(
vertices[ face.vertidx[0] ],
vertices[ face.vertidx[1] ],
vertices[ face.vertidx[2] ],
face_normal[i]
);
mat3.multiplyVec3( normalMat, face_normal[i] );
}
Upvotes: 2
Views: 1084