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