Matrices Mar 15, 2006
Matrices are important for 3d programming, as they can be used to store any order of translations, rotations, and scaling. Maybe in another article I'll go into detail about how matrices work for this, and how to build a matrix for each these transformations.
My main purpose behind this article is to start making some example code for the building blocks of game programming. Maybe I'll eventually have enough to start assembling sample programs with some of my advanced articles. This one builds on last week's article about 3D Vectors. C++ 4x4 Matrix Class
I chose to make a class that only does 4x4 matrices because this is what is commonly used and needed for 3D graphics. What functions you'll want in a matrix class depends on what you'll use it for, I just write new functions as needed for mine. Some things I think you'll definitely want is the ability to do matrix multiplication to concatenate the transformations represented by matrices, and to apply these transformations to a point. You'll also want to be able to create the matrix from rotating, scaling, and translating. I also decided to add the ability to invert a matrix (that is only made by rotating and translating) to my example class.
Using the Matrix Class
Here's an example that performs a (nonsensical) transformation on a single point. Most real world examples will be similar, but with variables instead of constant numbers. Because of the limited precision of floating point numbers, the results will be slightly innacurate, but this won't matter for normal use.
CVec3 Point( 100.0f, 0.0f, 0.0f ); CMatrix M; M.Rotate( 90, 0, 1, 0 ); M.Translate( CVec3( 0.0f, 0.0f, 50.0f ) ); CVec3 NewPoint = M * Point; CVec3 OldPoint = M.InvertSimple() * NewPoint;In this example, Matrix M will translate Point to (100, 0, 50) then rotate around the y=0 axis to ( -50, 0, 100). Although I actually don't recommend thinking about order of transformations in this way, proper order will come natural with practice. OldPoint will be the same as Point since it's transformed by the inverse of M. Note: I changed my matrix rotations to be counter-clockwise since OpenGL rotates in this direction. Not all matrix libraries use the same order of transformations or rotation direction. Download Code
matrix.h ( 4K ) :
This is a C++ matrix class I wrote. It uses the vector class from last week for some functions. A matrix class is a bit more complex than a vector class, so I recommend at least reading through all the code to see how to use it. This is based on the matrix class I use, but for simplicity's sake I removed most of the functionality. (One example of what I removed is Matrix from Quaternion. ) Later on when I see what I need, I may add some of these functions back. Hopefully all this playing around didn't break anything.
|