Lately I’ve been playing around with C++ template metaprogramming, pretty cool stuff. There are a couple of books that I found very useful on the subject:
Modern C++ design by Andrei Alexandreshu, and
C++ Template Metaprogramming by David Abrahams and Aleksey Gurtovoy
Since I wanted to do some practice on the subject I decided to start writing a matrix-vector library. Pretty much every graphics programmer has written such a library.
So what’s new about it?
Well, when I wrote my first matrix library for 3d graphics, I implemented the transformations as 4×4 matrices represented in memory as an array of 16 floats. Points and and direction vectors were both represented by the same class containing 3 floats. I had a different function transforming points and transforming vectors.
The thing is, many transformations in 3d graphics are not a full 4×4 dense matrix. A translation, for example, has only seven out of sixteen values different from zero, and four of them are always one. Even an arbitrary concatenation of rotation, translation, and scale, has twelve out of sixteen arbitrary values, the last row is always [0, 0, 0, 1].
Wouldn’t be cool to be able to multiply a y-rotation and a translation matrix and have the compiler automatically optimize out all the unnecessary mults and adds between values that are always zero or one? Also, isn’t it a waste to store all 16 floats for matrices that we already know at compile time have only 3 arbitrary values?
Besides, when using 4×4 transform, a more coherent way of representing points in 3d space is as [x, y, z, 1] and directions as [x, y, z, 0]. It would be nice to be able to use the same matrix - vector prod function to transform both points and directions, without loosing any performance.
Thanks to template metaprogramming, it’s actually possible to put all this features together in a generic library.
OpenMVL is an Open Source library that allows to define sparse matrices where the sparsity pattern is defined at compile time. The compiler will then remove all unnecessary computations, making it as fast as hand written code. There is no need to write specialized product for points or vectors, everything is handled automatically in a coherent framework.
OpenMVL can be downloaded from the Downloads link on the top of the page. I hope you like it. For feedback, tips & tricks and bug reports, please check the Forum.
- Nicola