- cmake was missing an inclide (IDE's wouldnt index)
[blender.git] / source / blender / python / generic / mathutils_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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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 "BLI_math.h"
31 #include "BLI_blenlib.h"
32 #include "BLI_utildefines.h"
33
34 #define MATRIX_APPLY_TO_COPY(matrix_meth_noargs, _self) \
35         MatrixObject *ret= (MatrixObject *)Matrix_copy(_self); \
36         PyObject *ret_dummy= matrix_meth_noargs(ret); \
37         if(ret_dummy) { \
38                 Py_DECREF(ret_dummy); \
39                 return (PyObject *)ret; \
40         } \
41         else { /* error */ \
42                 Py_DECREF(ret); \
43                 return NULL; \
44         } \
45
46
47 static PyObject *Matrix_copy(MatrixObject *self);
48
49 static int Matrix_ass_slice(MatrixObject *self, int begin, int end, PyObject *value);
50
51 /* matrix vector callbacks */
52 int mathutils_matrix_vector_cb_index= -1;
53
54 static int mathutils_matrix_vector_check(BaseMathObject *bmo)
55 {
56         MatrixObject *self= (MatrixObject *)bmo->cb_user;
57         return BaseMath_ReadCallback(self);
58 }
59
60 static int mathutils_matrix_vector_get(BaseMathObject *bmo, int subtype)
61 {
62         MatrixObject *self= (MatrixObject *)bmo->cb_user;
63         int i;
64
65         if(!BaseMath_ReadCallback(self))
66                 return 0;
67
68         for(i=0; i < self->colSize; i++)
69                 bmo->data[i]= self->matrix[subtype][i];
70
71         return 1;
72 }
73
74 static int mathutils_matrix_vector_set(BaseMathObject *bmo, int subtype)
75 {
76         MatrixObject *self= (MatrixObject *)bmo->cb_user;
77         int i;
78
79         if(!BaseMath_ReadCallback(self))
80                 return 0;
81
82         for(i=0; i < self->colSize; i++)
83                 self->matrix[subtype][i]= bmo->data[i];
84
85         (void)BaseMath_WriteCallback(self);
86         return 1;
87 }
88
89 static int mathutils_matrix_vector_get_index(BaseMathObject *bmo, int subtype, int index)
90 {
91         MatrixObject *self= (MatrixObject *)bmo->cb_user;
92
93         if(!BaseMath_ReadCallback(self))
94                 return 0;
95
96         bmo->data[index]= self->matrix[subtype][index];
97         return 1;
98 }
99
100 static int mathutils_matrix_vector_set_index(BaseMathObject *bmo, int subtype, int index)
101 {
102         MatrixObject *self= (MatrixObject *)bmo->cb_user;
103
104         if(!BaseMath_ReadCallback(self))
105                 return 0;
106
107         self->matrix[subtype][index]= bmo->data[index];
108
109         (void)BaseMath_WriteCallback(self);
110         return 1;
111 }
112
113 Mathutils_Callback mathutils_matrix_vector_cb = {
114         mathutils_matrix_vector_check,
115         mathutils_matrix_vector_get,
116         mathutils_matrix_vector_set,
117         mathutils_matrix_vector_get_index,
118         mathutils_matrix_vector_set_index
119 };
120 /* matrix vector callbacks, this is so you can do matrix[i][j] = val  */
121
122 //----------------------------------mathutils.Matrix() -----------------
123 //mat is a 1D array of floats - row[0][0],row[0][1], row[1][0], etc.
124 //create a new matrix type
125 static PyObject *Matrix_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
126 {
127         if(kwds && PyDict_Size(kwds)) {
128                 PyErr_SetString(PyExc_TypeError, "mathutils.Matrix(): takes no keyword args");
129                 return NULL;
130         }
131
132         switch(PyTuple_GET_SIZE(args)) {
133                 case 0:
134                         return (PyObject *) newMatrixObject(NULL, 4, 4, Py_NEW, type);
135                 case 1:
136                 {
137                         PyObject *arg= PyTuple_GET_ITEM(args, 0);
138
139                         const unsigned short row_size= PySequence_Size(arg); /* -1 is an error, size checks will accunt for this */
140
141                         if(IN_RANGE_INCL(row_size, 2, 4)) {
142                                 PyObject *item= PySequence_GetItem(arg, 0);
143                                 const unsigned short col_size= PySequence_Size(item);
144                                 Py_XDECREF(item);
145
146                                 if(IN_RANGE_INCL(col_size, 2, 4)) {
147                                         /* sane row & col size, new matrix and assign as slice  */
148                                         PyObject *matrix= newMatrixObject(NULL, row_size, col_size, Py_NEW, type);
149                                         if(Matrix_ass_slice((MatrixObject *)matrix, 0, INT_MAX, arg) == 0) {
150                                                 return matrix;
151                                         }
152                                         else { /* matrix ok, slice assignment not */
153                                                 Py_DECREF(matrix);
154                                         }
155                                 }
156                         }
157                 }
158         }
159
160         /* will overwrite error */
161         PyErr_SetString(PyExc_TypeError, "mathutils.Matrix(): expects no args or 2-4 numeric sequences");
162         return NULL;
163 }
164
165 /*-----------------------CLASS-METHODS----------------------------*/
166
167 //----------------------------------mathutils.RotationMatrix() ----------
168 //mat is a 1D array of floats - row[0][0],row[0][1], row[1][0], etc.
169 static char C_Matrix_Rotation_doc[] =
170 ".. classmethod:: Rotation(angle, size, axis)\n"
171 "\n"
172 "   Create a matrix representing a rotation.\n"
173 "\n"
174 "   :arg angle: The angle of rotation desired, in radians.\n"
175 "   :type angle: float\n"
176 "   :arg size: The size of the rotation matrix to construct [2, 4].\n"
177 "   :type size: int\n"
178 "   :arg axis: a string in ['X', 'Y', 'Z'] or a 3D Vector Object (optional when size is 2).\n"
179 "   :type axis: string or :class:`Vector`\n"
180 "   :return: A new rotation matrix.\n"
181 "   :rtype: :class:`Matrix`\n"
182 ;
183 static PyObject *C_Matrix_Rotation(PyObject *cls, PyObject *args)
184 {
185         PyObject *vec= NULL;
186         const char *axis= NULL;
187         int matSize;
188         double angle; /* use double because of precision problems at high values */
189         float mat[16] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
190                 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
191
192         if(!PyArg_ParseTuple(args, "di|O", &angle, &matSize, &vec)) {
193                 PyErr_SetString(PyExc_TypeError, "mathutils.RotationMatrix(angle, size, axis): expected float int and a string or vector");
194                 return NULL;
195         }
196
197         if(vec && PyUnicode_Check(vec)) {
198                 axis= _PyUnicode_AsString((PyObject *)vec);
199                 if(axis==NULL || axis[0]=='\0' || axis[1]!='\0' || axis[0] < 'X' || axis[0] > 'Z') {
200                         PyErr_SetString(PyExc_TypeError, "mathutils.RotationMatrix(): 3rd argument axis value must be a 3D vector or a string in 'X', 'Y', 'Z'");
201                         return NULL;
202                 }
203                 else {
204                         /* use the string */
205                         vec= NULL;
206                 }
207         }
208
209         /* clamp angle between -360 and 360 in radians */
210         angle= fmod(angle + M_PI*2, M_PI*4) - M_PI*2;
211
212         if(matSize != 2 && matSize != 3 && matSize != 4) {
213                 PyErr_SetString(PyExc_AttributeError, "mathutils.RotationMatrix(): can only return a 2x2 3x3 or 4x4 matrix");
214                 return NULL;
215         }
216         if(matSize == 2 && (vec != NULL)) {
217                 PyErr_SetString(PyExc_AttributeError, "mathutils.RotationMatrix(): cannot create a 2x2 rotation matrix around arbitrary axis");
218                 return NULL;
219         }
220         if((matSize == 3 || matSize == 4) && (axis == NULL) && (vec == NULL)) {
221                 PyErr_SetString(PyExc_AttributeError, "mathutils.RotationMatrix(): axis of rotation for 3d and 4d matrices is required");
222                 return NULL;
223         }
224
225         /* check for valid vector/axis above */
226         if(vec) {
227                 float tvec[3];
228
229                 if (mathutils_array_parse(tvec, 3, 3, vec, "mathutils.RotationMatrix(angle, size, axis), invalid 'axis' arg") == -1)
230                         return NULL;
231
232                 axis_angle_to_mat3((float (*)[3])mat, tvec, angle);
233         }
234         else if(matSize == 2) {
235                 //2D rotation matrix
236                 mat[0] = (float) cos (angle);
237                 mat[1] = (float) sin (angle);
238                 mat[2] = -((float) sin(angle));
239                 mat[3] = (float) cos(angle);
240         } else if(strcmp(axis, "X") == 0) {
241                 //rotation around X
242                 mat[0] = 1.0f;
243                 mat[4] = (float) cos(angle);
244                 mat[5] = (float) sin(angle);
245                 mat[7] = -((float) sin(angle));
246                 mat[8] = (float) cos(angle);
247         } else if(strcmp(axis, "Y") == 0) {
248                 //rotation around Y
249                 mat[0] = (float) cos(angle);
250                 mat[2] = -((float) sin(angle));
251                 mat[4] = 1.0f;
252                 mat[6] = (float) sin(angle);
253                 mat[8] = (float) cos(angle);
254         } else if(strcmp(axis, "Z") == 0) {
255                 //rotation around Z
256                 mat[0] = (float) cos(angle);
257                 mat[1] = (float) sin(angle);
258                 mat[3] = -((float) sin(angle));
259                 mat[4] = (float) cos(angle);
260                 mat[8] = 1.0f;
261         }
262         else {
263                 /* should never get here */
264                 PyErr_SetString(PyExc_AttributeError, "mathutils.RotationMatrix(): unknown error");
265                 return NULL;
266         }
267
268         if(matSize == 4) {
269                 //resize matrix
270                 mat[10] = mat[8];
271                 mat[9] = mat[7];
272                 mat[8] = mat[6];
273                 mat[7] = 0.0f;
274                 mat[6] = mat[5];
275                 mat[5] = mat[4];
276                 mat[4] = mat[3];
277                 mat[3] = 0.0f;
278         }
279         //pass to matrix creation
280         return newMatrixObject(mat, matSize, matSize, Py_NEW, (PyTypeObject *)cls);
281 }
282
283
284 static char C_Matrix_Translation_doc[] =
285 ".. classmethod:: Translation(vector)\n"
286 "\n"
287 "   Create a matrix representing a translation.\n"
288 "\n"
289 "   :arg vector: The translation vector.\n"
290 "   :type vector: :class:`Vector`\n"
291 "   :return: An identity matrix with a translation.\n"
292 "   :rtype: :class:`Matrix`\n"
293 ;
294 static PyObject *C_Matrix_Translation(PyObject *cls, PyObject *value)
295 {
296         float mat[16], tvec[3];
297
298         if (mathutils_array_parse(tvec, 3, 4, value, "mathutils.Matrix.Translation(vector), invalid vector arg") == -1)
299                 return NULL;
300
301         /* create a identity matrix and add translation */
302         unit_m4((float(*)[4]) mat);
303         copy_v3_v3(mat + 12, tvec); /* 12, 13, 14 */
304         return newMatrixObject(mat, 4, 4, Py_NEW, (PyTypeObject *)cls);
305 }
306 //----------------------------------mathutils.Matrix.Scale() -------------
307 //mat is a 1D array of floats - row[0][0],row[0][1], row[1][0], etc.
308 static char C_Matrix_Scale_doc[] =
309 ".. classmethod:: Scale(factor, size, axis)\n"
310 "\n"
311 "   Create a matrix representing a scaling.\n"
312 "\n"
313 "   :arg factor: The factor of scaling to apply.\n"
314 "   :type factor: float\n"
315 "   :arg size: The size of the scale matrix to construct [2, 4].\n"
316 "   :type size: int\n"
317 "   :arg axis: Direction to influence scale. (optional).\n"
318 "   :type axis: :class:`Vector`\n"
319 "   :return: A new scale matrix.\n"
320 "   :rtype: :class:`Matrix`\n"
321 ;
322 static PyObject *C_Matrix_Scale(PyObject *cls, PyObject *args)
323 {
324         VectorObject *vec = NULL;
325         float norm = 0.0f, factor;
326         int matSize, x;
327         float mat[16] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
328                 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
329
330         if(!PyArg_ParseTuple(args, "fi|O!:Matrix.Scale", &factor, &matSize, &vector_Type, &vec)) {
331                 return NULL;
332         }
333         if(matSize != 2 && matSize != 3 && matSize != 4) {
334                 PyErr_SetString(PyExc_AttributeError, "mathutils.Matrix.Scale(): can only return a 2x2 3x3 or 4x4 matrix");
335                 return NULL;
336         }
337         if(vec) {
338                 if(vec->size > 2 && matSize == 2) {
339                         PyErr_SetString(PyExc_AttributeError, "mathutils.Matrix.Scale(): 2D vectors when scaling in 2D required");
340                         return NULL;
341                 }
342
343                 if(!BaseMath_ReadCallback(vec))
344                         return NULL;
345
346         }
347         if(vec == NULL) {       //scaling along axis
348                 if(matSize == 2) {
349                         mat[0] = factor;
350                         mat[3] = factor;
351                 } else {
352                         mat[0] = factor;
353                         mat[4] = factor;
354                         mat[8] = factor;
355                 }
356         } else { //scaling in arbitrary direction
357                 //normalize arbitrary axis
358                 for(x = 0; x < vec->size; x++) {
359                         norm += vec->vec[x] * vec->vec[x];
360                 }
361                 norm = (float) sqrt(norm);
362                 for(x = 0; x < vec->size; x++) {
363                         vec->vec[x] /= norm;
364                 }
365                 if(matSize == 2) {
366                         mat[0] = 1 +((factor - 1) *(vec->vec[0] * vec->vec[0]));
367                         mat[1] =((factor - 1) *(vec->vec[0] * vec->vec[1]));
368                         mat[2] =((factor - 1) *(vec->vec[0] * vec->vec[1]));
369                         mat[3] = 1 + ((factor - 1) *(vec->vec[1] * vec->vec[1]));
370                 } else {
371                         mat[0] = 1 + ((factor - 1) *(vec->vec[0] * vec->vec[0]));
372                         mat[1] =((factor - 1) *(vec->vec[0] * vec->vec[1]));
373                         mat[2] =((factor - 1) *(vec->vec[0] * vec->vec[2]));
374                         mat[3] =((factor - 1) *(vec->vec[0] * vec->vec[1]));
375                         mat[4] = 1 + ((factor - 1) *(vec->vec[1] * vec->vec[1]));
376                         mat[5] =((factor - 1) *(vec->vec[1] * vec->vec[2]));
377                         mat[6] =((factor - 1) *(vec->vec[0] * vec->vec[2]));
378                         mat[7] =((factor - 1) *(vec->vec[1] * vec->vec[2]));
379                         mat[8] = 1 + ((factor - 1) *(vec->vec[2] * vec->vec[2]));
380                 }
381         }
382         if(matSize == 4) {
383                 //resize matrix
384                 mat[10] = mat[8];
385                 mat[9] = mat[7];
386                 mat[8] = mat[6];
387                 mat[7] = 0.0f;
388                 mat[6] = mat[5];
389                 mat[5] = mat[4];
390                 mat[4] = mat[3];
391                 mat[3] = 0.0f;
392         }
393         //pass to matrix creation
394         return newMatrixObject(mat, matSize, matSize, Py_NEW, (PyTypeObject *)cls);
395 }
396 //----------------------------------mathutils.Matrix.OrthoProjection() ---
397 //mat is a 1D array of floats - row[0][0],row[0][1], row[1][0], etc.
398 static char C_Matrix_OrthoProjection_doc[] =
399 ".. classmethod:: OrthoProjection(axis, size)\n"
400 "\n"
401 "   Create a matrix to represent an orthographic projection.\n"
402 "\n"
403 "   :arg axis: Can be any of the following: ['X', 'Y', 'XY', 'XZ', 'YZ'], where a single axis is for a 2D matrix. Or a vector for an arbitrary axis\n"
404 "   :type axis: string or :class:`Vector`\n"
405 "   :arg size: The size of the projection matrix to construct [2, 4].\n"
406 "   :type size: int\n"
407 "   :return: A new projection matrix.\n"
408 "   :rtype: :class:`Matrix`\n"
409 ;
410 static PyObject *C_Matrix_OrthoProjection(PyObject *cls, PyObject *args)
411 {
412         PyObject *axis;
413
414         int matSize, x;
415         float norm = 0.0f;
416         float mat[16] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
417                 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
418
419         if(!PyArg_ParseTuple(args, "Oi:Matrix.OrthoProjection", &axis, &matSize)) {
420                 return NULL;
421         }
422         if(matSize != 2 && matSize != 3 && matSize != 4) {
423                 PyErr_SetString(PyExc_AttributeError,"mathutils.Matrix.OrthoProjection(): can only return a 2x2 3x3 or 4x4 matrix");
424                 return NULL;
425         }
426
427         if(PyUnicode_Check(axis)) {     //ortho projection onto cardinal plane
428                 Py_ssize_t plane_len;
429                 const char *plane= _PyUnicode_AsStringAndSize(axis, &plane_len);
430                 if(matSize == 2) {
431                         if(plane_len == 1 && plane[0]=='X') {
432                                 mat[0]= 1.0f;
433                         }
434                         else if (plane_len == 1 && plane[0]=='Y') {
435                                 mat[3]= 1.0f;
436                         }
437                         else {
438                                 PyErr_Format(PyExc_ValueError, "mathutils.Matrix.OrthoProjection(): unknown plane, expected: X, Y, not '%.200s'", plane);
439                                 return NULL;
440                         }
441                 }
442                 else {
443                         if(plane_len == 2 && plane[0]=='X' && plane[1]=='Y') {
444                                 mat[0]= 1.0f;
445                                 mat[4]= 1.0f;
446                         }
447                         else if (plane_len == 2 && plane[0]=='X' && plane[1]=='Z') {
448                                 mat[0]= 1.0f;
449                                 mat[8]= 1.0f;
450                         }
451                         else if (plane_len == 2 && plane[0]=='Y' && plane[1]=='Z') {
452                                 mat[4]= 1.0f;
453                                 mat[8]= 1.0f;
454                         }
455                         else {
456                                 PyErr_Format(PyExc_ValueError, "mathutils.Matrix.OrthoProjection(): unknown plane, expected: XY, XZ, YZ, not '%.200s'", plane);
457                                 return NULL;
458                         }
459                 }
460         }
461         else {
462                 //arbitrary plane
463
464                 int vec_size= (matSize == 2 ? 2 : 3);
465                 float tvec[4];
466
467                 if(mathutils_array_parse(tvec, vec_size, vec_size, axis, "Matrix.OrthoProjection(axis, size), invalid 'axis' arg") == -1) {
468                         return NULL;
469                 }
470
471                 //normalize arbitrary axis
472                 for(x = 0; x < vec_size; x++) {
473                         norm += tvec[x] * tvec[x];
474                 }
475                 norm = (float) sqrt(norm);
476                 for(x = 0; x < vec_size; x++) {
477                         tvec[x] /= norm;
478                 }
479                 if(matSize == 2) {
480                         mat[0] = 1 - (tvec[0] * tvec[0]);
481                         mat[1] = -(tvec[0] * tvec[1]);
482                         mat[2] = -(tvec[0] * tvec[1]);
483                         mat[3] = 1 - (tvec[1] * tvec[1]);
484                 }
485                 else if(matSize > 2) {
486                         mat[0] = 1 - (tvec[0] * tvec[0]);
487                         mat[1] = -(tvec[0] * tvec[1]);
488                         mat[2] = -(tvec[0] * tvec[2]);
489                         mat[3] = -(tvec[0] * tvec[1]);
490                         mat[4] = 1 - (tvec[1] * tvec[1]);
491                         mat[5] = -(tvec[1] * tvec[2]);
492                         mat[6] = -(tvec[0] * tvec[2]);
493                         mat[7] = -(tvec[1] * tvec[2]);
494                         mat[8] = 1 - (tvec[2] * tvec[2]);
495                 }
496         }
497         if(matSize == 4) {
498                 //resize matrix
499                 mat[10] = mat[8];
500                 mat[9] = mat[7];
501                 mat[8] = mat[6];
502                 mat[7] = 0.0f;
503                 mat[6] = mat[5];
504                 mat[5] = mat[4];
505                 mat[4] = mat[3];
506                 mat[3] = 0.0f;
507         }
508         //pass to matrix creation
509         return newMatrixObject(mat, matSize, matSize, Py_NEW, (PyTypeObject *)cls);
510 }
511
512 static char C_Matrix_Shear_doc[] =
513 ".. classmethod:: Shear(plane, size, factor)\n"
514 "\n"
515 "   Create a matrix to represent an shear transformation.\n"
516 "\n"
517 "   :arg plane: Can be any of the following: ['X', 'Y', 'XY', 'XZ', 'YZ'], where a single axis is for a 2D matrix only.\n"
518 "   :type plane: string\n"
519 "   :arg size: The size of the shear matrix to construct [2, 4].\n"
520 "   :type size: int\n"
521 "   :arg factor: The factor of shear to apply. For a 3 or 4 *size* matrix pass a pair of floats corrasponding with the *plane* axis.\n"
522 "   :type factor: float or float pair\n"
523 "   :return: A new shear matrix.\n"
524 "   :rtype: :class:`Matrix`\n"
525 ;
526 static PyObject *C_Matrix_Shear(PyObject *cls, PyObject *args)
527 {
528         int matSize;
529         const char *plane;
530         PyObject *fac;
531         float mat[16] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
532                 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
533
534         if(!PyArg_ParseTuple(args, "siO:Matrix.Shear", &plane, &matSize, &fac)) {
535                 return NULL;
536         }
537         if(matSize != 2 && matSize != 3 && matSize != 4) {
538                 PyErr_SetString(PyExc_AttributeError,"mathutils.Matrix.Shear(): can only return a 2x2 3x3 or 4x4 matrix");
539                 return NULL;
540         }
541
542         if(matSize == 2) {
543                 float const factor= PyFloat_AsDouble(fac);
544
545                 if(factor==-1.0 && PyErr_Occurred()) {
546                         PyErr_SetString(PyExc_AttributeError, "mathutils.Matrix.Shear(): the factor to be a float");
547                         return NULL;
548                 }
549
550                 /* unit */
551                 mat[0] = 1.0f;
552                 mat[3] = 1.0f;
553
554                 if(strcmp(plane, "X") == 0) {
555                         mat[2] = factor;
556                 }
557                 else if(strcmp(plane, "Y") == 0) {
558                         mat[1] = factor;
559                 }
560                 else {
561                         PyErr_SetString(PyExc_AttributeError, "Matrix.Shear(): expected: X, Y or wrong matrix size for shearing plane");
562                         return NULL;
563                 }
564         }
565         else {
566                 /* 3 or 4, apply as 3x3, resize later if needed */
567                 float factor[2];
568
569                 if(mathutils_array_parse(factor, 2, 2, fac, "Matrix.Shear()") < 0) {
570                         return NULL;
571                 }
572
573                 /* unit */
574                 mat[0] = 1.0f;
575                 mat[4] = 1.0f;
576                 mat[8] = 1.0f;
577
578                 if(strcmp(plane, "XY") == 0) {
579                         mat[6] = factor[0];
580                         mat[7] = factor[1];
581                 }
582                 else if(strcmp(plane, "XZ") == 0) {
583                         mat[3] = factor[0];
584                         mat[5] = factor[1];
585                 }
586                 else if(strcmp(plane, "YZ") == 0) {
587                         mat[1] = factor[0];
588                         mat[2] = factor[1];
589                 }
590                 else {
591                         PyErr_SetString(PyExc_AttributeError, "mathutils.Matrix.Shear(): expected: X, Y, XY, XZ, YZ");
592                         return NULL;
593                 }
594         }
595
596         if(matSize == 4) {
597                 //resize matrix
598                 mat[10] = mat[8];
599                 mat[9] = mat[7];
600                 mat[8] = mat[6];
601                 mat[7] = 0.0f;
602                 mat[6] = mat[5];
603                 mat[5] = mat[4];
604                 mat[4] = mat[3];
605                 mat[3] = 0.0f;
606         }
607         //pass to matrix creation
608         return newMatrixObject(mat, matSize, matSize, Py_NEW, (PyTypeObject *)cls);
609 }
610
611 void matrix_as_3x3(float mat[3][3], MatrixObject *self)
612 {
613         copy_v3_v3(mat[0], self->matrix[0]);
614         copy_v3_v3(mat[1], self->matrix[1]);
615         copy_v3_v3(mat[2], self->matrix[2]);
616 }
617
618 /* assumes rowsize == colsize is checked and the read callback has run */
619 static float matrix_determinant_internal(MatrixObject *self)
620 {
621         if(self->rowSize == 2) {
622                 return determinant_m2(self->matrix[0][0], self->matrix[0][1],
623                                          self->matrix[1][0], self->matrix[1][1]);
624         } else if(self->rowSize == 3) {
625                 return determinant_m3(self->matrix[0][0], self->matrix[0][1],
626                                          self->matrix[0][2], self->matrix[1][0],
627                                          self->matrix[1][1], self->matrix[1][2],
628                                          self->matrix[2][0], self->matrix[2][1],
629                                          self->matrix[2][2]);
630         } else {
631                 return determinant_m4((float (*)[4])self->contigPtr);
632         }
633 }
634
635
636 /*-----------------------------METHODS----------------------------*/
637 static char Matrix_to_quaternion_doc[] =
638 ".. method:: to_quaternion()\n"
639 "\n"
640 "   Return a quaternion representation of the rotation matrix.\n"
641 "\n"
642 "   :return: Quaternion representation of the rotation matrix.\n"
643 "   :rtype: :class:`Quaternion`\n"
644 ;
645 static PyObject *Matrix_to_quaternion(MatrixObject *self)
646 {
647         float quat[4];
648
649         if(!BaseMath_ReadCallback(self))
650                 return NULL;
651
652         /*must be 3-4 cols, 3-4 rows, square matrix*/
653         if((self->colSize < 3) || (self->rowSize < 3) || (self->colSize != self->rowSize)) {
654                 PyErr_SetString(PyExc_AttributeError, "Matrix.to_quat(): inappropriate matrix size - expects 3x3 or 4x4 matrix");
655                 return NULL;
656         }
657         if(self->colSize == 3){
658                 mat3_to_quat( quat,(float (*)[3])self->contigPtr);
659         }else{
660                 mat4_to_quat( quat,(float (*)[4])self->contigPtr);
661         }
662
663         return newQuaternionObject(quat, Py_NEW, NULL);
664 }
665
666 /*---------------------------Matrix.toEuler() --------------------*/
667 static char Matrix_to_euler_doc[] =
668 ".. method:: to_euler(order, euler_compat)\n"
669 "\n"
670 "   Return an Euler representation of the rotation matrix (3x3 or 4x4 matrix only).\n"
671 "\n"
672 "   :arg order: Optional rotation order argument in ['XYZ', 'XZY', 'YXZ', 'YZX', 'ZXY', 'ZYX'].\n"
673 "   :type order: string\n"
674 "   :arg euler_compat: Optional euler argument the new euler will be made compatible with (no axis flipping between them). Useful for converting a series of matrices to animation curves.\n"
675 "   :type euler_compat: :class:`Euler`\n"
676 "   :return: Euler representation of the matrix.\n"
677 "   :rtype: :class:`Euler`\n"
678 ;
679 static PyObject *Matrix_to_euler(MatrixObject *self, PyObject *args)
680 {
681         const char *order_str= NULL;
682         short order= EULER_ORDER_XYZ;
683         float eul[3], eul_compatf[3];
684         EulerObject *eul_compat = NULL;
685
686         float tmat[3][3];
687         float (*mat)[3];
688
689         if(!BaseMath_ReadCallback(self))
690                 return NULL;
691
692         if(!PyArg_ParseTuple(args, "|sO!:to_euler", &order_str, &euler_Type, &eul_compat))
693                 return NULL;
694
695         if(eul_compat) {
696                 if(!BaseMath_ReadCallback(eul_compat))
697                         return NULL;
698
699                 copy_v3_v3(eul_compatf, eul_compat->eul);
700         }
701
702         /*must be 3-4 cols, 3-4 rows, square matrix*/
703         if(self->colSize ==3 && self->rowSize ==3) {
704                 mat= (float (*)[3])self->contigPtr;
705         }else if (self->colSize ==4 && self->rowSize ==4) {
706                 copy_m3_m4(tmat, (float (*)[4])self->contigPtr);
707                 mat= tmat;
708         }else {
709                 PyErr_SetString(PyExc_AttributeError, "Matrix.to_euler(): inappropriate matrix size - expects 3x3 or 4x4 matrix");
710                 return NULL;
711         }
712
713         if(order_str) {
714                 order= euler_order_from_string(order_str, "Matrix.to_euler()");
715
716                 if(order == -1)
717                         return NULL;
718         }
719
720         if(eul_compat) {
721                 if(order == 1)  mat3_to_compatible_eul( eul, eul_compatf, mat);
722                 else                    mat3_to_compatible_eulO(eul, eul_compatf, order, mat);
723         }
724         else {
725                 if(order == 1)  mat3_to_eul(eul, mat);
726                 else                    mat3_to_eulO(eul, order, mat);
727         }
728
729         return newEulerObject(eul, order, Py_NEW, NULL);
730 }
731
732 static char Matrix_resize_4x4_doc[] =
733 ".. method:: resize_4x4()\n"
734 "\n"
735 "   Resize the matrix to 4x4.\n"
736 ;
737 static PyObject *Matrix_resize_4x4(MatrixObject *self)
738 {
739         int x, first_row_elem, curr_pos, new_pos, blank_columns, blank_rows, index;
740
741         if(self->wrapped==Py_WRAP){
742                 PyErr_SetString(PyExc_TypeError, "cannot resize wrapped data - make a copy and resize that");
743                 return NULL;
744         }
745         if(self->cb_user){
746                 PyErr_SetString(PyExc_TypeError, "cannot resize owned data - make a copy and resize that");
747                 return NULL;
748         }
749
750         self->contigPtr = PyMem_Realloc(self->contigPtr, (sizeof(float) * 16));
751         if(self->contigPtr == NULL) {
752                 PyErr_SetString(PyExc_MemoryError, "matrix.resize_4x4(): problem allocating pointer space");
753                 return NULL;
754         }
755         /*set row pointers*/
756         for(x = 0; x < 4; x++) {
757                 self->matrix[x] = self->contigPtr + (x * 4);
758         }
759         /*move data to new spot in array + clean*/
760         for(blank_rows = (4 - self->rowSize); blank_rows > 0; blank_rows--){
761                 for(x = 0; x < 4; x++){
762                         index = (4 * (self->rowSize + (blank_rows - 1))) + x;
763                         if (index == 10 || index == 15){
764                                 self->contigPtr[index] = 1.0f;
765                         }else{
766                                 self->contigPtr[index] = 0.0f;
767                         }
768                 }
769         }
770         for(x = 1; x <= self->rowSize; x++){
771                 first_row_elem = (self->colSize * (self->rowSize - x));
772                 curr_pos = (first_row_elem + (self->colSize -1));
773                 new_pos = (4 * (self->rowSize - x )) + (curr_pos - first_row_elem);
774                 for(blank_columns = (4 - self->colSize); blank_columns > 0; blank_columns--){
775                         self->contigPtr[new_pos + blank_columns] = 0.0f;
776                 }
777                 for(curr_pos = curr_pos; curr_pos >= first_row_elem; curr_pos--){
778                         self->contigPtr[new_pos] = self->contigPtr[curr_pos];
779                         new_pos--;
780                 }
781         }
782         self->rowSize = 4;
783         self->colSize = 4;
784
785         Py_RETURN_NONE;
786 }
787
788 static char Matrix_to_4x4_doc[] =
789 ".. method:: to_4x4()\n"
790 "\n"
791 "   Return a 4x4 copy of this matrix.\n"
792 "\n"
793 "   :return: a new matrix.\n"
794 "   :rtype: :class:`Matrix`\n"
795 ;
796 static PyObject *Matrix_to_4x4(MatrixObject *self)
797 {
798         if(!BaseMath_ReadCallback(self))
799                 return NULL;
800
801         if(self->colSize==4 && self->rowSize==4) {
802                 return (PyObject *)newMatrixObject(self->contigPtr, 4, 4, Py_NEW, Py_TYPE(self));
803         }
804         else if(self->colSize==3 && self->rowSize==3) {
805                 float mat[4][4];
806                 copy_m4_m3(mat, (float (*)[3])self->contigPtr);
807                 return (PyObject *)newMatrixObject((float *)mat, 4, 4, Py_NEW, Py_TYPE(self));
808         }
809         /* TODO, 2x2 matrix */
810
811         PyErr_SetString(PyExc_TypeError, "Matrix.to_4x4(): inappropriate matrix size");
812         return NULL;
813 }
814
815 static char Matrix_to_3x3_doc[] =
816 ".. method:: to_3x3()\n"
817 "\n"
818 "   Return a 3x3 copy of this matrix.\n"
819 "\n"
820 "   :return: a new matrix.\n"
821 "   :rtype: :class:`Matrix`\n"
822 ;
823 static PyObject *Matrix_to_3x3(MatrixObject *self)
824 {
825         float mat[3][3];
826
827         if(!BaseMath_ReadCallback(self))
828                 return NULL;
829
830         if((self->colSize < 3) || (self->rowSize < 3)) {
831                 PyErr_SetString(PyExc_AttributeError, "Matrix.to_3x3(): inappropriate matrix size");
832                 return NULL;
833         }
834
835         matrix_as_3x3(mat, self);
836
837         return newMatrixObject((float *)mat, 3, 3, Py_NEW, Py_TYPE(self));
838 }
839
840 static char Matrix_to_translation_doc[] =
841 ".. method:: to_translation()\n"
842 "\n"
843 "   Return a the translation part of a 4 row matrix.\n"
844 "\n"
845 "   :return: Return a the translation of a matrix.\n"
846 "   :rtype: :class:`Vector`\n"
847 ;
848 static PyObject *Matrix_to_translation(MatrixObject *self)
849 {
850         if(!BaseMath_ReadCallback(self))
851                 return NULL;
852
853         if((self->colSize < 3) || self->rowSize < 4){
854                 PyErr_SetString(PyExc_AttributeError, "Matrix.to_translation(): inappropriate matrix size");
855                 return NULL;
856         }
857
858         return newVectorObject(self->matrix[3], 3, Py_NEW, NULL);
859 }
860
861 static char Matrix_to_scale_doc[] =
862 ".. method:: to_scale()\n"
863 "\n"
864 "   Return a the scale part of a 3x3 or 4x4 matrix.\n"
865 "\n"
866 "   :return: Return a the scale of a matrix.\n"
867 "   :rtype: :class:`Vector`\n"
868 "\n"
869 "   .. note:: This method does not return negative a scale on any axis because it is not possible to obtain this data from the matrix alone.\n"
870 ;
871 static PyObject *Matrix_to_scale(MatrixObject *self)
872 {
873         float rot[3][3];
874         float mat[3][3];
875         float size[3];
876
877         if(!BaseMath_ReadCallback(self))
878                 return NULL;
879
880         /*must be 3-4 cols, 3-4 rows, square matrix*/
881         if((self->colSize < 3) || (self->rowSize < 3)) {
882                 PyErr_SetString(PyExc_AttributeError, "Matrix.to_scale(): inappropriate matrix size, 3x3 minimum size");
883                 return NULL;
884         }
885
886         matrix_as_3x3(mat, self);
887
888         /* compatible mat4_to_loc_rot_size */
889         mat3_to_rot_size(rot, size, mat);
890
891         return newVectorObject(size, 3, Py_NEW, NULL);
892 }
893
894 /*---------------------------Matrix.invert() ---------------------*/
895 static char Matrix_invert_doc[] =
896 ".. method:: invert()\n"
897 "\n"
898 "   Set the matrix to its inverse.\n"
899 "\n"
900 "   :return: an instance of itself.\n"
901 "   :rtype: :class:`Matrix`\n"
902 "\n"
903 "   .. note:: :exc:`ValueError` exception is raised.\n"
904 "\n"
905 "   .. seealso:: <http://en.wikipedia.org/wiki/Inverse_matrix>\n"
906 ;
907 static PyObject *Matrix_invert(MatrixObject *self)
908 {
909
910         int x, y, z = 0;
911         float det = 0.0f;
912         float mat[16] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
913                 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
914
915         if(!BaseMath_ReadCallback(self))
916                 return NULL;
917
918         if(self->rowSize != self->colSize){
919                 PyErr_SetString(PyExc_AttributeError, "Matrix.invert(ed): only square matrices are supported");
920                 return NULL;
921         }
922
923         /*calculate the determinant*/
924         det = matrix_determinant_internal(self);
925
926         if(det != 0) {
927                 /*calculate the classical adjoint*/
928                 if(self->rowSize == 2) {
929                         mat[0] = self->matrix[1][1];
930                         mat[1] = -self->matrix[0][1];
931                         mat[2] = -self->matrix[1][0];
932                         mat[3] = self->matrix[0][0];
933                 } else if(self->rowSize == 3) {
934                         adjoint_m3_m3((float (*)[3]) mat,(float (*)[3])self->contigPtr);
935                 } else if(self->rowSize == 4) {
936                         adjoint_m4_m4((float (*)[4]) mat, (float (*)[4])self->contigPtr);
937                 }
938                 /*divide by determinate*/
939                 for(x = 0; x < (self->rowSize * self->colSize); x++) {
940                         mat[x] /= det;
941                 }
942                 /*set values*/
943                 for(x = 0; x < self->rowSize; x++) {
944                         for(y = 0; y < self->colSize; y++) {
945                                 self->matrix[x][y] = mat[z];
946                                 z++;
947                         }
948                 }
949                 /*transpose
950                 Matrix_transpose(self);*/
951         } else {
952                 PyErr_SetString(PyExc_ValueError, "matrix does not have an inverse");
953                 return NULL;
954         }
955
956         (void)BaseMath_WriteCallback(self);
957         Py_RETURN_NONE;
958 }
959
960 static char Matrix_inverted_doc[] =
961 ".. method:: invert()\n"
962 "\n"
963 "   Return an inverted copy of the matrix.\n"
964 "\n"
965 "   :return: the  inverted matrix.\n"
966 "   :rtype: :class:`Matrix`\n"
967 "\n"
968 "   .. note:: :exc:`ValueError` exception is raised.\n"
969 ;
970 static PyObject *Matrix_inverted(MatrixObject *self)
971 {
972         MATRIX_APPLY_TO_COPY(Matrix_invert, self);
973 }
974
975 static char Matrix_rotate_doc[] =
976 ".. method:: rotate(other)\n"
977 "\n"
978 "   Rotates the matrix a by another mathutils value.\n"
979 "\n"
980 "   :arg other: rotation component of mathutils value\n"
981 "   :type other: :class:`Euler`, :class:`Quaternion` or :class:`Matrix`\n"
982 "\n"
983 "   .. note:: If any of the columns are not unit length this may not have desired results.\n"
984 ;
985 static PyObject *Matrix_rotate(MatrixObject *self, PyObject *value)
986 {
987         float self_rmat[3][3], other_rmat[3][3], rmat[3][3];
988
989         if(!BaseMath_ReadCallback(self))
990                 return NULL;
991
992         if(mathutils_any_to_rotmat(other_rmat, value, "matrix.rotate(value)") == -1)
993                 return NULL;
994
995         if(self->colSize != 3 || self->rowSize != 3) {
996                 PyErr_SetString(PyExc_ValueError, "Matrix must have 3x3 dimensions");
997                 return NULL;
998         }
999
1000         matrix_as_3x3(self_rmat, self);
1001         mul_m3_m3m3(rmat, self_rmat, other_rmat);
1002
1003         copy_m3_m3((float (*)[3])(self->contigPtr), rmat);
1004
1005         (void)BaseMath_WriteCallback(self);
1006         Py_RETURN_NONE;
1007 }
1008
1009 /*---------------------------Matrix.decompose() ---------------------*/
1010 static char Matrix_decompose_doc[] =
1011 ".. method:: decompose()\n"
1012 "\n"
1013 "   Return the location, rotaion and scale components of this matrix.\n"
1014 "\n"
1015 "   :return: loc, rot, scale triple.\n"
1016 "   :rtype: (:class:`Vector`, :class:`Quaternion`, :class:`Vector`)"
1017 ;
1018 static PyObject *Matrix_decompose(MatrixObject *self)
1019 {
1020         PyObject *ret;
1021         float loc[3];
1022         float rot[3][3];
1023         float quat[4];
1024         float size[3];
1025
1026         if(self->colSize != 4 || self->rowSize != 4) {
1027                 PyErr_SetString(PyExc_AttributeError, "Matrix.decompose(): inappropriate matrix size - expects 4x4 matrix");
1028                 return NULL;
1029         }
1030
1031         if(!BaseMath_ReadCallback(self))
1032                 return NULL;
1033
1034         mat4_to_loc_rot_size(loc, rot, size, (float (*)[4])self->contigPtr);
1035         mat3_to_quat(quat, rot);
1036
1037         ret= PyTuple_New(3);
1038         PyTuple_SET_ITEM(ret, 0, newVectorObject(loc, 3, Py_NEW, NULL));
1039         PyTuple_SET_ITEM(ret, 1, newQuaternionObject(quat, Py_NEW, NULL));
1040         PyTuple_SET_ITEM(ret, 2, newVectorObject(size, 3, Py_NEW, NULL));
1041
1042         return ret;
1043 }
1044
1045
1046
1047 static char Matrix_lerp_doc[] =
1048 ".. function:: lerp(other, factor)\n"
1049 "\n"
1050 "   Returns the interpolation of two matricies.\n"
1051 "\n"
1052 "   :arg other: value to interpolate with.\n"
1053 "   :type other: :class:`Matrix`\n"
1054 "   :arg factor: The interpolation value in [0.0, 1.0].\n"
1055 "   :type factor: float\n"
1056 "   :return: The interpolated rotation.\n"
1057 "   :rtype: :class:`Matrix`\n"
1058 ;
1059 static PyObject *Matrix_lerp(MatrixObject *self, PyObject *args)
1060 {
1061         MatrixObject *mat2 = NULL;
1062         float fac, mat[MATRIX_MAX_DIM*MATRIX_MAX_DIM];
1063
1064         if(!PyArg_ParseTuple(args, "O!f:lerp", &matrix_Type, &mat2, &fac))
1065                 return NULL;
1066
1067         if(self->rowSize != mat2->rowSize || self->colSize != mat2->colSize) {
1068                 PyErr_SetString(PyExc_AttributeError, "matrix.lerp(): expects both matrix objects of the same dimensions");
1069                 return NULL;
1070         }
1071
1072         if(!BaseMath_ReadCallback(self) || !BaseMath_ReadCallback(mat2))
1073                 return NULL;
1074
1075         /* TODO, different sized matrix */
1076         if(self->rowSize==4 && self->colSize==4) {
1077                 blend_m4_m4m4((float (*)[4])mat, (float (*)[4])self->contigPtr, (float (*)[4])mat2->contigPtr, fac);
1078         }
1079         else if (self->rowSize==3 && self->colSize==3) {
1080                 blend_m3_m3m3((float (*)[3])mat, (float (*)[3])self->contigPtr, (float (*)[3])mat2->contigPtr, fac);
1081         }
1082         else {
1083                 PyErr_SetString(PyExc_AttributeError, "matrix.lerp(): only 3x3 and 4x4 matrices supported");
1084                 return NULL;
1085         }
1086
1087         return (PyObject*)newMatrixObject(mat, self->rowSize, self->colSize, Py_NEW, Py_TYPE(self));
1088 }
1089
1090 /*---------------------------Matrix.determinant() ----------------*/
1091 static char Matrix_determinant_doc[] =
1092 ".. method:: determinant()\n"
1093 "\n"
1094 "   Return the determinant of a matrix.\n"
1095 "\n"
1096 "   :return: Return a the determinant of a matrix.\n"
1097 "   :rtype: float\n"
1098 "\n"
1099 "   .. seealso:: <http://en.wikipedia.org/wiki/Determinant>\n"
1100 ;
1101 static PyObject *Matrix_determinant(MatrixObject *self)
1102 {
1103         if(!BaseMath_ReadCallback(self))
1104                 return NULL;
1105
1106         if(self->rowSize != self->colSize){
1107                 PyErr_SetString(PyExc_AttributeError, "Matrix.determinant: only square matrices are supported");
1108                 return NULL;
1109         }
1110
1111         return PyFloat_FromDouble((double)matrix_determinant_internal(self));
1112 }
1113 /*---------------------------Matrix.transpose() ------------------*/
1114 static char Matrix_transpose_doc[] =
1115 ".. method:: transpose()\n"
1116 "\n"
1117 "   Set the matrix to its transpose.\n"
1118 "\n"
1119 "   .. seealso:: <http://en.wikipedia.org/wiki/Transpose>\n"
1120 ;
1121 static PyObject *Matrix_transpose(MatrixObject *self)
1122 {
1123         float t = 0.0f;
1124
1125         if(!BaseMath_ReadCallback(self))
1126                 return NULL;
1127
1128         if(self->rowSize != self->colSize){
1129                 PyErr_SetString(PyExc_AttributeError, "Matrix.transpose(d): only square matrices are supported");
1130                 return NULL;
1131         }
1132
1133         if(self->rowSize == 2) {
1134                 t = self->matrix[1][0];
1135                 self->matrix[1][0] = self->matrix[0][1];
1136                 self->matrix[0][1] = t;
1137         } else if(self->rowSize == 3) {
1138                 transpose_m3((float (*)[3])self->contigPtr);
1139         } else {
1140                 transpose_m4((float (*)[4])self->contigPtr);
1141         }
1142
1143         (void)BaseMath_WriteCallback(self);
1144         Py_RETURN_NONE;
1145 }
1146
1147 static char Matrix_transposed_doc[] =
1148 ".. method:: transposed()\n"
1149 "\n"
1150 "   Return a new, transposed matrix.\n"
1151 "\n"
1152 "   :return: a transposed matrix\n"
1153 "   :rtype: :class:`Matrix`\n"
1154 ;
1155 static PyObject *Matrix_transposed(MatrixObject *self)
1156 {
1157         MATRIX_APPLY_TO_COPY(Matrix_transpose, self);
1158 }
1159
1160 /*---------------------------Matrix.zero() -----------------------*/
1161 static char Matrix_zero_doc[] =
1162 ".. method:: zero()\n"
1163 "\n"
1164 "   Set all the matrix values to zero.\n"
1165 "\n"
1166 "   :return: an instance of itself\n"
1167 "   :rtype: :class:`Matrix`\n"
1168 ;
1169 static PyObject *Matrix_zero(MatrixObject *self)
1170 {
1171         fill_vn(self->contigPtr, self->rowSize * self->colSize, 0.0f);
1172
1173         if(!BaseMath_WriteCallback(self))
1174                 return NULL;
1175
1176         Py_RETURN_NONE;
1177 }
1178 /*---------------------------Matrix.identity(() ------------------*/
1179 static char Matrix_identity_doc[] =
1180 ".. method:: identity()\n"
1181 "\n"
1182 "   Set the matrix to the identity matrix.\n"
1183 "\n"
1184 "   .. note:: An object with zero location and rotation, a scale of one, will have an identity matrix.\n"
1185 "\n"
1186 "   .. seealso:: <http://en.wikipedia.org/wiki/Identity_matrix>\n"
1187 ;
1188 static PyObject *Matrix_identity(MatrixObject *self)
1189 {
1190         if(!BaseMath_ReadCallback(self))
1191                 return NULL;
1192
1193         if(self->rowSize != self->colSize){
1194                 PyErr_SetString(PyExc_AttributeError, "Matrix.identity: only square matrices are supported");
1195                 return NULL;
1196         }
1197
1198         if(self->rowSize == 2) {
1199                 self->matrix[0][0] = 1.0f;
1200                 self->matrix[0][1] = 0.0f;
1201                 self->matrix[1][0] = 0.0f;
1202                 self->matrix[1][1] = 1.0f;
1203         } else if(self->rowSize == 3) {
1204                 unit_m3((float (*)[3])self->contigPtr);
1205         } else {
1206                 unit_m4((float (*)[4])self->contigPtr);
1207         }
1208
1209         if(!BaseMath_WriteCallback(self))
1210                 return NULL;
1211
1212         Py_RETURN_NONE;
1213 }
1214
1215 /*---------------------------Matrix.copy() ------------------*/
1216 static char Matrix_copy_doc[] =
1217 ".. method:: copy()\n"
1218 "\n"
1219 "   Returns a copy of this matrix.\n"
1220 "\n"
1221 "   :return: an instance of itself\n"
1222 "   :rtype: :class:`Matrix`\n"
1223 ;
1224 static PyObject *Matrix_copy(MatrixObject *self)
1225 {
1226         if(!BaseMath_ReadCallback(self))
1227                 return NULL;
1228
1229         return (PyObject*)newMatrixObject((float (*))self->contigPtr, self->rowSize, self->colSize, Py_NEW, Py_TYPE(self));
1230 }
1231
1232 /*----------------------------print object (internal)-------------*/
1233 /*print the object to screen*/
1234 static PyObject *Matrix_repr(MatrixObject *self)
1235 {
1236         int x, y;
1237         PyObject *rows[MATRIX_MAX_DIM]= {0};
1238
1239         if(!BaseMath_ReadCallback(self))
1240                 return NULL;
1241
1242         for(x = 0; x < self->rowSize; x++){
1243                 rows[x]= PyTuple_New(self->colSize);
1244                 for(y = 0; y < self->colSize; y++) {
1245                         PyTuple_SET_ITEM(rows[x], y, PyFloat_FromDouble(self->matrix[x][y]));
1246                 }
1247         }
1248         switch(self->rowSize) {
1249         case 2: return PyUnicode_FromFormat("Matrix(%R,\n"
1250                                                                                 "       %R)", rows[0], rows[1]);
1251
1252         case 3: return PyUnicode_FromFormat("Matrix(%R,\n"
1253                                                                                 "       %R,\n"
1254                                                                                 "       %R)", rows[0], rows[1], rows[2]);
1255
1256         case 4: return PyUnicode_FromFormat("Matrix(%R,\n"
1257                                                                                 "       %R,\n"
1258                                                                                 "       %R,\n"
1259                                                                                 "       %R)", rows[0], rows[1], rows[2], rows[3]);
1260         }
1261
1262         PyErr_SetString(PyExc_RuntimeError, "invalid matrix size");
1263         return NULL;
1264 }
1265
1266 static PyObject* Matrix_richcmpr(PyObject *a, PyObject *b, int op)
1267 {
1268         PyObject *res;
1269         int ok= -1; /* zero is true */
1270
1271         if (MatrixObject_Check(a) && MatrixObject_Check(b)) {
1272                 MatrixObject *matA= (MatrixObject*)a;
1273                 MatrixObject *matB= (MatrixObject*)b;
1274
1275                 if(!BaseMath_ReadCallback(matA) || !BaseMath_ReadCallback(matB))
1276                         return NULL;
1277
1278                 ok=     (       (matA->colSize == matB->colSize) &&
1279                                 (matA->rowSize == matB->rowSize) &&
1280                                 EXPP_VectorsAreEqual(matA->contigPtr, matB->contigPtr, (matA->rowSize * matA->colSize), 1)
1281                         ) ? 0 : -1;
1282         }
1283
1284         switch (op) {
1285         case Py_NE:
1286                 ok = !ok; /* pass through */
1287         case Py_EQ:
1288                 res = ok ? Py_False : Py_True;
1289                 break;
1290
1291         case Py_LT:
1292         case Py_LE:
1293         case Py_GT:
1294         case Py_GE:
1295                 res = Py_NotImplemented;
1296                 break;
1297         default:
1298                 PyErr_BadArgument();
1299                 return NULL;
1300         }
1301
1302         return Py_INCREF(res), res;
1303 }
1304
1305 /*---------------------SEQUENCE PROTOCOLS------------------------
1306   ----------------------------len(object)------------------------
1307   sequence length*/
1308 static int Matrix_len(MatrixObject *self)
1309 {
1310         return (self->rowSize);
1311 }
1312 /*----------------------------object[]---------------------------
1313   sequence accessor (get)
1314   the wrapped vector gives direct access to the matrix data*/
1315 static PyObject *Matrix_item(MatrixObject *self, int i)
1316 {
1317         if(!BaseMath_ReadCallback(self))
1318                 return NULL;
1319
1320         if(i < 0 || i >= self->rowSize) {
1321                 PyErr_SetString(PyExc_IndexError, "matrix[attribute]: array index out of range");
1322                 return NULL;
1323         }
1324         return newVectorObject_cb((PyObject *)self, self->colSize, mathutils_matrix_vector_cb_index, i);
1325 }
1326 /*----------------------------object[]-------------------------
1327   sequence accessor (set) */
1328
1329 static int Matrix_ass_item(MatrixObject *self, int i, PyObject *value)
1330 {
1331         float vec[4];
1332         if(!BaseMath_ReadCallback(self))
1333                 return -1;
1334
1335         if(i >= self->rowSize || i < 0){
1336                 PyErr_SetString(PyExc_TypeError, "matrix[attribute] = x: bad column");
1337                 return -1;
1338         }
1339
1340         if(mathutils_array_parse(vec, self->colSize, self->colSize, value, "matrix[i] = value assignment") < 0) {
1341                 return -1;
1342         }
1343
1344         memcpy(self->matrix[i], vec, self->colSize *sizeof(float));
1345
1346         (void)BaseMath_WriteCallback(self);
1347         return 0;
1348 }
1349
1350 /*----------------------------object[z:y]------------------------
1351   sequence slice (get)*/
1352 static PyObject *Matrix_slice(MatrixObject *self, int begin, int end)
1353 {
1354
1355         PyObject *tuple;
1356         int count;
1357
1358         if(!BaseMath_ReadCallback(self))
1359                 return NULL;
1360
1361         CLAMP(begin, 0, self->rowSize);
1362         CLAMP(end, 0, self->rowSize);
1363         begin= MIN2(begin,end);
1364
1365         tuple= PyTuple_New(end - begin);
1366         for(count= begin; count < end; count++) {
1367                 PyTuple_SET_ITEM(tuple, count - begin,
1368                                 newVectorObject_cb((PyObject *)self, self->colSize, mathutils_matrix_vector_cb_index, count));
1369
1370         }
1371
1372         return tuple;
1373 }
1374 /*----------------------------object[z:y]------------------------
1375   sequence slice (set)*/
1376 static int Matrix_ass_slice(MatrixObject *self, int begin, int end, PyObject *value)
1377 {
1378         PyObject *value_fast= NULL;
1379
1380         if(!BaseMath_ReadCallback(self))
1381                 return -1;
1382
1383         CLAMP(begin, 0, self->rowSize);
1384         CLAMP(end, 0, self->rowSize);
1385         begin = MIN2(begin,end);
1386
1387         /* non list/tuple cases */
1388         if(!(value_fast=PySequence_Fast(value, "matrix[begin:end] = value"))) {
1389                 /* PySequence_Fast sets the error */
1390                 return -1;
1391         }
1392         else {
1393                 const int size= end - begin;
1394                 int i;
1395                 float mat[16];
1396
1397                 if(PySequence_Fast_GET_SIZE(value_fast) != size) {
1398                         Py_DECREF(value_fast);
1399                         PyErr_SetString(PyExc_TypeError, "matrix[begin:end] = []: size mismatch in slice assignment");
1400                         return -1;
1401                 }
1402
1403                 /*parse sub items*/
1404                 for (i = 0; i < size; i++) {
1405                         /*parse each sub sequence*/
1406                         PyObject *item= PySequence_Fast_GET_ITEM(value_fast, i);
1407
1408                         if(mathutils_array_parse(&mat[i * self->colSize], self->colSize, self->colSize, item, "matrix[begin:end] = value assignment") < 0) {
1409                                 return -1;
1410                         }
1411                 }
1412
1413                 Py_DECREF(value_fast);
1414
1415                 /*parsed well - now set in matrix*/
1416                 memcpy(self->contigPtr + (begin * self->colSize), mat, sizeof(float) * (size * self->colSize));
1417
1418                 (void)BaseMath_WriteCallback(self);
1419                 return 0;
1420         }
1421 }
1422 /*------------------------NUMERIC PROTOCOLS----------------------
1423   ------------------------obj + obj------------------------------*/
1424 static PyObject *Matrix_add(PyObject *m1, PyObject *m2)
1425 {
1426         float mat[16];
1427         MatrixObject *mat1 = NULL, *mat2 = NULL;
1428
1429         mat1 = (MatrixObject*)m1;
1430         mat2 = (MatrixObject*)m2;
1431
1432         if(!MatrixObject_Check(m1) || !MatrixObject_Check(m2)) {
1433                 PyErr_SetString(PyExc_AttributeError, "Matrix addition: arguments not valid for this operation");
1434                 return NULL;
1435         }
1436
1437         if(!BaseMath_ReadCallback(mat1) || !BaseMath_ReadCallback(mat2))
1438                 return NULL;
1439
1440         if(mat1->rowSize != mat2->rowSize || mat1->colSize != mat2->colSize){
1441                 PyErr_SetString(PyExc_AttributeError, "Matrix addition: matrices must have the same dimensions for this operation");
1442                 return NULL;
1443         }
1444
1445         add_vn_vnvn(mat, mat1->contigPtr, mat2->contigPtr, mat1->rowSize * mat1->colSize);
1446
1447         return newMatrixObject(mat, mat1->rowSize, mat1->colSize, Py_NEW, Py_TYPE(mat1));
1448 }
1449 /*------------------------obj - obj------------------------------
1450   subtraction*/
1451 static PyObject *Matrix_sub(PyObject *m1, PyObject *m2)
1452 {
1453         float mat[16];
1454         MatrixObject *mat1 = NULL, *mat2 = NULL;
1455
1456         mat1 = (MatrixObject*)m1;
1457         mat2 = (MatrixObject*)m2;
1458
1459         if(!MatrixObject_Check(m1) || !MatrixObject_Check(m2)) {
1460                 PyErr_SetString(PyExc_AttributeError, "Matrix addition: arguments not valid for this operation");
1461                 return NULL;
1462         }
1463
1464         if(!BaseMath_ReadCallback(mat1) || !BaseMath_ReadCallback(mat2))
1465                 return NULL;
1466
1467         if(mat1->rowSize != mat2->rowSize || mat1->colSize != mat2->colSize){
1468                 PyErr_SetString(PyExc_AttributeError, "Matrix addition: matrices must have the same dimensions for this operation");
1469                 return NULL;
1470         }
1471
1472         sub_vn_vnvn(mat, mat1->contigPtr, mat2->contigPtr, mat1->rowSize * mat1->colSize);
1473
1474         return newMatrixObject(mat, mat1->rowSize, mat1->colSize, Py_NEW, Py_TYPE(mat1));
1475 }
1476 /*------------------------obj * obj------------------------------
1477   mulplication*/
1478 static PyObject *matrix_mul_float(MatrixObject *mat, const float scalar)
1479 {
1480         float tmat[16];
1481         mul_vn_vn_fl(tmat, mat->contigPtr, mat->rowSize * mat->colSize, scalar);
1482         return newMatrixObject(tmat, mat->rowSize, mat->colSize, Py_NEW, Py_TYPE(mat));
1483 }
1484
1485 static PyObject *Matrix_mul(PyObject * m1, PyObject * m2)
1486 {
1487         float scalar;
1488
1489         MatrixObject *mat1 = NULL, *mat2 = NULL;
1490
1491         if(MatrixObject_Check(m1)) {
1492                 mat1 = (MatrixObject*)m1;
1493                 if(!BaseMath_ReadCallback(mat1))
1494                         return NULL;
1495         }
1496         if(MatrixObject_Check(m2)) {
1497                 mat2 = (MatrixObject*)m2;
1498                 if(!BaseMath_ReadCallback(mat2))
1499                         return NULL;
1500         }
1501
1502         if(mat1 && mat2) { /*MATRIX * MATRIX*/
1503                 if(mat1->rowSize != mat2->colSize){
1504                         PyErr_SetString(PyExc_AttributeError,"Matrix multiplication: matrix A rowsize must equal matrix B colsize");
1505                         return NULL;
1506                 }
1507                 else {
1508                         float mat[16]= {0.0f, 0.0f, 0.0f, 0.0f,
1509                                                         0.0f, 0.0f, 0.0f, 0.0f,
1510                                                         0.0f, 0.0f, 0.0f, 0.0f,
1511                                                         0.0f, 0.0f, 0.0f, 1.0f};
1512                         double dot = 0.0f;
1513                         int x, y, z;
1514
1515                         for(x = 0; x < mat2->rowSize; x++) {
1516                                 for(y = 0; y < mat1->colSize; y++) {
1517                                         for(z = 0; z < mat1->rowSize; z++) {
1518                                                 dot += (mat1->matrix[z][y] * mat2->matrix[x][z]);
1519                                         }
1520                                         mat[((x * mat1->colSize) + y)] = (float)dot;
1521                                         dot = 0.0f;
1522                                 }
1523                         }
1524
1525                         return newMatrixObject(mat, mat2->rowSize, mat1->colSize, Py_NEW, Py_TYPE(mat1));
1526                 }
1527         }
1528         else if(mat2) {
1529                 if (((scalar= PyFloat_AsDouble(m1)) == -1.0 && PyErr_Occurred())==0) { /*FLOAT/INT * MATRIX */
1530                         return matrix_mul_float(mat2, scalar);
1531                 }
1532         }
1533         else if(mat1) {
1534                 if (((scalar= PyFloat_AsDouble(m2)) == -1.0 && PyErr_Occurred())==0) { /*FLOAT/INT * MATRIX */
1535                         return matrix_mul_float(mat1, scalar);
1536                 }
1537         }
1538         else {
1539                 BLI_assert(!"internal error");
1540         }
1541
1542         PyErr_Format(PyExc_TypeError, "Matrix multiplication: not supported between '%.200s' and '%.200s' types", Py_TYPE(m1)->tp_name, Py_TYPE(m2)->tp_name);
1543         return NULL;
1544 }
1545 static PyObject* Matrix_inv(MatrixObject *self)
1546 {
1547         if(!BaseMath_ReadCallback(self))
1548                 return NULL;
1549
1550         return Matrix_invert(self);
1551 }
1552
1553 /*-----------------PROTOCOL DECLARATIONS--------------------------*/
1554 static PySequenceMethods Matrix_SeqMethods = {
1555         (lenfunc) Matrix_len,                                           /* sq_length */
1556         (binaryfunc) NULL,                                                      /* sq_concat */
1557         (ssizeargfunc) NULL,                                            /* sq_repeat */
1558         (ssizeargfunc) Matrix_item,                                     /* sq_item */
1559         (ssizessizeargfunc) NULL,                                       /* sq_slice, deprecated */
1560         (ssizeobjargproc) Matrix_ass_item,                      /* sq_ass_item */
1561         (ssizessizeobjargproc) NULL,                            /* sq_ass_slice, deprecated */
1562         (objobjproc) NULL,                                                      /* sq_contains */
1563         (binaryfunc) NULL,                                                      /* sq_inplace_concat */
1564         (ssizeargfunc) NULL,                                            /* sq_inplace_repeat */
1565 };
1566
1567
1568 static PyObject *Matrix_subscript(MatrixObject* self, PyObject* item)
1569 {
1570         if (PyIndex_Check(item)) {
1571                 Py_ssize_t i;
1572                 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
1573                 if (i == -1 && PyErr_Occurred())
1574                         return NULL;
1575                 if (i < 0)
1576                         i += self->rowSize;
1577                 return Matrix_item(self, i);
1578         } else if (PySlice_Check(item)) {
1579                 Py_ssize_t start, stop, step, slicelength;
1580
1581                 if (PySlice_GetIndicesEx((void *)item, self->rowSize, &start, &stop, &step, &slicelength) < 0)
1582                         return NULL;
1583
1584                 if (slicelength <= 0) {
1585                         return PyTuple_New(0);
1586                 }
1587                 else if (step == 1) {
1588                         return Matrix_slice(self, start, stop);
1589                 }
1590                 else {
1591                         PyErr_SetString(PyExc_TypeError, "slice steps not supported with matricies");
1592                         return NULL;
1593                 }
1594         }
1595         else {
1596                 PyErr_Format(PyExc_TypeError, "vector indices must be integers, not %.200s", Py_TYPE(item)->tp_name);
1597                 return NULL;
1598         }
1599 }
1600
1601 static int Matrix_ass_subscript(MatrixObject* self, PyObject* item, PyObject* value)
1602 {
1603         if (PyIndex_Check(item)) {
1604                 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
1605                 if (i == -1 && PyErr_Occurred())
1606                         return -1;
1607                 if (i < 0)
1608                         i += self->rowSize;
1609                 return Matrix_ass_item(self, i, value);
1610         }
1611         else if (PySlice_Check(item)) {
1612                 Py_ssize_t start, stop, step, slicelength;
1613
1614                 if (PySlice_GetIndicesEx((void *)item, self->rowSize, &start, &stop, &step, &slicelength) < 0)
1615                         return -1;
1616
1617                 if (step == 1)
1618                         return Matrix_ass_slice(self, start, stop, value);
1619                 else {
1620                         PyErr_SetString(PyExc_TypeError, "slice steps not supported with matricies");
1621                         return -1;
1622                 }
1623         }
1624         else {
1625                 PyErr_Format(PyExc_TypeError, "matrix indices must be integers, not %.200s", Py_TYPE(item)->tp_name);
1626                 return -1;
1627         }
1628 }
1629
1630 static PyMappingMethods Matrix_AsMapping = {
1631         (lenfunc)Matrix_len,
1632         (binaryfunc)Matrix_subscript,
1633         (objobjargproc)Matrix_ass_subscript
1634 };
1635
1636
1637 static PyNumberMethods Matrix_NumMethods = {
1638                 (binaryfunc)    Matrix_add,     /*nb_add*/
1639                 (binaryfunc)    Matrix_sub,     /*nb_subtract*/
1640                 (binaryfunc)    Matrix_mul,     /*nb_multiply*/
1641                 0,                                                      /*nb_remainder*/
1642                 0,                                                      /*nb_divmod*/
1643                 0,                                                      /*nb_power*/
1644                 (unaryfunc)     0,      /*nb_negative*/
1645                 (unaryfunc)     0,      /*tp_positive*/
1646                 (unaryfunc)     0,      /*tp_absolute*/
1647                 (inquiry)       0,      /*tp_bool*/
1648                 (unaryfunc)     Matrix_inv,     /*nb_invert*/
1649                 0,                              /*nb_lshift*/
1650                 (binaryfunc)0,  /*nb_rshift*/
1651                 0,                              /*nb_and*/
1652                 0,                              /*nb_xor*/
1653                 0,                              /*nb_or*/
1654                 0,                              /*nb_int*/
1655                 0,                              /*nb_reserved*/
1656                 0,                              /*nb_float*/
1657                 0,                              /* nb_inplace_add */
1658                 0,                              /* nb_inplace_subtract */
1659                 0,                              /* nb_inplace_multiply */
1660                 0,                              /* nb_inplace_remainder */
1661                 0,                              /* nb_inplace_power */
1662                 0,                              /* nb_inplace_lshift */
1663                 0,                              /* nb_inplace_rshift */
1664                 0,                              /* nb_inplace_and */
1665                 0,                              /* nb_inplace_xor */
1666                 0,                              /* nb_inplace_or */
1667                 0,                              /* nb_floor_divide */
1668                 0,                              /* nb_true_divide */
1669                 0,                              /* nb_inplace_floor_divide */
1670                 0,                              /* nb_inplace_true_divide */
1671                 0,                              /* nb_index */
1672 };
1673
1674 static PyObject *Matrix_getRowSize(MatrixObject *self, void *UNUSED(closure))
1675 {
1676         return PyLong_FromLong((long) self->rowSize);
1677 }
1678
1679 static PyObject *Matrix_getColSize(MatrixObject *self, void *UNUSED(closure))
1680 {
1681         return PyLong_FromLong((long) self->colSize);
1682 }
1683
1684 static PyObject *Matrix_getMedianScale(MatrixObject *self, void *UNUSED(closure))
1685 {
1686         float mat[3][3];
1687
1688         if(!BaseMath_ReadCallback(self))
1689                 return NULL;
1690
1691         /*must be 3-4 cols, 3-4 rows, square matrix*/
1692         if((self->colSize < 3) || (self->rowSize < 3)) {
1693                 PyErr_SetString(PyExc_AttributeError, "Matrix.median_scale: inappropriate matrix size, 3x3 minimum");
1694                 return NULL;
1695         }
1696
1697         matrix_as_3x3(mat, self);
1698
1699         return PyFloat_FromDouble(mat3_to_scale(mat));
1700 }
1701
1702 static PyObject *Matrix_getIsNegative(MatrixObject *self, void *UNUSED(closure))
1703 {
1704         if(!BaseMath_ReadCallback(self))
1705                 return NULL;
1706
1707         /*must be 3-4 cols, 3-4 rows, square matrix*/
1708         if(self->colSize == 4 && self->rowSize == 4)
1709                 return PyBool_FromLong(is_negative_m4((float (*)[4])self->contigPtr));
1710         else if(self->colSize == 3 && self->rowSize == 3)
1711                 return PyBool_FromLong(is_negative_m3((float (*)[3])self->contigPtr));
1712         else {
1713                 PyErr_SetString(PyExc_AttributeError, "Matrix.is_negative: inappropriate matrix size - expects 3x3 or 4x4 matrix");
1714                 return NULL;
1715         }
1716 }
1717
1718
1719 /*****************************************************************************/
1720 /* Python attributes get/set structure:                                      */
1721 /*****************************************************************************/
1722 static PyGetSetDef Matrix_getseters[] = {
1723         {(char *)"row_size", (getter)Matrix_getRowSize, (setter)NULL, (char *)"The row size of the matrix (readonly).\n\n:type: int", NULL},
1724         {(char *)"col_size", (getter)Matrix_getColSize, (setter)NULL, (char *)"The column size of the matrix (readonly).\n\n:type: int", NULL},
1725         {(char *)"median_scale", (getter)Matrix_getMedianScale, (setter)NULL, (char *)"The average scale applied to each axis (readonly).\n\n:type: float", NULL},
1726         {(char *)"is_negative", (getter)Matrix_getIsNegative, (setter)NULL, (char *)"True if this matrix results in a negative scale, 3x3 and 4x4 only, (readonly).\n\n:type: bool", NULL},
1727         {(char *)"is_wrapped", (getter)BaseMathObject_getWrapped, (setter)NULL, (char *)BaseMathObject_Wrapped_doc, NULL},
1728         {(char *)"owner",(getter)BaseMathObject_getOwner, (setter)NULL, (char *)BaseMathObject_Owner_doc, NULL},
1729         {NULL,NULL,NULL,NULL,NULL}  /* Sentinel */
1730 };
1731
1732 /*-----------------------METHOD DEFINITIONS ----------------------*/
1733 static struct PyMethodDef Matrix_methods[] = {
1734         /* derived values */
1735         {"determinant", (PyCFunction) Matrix_determinant, METH_NOARGS, Matrix_determinant_doc},
1736         {"decompose", (PyCFunction) Matrix_decompose, METH_NOARGS, Matrix_decompose_doc},
1737
1738         /* in place only */
1739         {"zero", (PyCFunction) Matrix_zero, METH_NOARGS, Matrix_zero_doc},
1740         {"identity", (PyCFunction) Matrix_identity, METH_NOARGS, Matrix_identity_doc},
1741
1742         /* operate on original or copy */
1743         {"transpose", (PyCFunction) Matrix_transpose, METH_NOARGS, Matrix_transpose_doc},
1744         {"transposed", (PyCFunction) Matrix_transposed, METH_NOARGS, Matrix_transposed_doc},
1745         {"invert", (PyCFunction) Matrix_invert, METH_NOARGS, Matrix_invert_doc},
1746         {"inverted", (PyCFunction) Matrix_inverted, METH_NOARGS, Matrix_inverted_doc},
1747         {"to_3x3", (PyCFunction) Matrix_to_3x3, METH_NOARGS, Matrix_to_3x3_doc},
1748         // TODO. {"resize_3x3", (PyCFunction) Matrix_resize3x3, METH_NOARGS, Matrix_resize3x3_doc},
1749         {"to_4x4", (PyCFunction) Matrix_to_4x4, METH_NOARGS, Matrix_to_4x4_doc},
1750         {"resize_4x4", (PyCFunction) Matrix_resize_4x4, METH_NOARGS, Matrix_resize_4x4_doc},
1751         {"rotate", (PyCFunction) Matrix_rotate, METH_O, Matrix_rotate_doc},
1752
1753         /* return converted representation */
1754         {"to_euler", (PyCFunction) Matrix_to_euler, METH_VARARGS, Matrix_to_euler_doc},
1755         {"to_quaternion", (PyCFunction) Matrix_to_quaternion, METH_NOARGS, Matrix_to_quaternion_doc},
1756         {"to_scale", (PyCFunction) Matrix_to_scale, METH_NOARGS, Matrix_to_scale_doc},
1757         {"to_translation", (PyCFunction) Matrix_to_translation, METH_NOARGS, Matrix_to_translation_doc},
1758
1759         /* operation between 2 or more types  */
1760         {"lerp", (PyCFunction) Matrix_lerp, METH_VARARGS, Matrix_lerp_doc},
1761         {"copy", (PyCFunction) Matrix_copy, METH_NOARGS, Matrix_copy_doc},
1762         {"__copy__", (PyCFunction) Matrix_copy, METH_NOARGS, Matrix_copy_doc},
1763
1764         /* class methods */
1765         {"Rotation", (PyCFunction) C_Matrix_Rotation, METH_VARARGS | METH_CLASS, C_Matrix_Rotation_doc},
1766         {"Scale", (PyCFunction) C_Matrix_Scale, METH_VARARGS | METH_CLASS, C_Matrix_Scale_doc},
1767         {"Shear", (PyCFunction) C_Matrix_Shear, METH_VARARGS | METH_CLASS, C_Matrix_Shear_doc},
1768         {"Translation", (PyCFunction) C_Matrix_Translation, METH_O | METH_CLASS, C_Matrix_Translation_doc},
1769         {"OrthoProjection", (PyCFunction) C_Matrix_OrthoProjection,  METH_VARARGS | METH_CLASS, C_Matrix_OrthoProjection_doc},
1770         {NULL, NULL, 0, NULL}
1771 };
1772
1773 /*------------------PY_OBECT DEFINITION--------------------------*/
1774 static char matrix_doc[] =
1775 "This object gives access to Matrices in Blender."
1776 ;
1777 PyTypeObject matrix_Type = {
1778         PyVarObject_HEAD_INIT(NULL, 0)
1779         "mathutils.Matrix",                                             /*tp_name*/
1780         sizeof(MatrixObject),                   /*tp_basicsize*/
1781         0,                                                              /*tp_itemsize*/
1782         (destructor)BaseMathObject_dealloc,             /*tp_dealloc*/
1783         0,                                                              /*tp_print*/
1784         0,                                                              /*tp_getattr*/
1785         0,                                                              /*tp_setattr*/
1786         0,                                                              /*tp_compare*/
1787         (reprfunc) Matrix_repr,                 /*tp_repr*/
1788         &Matrix_NumMethods,                             /*tp_as_number*/
1789         &Matrix_SeqMethods,                             /*tp_as_sequence*/
1790         &Matrix_AsMapping,                              /*tp_as_mapping*/
1791         0,                                                              /*tp_hash*/
1792         0,                                                              /*tp_call*/
1793         0,                                                              /*tp_str*/
1794         0,                                                              /*tp_getattro*/
1795         0,                                                              /*tp_setattro*/
1796         0,                                                              /*tp_as_buffer*/
1797         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
1798         matrix_doc,                                             /*tp_doc*/
1799         0,                                                              /*tp_traverse*/
1800         0,                                                              /*tp_clear*/
1801         (richcmpfunc)Matrix_richcmpr,   /*tp_richcompare*/
1802         0,                                                              /*tp_weaklistoffset*/
1803         0,                                                              /*tp_iter*/
1804         0,                                                              /*tp_iternext*/
1805         Matrix_methods,                                 /*tp_methods*/
1806         0,                                                              /*tp_members*/
1807         Matrix_getseters,                               /*tp_getset*/
1808         0,                                                              /*tp_base*/
1809         0,                                                              /*tp_dict*/
1810         0,                                                              /*tp_descr_get*/
1811         0,                                                              /*tp_descr_set*/
1812         0,                                                              /*tp_dictoffset*/
1813         0,                                                              /*tp_init*/
1814         0,                                                              /*tp_alloc*/
1815         Matrix_new,                                             /*tp_new*/
1816         0,                                                              /*tp_free*/
1817         0,                                                              /*tp_is_gc*/
1818         0,                                                              /*tp_bases*/
1819         0,                                                              /*tp_mro*/
1820         0,                                                              /*tp_cache*/
1821         0,                                                              /*tp_subclasses*/
1822         0,                                                              /*tp_weaklist*/
1823         0                                                               /*tp_del*/
1824 };
1825
1826 /*------------------------newMatrixObject (internal)-------------
1827 creates a new matrix object
1828 self->matrix     self->contiguous_ptr (reference to data.xxx)
1829            [0]------------->[0]
1830                                                 [1]
1831                                                 [2]
1832            [1]------------->[3]
1833                                                 [4]
1834                                                 [5]
1835
1836 self->matrix[1][1] = self->contigPtr[4] */
1837
1838 /*pass Py_WRAP - if vector is a WRAPPER for data allocated by BLENDER
1839  (i.e. it was allocated elsewhere by MEM_mallocN())
1840   pass Py_NEW - if vector is not a WRAPPER and managed by PYTHON
1841  (i.e. it must be created here with PyMEM_malloc())*/
1842 PyObject *newMatrixObject(float *mat, const unsigned short rowSize, const unsigned short colSize, int type, PyTypeObject *base_type)
1843 {
1844         MatrixObject *self;
1845         int x, row, col;
1846
1847         /*matrix objects can be any 2-4row x 2-4col matrix*/
1848         if(rowSize < 2 || rowSize > 4 || colSize < 2 || colSize > 4){
1849                 PyErr_SetString(PyExc_RuntimeError, "matrix(): row and column sizes must be between 2 and 4");
1850                 return NULL;
1851         }
1852
1853         if(base_type)   self = (MatrixObject *)base_type->tp_alloc(base_type, 0);
1854         else                    self = PyObject_NEW(MatrixObject, &matrix_Type);
1855
1856         self->rowSize = rowSize;
1857         self->colSize = colSize;
1858
1859         /* init callbacks as NULL */
1860         self->cb_user= NULL;
1861         self->cb_type= self->cb_subtype= 0;
1862
1863         if(type == Py_WRAP){
1864                 self->contigPtr = mat;
1865                 /*pointer array points to contigous memory*/
1866                 for(x = 0; x < rowSize; x++) {
1867                         self->matrix[x] = self->contigPtr + (x * colSize);
1868                 }
1869                 self->wrapped = Py_WRAP;
1870         }else if (type == Py_NEW){
1871                 self->contigPtr = PyMem_Malloc(rowSize * colSize * sizeof(float));
1872                 if(self->contigPtr == NULL) { /*allocation failure*/
1873                         PyErr_SetString(PyExc_MemoryError, "matrix(): problem allocating pointer space");
1874                         return NULL;
1875                 }
1876                 /*pointer array points to contigous memory*/
1877                 for(x = 0; x < rowSize; x++) {
1878                         self->matrix[x] = self->contigPtr + (x * colSize);
1879                 }
1880                 /*parse*/
1881                 if(mat) {       /*if a float array passed*/
1882                         for(row = 0; row < rowSize; row++) {
1883                                 for(col = 0; col < colSize; col++) {
1884                                         self->matrix[row][col] = mat[(row * colSize) + col];
1885                                 }
1886                         }
1887                 } else if (rowSize == colSize ) { /*or if no arguments are passed return identity matrix for square matrices */
1888                         PyObject *ret_dummy= Matrix_identity(self);
1889                         Py_DECREF(ret_dummy);
1890                 }
1891                 self->wrapped = Py_NEW;
1892         }else{ /*bad type*/
1893                 return NULL;
1894         }
1895         return (PyObject *) self;
1896 }
1897
1898 PyObject *newMatrixObject_cb(PyObject *cb_user, int rowSize, int colSize, int cb_type, int cb_subtype)
1899 {
1900         MatrixObject *self= (MatrixObject *)newMatrixObject(NULL, rowSize, colSize, Py_NEW, NULL);
1901         if(self) {
1902                 Py_INCREF(cb_user);
1903                 self->cb_user=                  cb_user;
1904                 self->cb_type=                  (unsigned char)cb_type;
1905                 self->cb_subtype=               (unsigned char)cb_subtype;
1906         }
1907         return (PyObject *) self;
1908 }