Vector OperationsWe can perform operations on vectors like we would on our everyday numbers such as addition, subtraction, and multiplication (though multiplication has two different interpretations). Addition
inline Vector AddVect( Vector &v1, Vector &v2 ) { Vector v; v.x = v1.x + v2.x; v.y = v1.y + v2.y; v.z = v1.z + v2.z; return( v ); } Subtraction
inline Vector SubVect( Vector &v1, Vector &v2 ) { Vector v; v.x = v1.x - v2.x; v.y = v1.y - v2.y; v.z = v1.z - v2.z; return( v ); } Multiplication with a Scalar NumberTo increase the length of a vector we can multiply with a scalar number. inline Vector ScaleIncrease( Vector &v, float &s ) { v.x *= s; v.y *= s; v.z *= s; return( v ); } Division with a Scalar NumberTo decrease the length of a vector we can divide with a scalar number. inline Vector ScaleDecrease( Vector &v, float &s ) { v.x /= s; v.y /= s; v.z /= s; return( v ); } Dot ProductThe Dot Product is a vector operation which will return a scalar value (single number), which for unit vectors is equal to the cosine of the angle between the two input vectors (for non-unit vectors, it is equal to the length of each multiplied by the cosine, as shown in the equation below). We can represent the Dot Product equation with the ● symbol. U ● V = |U| * |V| * cos(q) alternatively ( x1, y1, z1 ) ● ( x2, y2, z2 ) = x1y1 + x2y2 + z1z2
In Figure 5, there are two vectors pointing in different directions. Where those vectors meet you can find the dot product. Before we do anything else let’s take a look at the dot product code. inline float DotProduct( Vector &v1, Vector &v2 ) { return( (v1.x*v2.x) + (v1.y*v2.y) + (v1.z*v2.z) ); } This seems to be a complex task, but it's actually quite simple in code. All we did was multiply each vector component together and sum the products. Our returned value is a scalar value - not a vector - and this is our dot product. It won’t take long in your exploration of 3-D graphics before you find yourself using the dot product frequently. Among other things, it is useful in backface culling, lighting and collision detection. Cross ProductAnother useful vector operation is the cross product. Unlike the dot product which returns a scalar value the cross product actually returns a vector. The vector which is returned is perpendicular to the two input vectors. inline Vector CrossProduct( Vector &v1, Vector &v2 ) { Vector v; v.x = ( v1.y * v2.z ) – ( v1.z * v2.y ); v.y = ( v1.z * v2.x ) – ( v1.x * v2.z ); v.z = ( v1.x * v2.y ) – ( v1.y * v2.x ); return( v ); } In 3D graphics, the most common use of the cross product is to calculate a polygon normal. Calculating the polygon normal can be great for backface culling and lighting. We do this by doing a cross product on two vectors that lie on the polygon's plane (more on planes in a sec).
|