HTML and CSS Reference
In-Depth Information
First, you need to find the normal of the triangle. This is a vector that is perpendicular to the
surface of the triangle, depicted in Figure 17-5 and mentioned briefly in the last chapter.
Imagine you had a triangular piece of wood and you put a nail through the back of it so it stuck
out directly through the face. The nail represents the normal of that surface. If you study anything
about 3D rendering and lighting, you see all kinds of references to surface normals.
normal
A
C
B
Figure 17-5. The normal is perpendicular to the surface of the triangle.
You can find the normal of a surface by taking two vectors that make up that surface plane and calculating
their cross product . A cross product of two vectors is a new vector, which is perpendicular to those two.
The two vectors you use are the lines between points A and B, and points B and C. Each vector is held in
an object with x, y, and z properties.
var ab = {
x: this.pointA.x - this.pointB.x,
y: this.pointA.y - this.pointB.y,
z: this.pointA.z - this.pointB.z
};
var bc = {
x: this.pointB.x - this.pointC.x,
y: this.pointB.y - this.pointC.y,
z: this.pointB.z - this.pointC.z
};
Then you calculate the normal, which is another vector, and you call this object norm . The following
code computes the cross product of the vectors ab and bc , using a standard formula from linear
algebra:
var norm = {
x: (ab.y * bc.z) - (ab.z * bc.y),
y: -((ab.x * bc.z) - (ab.z * bc.x)),
z: (ab.x * bc.y) - (ab.y * bc.x)
};
Now you need to know how closely that normal aligns with the angle of the light. Another bit of vector math
is the dot product, which is the difference between two vectors. You have the vector of the normal, and the
vector of the light. The following calculates that dot product:
var dotProd = norm.x * this.light.x +
 
Search WWH ::




Custom Search