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