At last... this merge should finally do the trick!
[blender.git] / source / blender / python / generic / matrix.c
1 /*
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * Contributor(s): Michel Selten & Joseph Gilbert
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 #include "Mathutils.h"
29
30 #include "BKE_utildefines.h"
31 #include "BLI_arithb.h"
32 #include "BLI_blenlib.h"
33
34 static PyObject *column_vector_multiplication(MatrixObject * mat, VectorObject* vec); /* utility func */
35
36
37 /* matrix vector callbacks */
38 int mathutils_matrix_vector_cb_index= -1;
39
40 static int mathutils_matrix_vector_check(MatrixObject *self)
41 {
42         return Matrix_ReadCallback(self);
43 }
44
45 static int mathutils_matrix_vector_get(MatrixObject *self, int subtype, float *vec_from)
46 {
47         int i;
48         if(!Matrix_ReadCallback(self))
49                 return 0;
50
51         for(i=0; i<self->colSize; i++)
52                 vec_from[i]= self->matrix[subtype][i];
53
54         return 1;
55 }
56
57 static int mathutils_matrix_vector_set(MatrixObject *self, int subtype, float *vec_to)
58 {
59         int i;
60         if(!Matrix_ReadCallback(self))
61                 return 0;
62
63         for(i=0; i<self->colSize; i++)
64                 self->matrix[subtype][i]= vec_to[i];
65
66         Matrix_WriteCallback(self);
67         return 1;
68 }
69
70 static int mathutils_matrix_vector_get_index(MatrixObject *self, int subtype, float *vec_from, int index)
71 {
72         if(!Matrix_ReadCallback(self))
73                 return 0;
74
75         vec_from[index]= self->matrix[subtype][index];
76         return 1;
77 }
78
79 static int mathutils_matrix_vector_set_index(MatrixObject *self, int subtype, float *vec_to, int index)
80 {
81         if(!Matrix_ReadCallback(self))
82                 return 0;
83
84         self->matrix[subtype][index]= vec_to[index];
85
86         Matrix_WriteCallback(self);
87         return 1;
88 }
89
90 Mathutils_Callback mathutils_matrix_vector_cb = {
91         mathutils_matrix_vector_check,
92         mathutils_matrix_vector_get,
93         mathutils_matrix_vector_set,
94         mathutils_matrix_vector_get_index,
95         mathutils_matrix_vector_set_index
96 };
97 /* matrix vector callbacks, this is so you can do matrix[i][j] = val  */
98
99 /*-------------------------DOC STRINGS ---------------------------*/
100 static char Matrix_Zero_doc[] = "() - set all values in the matrix to 0";
101 static char Matrix_Identity_doc[] = "() - set the square matrix to it's identity matrix";
102 static char Matrix_Transpose_doc[] = "() - set the matrix to it's transpose";
103 static char Matrix_Determinant_doc[] = "() - return the determinant of the matrix";
104 static char Matrix_Invert_doc[] =  "() - set the matrix to it's inverse if an inverse is possible";
105 static char Matrix_TranslationPart_doc[] = "() - return a vector encompassing the translation of the matrix";
106 static char Matrix_RotationPart_doc[] = "() - return a vector encompassing the rotation of the matrix";
107 static char Matrix_scalePart_doc[] = "() - convert matrix to a 3D vector";
108 static char Matrix_Resize4x4_doc[] = "() - resize the matrix to a 4x4 square matrix";
109 static char Matrix_toEuler_doc[] = "(eul_compat) - convert matrix to a euler angle rotation, optional euler argument that the new euler will be made compatible with.";
110 static char Matrix_toQuat_doc[] = "() - convert matrix to a quaternion rotation";
111 static char Matrix_copy_doc[] = "() - return a copy of the matrix";
112
113 static PyObject *Matrix_Zero( MatrixObject * self );
114 static PyObject *Matrix_Identity( MatrixObject * self );
115 static PyObject *Matrix_Transpose( MatrixObject * self );
116 static PyObject *Matrix_Determinant( MatrixObject * self );
117 static PyObject *Matrix_Invert( MatrixObject * self );
118 static PyObject *Matrix_TranslationPart( MatrixObject * self );
119 static PyObject *Matrix_RotationPart( MatrixObject * self );
120 static PyObject *Matrix_scalePart( MatrixObject * self );
121 static PyObject *Matrix_Resize4x4( MatrixObject * self );
122 static PyObject *Matrix_toEuler( MatrixObject * self, PyObject *args );
123 static PyObject *Matrix_toQuat( MatrixObject * self );
124 static PyObject *Matrix_copy( MatrixObject * self );
125
126 /*-----------------------METHOD DEFINITIONS ----------------------*/
127 static struct PyMethodDef Matrix_methods[] = {
128         {"zero", (PyCFunction) Matrix_Zero, METH_NOARGS, Matrix_Zero_doc},
129         {"identity", (PyCFunction) Matrix_Identity, METH_NOARGS, Matrix_Identity_doc},
130         {"transpose", (PyCFunction) Matrix_Transpose, METH_NOARGS, Matrix_Transpose_doc},
131         {"determinant", (PyCFunction) Matrix_Determinant, METH_NOARGS, Matrix_Determinant_doc},
132         {"invert", (PyCFunction) Matrix_Invert, METH_NOARGS, Matrix_Invert_doc},
133         {"translationPart", (PyCFunction) Matrix_TranslationPart, METH_NOARGS, Matrix_TranslationPart_doc},
134         {"rotationPart", (PyCFunction) Matrix_RotationPart, METH_NOARGS, Matrix_RotationPart_doc},
135         {"scalePart", (PyCFunction) Matrix_scalePart, METH_NOARGS, Matrix_scalePart_doc},
136         {"resize4x4", (PyCFunction) Matrix_Resize4x4, METH_NOARGS, Matrix_Resize4x4_doc},
137         {"toEuler", (PyCFunction) Matrix_toEuler, METH_VARARGS, Matrix_toEuler_doc},
138         {"toQuat", (PyCFunction) Matrix_toQuat, METH_NOARGS, Matrix_toQuat_doc},
139         {"copy", (PyCFunction) Matrix_copy, METH_NOARGS, Matrix_copy_doc},
140         {"__copy__", (PyCFunction) Matrix_copy, METH_NOARGS, Matrix_copy_doc},
141         {NULL, NULL, 0, NULL}
142 };
143
144 //----------------------------------Mathutils.Matrix() -----------------
145 //mat is a 1D array of floats - row[0][0],row[0][1], row[1][0], etc.
146 //create a new matrix type
147 static PyObject *Matrix_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
148 {
149         PyObject *argObject, *m, *s;
150         MatrixObject *mat;
151         int argSize, seqSize = 0, i, j;
152         float matrix[16] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
153                 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
154         float scalar;
155
156         argSize = PyTuple_GET_SIZE(args);
157         if(argSize > 4){        //bad arg nums
158                 PyErr_SetString(PyExc_AttributeError, "Mathutils.Matrix(): expects 0-4 numeric sequences of the same size\n");
159                 return NULL;
160         } else if (argSize == 0) { //return empty 4D matrix
161                 return (PyObject *) newMatrixObject(NULL, 4, 4, Py_NEW);
162         }else if (argSize == 1){
163                 //copy constructor for matrix objects
164                 argObject = PyTuple_GET_ITEM(args, 0);
165                 if(MatrixObject_Check(argObject)){
166                         mat = (MatrixObject*)argObject;
167                         if(!Matrix_ReadCallback(mat))
168                                 return NULL;
169
170                         argSize = mat->rowSize; //rows
171                         seqSize = mat->colSize; //col
172                         for(i = 0; i < (seqSize * argSize); i++){
173                                 matrix[i] = mat->contigPtr[i];
174                         }
175                 }
176         }else{ //2-4 arguments (all seqs? all same size?)
177                 for(i =0; i < argSize; i++){
178                         argObject = PyTuple_GET_ITEM(args, i);
179                         if (PySequence_Check(argObject)) { //seq?
180                                 if(seqSize){ //0 at first
181                                         if(PySequence_Length(argObject) != seqSize){ //seq size not same
182                                                 PyErr_SetString(PyExc_AttributeError, "Mathutils.Matrix(): expects 0-4 numeric sequences of the same size\n");
183                                                 return NULL;
184                                         }
185                                 }
186                                 seqSize = PySequence_Length(argObject);
187                         }else{ //arg not a sequence
188                                 PyErr_SetString(PyExc_TypeError, "Mathutils.Matrix(): expects 0-4 numeric sequences of the same size\n");
189                                 return NULL;
190                         }
191                 }
192                 //all is well... let's continue parsing
193                 for (i = 0; i < argSize; i++){
194                         m = PyTuple_GET_ITEM(args, i);
195                         if (m == NULL) { // Failed to read sequence
196                                 PyErr_SetString(PyExc_RuntimeError, "Mathutils.Matrix(): failed to parse arguments...\n");
197                                 return NULL;
198                         }
199
200                         for (j = 0; j < seqSize; j++) {
201                                 s = PySequence_GetItem(m, j);
202                                 if (s == NULL) { // Failed to read sequence
203                                         PyErr_SetString(PyExc_RuntimeError, "Mathutils.Matrix(): failed to parse arguments...\n");
204                                         return NULL;
205                                 }
206                                 
207                                 scalar= (float)PyFloat_AsDouble(s);
208                                 Py_DECREF(s);
209                                 
210                                 if(scalar==-1 && PyErr_Occurred()) { // parsed item is not a number
211                                         PyErr_SetString(PyExc_AttributeError, "Mathutils.Matrix(): expects 0-4 numeric sequences of the same size\n");
212                                         return NULL;
213                                 }
214
215                                 matrix[(seqSize*i)+j]= scalar;
216                         }
217                 }
218         }
219         return newMatrixObject(matrix, argSize, seqSize, Py_NEW);
220 }
221
222 /*-----------------------------METHODS----------------------------*/
223 /*---------------------------Matrix.toQuat() ---------------------*/
224 static PyObject *Matrix_toQuat(MatrixObject * self)
225 {
226         float quat[4];
227
228         if(!Matrix_ReadCallback(self))
229                 return NULL;
230         
231         /*must be 3-4 cols, 3-4 rows, square matrix*/
232         if(self->colSize < 3 || self->rowSize < 3 || (self->colSize != self->rowSize)) {
233                 PyErr_SetString(PyExc_AttributeError, "Matrix.toQuat(): inappropriate matrix size - expects 3x3 or 4x4 matrix");
234                 return NULL;
235         } 
236         if(self->colSize == 3){
237         Mat3ToQuat((float (*)[3])*self->matrix, quat);
238         }else{
239                 Mat4ToQuat((float (*)[4])*self->matrix, quat);
240         }
241         
242         return newQuaternionObject(quat, Py_NEW);
243 }
244 /*---------------------------Matrix.toEuler() --------------------*/
245 PyObject *Matrix_toEuler(MatrixObject * self, PyObject *args)
246 {
247         float eul[3], eul_compatf[3];
248         EulerObject *eul_compat = NULL;
249         int x;
250         
251         if(!Matrix_ReadCallback(self))
252                 return NULL;
253         
254         if(!PyArg_ParseTuple(args, "|O!:toEuler", &euler_Type, &eul_compat))
255                 return NULL;
256         
257         if(eul_compat) {
258                 for(x = 0; x < 3; x++) {
259                         eul_compatf[x] = eul_compat->eul[x] * ((float)Py_PI / 180);
260                 }
261         }
262         
263         /*must be 3-4 cols, 3-4 rows, square matrix*/
264         if(self->colSize ==3 && self->rowSize ==3) {
265                 if(eul_compat)  Mat3ToCompatibleEul((float (*)[3])*self->matrix, eul, eul_compatf);
266                 else                    Mat3ToEul((float (*)[3])*self->matrix, eul);
267         }else if (self->colSize ==4 && self->rowSize ==4) {
268                 float tempmat3[3][3];
269                 Mat3CpyMat4(tempmat3, (float (*)[4])*self->matrix);
270                 Mat3ToEul(tempmat3, eul);
271                 if(eul_compat)  Mat3ToCompatibleEul(tempmat3, eul, eul_compatf);
272                 else                    Mat3ToEul(tempmat3, eul);
273                 
274         }else {
275                 PyErr_SetString(PyExc_AttributeError, "Matrix.toEuler(): inappropriate matrix size - expects 3x3 or 4x4 matrix\n");
276                 return NULL;
277         }
278         /*have to convert to degrees*/
279         for(x = 0; x < 3; x++) {
280                 eul[x] *= (float) (180 / Py_PI);
281         }
282         return newEulerObject(eul, Py_NEW);
283 }
284 /*---------------------------Matrix.resize4x4() ------------------*/
285 PyObject *Matrix_Resize4x4(MatrixObject * self)
286 {
287         int x, first_row_elem, curr_pos, new_pos, blank_columns, blank_rows, index;
288
289         if(self->wrapped==Py_WRAP){
290                 PyErr_SetString(PyExc_TypeError, "cannot resize wrapped data - make a copy and resize that");
291                 return NULL;
292         }
293         if(self->cb_user){
294                 PyErr_SetString(PyExc_TypeError, "cannot resize owned data - make a copy and resize that");
295                 return NULL;
296         }
297         
298         self->contigPtr = PyMem_Realloc(self->contigPtr, (sizeof(float) * 16));
299         if(self->contigPtr == NULL) {
300                 PyErr_SetString(PyExc_MemoryError, "matrix.resize4x4(): problem allocating pointer space");
301                 return NULL;
302         }
303         self->matrix = PyMem_Realloc(self->matrix, (sizeof(float *) * 4));
304         if(self->matrix == NULL) {
305                 PyErr_SetString(PyExc_MemoryError, "matrix.resize4x4(): problem allocating pointer space");
306                 return NULL;
307         }
308         /*set row pointers*/
309         for(x = 0; x < 4; x++) {
310                 self->matrix[x] = self->contigPtr + (x * 4);
311         }
312         /*move data to new spot in array + clean*/
313         for(blank_rows = (4 - self->rowSize); blank_rows > 0; blank_rows--){
314                 for(x = 0; x < 4; x++){
315                         index = (4 * (self->rowSize + (blank_rows - 1))) + x;
316                         if (index == 10 || index == 15){
317                                 self->contigPtr[index] = 1.0f;
318                         }else{
319                                 self->contigPtr[index] = 0.0f;
320                         }
321                 }
322         }
323         for(x = 1; x <= self->rowSize; x++){
324                 first_row_elem = (self->colSize * (self->rowSize - x));
325                 curr_pos = (first_row_elem + (self->colSize -1));
326                 new_pos = (4 * (self->rowSize - x )) + (curr_pos - first_row_elem);
327                 for(blank_columns = (4 - self->colSize); blank_columns > 0; blank_columns--){
328                         self->contigPtr[new_pos + blank_columns] = 0.0f;
329                 }
330                 for(curr_pos = curr_pos; curr_pos >= first_row_elem; curr_pos--){
331                         self->contigPtr[new_pos] = self->contigPtr[curr_pos];
332                         new_pos--;
333                 }
334         }
335         self->rowSize = 4;
336         self->colSize = 4;
337         
338         Py_INCREF(self);
339         return (PyObject *)self;
340 }
341 /*---------------------------Matrix.translationPart() ------------*/
342 PyObject *Matrix_TranslationPart(MatrixObject * self)
343 {
344         float vec[4];
345         
346         if(!Matrix_ReadCallback(self))
347                 return NULL;
348         
349         if(self->colSize < 3 || self->rowSize < 4){
350                 PyErr_SetString(PyExc_AttributeError, "Matrix.translationPart: inappropriate matrix size");
351                 return NULL;
352         }
353
354         vec[0] = self->matrix[3][0];
355         vec[1] = self->matrix[3][1];
356         vec[2] = self->matrix[3][2];
357
358         return newVectorObject(vec, 3, Py_NEW);
359 }
360 /*---------------------------Matrix.rotationPart() ---------------*/
361 PyObject *Matrix_RotationPart(MatrixObject * self)
362 {
363         float mat[16] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
364                 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
365
366         if(!Matrix_ReadCallback(self))
367                 return NULL;
368
369         if(self->colSize < 3 || self->rowSize < 3){
370                 PyErr_SetString(PyExc_AttributeError, "Matrix.rotationPart: inappropriate matrix size\n");
371                 return NULL;
372         }
373
374         mat[0] = self->matrix[0][0];
375         mat[1] = self->matrix[0][1];
376         mat[2] = self->matrix[0][2];
377         mat[3] = self->matrix[1][0];
378         mat[4] = self->matrix[1][1];
379         mat[5] = self->matrix[1][2];
380         mat[6] = self->matrix[2][0];
381         mat[7] = self->matrix[2][1];
382         mat[8] = self->matrix[2][2];
383
384         return newMatrixObject(mat, 3, 3, Py_NEW);
385 }
386 /*---------------------------Matrix.scalePart() --------------------*/
387 PyObject *Matrix_scalePart(MatrixObject * self)
388 {
389         float scale[3], rot[3];
390         float mat[3][3], imat[3][3], tmat[3][3];
391
392         if(!Matrix_ReadCallback(self))
393                 return NULL;
394         
395         /*must be 3-4 cols, 3-4 rows, square matrix*/
396         if(self->colSize == 4 && self->rowSize == 4)
397                 Mat3CpyMat4(mat, (float (*)[4])*self->matrix);
398         else if(self->colSize == 3 && self->rowSize == 3)
399                 Mat3CpyMat3(mat, (float (*)[3])*self->matrix);
400         else {
401                 PyErr_SetString(PyExc_AttributeError, "Matrix.scalePart(): inappropriate matrix size - expects 3x3 or 4x4 matrix\n");
402                 return NULL;
403         }
404         /* functionality copied from editobject.c apply_obmat */
405         Mat3ToEul(mat, rot);
406         EulToMat3(rot, tmat);
407         Mat3Inv(imat, tmat);
408         Mat3MulMat3(tmat, imat, mat);
409         
410         scale[0]= tmat[0][0];
411         scale[1]= tmat[1][1];
412         scale[2]= tmat[2][2];
413         return newVectorObject(scale, 3, Py_NEW);
414 }
415 /*---------------------------Matrix.invert() ---------------------*/
416 PyObject *Matrix_Invert(MatrixObject * self)
417 {
418         
419         int x, y, z = 0;
420         float det = 0.0f;
421         PyObject *f = NULL;
422         float mat[16] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
423                 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
424
425         if(!Matrix_ReadCallback(self))
426                 return NULL;
427
428         if(self->rowSize != self->colSize){
429                 PyErr_SetString(PyExc_AttributeError, "Matrix.invert(ed): only square matrices are supported");
430                 return NULL;
431         }
432
433         /*calculate the determinant*/
434         f = Matrix_Determinant(self);
435         det = (float)PyFloat_AS_DOUBLE(f); /*Increfs, so we need to decref*/
436         Py_DECREF(f);
437
438         if(det != 0) {
439                 /*calculate the classical adjoint*/
440                 if(self->rowSize == 2) {
441                         mat[0] = self->matrix[1][1];
442                         mat[1] = -self->matrix[0][1];
443                         mat[2] = -self->matrix[1][0];
444                         mat[3] = self->matrix[0][0];
445                 } else if(self->rowSize == 3) {
446                         Mat3Adj((float (*)[3]) mat,(float (*)[3]) *self->matrix);
447                 } else if(self->rowSize == 4) {
448                         Mat4Adj((float (*)[4]) mat, (float (*)[4]) *self->matrix);
449                 }
450                 /*divide by determinate*/
451                 for(x = 0; x < (self->rowSize * self->colSize); x++) {
452                         mat[x] /= det;
453                 }
454                 /*set values*/
455                 for(x = 0; x < self->rowSize; x++) {
456                         for(y = 0; y < self->colSize; y++) {
457                                 self->matrix[x][y] = mat[z];
458                                 z++;
459                         }
460                 }
461                 /*transpose
462                 Matrix_Transpose(self);*/
463         } else {
464                 PyErr_SetString(PyExc_ValueError, "matrix does not have an inverse");
465                 return NULL;
466         }
467         
468         Matrix_WriteCallback(self);
469         Py_INCREF(self);
470         return (PyObject *)self;
471 }
472
473
474 /*---------------------------Matrix.determinant() ----------------*/
475 PyObject *Matrix_Determinant(MatrixObject * self)
476 {
477         float det = 0.0f;
478
479         if(!Matrix_ReadCallback(self))
480                 return NULL;
481         
482         if(self->rowSize != self->colSize){
483                 PyErr_SetString(PyExc_AttributeError, "Matrix.determinant: only square matrices are supported");
484                 return NULL;
485         }
486
487         if(self->rowSize == 2) {
488                 det = Det2x2(self->matrix[0][0], self->matrix[0][1],
489                                          self->matrix[1][0], self->matrix[1][1]);
490         } else if(self->rowSize == 3) {
491                 det = Det3x3(self->matrix[0][0], self->matrix[0][1],
492                                          self->matrix[0][2], self->matrix[1][0],
493                                          self->matrix[1][1], self->matrix[1][2],
494                                          self->matrix[2][0], self->matrix[2][1],
495                                          self->matrix[2][2]);
496         } else {
497                 det = Det4x4((float (*)[4]) *self->matrix);
498         }
499
500         return PyFloat_FromDouble( (double) det );
501 }
502 /*---------------------------Matrix.transpose() ------------------*/
503 PyObject *Matrix_Transpose(MatrixObject * self)
504 {
505         float t = 0.0f;
506
507         if(!Matrix_ReadCallback(self))
508                 return NULL;
509         
510         if(self->rowSize != self->colSize){
511                 PyErr_SetString(PyExc_AttributeError, "Matrix.transpose(d): only square matrices are supported");
512                 return NULL;
513         }
514
515         if(self->rowSize == 2) {
516                 t = self->matrix[1][0];
517                 self->matrix[1][0] = self->matrix[0][1];
518                 self->matrix[0][1] = t;
519         } else if(self->rowSize == 3) {
520                 Mat3Transp((float (*)[3])*self->matrix);
521         } else {
522                 Mat4Transp((float (*)[4])*self->matrix);
523         }
524
525         Matrix_WriteCallback(self);
526         Py_INCREF(self);
527         return (PyObject *)self;
528 }
529
530
531 /*---------------------------Matrix.zero() -----------------------*/
532 PyObject *Matrix_Zero(MatrixObject * self)
533 {
534         int row, col;
535         
536         for(row = 0; row < self->rowSize; row++) {
537                 for(col = 0; col < self->colSize; col++) {
538                         self->matrix[row][col] = 0.0f;
539                 }
540         }
541         
542         if(!Matrix_WriteCallback(self))
543                 return NULL;
544         
545         Py_INCREF(self);
546         return (PyObject *)self;
547 }
548 /*---------------------------Matrix.identity(() ------------------*/
549 PyObject *Matrix_Identity(MatrixObject * self)
550 {
551         if(!Matrix_ReadCallback(self))
552                 return NULL;
553         
554         if(self->rowSize != self->colSize){
555                 PyErr_SetString(PyExc_AttributeError, "Matrix.identity: only square matrices are supported\n");
556                 return NULL;
557         }
558
559         if(self->rowSize == 2) {
560                 self->matrix[0][0] = 1.0f;
561                 self->matrix[0][1] = 0.0f;
562                 self->matrix[1][0] = 0.0f;
563                 self->matrix[1][1] = 1.0f;
564         } else if(self->rowSize == 3) {
565                 Mat3One((float (*)[3]) *self->matrix);
566         } else {
567                 Mat4One((float (*)[4]) *self->matrix);
568         }
569
570         if(!Matrix_WriteCallback(self))
571                 return NULL;
572         
573         Py_INCREF(self);
574         return (PyObject *)self;
575 }
576
577 /*---------------------------Matrix.inverted() ------------------*/
578 PyObject *Matrix_copy(MatrixObject * self)
579 {
580         if(!Matrix_ReadCallback(self))
581                 return NULL;
582         
583         return (PyObject*)(MatrixObject*)newMatrixObject((float (*))*self->matrix, self->rowSize, self->colSize, Py_NEW);
584 }
585
586 /*----------------------------dealloc()(internal) ----------------*/
587 /*free the py_object*/
588 static void Matrix_dealloc(MatrixObject * self)
589 {
590         PyMem_Free(self->matrix);
591         /*only free py_data*/
592         if(self->wrapped==Py_WRAP)
593                 PyMem_Free(self->contigPtr);
594         
595         Py_XDECREF(self->cb_user);
596         PyObject_DEL(self);
597 }
598
599 /*----------------------------print object (internal)-------------*/
600 /*print the object to screen*/
601 static PyObject *Matrix_repr(MatrixObject * self)
602 {
603         int x, y;
604         char buffer[48], str[1024];
605
606         if(!Matrix_ReadCallback(self))
607                 return NULL;
608         
609         BLI_strncpy(str,"",1024);
610         for(x = 0; x < self->rowSize; x++){
611                 sprintf(buffer, "[");
612                 strcat(str,buffer);
613                 for(y = 0; y < (self->colSize - 1); y++) {
614                         sprintf(buffer, "%.6f, ", self->matrix[x][y]);
615                         strcat(str,buffer);
616                 }
617                 if(x < (self->rowSize-1)){
618                         sprintf(buffer, "%.6f](matrix [row %d])\n", self->matrix[x][y], x);
619                         strcat(str,buffer);
620                 }else{
621                         sprintf(buffer, "%.6f](matrix [row %d])", self->matrix[x][y], x);
622                         strcat(str,buffer);
623                 }
624         }
625
626         return PyUnicode_FromString(str);
627 }
628 /*------------------------tp_richcmpr*/
629 /*returns -1 execption, 0 false, 1 true*/
630 static PyObject* Matrix_richcmpr(PyObject *objectA, PyObject *objectB, int comparison_type)
631 {
632         MatrixObject *matA = NULL, *matB = NULL;
633         int result = 0;
634
635         if (!MatrixObject_Check(objectA) || !MatrixObject_Check(objectB)){
636                 if (comparison_type == Py_NE){
637                         Py_RETURN_TRUE;
638                 }else{
639                         Py_RETURN_FALSE;
640                 }
641         }
642         matA = (MatrixObject*)objectA;
643         matB = (MatrixObject*)objectB;
644
645         if(!Matrix_ReadCallback(matA) || !Matrix_ReadCallback(matB))
646                 return NULL;
647         
648         if (matA->colSize != matB->colSize || matA->rowSize != matB->rowSize){
649                 if (comparison_type == Py_NE){
650                         Py_RETURN_TRUE;
651                 }else{
652                         Py_RETURN_FALSE;
653                 }
654         }
655
656         switch (comparison_type){
657                 case Py_EQ:
658                         /*contigPtr is basically a really long vector*/
659                         result = EXPP_VectorsAreEqual(matA->contigPtr, matB->contigPtr,
660                                 (matA->rowSize * matA->colSize), 1);
661                         break;
662                 case Py_NE:
663                         result = EXPP_VectorsAreEqual(matA->contigPtr, matB->contigPtr,
664                                 (matA->rowSize * matA->colSize), 1);
665                         if (result == 0){
666                                 result = 1;
667                         }else{
668                                 result = 0;
669                         }
670                         break;
671                 default:
672                         printf("The result of the comparison could not be evaluated");
673                         break;
674         }
675         if (result == 1){
676                 Py_RETURN_TRUE;
677         }else{
678                 Py_RETURN_FALSE;
679         }
680 }
681 /*------------------------tp_doc*/
682 static char MatrixObject_doc[] = "This is a wrapper for matrix objects.";
683 /*---------------------SEQUENCE PROTOCOLS------------------------
684   ----------------------------len(object)------------------------
685   sequence length*/
686 static int Matrix_len(MatrixObject * self)
687 {
688         return (self->rowSize);
689 }
690 /*----------------------------object[]---------------------------
691   sequence accessor (get)
692   the wrapped vector gives direct access to the matrix data*/
693 static PyObject *Matrix_item(MatrixObject * self, int i)
694 {
695         if(!Matrix_ReadCallback(self))
696                 return NULL;
697         
698         if(i < 0 || i >= self->rowSize) {
699                 PyErr_SetString(PyExc_IndexError, "matrix[attribute]: array index out of range");
700                 return NULL;
701         }
702         return newVectorObject_cb((PyObject *)self, self->colSize, mathutils_matrix_vector_cb_index, i);
703 }
704 /*----------------------------object[]-------------------------
705   sequence accessor (set)*/
706 static int Matrix_ass_item(MatrixObject * self, int i, PyObject * ob)
707 {
708         int y, x, size = 0;
709         float vec[4];
710         PyObject *m, *f;
711
712         if(!Matrix_ReadCallback(self))
713                 return -1;
714         
715         if(i >= self->rowSize || i < 0){
716                 PyErr_SetString(PyExc_TypeError, "matrix[attribute] = x: bad row\n");
717                 return -1;
718         }
719
720         if(PySequence_Check(ob)){
721                 size = PySequence_Length(ob);
722                 if(size != self->colSize){
723                         PyErr_SetString(PyExc_TypeError, "matrix[attribute] = x: bad sequence size\n");
724                         return -1;
725                 }
726                 for (x = 0; x < size; x++) {
727                         m = PySequence_GetItem(ob, x);
728                         if (m == NULL) { /*Failed to read sequence*/
729                                 PyErr_SetString(PyExc_RuntimeError, "matrix[attribute] = x: unable to read sequence\n");
730                                 return -1;
731                         }
732
733                         f = PyNumber_Float(m);
734                         if(f == NULL) { /*parsed item not a number*/
735                                 Py_DECREF(m);
736                                 PyErr_SetString(PyExc_TypeError, "matrix[attribute] = x: sequence argument not a number\n");
737                                 return -1;
738                         }
739
740                         vec[x] = (float)PyFloat_AS_DOUBLE(f);
741                         Py_DECREF(m);
742                         Py_DECREF(f);
743                 }
744                 /*parsed well - now set in matrix*/
745                 for(y = 0; y < size; y++){
746                         self->matrix[i][y] = vec[y];
747                 }
748                 
749                 Matrix_WriteCallback(self);
750                 return 0;
751         }else{
752                 PyErr_SetString(PyExc_TypeError, "matrix[attribute] = x: expects a sequence of column size\n");
753                 return -1;
754         }
755 }
756 /*----------------------------object[z:y]------------------------
757   sequence slice (get)*/
758 static PyObject *Matrix_slice(MatrixObject * self, int begin, int end)
759 {
760
761         PyObject *list = NULL;
762         int count;
763         
764         if(!Matrix_ReadCallback(self))
765                 return NULL;
766
767         CLAMP(begin, 0, self->rowSize);
768         CLAMP(end, 0, self->rowSize);
769         begin = MIN2(begin,end);
770
771         list = PyList_New(end - begin);
772         for(count = begin; count < end; count++) {
773                 PyList_SetItem(list, count - begin,
774                                 newVectorObject_cb((PyObject *)self, self->colSize, mathutils_matrix_vector_cb_index, count));
775
776         }
777
778         return list;
779 }
780 /*----------------------------object[z:y]------------------------
781   sequence slice (set)*/
782 static int Matrix_ass_slice(MatrixObject * self, int begin, int end,
783                              PyObject * seq)
784 {
785         int i, x, y, size, sub_size = 0;
786         float mat[16], f;
787         PyObject *subseq;
788         PyObject *m;
789
790         if(!Matrix_ReadCallback(self))
791                 return -1;
792         
793         CLAMP(begin, 0, self->rowSize);
794         CLAMP(end, 0, self->rowSize);
795         begin = MIN2(begin,end);
796
797         if(PySequence_Check(seq)){
798                 size = PySequence_Length(seq);
799                 if(size != (end - begin)){
800                         PyErr_SetString(PyExc_TypeError, "matrix[begin:end] = []: size mismatch in slice assignment\n");
801                         return -1;
802                 }
803                 /*parse sub items*/
804                 for (i = 0; i < size; i++) {
805                         /*parse each sub sequence*/
806                         subseq = PySequence_GetItem(seq, i);
807                         if (subseq == NULL) { /*Failed to read sequence*/
808                                 PyErr_SetString(PyExc_RuntimeError, "matrix[begin:end] = []: unable to read sequence");
809                                 return -1;
810                         }
811
812                         if(PySequence_Check(subseq)){
813                                 /*subsequence is also a sequence*/
814                                 sub_size = PySequence_Length(subseq);
815                                 if(sub_size != self->colSize){
816                                         Py_DECREF(subseq);
817                                         PyErr_SetString(PyExc_TypeError, "matrix[begin:end] = []: size mismatch in slice assignment\n");
818                                         return -1;
819                                 }
820                                 for (y = 0; y < sub_size; y++) {
821                                         m = PySequence_GetItem(subseq, y);
822                                         if (m == NULL) { /*Failed to read sequence*/
823                                                 Py_DECREF(subseq);
824                                                 PyErr_SetString(PyExc_RuntimeError, "matrix[begin:end] = []: unable to read sequence\n");
825                                                 return -1;
826                                         }
827                                         
828                                         f = PyFloat_AsDouble(m); /* faster to assume a float and raise an error after */
829                                         if(f == -1 && PyErr_Occurred()) { /*parsed item not a number*/
830                                                 Py_DECREF(m);
831                                                 Py_DECREF(subseq);
832                                                 PyErr_SetString(PyExc_TypeError, "matrix[begin:end] = []: sequence argument not a number\n");
833                                                 return -1;
834                                         }
835
836                                         mat[(i * self->colSize) + y] = f;
837                                         Py_DECREF(m);
838                                 }
839                         }else{
840                                 Py_DECREF(subseq);
841                                 PyErr_SetString(PyExc_TypeError, "matrix[begin:end] = []: illegal argument type for built-in operation\n");
842                                 return -1;
843                         }
844                         Py_DECREF(subseq);
845                 }
846                 /*parsed well - now set in matrix*/
847                 for(x = 0; x < (size * sub_size); x++){
848                         self->matrix[begin + (int)floor(x / self->colSize)][x % self->colSize] = mat[x];
849                 }
850                 
851                 Matrix_WriteCallback(self);
852                 return 0;
853         }else{
854                 PyErr_SetString(PyExc_TypeError, "matrix[begin:end] = []: illegal argument type for built-in operation\n");
855                 return -1;
856         }
857 }
858 /*------------------------NUMERIC PROTOCOLS----------------------
859   ------------------------obj + obj------------------------------*/
860 static PyObject *Matrix_add(PyObject * m1, PyObject * m2)
861 {
862         int x, y;
863         float mat[16] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
864                 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
865         MatrixObject *mat1 = NULL, *mat2 = NULL;
866
867         mat1 = (MatrixObject*)m1;
868         mat2 = (MatrixObject*)m2;
869
870         if(!MatrixObject_Check(m1) || !MatrixObject_Check(m2)) {
871                 PyErr_SetString(PyExc_AttributeError, "Matrix addition: arguments not valid for this operation....");
872                 return NULL;
873         }
874         
875         if(!Matrix_ReadCallback(mat1) || !Matrix_ReadCallback(mat2))
876                 return NULL;
877         
878         if(mat1->rowSize != mat2->rowSize || mat1->colSize != mat2->colSize){
879                 PyErr_SetString(PyExc_AttributeError, "Matrix addition: matrices must have the same dimensions for this operation");
880                 return NULL;
881         }
882
883         for(x = 0; x < mat1->rowSize; x++) {
884                 for(y = 0; y < mat1->colSize; y++) {
885                         mat[((x * mat1->colSize) + y)] = mat1->matrix[x][y] + mat2->matrix[x][y];
886                 }
887         }
888
889         return newMatrixObject(mat, mat1->rowSize, mat1->colSize, Py_NEW);
890 }
891 /*------------------------obj - obj------------------------------
892   subtraction*/
893 static PyObject *Matrix_sub(PyObject * m1, PyObject * m2)
894 {
895         int x, y;
896         float mat[16] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
897                 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
898         MatrixObject *mat1 = NULL, *mat2 = NULL;
899
900         mat1 = (MatrixObject*)m1;
901         mat2 = (MatrixObject*)m2;
902
903         if(!MatrixObject_Check(m1) || !MatrixObject_Check(m2)) {
904                 PyErr_SetString(PyExc_AttributeError, "Matrix addition: arguments not valid for this operation....");
905                 return NULL;
906         }
907         
908         if(!Matrix_ReadCallback(mat1) || !Matrix_ReadCallback(mat2))
909                 return NULL;
910         
911         if(mat1->rowSize != mat2->rowSize || mat1->colSize != mat2->colSize){
912                 PyErr_SetString(PyExc_AttributeError, "Matrix addition: matrices must have the same dimensions for this operation");
913                 return NULL;
914         }
915
916         for(x = 0; x < mat1->rowSize; x++) {
917                 for(y = 0; y < mat1->colSize; y++) {
918                         mat[((x * mat1->colSize) + y)] = mat1->matrix[x][y] - mat2->matrix[x][y];
919                 }
920         }
921
922         return newMatrixObject(mat, mat1->rowSize, mat1->colSize, Py_NEW);
923 }
924 /*------------------------obj * obj------------------------------
925   mulplication*/
926 static PyObject *Matrix_mul(PyObject * m1, PyObject * m2)
927 {
928         int x, y, z;
929         float scalar;
930         float mat[16] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
931                 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
932         double dot = 0.0f;
933         MatrixObject *mat1 = NULL, *mat2 = NULL;
934
935         if(MatrixObject_Check(m1)) {
936                 mat1 = (MatrixObject*)m1;
937                 if(!Matrix_ReadCallback(mat1))
938                         return NULL;
939         }
940         if(MatrixObject_Check(m2)) {
941                 mat2 = (MatrixObject*)m2;
942                 if(!Matrix_ReadCallback(mat2))
943                         return NULL;
944         }
945
946         if(mat1 && mat2) { /*MATRIX * MATRIX*/
947                 if(mat1->colSize != mat2->rowSize){
948                         PyErr_SetString(PyExc_AttributeError,"Matrix multiplication: matrix A rowsize must equal matrix B colsize");
949                         return NULL;
950                 }
951                 for(x = 0; x < mat1->rowSize; x++) {
952                         for(y = 0; y < mat2->colSize; y++) {
953                                 for(z = 0; z < mat1->colSize; z++) {
954                                         dot += (mat1->matrix[x][z] * mat2->matrix[z][y]);
955                                 }
956                                 mat[((x * mat1->rowSize) + y)] = (float)dot;
957                                 dot = 0.0f;
958                         }
959                 }
960                 
961                 return newMatrixObject(mat, mat1->rowSize, mat2->colSize, Py_NEW);
962         }
963         
964         if(mat1==NULL){
965                 scalar=PyFloat_AsDouble(m1); // may not be a float...
966                 if ((scalar == -1.0 && PyErr_Occurred())==0) { /*FLOAT/INT * MATRIX, this line annoys theeth, lets see if he finds it */
967                         for(x = 0; x < mat2->rowSize; x++) {
968                                 for(y = 0; y < mat2->colSize; y++) {
969                                         mat[((x * mat2->colSize) + y)] = scalar * mat2->matrix[x][y];
970                                 }
971                         }
972                         return newMatrixObject(mat, mat2->rowSize, mat2->colSize, Py_NEW);
973                 }
974                 
975                 PyErr_SetString(PyExc_TypeError, "Matrix multiplication: arguments not acceptable for this operation");
976                 return NULL;
977         }
978         else /* if(mat1) { */ {
979                 
980                 if(VectorObject_Check(m2)) { /* MATRIX*VECTOR */
981                         return column_vector_multiplication(mat1, (VectorObject *)m2); /* vector update done inside the function */
982                 }
983                 else {
984                         scalar= PyFloat_AsDouble(m2);
985                         if ((scalar == -1.0 && PyErr_Occurred())==0) { /* MATRIX*FLOAT/INT */
986                                 for(x = 0; x < mat1->rowSize; x++) {
987                                         for(y = 0; y < mat1->colSize; y++) {
988                                                 mat[((x * mat1->colSize) + y)] = scalar * mat1->matrix[x][y];
989                                         }
990                                 }
991                                 return newMatrixObject(mat, mat1->rowSize, mat1->colSize, Py_NEW);
992                         }
993                 }
994                 PyErr_SetString(PyExc_TypeError, "Matrix multiplication: arguments not acceptable for this operation");
995                 return NULL;
996         }
997
998         PyErr_SetString(PyExc_TypeError, "Matrix multiplication: arguments not acceptable for this operation\n");
999         return NULL;
1000 }
1001 static PyObject* Matrix_inv(MatrixObject *self)
1002 {
1003         if(!Matrix_ReadCallback(self))
1004                 return NULL;
1005         
1006         return Matrix_Invert(self);
1007 }
1008
1009 /*-----------------PROTOCOL DECLARATIONS--------------------------*/
1010 static PySequenceMethods Matrix_SeqMethods = {
1011         (inquiry) Matrix_len,                                   /* sq_length */
1012         (binaryfunc) 0,                                                 /* sq_concat */
1013         (ssizeargfunc) 0,                                                       /* sq_repeat */
1014         (ssizeargfunc) Matrix_item,                             /* sq_item */
1015         (ssizessizeargfunc) Matrix_slice,                       /* sq_slice */
1016         (ssizeobjargproc) Matrix_ass_item,              /* sq_ass_item */
1017         (ssizessizeobjargproc) Matrix_ass_slice,        /* sq_ass_slice */
1018 };
1019 static PyNumberMethods Matrix_NumMethods = {
1020         (binaryfunc) Matrix_add,                                /* __add__ */
1021         (binaryfunc) Matrix_sub,                                /* __sub__ */
1022         (binaryfunc) Matrix_mul,                                /* __mul__ */
1023         (binaryfunc) 0,                                                 /* __div__ */
1024         (binaryfunc) 0,                                                 /* __mod__ */
1025         (binaryfunc) 0,                                                 /* __divmod__ */
1026         (ternaryfunc) 0,                                                /* __pow__ */
1027         (unaryfunc) 0,                                                  /* __neg__ */
1028         (unaryfunc) 0,                                                  /* __pos__ */
1029         (unaryfunc) 0,                                                  /* __abs__ */
1030         (inquiry) 0,                                                    /* __nonzero__ */
1031         (unaryfunc) Matrix_inv,                                 /* __invert__ */
1032         (binaryfunc) 0,                                                 /* __lshift__ */
1033         (binaryfunc) 0,                                                 /* __rshift__ */
1034         (binaryfunc) 0,                                                 /* __and__ */
1035         (binaryfunc) 0,                                                 /* __xor__ */
1036         (binaryfunc) 0,                                                 /* __or__ */
1037         /*(coercion)*/ 0,                                                       /* __coerce__ */
1038         (unaryfunc) 0,                                                  /* __int__ */
1039         (unaryfunc) 0,                                                  /* __long__ */
1040         (unaryfunc) 0,                                                  /* __float__ */
1041         (unaryfunc) 0,                                                  /* __oct__ */
1042         (unaryfunc) 0,                                                  /* __hex__ */
1043 };
1044
1045 static PyObject *Matrix_getRowSize( MatrixObject * self, void *type )
1046 {
1047         return PyLong_FromLong((long) self->rowSize);
1048 }
1049
1050 static PyObject *Matrix_getColSize( MatrixObject * self, void *type )
1051 {
1052         return PyLong_FromLong((long) self->colSize);
1053 }
1054
1055 static PyObject *Matrix_getOwner( MatrixObject * self, void *type )
1056 {
1057         if(self->cb_user==NULL) {
1058                 Py_RETURN_NONE;
1059         }
1060         else {
1061                 Py_INCREF(self->cb_user);
1062                 return self->cb_user;
1063         }
1064 }
1065
1066 static PyObject *Matrix_getWrapped( MatrixObject * self, void *type )
1067 {
1068         if (self->wrapped == Py_WRAP)
1069                 Py_RETURN_TRUE;
1070         else
1071                 Py_RETURN_FALSE;
1072 }
1073
1074 /*****************************************************************************/
1075 /* Python attributes get/set structure:                                      */
1076 /*****************************************************************************/
1077 static PyGetSetDef Matrix_getseters[] = {
1078         {"rowSize", (getter)Matrix_getRowSize, (setter)NULL, "", NULL},
1079         {"colSize", (getter)Matrix_getColSize, (setter)NULL, "", NULL},
1080         {"wrapped", (getter)Matrix_getWrapped, (setter)NULL, "", NULL},
1081         {"__owner__",(getter)Matrix_getOwner, (setter)NULL, "Read only owner for vectors that depend on another object", NULL},
1082         {NULL,NULL,NULL,NULL,NULL}  /* Sentinel */
1083 };
1084
1085 /*------------------PY_OBECT DEFINITION--------------------------*/
1086 PyTypeObject matrix_Type = {
1087 #if (PY_VERSION_HEX >= 0x02060000)
1088         PyVarObject_HEAD_INIT(NULL, 0)
1089 #else
1090         /* python 2.5 and below */
1091         PyObject_HEAD_INIT( NULL )  /* required py macro */
1092         0,                          /* ob_size */
1093 #endif
1094         "matrix",                                               /*tp_name*/
1095         sizeof(MatrixObject),                   /*tp_basicsize*/
1096         0,                                                              /*tp_itemsize*/
1097         (destructor)Matrix_dealloc,             /*tp_dealloc*/
1098         0,                                                              /*tp_print*/
1099         0,                                                              /*tp_getattr*/
1100         0,                                                              /*tp_setattr*/
1101         0,                                                              /*tp_compare*/
1102         (reprfunc) Matrix_repr,                 /*tp_repr*/
1103         &Matrix_NumMethods,                             /*tp_as_number*/
1104         &Matrix_SeqMethods,                             /*tp_as_sequence*/
1105         0,                                                              /*tp_as_mapping*/
1106         0,                                                              /*tp_hash*/
1107         0,                                                              /*tp_call*/
1108         0,                                                              /*tp_str*/
1109         0,                                                              /*tp_getattro*/
1110         0,                                                              /*tp_setattro*/
1111         0,                                                              /*tp_as_buffer*/
1112         Py_TPFLAGS_DEFAULT,                             /*tp_flags*/
1113         MatrixObject_doc,                               /*tp_doc*/
1114         0,                                                              /*tp_traverse*/
1115         0,                                                              /*tp_clear*/
1116         (richcmpfunc)Matrix_richcmpr,   /*tp_richcompare*/
1117         0,                                                              /*tp_weaklistoffset*/
1118         0,                                                              /*tp_iter*/
1119         0,                                                              /*tp_iternext*/
1120         Matrix_methods,                                 /*tp_methods*/
1121         0,                                                              /*tp_members*/
1122         Matrix_getseters,                               /*tp_getset*/
1123         0,                                                              /*tp_base*/
1124         0,                                                              /*tp_dict*/
1125         0,                                                              /*tp_descr_get*/
1126         0,                                                              /*tp_descr_set*/
1127         0,                                                              /*tp_dictoffset*/
1128         0,                                                              /*tp_init*/
1129         0,                                                              /*tp_alloc*/
1130         Matrix_new,                                             /*tp_new*/
1131         0,                                                              /*tp_free*/
1132         0,                                                              /*tp_is_gc*/
1133         0,                                                              /*tp_bases*/
1134         0,                                                              /*tp_mro*/
1135         0,                                                              /*tp_cache*/
1136         0,                                                              /*tp_subclasses*/
1137         0,                                                              /*tp_weaklist*/
1138         0                                                               /*tp_del*/
1139 };
1140
1141 /*------------------------newMatrixObject (internal)-------------
1142 creates a new matrix object
1143 self->matrix     self->contiguous_ptr (reference to data.xxx)
1144        [0]------------->[0]
1145                         [1]
1146                         [2]
1147        [1]------------->[3]
1148                         [4]
1149                         [5]
1150                      ....
1151 self->matrix[1][1] = self->contigPtr[4] */
1152
1153 /*pass Py_WRAP - if vector is a WRAPPER for data allocated by BLENDER
1154  (i.e. it was allocated elsewhere by MEM_mallocN())
1155   pass Py_NEW - if vector is not a WRAPPER and managed by PYTHON
1156  (i.e. it must be created here with PyMEM_malloc())*/
1157 PyObject *newMatrixObject(float *mat, int rowSize, int colSize, int type)
1158 {
1159         MatrixObject *self;
1160         int x, row, col;
1161
1162         /*matrix objects can be any 2-4row x 2-4col matrix*/
1163         if(rowSize < 2 || rowSize > 4 || colSize < 2 || colSize > 4){
1164                 PyErr_SetString(PyExc_RuntimeError, "matrix(): row and column sizes must be between 2 and 4");
1165                 return NULL;
1166         }
1167
1168         self = PyObject_NEW(MatrixObject, &matrix_Type);
1169         self->rowSize = rowSize;
1170         self->colSize = colSize;
1171         
1172         /* init callbacks as NULL */
1173         self->cb_user= NULL;
1174         self->cb_type= self->cb_subtype= 0;
1175
1176         if(type == Py_WRAP){
1177                 self->contigPtr = mat;
1178                 /*create pointer array*/
1179                 self->matrix = PyMem_Malloc(rowSize * sizeof(float *));
1180                 if(self->matrix == NULL) { /*allocation failure*/
1181                         PyErr_SetString( PyExc_MemoryError, "matrix(): problem allocating pointer space");
1182                         return NULL;
1183                 }
1184                 /*pointer array points to contigous memory*/
1185                 for(x = 0; x < rowSize; x++) {
1186                         self->matrix[x] = self->contigPtr + (x * colSize);
1187                 }
1188                 self->wrapped = Py_WRAP;
1189         }else if (type == Py_NEW){
1190                 self->contigPtr = PyMem_Malloc(rowSize * colSize * sizeof(float));
1191                 if(self->contigPtr == NULL) { /*allocation failure*/
1192                         PyErr_SetString( PyExc_MemoryError, "matrix(): problem allocating pointer space\n");
1193                         return NULL;
1194                 }
1195                 /*create pointer array*/
1196                 self->matrix = PyMem_Malloc(rowSize * sizeof(float *));
1197                 if(self->matrix == NULL) { /*allocation failure*/
1198                         PyMem_Free(self->contigPtr);
1199                         PyErr_SetString( PyExc_MemoryError, "matrix(): problem allocating pointer space");
1200                         return NULL;
1201                 }
1202                 /*pointer array points to contigous memory*/
1203                 for(x = 0; x < rowSize; x++) {
1204                         self->matrix[x] = self->contigPtr + (x * colSize);
1205                 }
1206                 /*parse*/
1207                 if(mat) {       /*if a float array passed*/
1208                         for(row = 0; row < rowSize; row++) {
1209                                 for(col = 0; col < colSize; col++) {
1210                                         self->matrix[row][col] = mat[(row * colSize) + col];
1211                                 }
1212                         }
1213                 } else if (rowSize == colSize ) { /*or if no arguments are passed return identity matrix for square matrices */
1214                         Matrix_Identity(self);
1215                         Py_DECREF(self);
1216                 }
1217                 self->wrapped = Py_NEW;
1218         }else{ /*bad type*/
1219                 return NULL;
1220         }
1221         return (PyObject *) self;
1222 }
1223
1224 PyObject *newMatrixObject_cb(PyObject *cb_user, int rowSize, int colSize, int cb_type, int cb_subtype)
1225 {
1226         MatrixObject *self= (MatrixObject *)newMatrixObject(NULL, rowSize, colSize, Py_NEW);
1227         if(self) {
1228                 Py_INCREF(cb_user);
1229                 self->cb_user=                  cb_user;
1230                 self->cb_type=                  (unsigned char)cb_type;
1231                 self->cb_subtype=               (unsigned char)cb_subtype;
1232         }
1233         return (PyObject *) self;
1234 }
1235
1236 //----------------column_vector_multiplication (internal)---------
1237 //COLUMN VECTOR Multiplication (Matrix X Vector)
1238 // [1][2][3]   [a]
1239 // [4][5][6] * [b]
1240 // [7][8][9]   [c]
1241 //vector/matrix multiplication IS NOT COMMUTATIVE!!!!
1242 static PyObject *column_vector_multiplication(MatrixObject * mat, VectorObject* vec)
1243 {
1244         float vecNew[4], vecCopy[4];
1245         double dot = 0.0f;
1246         int x, y, z = 0;
1247
1248         if(!Matrix_ReadCallback(mat) || !Vector_ReadCallback(vec))
1249                 return NULL;
1250         
1251         if(mat->rowSize != vec->size){
1252                 if(mat->rowSize == 4 && vec->size != 3){
1253                         PyErr_SetString(PyExc_AttributeError, "matrix * vector: matrix row size and vector size must be the same");
1254                         return NULL;
1255                 }else{
1256                         vecCopy[3] = 1.0f;
1257                 }
1258         }
1259
1260         for(x = 0; x < vec->size; x++){
1261                 vecCopy[x] = vec->vec[x];
1262                 }
1263
1264         for(x = 0; x < mat->rowSize; x++) {
1265                 for(y = 0; y < mat->colSize; y++) {
1266                         dot += mat->matrix[x][y] * vecCopy[y];
1267                 }
1268                 vecNew[z++] = (float)dot;
1269                 dot = 0.0f;
1270         }
1271         return newVectorObject(vecNew, vec->size, Py_NEW);
1272 }