3D Vectors Mar 08, 2006
I've decided to do a few simpler articles, so I'd have somewhere on my site to link to from the advanced ones if anyone wants to brush up on a subject, or just read my take on it. This week: vectors, Next week: matrices.
C++ Vector Class
I'm referring to 3D vectors of course, not the C++ STL container unfortunately named vector. I recommend making and using a C++ class for 3D vectors with overloaded operators. I prefer to write my own classes for short things like this, so I'm comfortable using, adding to, and altering the class. Using a vector class leads to shorter code that looks more like a mathematical formula, that in my opinion is much easier to read and write. This is personal preference, some people may prefer standard C functions. A disadvantage is that for some cases the compiler may generate slower code, but from my tests for a complete editor/engine it never made even a single fps difference.
What functions should we start with in our vector class? Using the Vector Class
I use this class for both points and vectors, since they are both defined by (x,y,z) data. Which term used suggests what we're using this data to represent. Unlike points, vectors define magnitude and direction, and are usually drawn in diagrams as an arrow. Here are some examples: // finding the midpoint of a line defined by points L1, L2 CVec3 Mid = (L1 + L2) * 0.5f; // calculating the normal vector of a triangle face defined by points P1, P2, P3 CVec3 Norm = ( P2 - P1 ).CrossProduct( P3 - P1 ); // implementation of the Reflecting a Vector formula CVec3 ReflectVector( CVec3 VIn, CVec3 N ) { N.Normalize(); // only needed if N isn't normalized already return N * ( 2.0f * VIn.Dot( N ) ) - VIn; } Download Code
vec3.h ( 2K ) :
This is a bare-bones C++ vector class I wrote. All the functions are in the header to make it easier for the compiler to inline them. There really isn't much room for creativity here, so I suspect most vector class code will look similar, and I don't mind if you use this code as a starting point. You need to include math.h first. As usual this is based on working code of mine, but to keep it simple I've removed some features and made untested changes, so no guarantees =)
|