Made Mathutils use radians rather then degrees. defining USE_MATHUTILS_DEG for testin...
[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 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(!BaseMath_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(!BaseMath_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(!BaseMath_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                 if(!BaseMath_ReadCallback(eul_compat))
259                         return NULL;
260
261 #ifdef USE_MATHUTILS_DEG
262                 for(x = 0; x < 3; x++) {
263                         eul_compatf[x] = eul_compat->eul[x] * ((float)Py_PI / 180);
264                 }
265 #else
266                 VECCOPY(eul_compatf, eul_compat->eul);
267 #endif
268         }
269         
270         /*must be 3-4 cols, 3-4 rows, square matrix*/
271         if(self->colSize ==3 && self->rowSize ==3) {
272                 if(eul_compat)  Mat3ToCompatibleEul((float (*)[3])*self->matrix, eul, eul_compatf);
273                 else                    Mat3ToEul((float (*)[3])*self->matrix, eul);
274         }else if (self->colSize ==4 && self->rowSize ==4) {
275                 float tempmat3[3][3];
276                 Mat3CpyMat4(tempmat3, (float (*)[4])*self->matrix);
277                 Mat3ToEul(tempmat3, eul);
278                 if(eul_compat)  Mat3ToCompatibleEul(tempmat3, eul, eul_compatf);
279                 else                    Mat3ToEul(tempmat3, eul);
280                 
281         }else {
282                 PyErr_SetString(PyExc_AttributeError, "Matrix.toEuler(): inappropriate matrix size - expects 3x3 or 4x4 matrix\n");
283                 return NULL;
284         }
285 #ifdef USE_MATHUTILS_DEG
286         /*have to convert to degrees*/
287         for(x = 0; x < 3; x++) {
288                 eul[x] *= (float) (180 / Py_PI);
289         }
290 #endif
291         return newEulerObject(eul, Py_NEW);
292 }
293 /*---------------------------Matrix.resize4x4() ------------------*/
294 PyObject *Matrix_Resize4x4(MatrixObject * self)
295 {
296         int x, first_row_elem, curr_pos, new_pos, blank_columns, blank_rows, index;
297
298         if(self->wrapped==Py_WRAP){
299                 PyErr_SetString(PyExc_TypeError, "cannot resize wrapped data - make a copy and resize that");
300                 return NULL;
301         }
302         if(self->cb_user){
303                 PyErr_SetString(PyExc_TypeError, "cannot resize owned data - make a copy and resize that");
304                 return NULL;
305         }
306         
307         self->contigPtr = PyMem_Realloc(self->contigPtr, (sizeof(float) * 16));
308         if(self->contigPtr == NULL) {
309                 PyErr_SetString(PyExc_MemoryError, "matrix.resize4x4(): problem allocating pointer space");
310                 return NULL;
311         }
312         self->matrix = PyMem_Realloc(self->matrix, (sizeof(float *) * 4));
313         if(self->matrix == NULL) {
314                 PyErr_SetString(PyExc_MemoryError, "matrix.resize4x4(): problem allocating pointer space");
315                 return NULL;
316         }
317         /*set row pointers*/
318         for(x = 0; x < 4; x++) {
319                 self->matrix[x] = self->contigPtr + (x * 4);
320         }
321         /*move data to new spot in array + clean*/
322         for(blank_rows = (4 - self->rowSize); blank_rows > 0; blank_rows--){
323                 for(x = 0; x < 4; x++){
324                         index = (4 * (self->rowSize + (blank_rows - 1))) + x;
325                         if (index == 10 || index == 15){
326                                 self->contigPtr[index] = 1.0f;
327                         }else{
328                                 self->contigPtr[index] = 0.0f;
329                         }
330                 }
331         }
332         for(x = 1; x <= self->rowSize; x++){
333                 first_row_elem = (self->colSize * (self->rowSize - x));
334                 curr_pos = (first_row_elem + (self->colSize -1));
335                 new_pos = (4 * (self->rowSize - x )) + (curr_pos - first_row_elem);
336                 for(blank_columns = (4 - self->colSize); blank_columns > 0; blank_columns--){
337                         self->contigPtr[new_pos + blank_columns] = 0.0f;
338                 }
339                 for(curr_pos = curr_pos; curr_pos >= first_row_elem; curr_pos--){
340                         self->contigPtr[new_pos] = self->contigPtr[curr_pos];
341                         new_pos--;
342                 }
343         }
344         self->rowSize = 4;
345         self->colSize = 4;
346         
347         Py_INCREF(self);
348         return (PyObject *)self;
349 }
350 /*---------------------------Matrix.translationPart() ------------*/
351 PyObject *Matrix_TranslationPart(MatrixObject * self)
352 {
353         float vec[4];
354         
355         if(!BaseMath_ReadCallback(self))
356                 return NULL;
357         
358         if(self->colSize < 3 || self->rowSize < 4){
359                 PyErr_SetString(PyExc_AttributeError, "Matrix.translationPart: inappropriate matrix size");
360                 return NULL;
361         }
362
363         vec[0] = self->matrix[3][0];
364         vec[1] = self->matrix[3][1];
365         vec[2] = self->matrix[3][2];
366
367         return newVectorObject(vec, 3, Py_NEW);
368 }
369 /*---------------------------Matrix.rotationPart() ---------------*/
370 PyObject *Matrix_RotationPart(MatrixObject * self)
371 {
372         float mat[16] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
373                 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
374
375         if(!BaseMath_ReadCallback(self))
376                 return NULL;
377
378         if(self->colSize < 3 || self->rowSize < 3){
379                 PyErr_SetString(PyExc_AttributeError, "Matrix.rotationPart: inappropriate matrix size\n");
380                 return NULL;
381         }
382
383         mat[0] = self->matrix[0][0];
384         mat[1] = self->matrix[0][1];
385         mat[2] = self->matrix[0][2];
386         mat[3] = self->matrix[1][0];
387         mat[4] = self->matrix[1][1];
388         mat[5] = self->matrix[1][2];
389         mat[6] = self->matrix[2][0];
390         mat[7] = self->matrix[2][1];
391         mat[8] = self->matrix[2][2];
392
393         return newMatrixObject(mat, 3, 3, Py_NEW);
394 }
395 /*---------------------------Matrix.scalePart() --------------------*/
396 PyObject *Matrix_scalePart(MatrixObject * self)
397 {
398         float scale[3], rot[3];
399         float mat[3][3], imat[3][3], tmat[3][3];
400
401         if(!BaseMath_ReadCallback(self))
402                 return NULL;
403         
404         /*must be 3-4 cols, 3-4 rows, square matrix*/
405         if(self->colSize == 4 && self->rowSize == 4)
406                 Mat3CpyMat4(mat, (float (*)[4])*self->matrix);
407         else if(self->colSize == 3 && self->rowSize == 3)
408                 Mat3CpyMat3(mat, (float (*)[3])*self->matrix);
409         else {
410                 PyErr_SetString(PyExc_AttributeError, "Matrix.scalePart(): inappropriate matrix size - expects 3x3 or 4x4 matrix\n");
411                 return NULL;
412         }
413         /* functionality copied from editobject.c apply_obmat */
414         Mat3ToEul(mat, rot);
415         EulToMat3(rot, tmat);
416         Mat3Inv(imat, tmat);
417         Mat3MulMat3(tmat, imat, mat);
418         
419         scale[0]= tmat[0][0];
420         scale[1]= tmat[1][1];
421         scale[2]= tmat[2][2];
422         return newVectorObject(scale, 3, Py_NEW);
423 }
424 /*---------------------------Matrix.invert() ---------------------*/
425 PyObject *Matrix_Invert(MatrixObject * self)
426 {
427         
428         int x, y, z = 0;
429         float det = 0.0f;
430         PyObject *f = NULL;
431         float mat[16] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
432                 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
433
434         if(!BaseMath_ReadCallback(self))
435                 return NULL;
436
437         if(self->rowSize != self->colSize){
438                 PyErr_SetString(PyExc_AttributeError, "Matrix.invert(ed): only square matrices are supported");
439                 return NULL;
440         }
441
442         /*calculate the determinant*/
443         f = Matrix_Determinant(self);
444         det = (float)PyFloat_AS_DOUBLE(f); /*Increfs, so we need to decref*/
445         Py_DECREF(f);
446
447         if(det != 0) {
448                 /*calculate the classical adjoint*/
449                 if(self->rowSize == 2) {
450                         mat[0] = self->matrix[1][1];
451                         mat[1] = -self->matrix[0][1];
452                         mat[2] = -self->matrix[1][0];
453                         mat[3] = self->matrix[0][0];
454                 } else if(self->rowSize == 3) {
455                         Mat3Adj((float (*)[3]) mat,(float (*)[3]) *self->matrix);
456                 } else if(self->rowSize == 4) {
457                         Mat4Adj((float (*)[4]) mat, (float (*)[4]) *self->matrix);
458                 }
459                 /*divide by determinate*/
460                 for(x = 0; x < (self->rowSize * self->colSize); x++) {
461                         mat[x] /= det;
462                 }
463                 /*set values*/
464                 for(x = 0; x < self->rowSize; x++) {
465                         for(y = 0; y < self->colSize; y++) {
466                                 self->matrix[x][y] = mat[z];
467                                 z++;
468                         }
469                 }
470                 /*transpose
471                 Matrix_Transpose(self);*/
472         } else {
473                 PyErr_SetString(PyExc_ValueError, "matrix does not have an inverse");
474                 return NULL;
475         }
476         
477         BaseMath_WriteCallback(self);
478         Py_INCREF(self);
479         return (PyObject *)self;
480 }
481
482
483 /*---------------------------Matrix.determinant() ----------------*/
484 PyObject *Matrix_Determinant(MatrixObject * self)
485 {
486         float det = 0.0f;
487
488         if(!BaseMath_ReadCallback(self))
489                 return NULL;
490         
491         if(self->rowSize != self->colSize){
492                 PyErr_SetString(PyExc_AttributeError, "Matrix.determinant: only square matrices are supported");
493                 return NULL;
494         }
495
496         if(self->rowSize == 2) {
497                 det = Det2x2(self->matrix[0][0], self->matrix[0][1],
498                                          self->matrix[1][0], self->matrix[1][1]);
499         } else if(self->rowSize == 3) {
500                 det = Det3x3(self->matrix[0][0], self->matrix[0][1],
501                                          self->matrix[0][2], self->matrix[1][0],
502                                          self->matrix[1][1], self->matrix[1][2],
503                                          self->matrix[2][0], self->matrix[2][1],
504                                          self->matrix[2][2]);
505         } else {
506                 det = Det4x4((float (*)[4]) *self->matrix);
507         }
508
509         return PyFloat_FromDouble( (double) det );
510 }
511 /*---------------------------Matrix.transpose() ------------------*/
512 PyObject *Matrix_Transpose(MatrixObject * self)
513 {
514         float t = 0.0f;
515
516         if(!BaseMath_ReadCallback(self))
517                 return NULL;
518         
519         if(self->rowSize != self->colSize){
520                 PyErr_SetString(PyExc_AttributeError, "Matrix.transpose(d): only square matrices are supported");
521                 return NULL;
522         }
523
524         if(self->rowSize == 2) {
525                 t = self->matrix[1][0];
526                 self->matrix[1][0] = self->matrix[0][1];
527                 self->matrix[0][1] = t;
528         } else if(self->rowSize == 3) {
529                 Mat3Transp((float (*)[3])*self->matrix);
530         } else {
531                 Mat4Transp((float (*)[4])*self->matrix);
532         }
533
534         BaseMath_WriteCallback(self);
535         Py_INCREF(self);
536         return (PyObject *)self;
537 }
538
539
540 /*---------------------------Matrix.zero() -----------------------*/
541 PyObject *Matrix_Zero(MatrixObject * self)
542 {
543         int row, col;
544         
545         for(row = 0; row < self->rowSize; row++) {
546                 for(col = 0; col < self->colSize; col++) {
547                         self->matrix[row][col] = 0.0f;
548                 }
549         }
550         
551         if(!BaseMath_WriteCallback(self))
552                 return NULL;
553         
554         Py_INCREF(self);
555         return (PyObject *)self;
556 }
557 /*---------------------------Matrix.identity(() ------------------*/
558 PyObject *Matrix_Identity(MatrixObject * self)
559 {
560         if(!BaseMath_ReadCallback(self))
561                 return NULL;
562         
563         if(self->rowSize != self->colSize){
564                 PyErr_SetString(PyExc_AttributeError, "Matrix.identity: only square matrices are supported\n");
565                 return NULL;
566         }
567
568         if(self->rowSize == 2) {
569                 self->matrix[0][0] = 1.0f;
570                 self->matrix[0][1] = 0.0f;
571                 self->matrix[1][0] = 0.0f;
572                 self->matrix[1][1] = 1.0f;
573         } else if(self->rowSize == 3) {
574                 Mat3One((float (*)[3]) *self->matrix);
575         } else {
576                 Mat4One((float (*)[4]) *self->matrix);
577         }
578
579         if(!BaseMath_WriteCallback(self))
580                 return NULL;
581         
582         Py_INCREF(self);
583         return (PyObject *)self;
584 }
585
586 /*---------------------------Matrix.inverted() ------------------*/
587 PyObject *Matrix_copy(MatrixObject * self)
588 {
589         if(!BaseMath_ReadCallback(self))
590                 return NULL;
591         
592         return (PyObject*)(MatrixObject*)newMatrixObject((float (*))*self->matrix, self->rowSize, self->colSize, Py_NEW);
593 }
594
595 /*----------------------------print object (internal)-------------*/
596 /*print the object to screen*/
597 static PyObject *Matrix_repr(MatrixObject * self)
598 {
599         int x, y;
600         char buffer[48], str[1024];
601
602         if(!BaseMath_ReadCallback(self))
603                 return NULL;
604         
605         BLI_strncpy(str,"",1024);
606         for(x = 0; x < self->rowSize; x++){
607                 sprintf(buffer, "[");
608                 strcat(str,buffer);
609                 for(y = 0; y < (self->colSize - 1); y++) {
610                         sprintf(buffer, "%.6f, ", self->matrix[x][y]);
611                         strcat(str,buffer);
612                 }
613                 if(x < (self->rowSize-1)){
614                         sprintf(buffer, "%.6f](matrix [row %d])\n", self->matrix[x][y], x);
615                         strcat(str,buffer);
616                 }else{
617                         sprintf(buffer, "%.6f](matrix [row %d])", self->matrix[x][y], x);
618                         strcat(str,buffer);
619                 }
620         }
621
622         return PyUnicode_FromString(str);
623 }
624 /*------------------------tp_richcmpr*/
625 /*returns -1 execption, 0 false, 1 true*/
626 static PyObject* Matrix_richcmpr(PyObject *objectA, PyObject *objectB, int comparison_type)
627 {
628         MatrixObject *matA = NULL, *matB = NULL;
629         int result = 0;
630
631         if (!MatrixObject_Check(objectA) || !MatrixObject_Check(objectB)){
632                 if (comparison_type == Py_NE){
633                         Py_RETURN_TRUE;
634                 }else{
635                         Py_RETURN_FALSE;
636                 }
637         }
638         matA = (MatrixObject*)objectA;
639         matB = (MatrixObject*)objectB;
640
641         if(!BaseMath_ReadCallback(matA) || !BaseMath_ReadCallback(matB))
642                 return NULL;
643         
644         if (matA->colSize != matB->colSize || matA->rowSize != matB->rowSize){
645                 if (comparison_type == Py_NE){
646                         Py_RETURN_TRUE;
647                 }else{
648                         Py_RETURN_FALSE;
649                 }
650         }
651
652         switch (comparison_type){
653                 case Py_EQ:
654                         /*contigPtr is basically a really long vector*/
655                         result = EXPP_VectorsAreEqual(matA->contigPtr, matB->contigPtr,
656                                 (matA->rowSize * matA->colSize), 1);
657                         break;
658                 case Py_NE:
659                         result = EXPP_VectorsAreEqual(matA->contigPtr, matB->contigPtr,
660                                 (matA->rowSize * matA->colSize), 1);
661                         if (result == 0){
662                                 result = 1;
663                         }else{
664                                 result = 0;
665                         }
666                         break;
667                 default:
668                         printf("The result of the comparison could not be evaluated");
669                         break;
670         }
671         if (result == 1){
672                 Py_RETURN_TRUE;
673         }else{
674                 Py_RETURN_FALSE;
675         }
676 }
677 /*------------------------tp_doc*/
678 static char MatrixObject_doc[] = "This is a wrapper for matrix objects.";
679 /*---------------------SEQUENCE PROTOCOLS------------------------
680   ----------------------------len(object)------------------------
681   sequence length*/
682 static int Matrix_len(MatrixObject * self)
683 {
684         return (self->rowSize);
685 }
686 /*----------------------------object[]---------------------------
687   sequence accessor (get)
688   the wrapped vector gives direct access to the matrix data*/
689 static PyObject *Matrix_item(MatrixObject * self, int i)
690 {
691         if(!BaseMath_ReadCallback(self))
692                 return NULL;
693         
694         if(i < 0 || i >= self->rowSize) {
695                 PyErr_SetString(PyExc_IndexError, "matrix[attribute]: array index out of range");
696                 return NULL;
697         }
698         return newVectorObject_cb((PyObject *)self, self->colSize, mathutils_matrix_vector_cb_index, i);
699 }
700 /*----------------------------object[]-------------------------
701   sequence accessor (set)*/
702 static int Matrix_ass_item(MatrixObject * self, int i, PyObject * ob)
703 {
704         int y, x, size = 0;
705         float vec[4];
706         PyObject *m, *f;
707
708         if(!BaseMath_ReadCallback(self))
709                 return -1;
710         
711         if(i >= self->rowSize || i < 0){
712                 PyErr_SetString(PyExc_TypeError, "matrix[attribute] = x: bad row\n");
713                 return -1;
714         }
715
716         if(PySequence_Check(ob)){
717                 size = PySequence_Length(ob);
718                 if(size != self->colSize){
719                         PyErr_SetString(PyExc_TypeError, "matrix[attribute] = x: bad sequence size\n");
720                         return -1;
721                 }
722                 for (x = 0; x < size; x++) {
723                         m = PySequence_GetItem(ob, x);
724                         if (m == NULL) { /*Failed to read sequence*/
725                                 PyErr_SetString(PyExc_RuntimeError, "matrix[attribute] = x: unable to read sequence\n");
726                                 return -1;
727                         }
728
729                         f = PyNumber_Float(m);
730                         if(f == NULL) { /*parsed item not a number*/
731                                 Py_DECREF(m);
732                                 PyErr_SetString(PyExc_TypeError, "matrix[attribute] = x: sequence argument not a number\n");
733                                 return -1;
734                         }
735
736                         vec[x] = (float)PyFloat_AS_DOUBLE(f);
737                         Py_DECREF(m);
738                         Py_DECREF(f);
739                 }
740                 /*parsed well - now set in matrix*/
741                 for(y = 0; y < size; y++){
742                         self->matrix[i][y] = vec[y];
743                 }
744                 
745                 BaseMath_WriteCallback(self);
746                 return 0;
747         }else{
748                 PyErr_SetString(PyExc_TypeError, "matrix[attribute] = x: expects a sequence of column size\n");
749                 return -1;
750         }
751 }
752 /*----------------------------object[z:y]------------------------
753   sequence slice (get)*/
754 static PyObject *Matrix_slice(MatrixObject * self, int begin, int end)
755 {
756
757         PyObject *list = NULL;
758         int count;
759         
760         if(!BaseMath_ReadCallback(self))
761                 return NULL;
762
763         CLAMP(begin, 0, self->rowSize);
764         CLAMP(end, 0, self->rowSize);
765         begin = MIN2(begin,end);
766
767         list = PyList_New(end - begin);
768         for(count = begin; count < end; count++) {
769                 PyList_SetItem(list, count - begin,
770                                 newVectorObject_cb((PyObject *)self, self->colSize, mathutils_matrix_vector_cb_index, count));
771
772         }
773
774         return list;
775 }
776 /*----------------------------object[z:y]------------------------
777   sequence slice (set)*/
778 static int Matrix_ass_slice(MatrixObject * self, int begin, int end,
779                              PyObject * seq)
780 {
781         int i, x, y, size, sub_size = 0;
782         float mat[16], f;
783         PyObject *subseq;
784         PyObject *m;
785
786         if(!BaseMath_ReadCallback(self))
787                 return -1;
788         
789         CLAMP(begin, 0, self->rowSize);
790         CLAMP(end, 0, self->rowSize);
791         begin = MIN2(begin,end);
792
793         if(PySequence_Check(seq)){
794                 size = PySequence_Length(seq);
795                 if(size != (end - begin)){
796                         PyErr_SetString(PyExc_TypeError, "matrix[begin:end] = []: size mismatch in slice assignment\n");
797                         return -1;
798                 }
799                 /*parse sub items*/
800                 for (i = 0; i < size; i++) {
801                         /*parse each sub sequence*/
802                         subseq = PySequence_GetItem(seq, i);
803                         if (subseq == NULL) { /*Failed to read sequence*/
804                                 PyErr_SetString(PyExc_RuntimeError, "matrix[begin:end] = []: unable to read sequence");
805                                 return -1;
806                         }
807
808                         if(PySequence_Check(subseq)){
809                                 /*subsequence is also a sequence*/
810                                 sub_size = PySequence_Length(subseq);
811                                 if(sub_size != self->colSize){
812                                         Py_DECREF(subseq);
813                                         PyErr_SetString(PyExc_TypeError, "matrix[begin:end] = []: size mismatch in slice assignment\n");
814                                         return -1;
815                                 }
816                                 for (y = 0; y < sub_size; y++) {
817                                         m = PySequence_GetItem(subseq, y);
818                                         if (m == NULL) { /*Failed to read sequence*/
819                                                 Py_DECREF(subseq);
820                                                 PyErr_SetString(PyExc_RuntimeError, "matrix[begin:end] = []: unable to read sequence\n");
821                                                 return -1;
822                                         }
823                                         
824                                         f = PyFloat_AsDouble(m); /* faster to assume a float and raise an error after */
825                                         if(f == -1 && PyErr_Occurred()) { /*parsed item not a number*/
826                                                 Py_DECREF(m);
827                                                 Py_DECREF(subseq);
828                                                 PyErr_SetString(PyExc_TypeError, "matrix[begin:end] = []: sequence argument not a number\n");
829                                                 return -1;
830                                         }
831
832                                         mat[(i * self->colSize) + y] = f;
833                                         Py_DECREF(m);
834                                 }
835                         }else{
836                                 Py_DECREF(subseq);
837                                 PyErr_SetString(PyExc_TypeError, "matrix[begin:end] = []: illegal argument type for built-in operation\n");
838                                 return -1;
839                         }
840                         Py_DECREF(subseq);
841                 }
842                 /*parsed well - now set in matrix*/
843                 for(x = 0; x < (size * sub_size); x++){
844                         self->matrix[begin + (int)floor(x / self->colSize)][x % self->colSize] = mat[x];
845                 }
846                 
847                 BaseMath_WriteCallback(self);
848                 return 0;
849         }else{
850                 PyErr_SetString(PyExc_TypeError, "matrix[begin:end] = []: illegal argument type for built-in operation\n");
851                 return -1;
852         }
853 }
854 /*------------------------NUMERIC PROTOCOLS----------------------
855   ------------------------obj + obj------------------------------*/
856 static PyObject *Matrix_add(PyObject * m1, PyObject * m2)
857 {
858         int x, y;
859         float mat[16] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
860                 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
861         MatrixObject *mat1 = NULL, *mat2 = NULL;
862
863         mat1 = (MatrixObject*)m1;
864         mat2 = (MatrixObject*)m2;
865
866         if(!MatrixObject_Check(m1) || !MatrixObject_Check(m2)) {
867                 PyErr_SetString(PyExc_AttributeError, "Matrix addition: arguments not valid for this operation....");
868                 return NULL;
869         }
870         
871         if(!BaseMath_ReadCallback(mat1) || !BaseMath_ReadCallback(mat2))
872                 return NULL;
873         
874         if(mat1->rowSize != mat2->rowSize || mat1->colSize != mat2->colSize){
875                 PyErr_SetString(PyExc_AttributeError, "Matrix addition: matrices must have the same dimensions for this operation");
876                 return NULL;
877         }
878
879         for(x = 0; x < mat1->rowSize; x++) {
880                 for(y = 0; y < mat1->colSize; y++) {
881                         mat[((x * mat1->colSize) + y)] = mat1->matrix[x][y] + mat2->matrix[x][y];
882                 }
883         }
884
885         return newMatrixObject(mat, mat1->rowSize, mat1->colSize, Py_NEW);
886 }
887 /*------------------------obj - obj------------------------------
888   subtraction*/
889 static PyObject *Matrix_sub(PyObject * m1, PyObject * m2)
890 {
891         int x, y;
892         float mat[16] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
893                 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
894         MatrixObject *mat1 = NULL, *mat2 = NULL;
895
896         mat1 = (MatrixObject*)m1;
897         mat2 = (MatrixObject*)m2;
898
899         if(!MatrixObject_Check(m1) || !MatrixObject_Check(m2)) {
900                 PyErr_SetString(PyExc_AttributeError, "Matrix addition: arguments not valid for this operation....");
901                 return NULL;
902         }
903         
904         if(!BaseMath_ReadCallback(mat1) || !BaseMath_ReadCallback(mat2))
905                 return NULL;
906         
907         if(mat1->rowSize != mat2->rowSize || mat1->colSize != mat2->colSize){
908                 PyErr_SetString(PyExc_AttributeError, "Matrix addition: matrices must have the same dimensions for this operation");
909                 return NULL;
910         }
911
912         for(x = 0; x < mat1->rowSize; x++) {
913                 for(y = 0; y < mat1->colSize; y++) {
914                         mat[((x * mat1->colSize) + y)] = mat1->matrix[x][y] - mat2->matrix[x][y];
915                 }
916         }
917
918         return newMatrixObject(mat, mat1->rowSize, mat1->colSize, Py_NEW);
919 }
920 /*------------------------obj * obj------------------------------
921   mulplication*/
922 static PyObject *Matrix_mul(PyObject * m1, PyObject * m2)
923 {
924         int x, y, z;
925         float scalar;
926         float mat[16] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
927                 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
928         double dot = 0.0f;
929         MatrixObject *mat1 = NULL, *mat2 = NULL;
930
931         if(MatrixObject_Check(m1)) {
932                 mat1 = (MatrixObject*)m1;
933                 if(!BaseMath_ReadCallback(mat1))
934                         return NULL;
935         }
936         if(MatrixObject_Check(m2)) {
937                 mat2 = (MatrixObject*)m2;
938                 if(!BaseMath_ReadCallback(mat2))
939                         return NULL;
940         }
941
942         if(mat1 && mat2) { /*MATRIX * MATRIX*/
943                 if(mat1->colSize != mat2->rowSize){
944                         PyErr_SetString(PyExc_AttributeError,"Matrix multiplication: matrix A rowsize must equal matrix B colsize");
945                         return NULL;
946                 }
947                 for(x = 0; x < mat1->rowSize; x++) {
948                         for(y = 0; y < mat2->colSize; y++) {
949                                 for(z = 0; z < mat1->colSize; z++) {
950                                         dot += (mat1->matrix[x][z] * mat2->matrix[z][y]);
951                                 }
952                                 mat[((x * mat1->rowSize) + y)] = (float)dot;
953                                 dot = 0.0f;
954                         }
955                 }
956                 
957                 return newMatrixObject(mat, mat1->rowSize, mat2->colSize, Py_NEW);
958         }
959         
960         if(mat1==NULL){
961                 scalar=PyFloat_AsDouble(m1); // may not be a float...
962                 if ((scalar == -1.0 && PyErr_Occurred())==0) { /*FLOAT/INT * MATRIX, this line annoys theeth, lets see if he finds it */
963                         for(x = 0; x < mat2->rowSize; x++) {
964                                 for(y = 0; y < mat2->colSize; y++) {
965                                         mat[((x * mat2->colSize) + y)] = scalar * mat2->matrix[x][y];
966                                 }
967                         }
968                         return newMatrixObject(mat, mat2->rowSize, mat2->colSize, Py_NEW);
969                 }
970                 
971                 PyErr_SetString(PyExc_TypeError, "Matrix multiplication: arguments not acceptable for this operation");
972                 return NULL;
973         }
974         else /* if(mat1) { */ {
975                 
976                 if(VectorObject_Check(m2)) { /* MATRIX*VECTOR */
977                         return column_vector_multiplication(mat1, (VectorObject *)m2); /* vector update done inside the function */
978                 }
979                 else {
980                         scalar= PyFloat_AsDouble(m2);
981                         if ((scalar == -1.0 && PyErr_Occurred())==0) { /* MATRIX*FLOAT/INT */
982                                 for(x = 0; x < mat1->rowSize; x++) {
983                                         for(y = 0; y < mat1->colSize; y++) {
984                                                 mat[((x * mat1->colSize) + y)] = scalar * mat1->matrix[x][y];
985                                         }
986                                 }
987                                 return newMatrixObject(mat, mat1->rowSize, mat1->colSize, Py_NEW);
988                         }
989                 }
990                 PyErr_SetString(PyExc_TypeError, "Matrix multiplication: arguments not acceptable for this operation");
991                 return NULL;
992         }
993
994         PyErr_SetString(PyExc_TypeError, "Matrix multiplication: arguments not acceptable for this operation\n");
995         return NULL;
996 }
997 static PyObject* Matrix_inv(MatrixObject *self)
998 {
999         if(!BaseMath_ReadCallback(self))
1000                 return NULL;
1001         
1002         return Matrix_Invert(self);
1003 }
1004
1005 /*-----------------PROTOCOL DECLARATIONS--------------------------*/
1006 static PySequenceMethods Matrix_SeqMethods = {
1007         (inquiry) Matrix_len,                                   /* sq_length */
1008         (binaryfunc) 0,                                                 /* sq_concat */
1009         (ssizeargfunc) 0,                                                       /* sq_repeat */
1010         (ssizeargfunc) Matrix_item,                             /* sq_item */
1011         (ssizessizeargfunc) Matrix_slice,                       /* sq_slice */
1012         (ssizeobjargproc) Matrix_ass_item,              /* sq_ass_item */
1013         (ssizessizeobjargproc) Matrix_ass_slice,        /* sq_ass_slice */
1014 };
1015 static PyNumberMethods Matrix_NumMethods = {
1016         (binaryfunc) Matrix_add,                                /* __add__ */
1017         (binaryfunc) Matrix_sub,                                /* __sub__ */
1018         (binaryfunc) Matrix_mul,                                /* __mul__ */
1019         (binaryfunc) 0,                                                 /* __div__ */
1020         (binaryfunc) 0,                                                 /* __mod__ */
1021         (binaryfunc) 0,                                                 /* __divmod__ */
1022         (ternaryfunc) 0,                                                /* __pow__ */
1023         (unaryfunc) 0,                                                  /* __neg__ */
1024         (unaryfunc) 0,                                                  /* __pos__ */
1025         (unaryfunc) 0,                                                  /* __abs__ */
1026         (inquiry) 0,                                                    /* __nonzero__ */
1027         (unaryfunc) Matrix_inv,                                 /* __invert__ */
1028         (binaryfunc) 0,                                                 /* __lshift__ */
1029         (binaryfunc) 0,                                                 /* __rshift__ */
1030         (binaryfunc) 0,                                                 /* __and__ */
1031         (binaryfunc) 0,                                                 /* __xor__ */
1032         (binaryfunc) 0,                                                 /* __or__ */
1033         /*(coercion)*/ 0,                                                       /* __coerce__ */
1034         (unaryfunc) 0,                                                  /* __int__ */
1035         (unaryfunc) 0,                                                  /* __long__ */
1036         (unaryfunc) 0,                                                  /* __float__ */
1037         (unaryfunc) 0,                                                  /* __oct__ */
1038         (unaryfunc) 0,                                                  /* __hex__ */
1039 };
1040
1041 static PyObject *Matrix_getRowSize( MatrixObject * self, void *type )
1042 {
1043         return PyLong_FromLong((long) self->rowSize);
1044 }
1045
1046 static PyObject *Matrix_getColSize( MatrixObject * self, void *type )
1047 {
1048         return PyLong_FromLong((long) self->colSize);
1049 }
1050
1051 /*****************************************************************************/
1052 /* Python attributes get/set structure:                                      */
1053 /*****************************************************************************/
1054 static PyGetSetDef Matrix_getseters[] = {
1055         {"rowSize", (getter)Matrix_getRowSize, (setter)NULL, "", NULL},
1056         {"colSize", (getter)Matrix_getColSize, (setter)NULL, "", NULL},
1057         {"wrapped", (getter)BaseMathObject_getWrapped, (setter)NULL, "", NULL},
1058         {"__owner__",(getter)BaseMathObject_getOwner, (setter)NULL, "",
1059          NULL},
1060         {NULL,NULL,NULL,NULL,NULL}  /* Sentinel */
1061 };
1062
1063 /*------------------PY_OBECT DEFINITION--------------------------*/
1064 PyTypeObject matrix_Type = {
1065 #if (PY_VERSION_HEX >= 0x02060000)
1066         PyVarObject_HEAD_INIT(NULL, 0)
1067 #else
1068         /* python 2.5 and below */
1069         PyObject_HEAD_INIT( NULL )  /* required py macro */
1070         0,                          /* ob_size */
1071 #endif
1072         "matrix",                                               /*tp_name*/
1073         sizeof(MatrixObject),                   /*tp_basicsize*/
1074         0,                                                              /*tp_itemsize*/
1075         (destructor)BaseMathObject_dealloc,             /*tp_dealloc*/
1076         0,                                                              /*tp_print*/
1077         0,                                                              /*tp_getattr*/
1078         0,                                                              /*tp_setattr*/
1079         0,                                                              /*tp_compare*/
1080         (reprfunc) Matrix_repr,                 /*tp_repr*/
1081         &Matrix_NumMethods,                             /*tp_as_number*/
1082         &Matrix_SeqMethods,                             /*tp_as_sequence*/
1083         0,                                                              /*tp_as_mapping*/
1084         0,                                                              /*tp_hash*/
1085         0,                                                              /*tp_call*/
1086         0,                                                              /*tp_str*/
1087         0,                                                              /*tp_getattro*/
1088         0,                                                              /*tp_setattro*/
1089         0,                                                              /*tp_as_buffer*/
1090         Py_TPFLAGS_DEFAULT,                             /*tp_flags*/
1091         MatrixObject_doc,                               /*tp_doc*/
1092         0,                                                              /*tp_traverse*/
1093         0,                                                              /*tp_clear*/
1094         (richcmpfunc)Matrix_richcmpr,   /*tp_richcompare*/
1095         0,                                                              /*tp_weaklistoffset*/
1096         0,                                                              /*tp_iter*/
1097         0,                                                              /*tp_iternext*/
1098         Matrix_methods,                                 /*tp_methods*/
1099         0,                                                              /*tp_members*/
1100         Matrix_getseters,                               /*tp_getset*/
1101         0,                                                              /*tp_base*/
1102         0,                                                              /*tp_dict*/
1103         0,                                                              /*tp_descr_get*/
1104         0,                                                              /*tp_descr_set*/
1105         0,                                                              /*tp_dictoffset*/
1106         0,                                                              /*tp_init*/
1107         0,                                                              /*tp_alloc*/
1108         Matrix_new,                                             /*tp_new*/
1109         0,                                                              /*tp_free*/
1110         0,                                                              /*tp_is_gc*/
1111         0,                                                              /*tp_bases*/
1112         0,                                                              /*tp_mro*/
1113         0,                                                              /*tp_cache*/
1114         0,                                                              /*tp_subclasses*/
1115         0,                                                              /*tp_weaklist*/
1116         0                                                               /*tp_del*/
1117 };
1118
1119 /*------------------------newMatrixObject (internal)-------------
1120 creates a new matrix object
1121 self->matrix     self->contiguous_ptr (reference to data.xxx)
1122        [0]------------->[0]
1123                         [1]
1124                         [2]
1125        [1]------------->[3]
1126                         [4]
1127                         [5]
1128                      ....
1129 self->matrix[1][1] = self->contigPtr[4] */
1130
1131 /*pass Py_WRAP - if vector is a WRAPPER for data allocated by BLENDER
1132  (i.e. it was allocated elsewhere by MEM_mallocN())
1133   pass Py_NEW - if vector is not a WRAPPER and managed by PYTHON
1134  (i.e. it must be created here with PyMEM_malloc())*/
1135 PyObject *newMatrixObject(float *mat, int rowSize, int colSize, int type)
1136 {
1137         MatrixObject *self;
1138         int x, row, col;
1139
1140         /*matrix objects can be any 2-4row x 2-4col matrix*/
1141         if(rowSize < 2 || rowSize > 4 || colSize < 2 || colSize > 4){
1142                 PyErr_SetString(PyExc_RuntimeError, "matrix(): row and column sizes must be between 2 and 4");
1143                 return NULL;
1144         }
1145
1146         self = PyObject_NEW(MatrixObject, &matrix_Type);
1147         self->rowSize = rowSize;
1148         self->colSize = colSize;
1149         
1150         /* init callbacks as NULL */
1151         self->cb_user= NULL;
1152         self->cb_type= self->cb_subtype= 0;
1153
1154         if(type == Py_WRAP){
1155                 self->contigPtr = mat;
1156                 /*create pointer array*/
1157                 self->matrix = PyMem_Malloc(rowSize * sizeof(float *));
1158                 if(self->matrix == NULL) { /*allocation failure*/
1159                         PyErr_SetString( PyExc_MemoryError, "matrix(): problem allocating pointer space");
1160                         return NULL;
1161                 }
1162                 /*pointer array points to contigous memory*/
1163                 for(x = 0; x < rowSize; x++) {
1164                         self->matrix[x] = self->contigPtr + (x * colSize);
1165                 }
1166                 self->wrapped = Py_WRAP;
1167         }else if (type == Py_NEW){
1168                 self->contigPtr = PyMem_Malloc(rowSize * colSize * sizeof(float));
1169                 if(self->contigPtr == NULL) { /*allocation failure*/
1170                         PyErr_SetString( PyExc_MemoryError, "matrix(): problem allocating pointer space\n");
1171                         return NULL;
1172                 }
1173                 /*create pointer array*/
1174                 self->matrix = PyMem_Malloc(rowSize * sizeof(float *));
1175                 if(self->matrix == NULL) { /*allocation failure*/
1176                         PyMem_Free(self->contigPtr);
1177                         PyErr_SetString( PyExc_MemoryError, "matrix(): problem allocating pointer space");
1178                         return NULL;
1179                 }
1180                 /*pointer array points to contigous memory*/
1181                 for(x = 0; x < rowSize; x++) {
1182                         self->matrix[x] = self->contigPtr + (x * colSize);
1183                 }
1184                 /*parse*/
1185                 if(mat) {       /*if a float array passed*/
1186                         for(row = 0; row < rowSize; row++) {
1187                                 for(col = 0; col < colSize; col++) {
1188                                         self->matrix[row][col] = mat[(row * colSize) + col];
1189                                 }
1190                         }
1191                 } else if (rowSize == colSize ) { /*or if no arguments are passed return identity matrix for square matrices */
1192                         Matrix_Identity(self);
1193                         Py_DECREF(self);
1194                 }
1195                 self->wrapped = Py_NEW;
1196         }else{ /*bad type*/
1197                 return NULL;
1198         }
1199         return (PyObject *) self;
1200 }
1201
1202 PyObject *newMatrixObject_cb(PyObject *cb_user, int rowSize, int colSize, int cb_type, int cb_subtype)
1203 {
1204         MatrixObject *self= (MatrixObject *)newMatrixObject(NULL, rowSize, colSize, Py_NEW);
1205         if(self) {
1206                 Py_INCREF(cb_user);
1207                 self->cb_user=                  cb_user;
1208                 self->cb_type=                  (unsigned char)cb_type;
1209                 self->cb_subtype=               (unsigned char)cb_subtype;
1210         }
1211         return (PyObject *) self;
1212 }
1213
1214 //----------------column_vector_multiplication (internal)---------
1215 //COLUMN VECTOR Multiplication (Matrix X Vector)
1216 // [1][2][3]   [a]
1217 // [4][5][6] * [b]
1218 // [7][8][9]   [c]
1219 //vector/matrix multiplication IS NOT COMMUTATIVE!!!!
1220 static PyObject *column_vector_multiplication(MatrixObject * mat, VectorObject* vec)
1221 {
1222         float vecNew[4], vecCopy[4];
1223         double dot = 0.0f;
1224         int x, y, z = 0;
1225
1226         if(!BaseMath_ReadCallback(mat) || !BaseMath_ReadCallback(vec))
1227                 return NULL;
1228         
1229         if(mat->rowSize != vec->size){
1230                 if(mat->rowSize == 4 && vec->size != 3){
1231                         PyErr_SetString(PyExc_AttributeError, "matrix * vector: matrix row size and vector size must be the same");
1232                         return NULL;
1233                 }else{
1234                         vecCopy[3] = 1.0f;
1235                 }
1236         }
1237
1238         for(x = 0; x < vec->size; x++){
1239                 vecCopy[x] = vec->vec[x];
1240                 }
1241
1242         for(x = 0; x < mat->rowSize; x++) {
1243                 for(y = 0; y < mat->colSize; y++) {
1244                         dot += mat->matrix[x][y] * vecCopy[y];
1245                 }
1246                 vecNew[z++] = (float)dot;
1247                 dot = 0.0f;
1248         }
1249         return newVectorObject(vecNew, vec->size, Py_NEW);
1250 }