Friday, 5 September 2008

Reinventing the wheel

Matrix multiplication is fundamental in computer graphics, expecially when you're dealing with shadow maps and texture projections.

Unfortunately, there are no standard functions for matrix multiplication, so it was time for DIY. Here comes my snippet:



float* matrixProduct(float* A, float* B) {

// we have to allocate space for a 4x4 floats matrix
float* pointer= (float *) calloc(sizeof(float), 16);

// in order to compute the resulting matrix, we have to use two nested fors
for (int r=0; r<4; r++) {
for (int c=0; c<4; c++) {

// actual multiplications
for (int i=0; i<4; i++) {
pointer[r*4+c] = pointer[r*4+c] + A[r*4+i]*B[c+i*4];
}
}
}

return
pointer;

}


This simple function returns a pointer to an handful 4x4 array of floats, without memory flaws. Maybe this snippet will be helpful for someone in the future.