8f8d3267cc6e74895779ab22ca26ce84b03308ea
[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 static 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_quat()\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 "\n"
737 "   :return: an instance of itself.\n"
738 "   :rtype: :class:`Matrix`\n"
739 ;
740 static PyObject *Matrix_resize_4x4(MatrixObject *self)
741 {
742         int x, first_row_elem, curr_pos, new_pos, blank_columns, blank_rows, index;
743
744         if(self->wrapped==Py_WRAP){
745                 PyErr_SetString(PyExc_TypeError, "cannot resize wrapped data - make a copy and resize that");
746                 return NULL;
747         }
748         if(self->cb_user){
749                 PyErr_SetString(PyExc_TypeError, "cannot resize owned data - make a copy and resize that");
750                 return NULL;
751         }
752
753         self->contigPtr = PyMem_Realloc(self->contigPtr, (sizeof(float) * 16));
754         if(self->contigPtr == NULL) {
755                 PyErr_SetString(PyExc_MemoryError, "matrix.resize_4x4(): problem allocating pointer space");
756                 return NULL;
757         }
758         /*set row pointers*/
759         for(x = 0; x < 4; x++) {
760                 self->matrix[x] = self->contigPtr + (x * 4);
761         }
762         /*move data to new spot in array + clean*/
763         for(blank_rows = (4 - self->rowSize); blank_rows > 0; blank_rows--){
764                 for(x = 0; x < 4; x++){
765                         index = (4 * (self->rowSize + (blank_rows - 1))) + x;
766                         if (index == 10 || index == 15){
767                                 self->contigPtr[index] = 1.0f;
768                         }else{
769                                 self->contigPtr[index] = 0.0f;
770                         }
771                 }
772         }
773         for(x = 1; x <= self->rowSize; x++){
774                 first_row_elem = (self->colSize * (self->rowSize - x));
775                 curr_pos = (first_row_elem + (self->colSize -1));
776                 new_pos = (4 * (self->rowSize - x )) + (curr_pos - first_row_elem);
777                 for(blank_columns = (4 - self->colSize); blank_columns > 0; blank_columns--){
778                         self->contigPtr[new_pos + blank_columns] = 0.0f;
779                 }
780                 for(curr_pos = curr_pos; curr_pos >= first_row_elem; curr_pos--){
781                         self->contigPtr[new_pos] = self->contigPtr[curr_pos];
782                         new_pos--;
783                 }
784         }
785         self->rowSize = 4;
786         self->colSize = 4;
787
788         Py_INCREF(self);
789         return (PyObject *)self;
790 }
791
792 static char Matrix_to_4x4_doc[] =
793 ".. method:: to_4x4()\n"
794 "\n"
795 "   Return a 4x4 copy of this matrix.\n"
796 "\n"
797 "   :return: a new matrix.\n"
798 "   :rtype: :class:`Matrix`\n"
799 ;
800 static PyObject *Matrix_to_4x4(MatrixObject *self)
801 {
802         if(!BaseMath_ReadCallback(self))
803                 return NULL;
804
805         if(self->colSize==4 && self->rowSize==4) {
806                 return (PyObject *)newMatrixObject(self->contigPtr, 4, 4, Py_NEW, Py_TYPE(self));
807         }
808         else if(self->colSize==3 && self->rowSize==3) {
809                 float mat[4][4];
810                 copy_m4_m3(mat, (float (*)[3])self->contigPtr);
811                 return (PyObject *)newMatrixObject((float *)mat, 4, 4, Py_NEW, Py_TYPE(self));
812         }
813         /* TODO, 2x2 matrix */
814
815         PyErr_SetString(PyExc_TypeError, "Matrix.to_4x4(): inappropriate matrix size");
816         return NULL;
817 }
818
819 static char Matrix_to_3x3_doc[] =
820 ".. method:: to_3x3()\n"
821 "\n"
822 "   Return a 3x3 copy of this matrix.\n"
823 "\n"
824 "   :return: a new matrix.\n"
825 "   :rtype: :class:`Matrix`\n"
826 ;
827 static PyObject *Matrix_to_3x3(MatrixObject *self)
828 {
829         float mat[3][3];
830
831         if(!BaseMath_ReadCallback(self))
832                 return NULL;
833
834         if((self->colSize < 3) || (self->rowSize < 3)) {
835                 PyErr_SetString(PyExc_AttributeError, "Matrix.to_3x3(): inappropriate matrix size");
836                 return NULL;
837         }
838
839         matrix_as_3x3(mat, self);
840
841         return newMatrixObject((float *)mat, 3, 3, Py_NEW, Py_TYPE(self));
842 }
843
844 static char Matrix_to_translation_doc[] =
845 ".. method:: to_translation()\n"
846 "\n"
847 "   Return a the translation part of a 4 row matrix.\n"
848 "\n"
849 "   :return: Return a the translation of a matrix.\n"
850 "   :rtype: :class:`Vector`\n"
851 ;
852 static PyObject *Matrix_to_translation(MatrixObject *self)
853 {
854         if(!BaseMath_ReadCallback(self))
855                 return NULL;
856
857         if((self->colSize < 3) || self->rowSize < 4){
858                 PyErr_SetString(PyExc_AttributeError, "Matrix.to_translation(): inappropriate matrix size");
859                 return NULL;
860         }
861
862         return newVectorObject(self->matrix[3], 3, Py_NEW, NULL);
863 }
864
865 static char Matrix_to_scale_doc[] =
866 ".. method:: to_scale()\n"
867 "\n"
868 "   Return a the scale part of a 3x3 or 4x4 matrix.\n"
869 "\n"
870 "   :return: Return a the scale of a matrix.\n"
871 "   :rtype: :class:`Vector`\n"
872 "\n"
873 "   .. 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"
874 ;
875 static PyObject *Matrix_to_scale(MatrixObject *self)
876 {
877         float rot[3][3];
878         float mat[3][3];
879         float size[3];
880
881         if(!BaseMath_ReadCallback(self))
882                 return NULL;
883
884         /*must be 3-4 cols, 3-4 rows, square matrix*/
885         if((self->colSize < 3) || (self->rowSize < 3)) {
886                 PyErr_SetString(PyExc_AttributeError, "Matrix.to_scale(): inappropriate matrix size, 3x3 minimum size");
887                 return NULL;
888         }
889
890         matrix_as_3x3(mat, self);
891
892         /* compatible mat4_to_loc_rot_size */
893         mat3_to_rot_size(rot, size, mat);
894
895         return newVectorObject(size, 3, Py_NEW, NULL);
896 }
897
898 /*---------------------------Matrix.invert() ---------------------*/
899 static char Matrix_invert_doc[] =
900 ".. method:: invert()\n"
901 "\n"
902 "   Set the matrix to its inverse.\n"
903 "\n"
904 "   :return: an instance of itself.\n"
905 "   :rtype: :class:`Matrix`\n"
906 "\n"
907 "   .. note:: :exc:`ValueError` exception is raised.\n"
908 "\n"
909 "   .. seealso:: <http://en.wikipedia.org/wiki/Inverse_matrix>\n"
910 ;
911 static PyObject *Matrix_invert(MatrixObject *self)
912 {
913
914         int x, y, z = 0;
915         float det = 0.0f;
916         float mat[16] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
917                 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
918
919         if(!BaseMath_ReadCallback(self))
920                 return NULL;
921
922         if(self->rowSize != self->colSize){
923                 PyErr_SetString(PyExc_AttributeError, "Matrix.invert(ed): only square matrices are supported");
924                 return NULL;
925         }
926
927         /*calculate the determinant*/
928         det = matrix_determinant_internal(self);
929
930         if(det != 0) {
931                 /*calculate the classical adjoint*/
932                 if(self->rowSize == 2) {
933                         mat[0] = self->matrix[1][1];
934                         mat[1] = -self->matrix[0][1];
935                         mat[2] = -self->matrix[1][0];
936                         mat[3] = self->matrix[0][0];
937                 } else if(self->rowSize == 3) {
938                         adjoint_m3_m3((float (*)[3]) mat,(float (*)[3])self->contigPtr);
939                 } else if(self->rowSize == 4) {
940                         adjoint_m4_m4((float (*)[4]) mat, (float (*)[4])self->contigPtr);
941                 }
942                 /*divide by determinate*/
943                 for(x = 0; x < (self->rowSize * self->colSize); x++) {
944                         mat[x] /= det;
945                 }
946                 /*set values*/
947                 for(x = 0; x < self->rowSize; x++) {
948                         for(y = 0; y < self->colSize; y++) {
949                                 self->matrix[x][y] = mat[z];
950                                 z++;
951                         }
952                 }
953                 /*transpose
954                 Matrix_transpose(self);*/
955         } else {
956                 PyErr_SetString(PyExc_ValueError, "matrix does not have an inverse");
957                 return NULL;
958         }
959
960         (void)BaseMath_WriteCallback(self);
961         Py_RETURN_NONE;
962 }
963
964 static char Matrix_inverted_doc[] =
965 ".. method:: invert()\n"
966 "\n"
967 "   Return an inverted copy of the matrix.\n"
968 "\n"
969 "   :return: the  inverted matrix.\n"
970 "   :rtype: :class:`Matrix`\n"
971 "\n"
972 "   .. note:: :exc:`ValueError` exception is raised.\n"
973 ;
974 static PyObject *Matrix_inverted(MatrixObject *self)
975 {
976         MATRIX_APPLY_TO_COPY(Matrix_invert, self);
977 }
978
979 /*---------------------------Matrix.decompose() ---------------------*/
980 static char Matrix_decompose_doc[] =
981 ".. method:: decompose()\n"
982 "\n"
983 "   Return the location, rotaion and scale components of this matrix.\n"
984 "\n"
985 "   :return: loc, rot, scale triple.\n"
986 "   :rtype: (:class:`Vector`, :class:`Quaternion`, :class:`Vector`)"
987 ;
988 static PyObject *Matrix_decompose(MatrixObject *self)
989 {
990         PyObject *ret;
991         float loc[3];
992         float rot[3][3];
993         float quat[4];
994         float size[3];
995
996         if(self->colSize != 4 || self->rowSize != 4) {
997                 PyErr_SetString(PyExc_AttributeError, "Matrix.decompose(): inappropriate matrix size - expects 4x4 matrix");
998                 return NULL;
999         }
1000
1001         if(!BaseMath_ReadCallback(self))
1002                 return NULL;
1003
1004         mat4_to_loc_rot_size(loc, rot, size, (float (*)[4])self->contigPtr);
1005         mat3_to_quat(quat, rot);
1006
1007         ret= PyTuple_New(3);
1008         PyTuple_SET_ITEM(ret, 0, newVectorObject(loc, 3, Py_NEW, NULL));
1009         PyTuple_SET_ITEM(ret, 1, newQuaternionObject(quat, Py_NEW, NULL));
1010         PyTuple_SET_ITEM(ret, 2, newVectorObject(size, 3, Py_NEW, NULL));
1011
1012         return ret;
1013 }
1014
1015
1016
1017 static char Matrix_lerp_doc[] =
1018 ".. function:: lerp(other, factor)\n"
1019 "\n"
1020 "   Returns the interpolation of two matricies.\n"
1021 "\n"
1022 "   :arg other: value to interpolate with.\n"
1023 "   :type other: :class:`Matrix`\n"
1024 "   :arg factor: The interpolation value in [0.0, 1.0].\n"
1025 "   :type factor: float\n"
1026 "   :return: The interpolated rotation.\n"
1027 "   :rtype: :class:`Matrix`\n"
1028 ;
1029 static PyObject *Matrix_lerp(MatrixObject *self, PyObject *args)
1030 {
1031         MatrixObject *mat2 = NULL;
1032         float fac, mat[MATRIX_MAX_DIM*MATRIX_MAX_DIM];
1033
1034         if(!PyArg_ParseTuple(args, "O!f:lerp", &matrix_Type, &mat2, &fac))
1035                 return NULL;
1036
1037         if(self->rowSize != mat2->rowSize || self->colSize != mat2->colSize) {
1038                 PyErr_SetString(PyExc_AttributeError, "matrix.lerp(): expects both matrix objects of the same dimensions");
1039                 return NULL;
1040         }
1041
1042         if(!BaseMath_ReadCallback(self) || !BaseMath_ReadCallback(mat2))
1043                 return NULL;
1044
1045         /* TODO, different sized matrix */
1046         if(self->rowSize==4 && self->colSize==4) {
1047                 blend_m4_m4m4((float (*)[4])mat, (float (*)[4])self->contigPtr, (float (*)[4])mat2->contigPtr, fac);
1048         }
1049         else if (self->rowSize==3 && self->colSize==3) {
1050                 blend_m3_m3m3((float (*)[3])mat, (float (*)[3])self->contigPtr, (float (*)[3])mat2->contigPtr, fac);
1051         }
1052         else {
1053                 PyErr_SetString(PyExc_AttributeError, "matrix.lerp(): only 3x3 and 4x4 matrices supported");
1054                 return NULL;
1055         }
1056
1057         return (PyObject*)newMatrixObject(mat, self->rowSize, self->colSize, Py_NEW, Py_TYPE(self));
1058 }
1059
1060 /*---------------------------Matrix.determinant() ----------------*/
1061 static char Matrix_determinant_doc[] =
1062 ".. method:: determinant()\n"
1063 "\n"
1064 "   Return the determinant of a matrix.\n"
1065 "\n"
1066 "   :return: Return a the determinant of a matrix.\n"
1067 "   :rtype: float\n"
1068 "\n"
1069 "   .. seealso:: <http://en.wikipedia.org/wiki/Determinant>\n"
1070 ;
1071 static PyObject *Matrix_determinant(MatrixObject *self)
1072 {
1073         if(!BaseMath_ReadCallback(self))
1074                 return NULL;
1075
1076         if(self->rowSize != self->colSize){
1077                 PyErr_SetString(PyExc_AttributeError, "Matrix.determinant: only square matrices are supported");
1078                 return NULL;
1079         }
1080
1081         return PyFloat_FromDouble((double)matrix_determinant_internal(self));
1082 }
1083 /*---------------------------Matrix.transpose() ------------------*/
1084 static char Matrix_transpose_doc[] =
1085 ".. method:: transpose()\n"
1086 "\n"
1087 "   Set the matrix to its transpose.\n"
1088 "\n"
1089 "   .. seealso:: <http://en.wikipedia.org/wiki/Transpose>\n"
1090 ;
1091 static PyObject *Matrix_transpose(MatrixObject *self)
1092 {
1093         float t = 0.0f;
1094
1095         if(!BaseMath_ReadCallback(self))
1096                 return NULL;
1097
1098         if(self->rowSize != self->colSize){
1099                 PyErr_SetString(PyExc_AttributeError, "Matrix.transpose(d): only square matrices are supported");
1100                 return NULL;
1101         }
1102
1103         if(self->rowSize == 2) {
1104                 t = self->matrix[1][0];
1105                 self->matrix[1][0] = self->matrix[0][1];
1106                 self->matrix[0][1] = t;
1107         } else if(self->rowSize == 3) {
1108                 transpose_m3((float (*)[3])self->contigPtr);
1109         } else {
1110                 transpose_m4((float (*)[4])self->contigPtr);
1111         }
1112
1113         (void)BaseMath_WriteCallback(self);
1114         Py_RETURN_NONE;
1115 }
1116
1117 static char Matrix_transposed_doc[] =
1118 ".. method:: transposed()\n"
1119 "\n"
1120 "   Return a new, transposed matrix.\n"
1121 "\n"
1122 "   :return: a transposed matrix\n"
1123 "   :rtype: :class:`Matrix`\n"
1124 ;
1125 static PyObject *Matrix_transposed(MatrixObject *self)
1126 {
1127         MATRIX_APPLY_TO_COPY(Matrix_transpose, self);
1128 }
1129
1130 /*---------------------------Matrix.zero() -----------------------*/
1131 static char Matrix_zero_doc[] =
1132 ".. method:: zero()\n"
1133 "\n"
1134 "   Set all the matrix values to zero.\n"
1135 "\n"
1136 "   :return: an instance of itself\n"
1137 "   :rtype: :class:`Matrix`\n"
1138 ;
1139 static PyObject *Matrix_zero(MatrixObject *self)
1140 {
1141         fill_vn(self->contigPtr, self->rowSize * self->colSize, 0.0f);
1142
1143         if(!BaseMath_WriteCallback(self))
1144                 return NULL;
1145
1146         Py_RETURN_NONE;
1147 }
1148 /*---------------------------Matrix.identity(() ------------------*/
1149 static char Matrix_identity_doc[] =
1150 ".. method:: identity()\n"
1151 "\n"
1152 "   Set the matrix to the identity matrix.\n"
1153 "\n"
1154 "   .. note:: An object with zero location and rotation, a scale of one, will have an identity matrix.\n"
1155 "\n"
1156 "   .. seealso:: <http://en.wikipedia.org/wiki/Identity_matrix>\n"
1157 ;
1158 static PyObject *Matrix_identity(MatrixObject *self)
1159 {
1160         if(!BaseMath_ReadCallback(self))
1161                 return NULL;
1162
1163         if(self->rowSize != self->colSize){
1164                 PyErr_SetString(PyExc_AttributeError, "Matrix.identity: only square matrices are supported");
1165                 return NULL;
1166         }
1167
1168         if(self->rowSize == 2) {
1169                 self->matrix[0][0] = 1.0f;
1170                 self->matrix[0][1] = 0.0f;
1171                 self->matrix[1][0] = 0.0f;
1172                 self->matrix[1][1] = 1.0f;
1173         } else if(self->rowSize == 3) {
1174                 unit_m3((float (*)[3])self->contigPtr);
1175         } else {
1176                 unit_m4((float (*)[4])self->contigPtr);
1177         }
1178
1179         if(!BaseMath_WriteCallback(self))
1180                 return NULL;
1181
1182         Py_RETURN_NONE;
1183 }
1184
1185 /*---------------------------Matrix.copy() ------------------*/
1186 static char Matrix_copy_doc[] =
1187 ".. method:: copy()\n"
1188 "\n"
1189 "   Returns a copy of this matrix.\n"
1190 "\n"
1191 "   :return: an instance of itself\n"
1192 "   :rtype: :class:`Matrix`\n"
1193 ;
1194 static PyObject *Matrix_copy(MatrixObject *self)
1195 {
1196         if(!BaseMath_ReadCallback(self))
1197                 return NULL;
1198
1199         return (PyObject*)newMatrixObject((float (*))self->contigPtr, self->rowSize, self->colSize, Py_NEW, Py_TYPE(self));
1200 }
1201
1202 /*----------------------------print object (internal)-------------*/
1203 /*print the object to screen*/
1204 static PyObject *Matrix_repr(MatrixObject *self)
1205 {
1206         int x, y;
1207         PyObject *rows[MATRIX_MAX_DIM]= {0};
1208
1209         if(!BaseMath_ReadCallback(self))
1210                 return NULL;
1211
1212         for(x = 0; x < self->rowSize; x++){
1213                 rows[x]= PyTuple_New(self->colSize);
1214                 for(y = 0; y < self->colSize; y++) {
1215                         PyTuple_SET_ITEM(rows[x], y, PyFloat_FromDouble(self->matrix[x][y]));
1216                 }
1217         }
1218         switch(self->rowSize) {
1219         case 2: return PyUnicode_FromFormat("Matrix(%R,\n"
1220                                                                                 "       %R)", rows[0], rows[1]);
1221
1222         case 3: return PyUnicode_FromFormat("Matrix(%R,\n"
1223                                                                                 "       %R,\n"
1224                                                                                 "       %R)", rows[0], rows[1], rows[2]);
1225
1226         case 4: return PyUnicode_FromFormat("Matrix(%R,\n"
1227                                                                                 "       %R,\n"
1228                                                                                 "       %R,\n"
1229                                                                                 "       %R)", rows[0], rows[1], rows[2], rows[3]);
1230         }
1231
1232         PyErr_SetString(PyExc_RuntimeError, "invalid matrix size");
1233         return NULL;
1234 }
1235
1236 /*------------------------tp_richcmpr*/
1237 /*returns -1 execption, 0 false, 1 true*/
1238 static PyObject* Matrix_richcmpr(PyObject *objectA, PyObject *objectB, int comparison_type)
1239 {
1240         MatrixObject *matA = NULL, *matB = NULL;
1241         int result = 0;
1242
1243         if (!MatrixObject_Check(objectA) || !MatrixObject_Check(objectB)){
1244                 if (comparison_type == Py_NE){
1245                         Py_RETURN_TRUE;
1246                 }else{
1247                         Py_RETURN_FALSE;
1248                 }
1249         }
1250         matA = (MatrixObject*)objectA;
1251         matB = (MatrixObject*)objectB;
1252
1253         if(!BaseMath_ReadCallback(matA) || !BaseMath_ReadCallback(matB))
1254                 return NULL;
1255
1256         if (matA->colSize != matB->colSize || matA->rowSize != matB->rowSize){
1257                 if (comparison_type == Py_NE){
1258                         Py_RETURN_TRUE;
1259                 }else{
1260                         Py_RETURN_FALSE;
1261                 }
1262         }
1263
1264         switch (comparison_type){
1265                 case Py_EQ:
1266                         /*contigPtr is basically a really long vector*/
1267                         result = EXPP_VectorsAreEqual(matA->contigPtr, matB->contigPtr,
1268                                 (matA->rowSize * matA->colSize), 1);
1269                         break;
1270                 case Py_NE:
1271                         result = EXPP_VectorsAreEqual(matA->contigPtr, matB->contigPtr,
1272                                 (matA->rowSize * matA->colSize), 1);
1273                         if (result == 0){
1274                                 result = 1;
1275                         }else{
1276                                 result = 0;
1277                         }
1278                         break;
1279                 default:
1280                         printf("The result of the comparison could not be evaluated");
1281                         break;
1282         }
1283         if (result == 1){
1284                 Py_RETURN_TRUE;
1285         }else{
1286                 Py_RETURN_FALSE;
1287         }
1288 }
1289
1290 /*---------------------SEQUENCE PROTOCOLS------------------------
1291   ----------------------------len(object)------------------------
1292   sequence length*/
1293 static int Matrix_len(MatrixObject *self)
1294 {
1295         return (self->rowSize);
1296 }
1297 /*----------------------------object[]---------------------------
1298   sequence accessor (get)
1299   the wrapped vector gives direct access to the matrix data*/
1300 static PyObject *Matrix_item(MatrixObject *self, int i)
1301 {
1302         if(!BaseMath_ReadCallback(self))
1303                 return NULL;
1304
1305         if(i < 0 || i >= self->rowSize) {
1306                 PyErr_SetString(PyExc_IndexError, "matrix[attribute]: array index out of range");
1307                 return NULL;
1308         }
1309         return newVectorObject_cb((PyObject *)self, self->colSize, mathutils_matrix_vector_cb_index, i);
1310 }
1311 /*----------------------------object[]-------------------------
1312   sequence accessor (set) */
1313
1314 static int Matrix_ass_item(MatrixObject *self, int i, PyObject *value)
1315 {
1316         float vec[4];
1317         if(!BaseMath_ReadCallback(self))
1318                 return -1;
1319
1320         if(i >= self->rowSize || i < 0){
1321                 PyErr_SetString(PyExc_TypeError, "matrix[attribute] = x: bad column");
1322                 return -1;
1323         }
1324
1325         if(mathutils_array_parse(vec, self->colSize, self->colSize, value, "matrix[i] = value assignment") < 0) {
1326                 return -1;
1327         }
1328
1329         memcpy(self->matrix[i], vec, self->colSize *sizeof(float));
1330
1331         (void)BaseMath_WriteCallback(self);
1332         return 0;
1333 }
1334
1335 /*----------------------------object[z:y]------------------------
1336   sequence slice (get)*/
1337 static PyObject *Matrix_slice(MatrixObject *self, int begin, int end)
1338 {
1339
1340         PyObject *tuple;
1341         int count;
1342
1343         if(!BaseMath_ReadCallback(self))
1344                 return NULL;
1345
1346         CLAMP(begin, 0, self->rowSize);
1347         CLAMP(end, 0, self->rowSize);
1348         begin= MIN2(begin,end);
1349
1350         tuple= PyTuple_New(end - begin);
1351         for(count= begin; count < end; count++) {
1352                 PyTuple_SET_ITEM(tuple, count - begin,
1353                                 newVectorObject_cb((PyObject *)self, self->colSize, mathutils_matrix_vector_cb_index, count));
1354
1355         }
1356
1357         return tuple;
1358 }
1359 /*----------------------------object[z:y]------------------------
1360   sequence slice (set)*/
1361 static int Matrix_ass_slice(MatrixObject *self, int begin, int end, PyObject *value)
1362 {
1363         PyObject *value_fast= NULL;
1364
1365         if(!BaseMath_ReadCallback(self))
1366                 return -1;
1367
1368         CLAMP(begin, 0, self->rowSize);
1369         CLAMP(end, 0, self->rowSize);
1370         begin = MIN2(begin,end);
1371
1372         /* non list/tuple cases */
1373         if(!(value_fast=PySequence_Fast(value, "matrix[begin:end] = value"))) {
1374                 /* PySequence_Fast sets the error */
1375                 return -1;
1376         }
1377         else {
1378                 const int size= end - begin;
1379                 int i;
1380                 float mat[16];
1381
1382                 if(PySequence_Fast_GET_SIZE(value_fast) != size) {
1383                         Py_DECREF(value_fast);
1384                         PyErr_SetString(PyExc_TypeError, "matrix[begin:end] = []: size mismatch in slice assignment");
1385                         return -1;
1386                 }
1387
1388                 /*parse sub items*/
1389                 for (i = 0; i < size; i++) {
1390                         /*parse each sub sequence*/
1391                         PyObject *item= PySequence_Fast_GET_ITEM(value_fast, i);
1392
1393                         if(mathutils_array_parse(&mat[i * self->colSize], self->colSize, self->colSize, item, "matrix[begin:end] = value assignment") < 0) {
1394                                 return -1;
1395                         }
1396                 }
1397
1398                 Py_DECREF(value_fast);
1399
1400                 /*parsed well - now set in matrix*/
1401                 memcpy(self->contigPtr + (begin * self->colSize), mat, sizeof(float) * (size * self->colSize));
1402
1403                 (void)BaseMath_WriteCallback(self);
1404                 return 0;
1405         }
1406 }
1407 /*------------------------NUMERIC PROTOCOLS----------------------
1408   ------------------------obj + obj------------------------------*/
1409 static PyObject *Matrix_add(PyObject *m1, PyObject *m2)
1410 {
1411         float mat[16];
1412         MatrixObject *mat1 = NULL, *mat2 = NULL;
1413
1414         mat1 = (MatrixObject*)m1;
1415         mat2 = (MatrixObject*)m2;
1416
1417         if(!MatrixObject_Check(m1) || !MatrixObject_Check(m2)) {
1418                 PyErr_SetString(PyExc_AttributeError, "Matrix addition: arguments not valid for this operation");
1419                 return NULL;
1420         }
1421
1422         if(!BaseMath_ReadCallback(mat1) || !BaseMath_ReadCallback(mat2))
1423                 return NULL;
1424
1425         if(mat1->rowSize != mat2->rowSize || mat1->colSize != mat2->colSize){
1426                 PyErr_SetString(PyExc_AttributeError, "Matrix addition: matrices must have the same dimensions for this operation");
1427                 return NULL;
1428         }
1429
1430         add_vn_vnvn(mat, mat1->contigPtr, mat2->contigPtr, mat1->rowSize * mat1->colSize);
1431
1432         return newMatrixObject(mat, mat1->rowSize, mat1->colSize, Py_NEW, Py_TYPE(mat1));
1433 }
1434 /*------------------------obj - obj------------------------------
1435   subtraction*/
1436 static PyObject *Matrix_sub(PyObject *m1, PyObject *m2)
1437 {
1438         float mat[16];
1439         MatrixObject *mat1 = NULL, *mat2 = NULL;
1440
1441         mat1 = (MatrixObject*)m1;
1442         mat2 = (MatrixObject*)m2;
1443
1444         if(!MatrixObject_Check(m1) || !MatrixObject_Check(m2)) {
1445                 PyErr_SetString(PyExc_AttributeError, "Matrix addition: arguments not valid for this operation");
1446                 return NULL;
1447         }
1448
1449         if(!BaseMath_ReadCallback(mat1) || !BaseMath_ReadCallback(mat2))
1450                 return NULL;
1451
1452         if(mat1->rowSize != mat2->rowSize || mat1->colSize != mat2->colSize){
1453                 PyErr_SetString(PyExc_AttributeError, "Matrix addition: matrices must have the same dimensions for this operation");
1454                 return NULL;
1455         }
1456
1457         sub_vn_vnvn(mat, mat1->contigPtr, mat2->contigPtr, mat1->rowSize * mat1->colSize);
1458
1459         return newMatrixObject(mat, mat1->rowSize, mat1->colSize, Py_NEW, Py_TYPE(mat1));
1460 }
1461 /*------------------------obj * obj------------------------------
1462   mulplication*/
1463 static PyObject *matrix_mul_float(MatrixObject *mat, const float scalar)
1464 {
1465         float tmat[16];
1466         mul_vn_vn_fl(tmat, mat->contigPtr, mat->rowSize * mat->colSize, scalar);
1467         return newMatrixObject(tmat, mat->rowSize, mat->colSize, Py_NEW, Py_TYPE(mat));
1468 }
1469
1470 static PyObject *Matrix_mul(PyObject * m1, PyObject * m2)
1471 {
1472         float scalar;
1473
1474         MatrixObject *mat1 = NULL, *mat2 = NULL;
1475
1476         if(MatrixObject_Check(m1)) {
1477                 mat1 = (MatrixObject*)m1;
1478                 if(!BaseMath_ReadCallback(mat1))
1479                         return NULL;
1480         }
1481         if(MatrixObject_Check(m2)) {
1482                 mat2 = (MatrixObject*)m2;
1483                 if(!BaseMath_ReadCallback(mat2))
1484                         return NULL;
1485         }
1486
1487         if(mat1 && mat2) { /*MATRIX * MATRIX*/
1488                 if(mat1->rowSize != mat2->colSize){
1489                         PyErr_SetString(PyExc_AttributeError,"Matrix multiplication: matrix A rowsize must equal matrix B colsize");
1490                         return NULL;
1491                 }
1492                 else {
1493                         float mat[16]= {0.0f, 0.0f, 0.0f, 0.0f,
1494                                                         0.0f, 0.0f, 0.0f, 0.0f,
1495                                                         0.0f, 0.0f, 0.0f, 0.0f,
1496                                                         0.0f, 0.0f, 0.0f, 1.0f};
1497                         double dot = 0.0f;
1498                         int x, y, z;
1499
1500                         for(x = 0; x < mat2->rowSize; x++) {
1501                                 for(y = 0; y < mat1->colSize; y++) {
1502                                         for(z = 0; z < mat1->rowSize; z++) {
1503                                                 dot += (mat1->matrix[z][y] * mat2->matrix[x][z]);
1504                                         }
1505                                         mat[((x * mat1->colSize) + y)] = (float)dot;
1506                                         dot = 0.0f;
1507                                 }
1508                         }
1509
1510                         return newMatrixObject(mat, mat2->rowSize, mat1->colSize, Py_NEW, Py_TYPE(mat1));
1511                 }
1512         }
1513         else if(mat2) {
1514                 if (((scalar= PyFloat_AsDouble(m1)) == -1.0 && PyErr_Occurred())==0) { /*FLOAT/INT * MATRIX */
1515                         return matrix_mul_float(mat2, scalar);
1516                 }
1517         }
1518         else if(mat1) {
1519                 if (((scalar= PyFloat_AsDouble(m2)) == -1.0 && PyErr_Occurred())==0) { /*FLOAT/INT * MATRIX */
1520                         return matrix_mul_float(mat1, scalar);
1521                 }
1522         }
1523         else {
1524                 BLI_assert(!"internal error");
1525         }
1526
1527         PyErr_Format(PyExc_TypeError, "Matrix multiplication: not supported between '%.200s' and '%.200s' types", Py_TYPE(m1)->tp_name, Py_TYPE(m2)->tp_name);
1528         return NULL;
1529 }
1530 static PyObject* Matrix_inv(MatrixObject *self)
1531 {
1532         if(!BaseMath_ReadCallback(self))
1533                 return NULL;
1534
1535         return Matrix_invert(self);
1536 }
1537
1538 /*-----------------PROTOCOL DECLARATIONS--------------------------*/
1539 static PySequenceMethods Matrix_SeqMethods = {
1540         (lenfunc) Matrix_len,                                           /* sq_length */
1541         (binaryfunc) NULL,                                                      /* sq_concat */
1542         (ssizeargfunc) NULL,                                            /* sq_repeat */
1543         (ssizeargfunc) Matrix_item,                                     /* sq_item */
1544         (ssizessizeargfunc) NULL,                                       /* sq_slice, deprecated */
1545         (ssizeobjargproc) Matrix_ass_item,                      /* sq_ass_item */
1546         (ssizessizeobjargproc) NULL,                            /* sq_ass_slice, deprecated */
1547         (objobjproc) NULL,                                                      /* sq_contains */
1548         (binaryfunc) NULL,                                                      /* sq_inplace_concat */
1549         (ssizeargfunc) NULL,                                            /* sq_inplace_repeat */
1550 };
1551
1552
1553 static PyObject *Matrix_subscript(MatrixObject* self, PyObject* item)
1554 {
1555         if (PyIndex_Check(item)) {
1556                 Py_ssize_t i;
1557                 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
1558                 if (i == -1 && PyErr_Occurred())
1559                         return NULL;
1560                 if (i < 0)
1561                         i += self->rowSize;
1562                 return Matrix_item(self, i);
1563         } else if (PySlice_Check(item)) {
1564                 Py_ssize_t start, stop, step, slicelength;
1565
1566                 if (PySlice_GetIndicesEx((void *)item, self->rowSize, &start, &stop, &step, &slicelength) < 0)
1567                         return NULL;
1568
1569                 if (slicelength <= 0) {
1570                         return PyTuple_New(0);
1571                 }
1572                 else if (step == 1) {
1573                         return Matrix_slice(self, start, stop);
1574                 }
1575                 else {
1576                         PyErr_SetString(PyExc_TypeError, "slice steps not supported with matricies");
1577                         return NULL;
1578                 }
1579         }
1580         else {
1581                 PyErr_Format(PyExc_TypeError, "vector indices must be integers, not %.200s", Py_TYPE(item)->tp_name);
1582                 return NULL;
1583         }
1584 }
1585
1586 static int Matrix_ass_subscript(MatrixObject* self, PyObject* item, PyObject* value)
1587 {
1588         if (PyIndex_Check(item)) {
1589                 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
1590                 if (i == -1 && PyErr_Occurred())
1591                         return -1;
1592                 if (i < 0)
1593                         i += self->rowSize;
1594                 return Matrix_ass_item(self, i, value);
1595         }
1596         else if (PySlice_Check(item)) {
1597                 Py_ssize_t start, stop, step, slicelength;
1598
1599                 if (PySlice_GetIndicesEx((void *)item, self->rowSize, &start, &stop, &step, &slicelength) < 0)
1600                         return -1;
1601
1602                 if (step == 1)
1603                         return Matrix_ass_slice(self, start, stop, value);
1604                 else {
1605                         PyErr_SetString(PyExc_TypeError, "slice steps not supported with matricies");
1606                         return -1;
1607                 }
1608         }
1609         else {
1610                 PyErr_Format(PyExc_TypeError, "matrix indices must be integers, not %.200s", Py_TYPE(item)->tp_name);
1611                 return -1;
1612         }
1613 }
1614
1615 static PyMappingMethods Matrix_AsMapping = {
1616         (lenfunc)Matrix_len,
1617         (binaryfunc)Matrix_subscript,
1618         (objobjargproc)Matrix_ass_subscript
1619 };
1620
1621
1622 static PyNumberMethods Matrix_NumMethods = {
1623                 (binaryfunc)    Matrix_add,     /*nb_add*/
1624                 (binaryfunc)    Matrix_sub,     /*nb_subtract*/
1625                 (binaryfunc)    Matrix_mul,     /*nb_multiply*/
1626                 0,                                                      /*nb_remainder*/
1627                 0,                                                      /*nb_divmod*/
1628                 0,                                                      /*nb_power*/
1629                 (unaryfunc)     0,      /*nb_negative*/
1630                 (unaryfunc)     0,      /*tp_positive*/
1631                 (unaryfunc)     0,      /*tp_absolute*/
1632                 (inquiry)       0,      /*tp_bool*/
1633                 (unaryfunc)     Matrix_inv,     /*nb_invert*/
1634                 0,                              /*nb_lshift*/
1635                 (binaryfunc)0,  /*nb_rshift*/
1636                 0,                              /*nb_and*/
1637                 0,                              /*nb_xor*/
1638                 0,                              /*nb_or*/
1639                 0,                              /*nb_int*/
1640                 0,                              /*nb_reserved*/
1641                 0,                              /*nb_float*/
1642                 0,                              /* nb_inplace_add */
1643                 0,                              /* nb_inplace_subtract */
1644                 0,                              /* nb_inplace_multiply */
1645                 0,                              /* nb_inplace_remainder */
1646                 0,                              /* nb_inplace_power */
1647                 0,                              /* nb_inplace_lshift */
1648                 0,                              /* nb_inplace_rshift */
1649                 0,                              /* nb_inplace_and */
1650                 0,                              /* nb_inplace_xor */
1651                 0,                              /* nb_inplace_or */
1652                 0,                              /* nb_floor_divide */
1653                 0,                              /* nb_true_divide */
1654                 0,                              /* nb_inplace_floor_divide */
1655                 0,                              /* nb_inplace_true_divide */
1656                 0,                              /* nb_index */
1657 };
1658
1659 static PyObject *Matrix_getRowSize(MatrixObject *self, void *UNUSED(closure))
1660 {
1661         return PyLong_FromLong((long) self->rowSize);
1662 }
1663
1664 static PyObject *Matrix_getColSize(MatrixObject *self, void *UNUSED(closure))
1665 {
1666         return PyLong_FromLong((long) self->colSize);
1667 }
1668
1669 static PyObject *Matrix_getMedianScale(MatrixObject *self, void *UNUSED(closure))
1670 {
1671         float mat[3][3];
1672
1673         if(!BaseMath_ReadCallback(self))
1674                 return NULL;
1675
1676         /*must be 3-4 cols, 3-4 rows, square matrix*/
1677         if((self->colSize < 3) || (self->rowSize < 3)) {
1678                 PyErr_SetString(PyExc_AttributeError, "Matrix.median_scale: inappropriate matrix size, 3x3 minimum");
1679                 return NULL;
1680         }
1681
1682         matrix_as_3x3(mat, self);
1683
1684         return PyFloat_FromDouble(mat3_to_scale(mat));
1685 }
1686
1687 static PyObject *Matrix_getIsNegative(MatrixObject *self, void *UNUSED(closure))
1688 {
1689         if(!BaseMath_ReadCallback(self))
1690                 return NULL;
1691
1692         /*must be 3-4 cols, 3-4 rows, square matrix*/
1693         if(self->colSize == 4 && self->rowSize == 4)
1694                 return PyBool_FromLong(is_negative_m4((float (*)[4])self->contigPtr));
1695         else if(self->colSize == 3 && self->rowSize == 3)
1696                 return PyBool_FromLong(is_negative_m3((float (*)[3])self->contigPtr));
1697         else {
1698                 PyErr_SetString(PyExc_AttributeError, "Matrix.is_negative: inappropriate matrix size - expects 3x3 or 4x4 matrix");
1699                 return NULL;
1700         }
1701 }
1702
1703
1704 /*****************************************************************************/
1705 /* Python attributes get/set structure:                                      */
1706 /*****************************************************************************/
1707 static PyGetSetDef Matrix_getseters[] = {
1708         {(char *)"row_size", (getter)Matrix_getRowSize, (setter)NULL, (char *)"The row size of the matrix (readonly).\n\n:type: int", NULL},
1709         {(char *)"col_size", (getter)Matrix_getColSize, (setter)NULL, (char *)"The column size of the matrix (readonly).\n\n:type: int", NULL},
1710         {(char *)"median_scale", (getter)Matrix_getMedianScale, (setter)NULL, (char *)"The average scale applied to each axis (readonly).\n\n:type: float", NULL},
1711         {(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},
1712         {(char *)"is_wrapped", (getter)BaseMathObject_getWrapped, (setter)NULL, (char *)BaseMathObject_Wrapped_doc, NULL},
1713         {(char *)"owner",(getter)BaseMathObject_getOwner, (setter)NULL, (char *)BaseMathObject_Owner_doc, NULL},
1714         {NULL,NULL,NULL,NULL,NULL}  /* Sentinel */
1715 };
1716
1717 /*-----------------------METHOD DEFINITIONS ----------------------*/
1718 static struct PyMethodDef Matrix_methods[] = {
1719         /* derived values */
1720         {"determinant", (PyCFunction) Matrix_determinant, METH_NOARGS, Matrix_determinant_doc},
1721         {"decompose", (PyCFunction) Matrix_decompose, METH_NOARGS, Matrix_decompose_doc},
1722
1723         /* in place only */
1724         {"zero", (PyCFunction) Matrix_zero, METH_NOARGS, Matrix_zero_doc},
1725         {"identity", (PyCFunction) Matrix_identity, METH_NOARGS, Matrix_identity_doc},
1726
1727         /* operate on original or copy */
1728         {"transpose", (PyCFunction) Matrix_transpose, METH_NOARGS, Matrix_transpose_doc},
1729         {"transposed", (PyCFunction) Matrix_transposed, METH_NOARGS, Matrix_transposed_doc},
1730         {"invert", (PyCFunction) Matrix_invert, METH_NOARGS, Matrix_invert_doc},
1731         {"inverted", (PyCFunction) Matrix_inverted, METH_NOARGS, Matrix_inverted_doc},
1732         {"to_3x3", (PyCFunction) Matrix_to_3x3, METH_NOARGS, Matrix_to_3x3_doc},
1733         // TODO. {"resize_3x3", (PyCFunction) Matrix_resize3x3, METH_NOARGS, Matrix_resize3x3_doc},
1734         {"to_4x4", (PyCFunction) Matrix_to_4x4, METH_NOARGS, Matrix_to_4x4_doc},
1735         {"resize_4x4", (PyCFunction) Matrix_resize_4x4, METH_NOARGS, Matrix_resize_4x4_doc},
1736
1737         /* return converted representation */
1738         {"to_euler", (PyCFunction) Matrix_to_euler, METH_VARARGS, Matrix_to_euler_doc},
1739         {"to_quaternion", (PyCFunction) Matrix_to_quaternion, METH_NOARGS, Matrix_to_quaternion_doc},
1740         {"to_scale", (PyCFunction) Matrix_to_scale, METH_NOARGS, Matrix_to_scale_doc},
1741         {"to_translation", (PyCFunction) Matrix_to_translation, METH_NOARGS, Matrix_to_translation_doc},
1742
1743         /* operation between 2 or more types  */
1744         {"lerp", (PyCFunction) Matrix_lerp, METH_VARARGS, Matrix_lerp_doc},
1745         {"copy", (PyCFunction) Matrix_copy, METH_NOARGS, Matrix_copy_doc},
1746         {"__copy__", (PyCFunction) Matrix_copy, METH_NOARGS, Matrix_copy_doc},
1747
1748         /* class methods */
1749         {"Rotation", (PyCFunction) C_Matrix_Rotation, METH_VARARGS | METH_CLASS, C_Matrix_Rotation_doc},
1750         {"Scale", (PyCFunction) C_Matrix_Scale, METH_VARARGS | METH_CLASS, C_Matrix_Scale_doc},
1751         {"Shear", (PyCFunction) C_Matrix_Shear, METH_VARARGS | METH_CLASS, C_Matrix_Shear_doc},
1752         {"Translation", (PyCFunction) C_Matrix_Translation, METH_O | METH_CLASS, C_Matrix_Translation_doc},
1753         {"OrthoProjection", (PyCFunction) C_Matrix_OrthoProjection,  METH_VARARGS | METH_CLASS, C_Matrix_OrthoProjection_doc},
1754         {NULL, NULL, 0, NULL}
1755 };
1756
1757 /*------------------PY_OBECT DEFINITION--------------------------*/
1758 static char matrix_doc[] =
1759 "This object gives access to Matrices in Blender."
1760 ;
1761 PyTypeObject matrix_Type = {
1762         PyVarObject_HEAD_INIT(NULL, 0)
1763         "mathutils.Matrix",                                             /*tp_name*/
1764         sizeof(MatrixObject),                   /*tp_basicsize*/
1765         0,                                                              /*tp_itemsize*/
1766         (destructor)BaseMathObject_dealloc,             /*tp_dealloc*/
1767         0,                                                              /*tp_print*/
1768         0,                                                              /*tp_getattr*/
1769         0,                                                              /*tp_setattr*/
1770         0,                                                              /*tp_compare*/
1771         (reprfunc) Matrix_repr,                 /*tp_repr*/
1772         &Matrix_NumMethods,                             /*tp_as_number*/
1773         &Matrix_SeqMethods,                             /*tp_as_sequence*/
1774         &Matrix_AsMapping,                              /*tp_as_mapping*/
1775         0,                                                              /*tp_hash*/
1776         0,                                                              /*tp_call*/
1777         0,                                                              /*tp_str*/
1778         0,                                                              /*tp_getattro*/
1779         0,                                                              /*tp_setattro*/
1780         0,                                                              /*tp_as_buffer*/
1781         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
1782         matrix_doc,                                             /*tp_doc*/
1783         0,                                                              /*tp_traverse*/
1784         0,                                                              /*tp_clear*/
1785         (richcmpfunc)Matrix_richcmpr,   /*tp_richcompare*/
1786         0,                                                              /*tp_weaklistoffset*/
1787         0,                                                              /*tp_iter*/
1788         0,                                                              /*tp_iternext*/
1789         Matrix_methods,                                 /*tp_methods*/
1790         0,                                                              /*tp_members*/
1791         Matrix_getseters,                               /*tp_getset*/
1792         0,                                                              /*tp_base*/
1793         0,                                                              /*tp_dict*/
1794         0,                                                              /*tp_descr_get*/
1795         0,                                                              /*tp_descr_set*/
1796         0,                                                              /*tp_dictoffset*/
1797         0,                                                              /*tp_init*/
1798         0,                                                              /*tp_alloc*/
1799         Matrix_new,                                             /*tp_new*/
1800         0,                                                              /*tp_free*/
1801         0,                                                              /*tp_is_gc*/
1802         0,                                                              /*tp_bases*/
1803         0,                                                              /*tp_mro*/
1804         0,                                                              /*tp_cache*/
1805         0,                                                              /*tp_subclasses*/
1806         0,                                                              /*tp_weaklist*/
1807         0                                                               /*tp_del*/
1808 };
1809
1810 /*------------------------newMatrixObject (internal)-------------
1811 creates a new matrix object
1812 self->matrix     self->contiguous_ptr (reference to data.xxx)
1813            [0]------------->[0]
1814                                                 [1]
1815                                                 [2]
1816            [1]------------->[3]
1817                                                 [4]
1818                                                 [5]
1819
1820 self->matrix[1][1] = self->contigPtr[4] */
1821
1822 /*pass Py_WRAP - if vector is a WRAPPER for data allocated by BLENDER
1823  (i.e. it was allocated elsewhere by MEM_mallocN())
1824   pass Py_NEW - if vector is not a WRAPPER and managed by PYTHON
1825  (i.e. it must be created here with PyMEM_malloc())*/
1826 PyObject *newMatrixObject(float *mat, const unsigned short rowSize, const unsigned short colSize, int type, PyTypeObject *base_type)
1827 {
1828         MatrixObject *self;
1829         int x, row, col;
1830
1831         /*matrix objects can be any 2-4row x 2-4col matrix*/
1832         if(rowSize < 2 || rowSize > 4 || colSize < 2 || colSize > 4){
1833                 PyErr_SetString(PyExc_RuntimeError, "matrix(): row and column sizes must be between 2 and 4");
1834                 return NULL;
1835         }
1836
1837         if(base_type)   self = (MatrixObject *)base_type->tp_alloc(base_type, 0);
1838         else                    self = PyObject_NEW(MatrixObject, &matrix_Type);
1839
1840         self->rowSize = rowSize;
1841         self->colSize = colSize;
1842
1843         /* init callbacks as NULL */
1844         self->cb_user= NULL;
1845         self->cb_type= self->cb_subtype= 0;
1846
1847         if(type == Py_WRAP){
1848                 self->contigPtr = mat;
1849                 /*pointer array points to contigous memory*/
1850                 for(x = 0; x < rowSize; x++) {
1851                         self->matrix[x] = self->contigPtr + (x * colSize);
1852                 }
1853                 self->wrapped = Py_WRAP;
1854         }else if (type == Py_NEW){
1855                 self->contigPtr = PyMem_Malloc(rowSize * colSize * sizeof(float));
1856                 if(self->contigPtr == NULL) { /*allocation failure*/
1857                         PyErr_SetString(PyExc_MemoryError, "matrix(): problem allocating pointer space");
1858                         return NULL;
1859                 }
1860                 /*pointer array points to contigous memory*/
1861                 for(x = 0; x < rowSize; x++) {
1862                         self->matrix[x] = self->contigPtr + (x * colSize);
1863                 }
1864                 /*parse*/
1865                 if(mat) {       /*if a float array passed*/
1866                         for(row = 0; row < rowSize; row++) {
1867                                 for(col = 0; col < colSize; col++) {
1868                                         self->matrix[row][col] = mat[(row * colSize) + col];
1869                                 }
1870                         }
1871                 } else if (rowSize == colSize ) { /*or if no arguments are passed return identity matrix for square matrices */
1872                         PyObject *ret_dummy= Matrix_identity(self);
1873                         Py_DECREF(ret_dummy);
1874                 }
1875                 self->wrapped = Py_NEW;
1876         }else{ /*bad type*/
1877                 return NULL;
1878         }
1879         return (PyObject *) self;
1880 }
1881
1882 PyObject *newMatrixObject_cb(PyObject *cb_user, int rowSize, int colSize, int cb_type, int cb_subtype)
1883 {
1884         MatrixObject *self= (MatrixObject *)newMatrixObject(NULL, rowSize, colSize, Py_NEW, NULL);
1885         if(self) {
1886                 Py_INCREF(cb_user);
1887                 self->cb_user=                  cb_user;
1888                 self->cb_type=                  (unsigned char)cb_type;
1889                 self->cb_subtype=               (unsigned char)cb_subtype;
1890         }
1891         return (PyObject *) self;
1892 }