3a9617c05c47cd782bf429311d8be231b129e012
[blender.git] / source / blender / python / generic / quat.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  * 
24  * Contributor(s): Joseph Gilbert
25  *
26  * ***** END GPL LICENSE BLOCK *****
27  */
28
29 #include "Mathutils.h"
30
31 #include "BLI_math.h"
32 #include "BKE_utildefines.h"
33 #include "BLI_blenlib.h"
34
35 //-----------------------------METHODS------------------------------
36 static char Quaternion_ToEuler_doc[] =
37 ".. method:: to_euler(order, euler_compat)\n"
38 "\n"
39 "   Return Euler representation of the quaternion.\n"
40 "\n"
41 "   :arg order: Optional rotation order argument in ['XYZ', 'XZY', 'YXZ', 'YZX', 'ZXY', 'ZYX'].\n"
42 "   :type order: string\n"
43 "   :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"
44 "   :type euler_compat: :class:`Euler`\n"
45 "   :return: Euler representation of the quaternion.\n"
46 "   :rtype: :class:`Euler`\n";
47
48 static PyObject *Quaternion_ToEuler(QuaternionObject * self, PyObject *args)
49 {
50         float eul[3];
51         char *order_str= NULL;
52         short order= 0;
53         EulerObject *eul_compat = NULL;
54         
55         if(!PyArg_ParseTuple(args, "|sO!:to_euler", &order_str, &euler_Type, &eul_compat))
56                 return NULL;
57         
58         if(!BaseMath_ReadCallback(self))
59                 return NULL;
60
61         if(order_str) {
62                 order= euler_order_from_string(order_str, "Matrix.to_euler()");
63
64                 if(order < 0)
65                         return NULL;
66         }
67
68         if(eul_compat) {
69                 float mat[3][3];
70                 
71                 if(!BaseMath_ReadCallback(eul_compat))
72                         return NULL;
73                 
74                 quat_to_mat3(mat, self->quat);
75
76                 if(order == 0)  mat3_to_compatible_eul(eul, eul_compat->eul, mat);
77                 else                    mat3_to_compatible_eulO(eul, eul_compat->eul, order, mat);
78         }
79         else {
80                 if(order == 0)  quat_to_eul(eul, self->quat);
81                 else                    quat_to_eulO(eul, order, self->quat);
82         }
83         
84         return newEulerObject(eul, order, Py_NEW, NULL);
85 }
86 //----------------------------Quaternion.toMatrix()------------------
87 static char Quaternion_ToMatrix_doc[] =
88 ".. method:: to_matrix(other)\n"
89 "\n"
90 "   Return a matrix representation of the quaternion.\n"
91 "\n"
92 "   :return: A 3x3 rotation matrix representation of the quaternion.\n"
93 "   :rtype: :class:`Matrix`\n";
94
95 static PyObject *Quaternion_ToMatrix(QuaternionObject * self)
96 {
97         float mat[9]; /* all values are set */
98
99         if(!BaseMath_ReadCallback(self))
100                 return NULL;
101
102         quat_to_mat3( (float (*)[3]) mat,self->quat);
103         return newMatrixObject(mat, 3, 3, Py_NEW, NULL);
104 }
105
106 //----------------------------Quaternion.cross(other)------------------
107 static char Quaternion_Cross_doc[] =
108 ".. method:: cross(other)\n"
109 "\n"
110 "   Return the cross product of this quaternion and another.\n"
111 "\n"
112 "   :arg other: The other quaternion to perform the cross product with.\n"
113 "   :type other: :class:`Quaternion`\n"
114 "   :return: The cross product.\n"
115 "   :rtype: :class:`Quaternion`\n";
116
117 static PyObject *Quaternion_Cross(QuaternionObject * self, QuaternionObject * value)
118 {
119         float quat[4];
120         
121         if (!QuaternionObject_Check(value)) {
122                 PyErr_SetString( PyExc_TypeError, "quat.cross(value): expected a quaternion argument" );
123                 return NULL;
124         }
125         
126         if(!BaseMath_ReadCallback(self) || !BaseMath_ReadCallback(value))
127                 return NULL;
128
129         mul_qt_qtqt(quat, self->quat, value->quat);
130         return newQuaternionObject(quat, Py_NEW, NULL);
131 }
132
133 //----------------------------Quaternion.dot(other)------------------
134 static char Quaternion_Dot_doc[] =
135 ".. method:: dot(other)\n"
136 "\n"
137 "   Return the dot product of this quaternion and another.\n"
138 "\n"
139 "   :arg other: The other quaternion to perform the dot product with.\n"
140 "   :type other: :class:`Quaternion`\n"
141 "   :return: The dot product.\n"
142 "   :rtype: :class:`Quaternion`\n";
143
144 static PyObject *Quaternion_Dot(QuaternionObject * self, QuaternionObject * value)
145 {
146         if (!QuaternionObject_Check(value)) {
147                 PyErr_SetString( PyExc_TypeError, "quat.dot(value): expected a quaternion argument" );
148                 return NULL;
149         }
150
151         if(!BaseMath_ReadCallback(self) || !BaseMath_ReadCallback(value))
152                 return NULL;
153
154         return PyFloat_FromDouble(dot_qtqt(self->quat, value->quat));
155 }
156
157 static char Quaternion_Difference_doc[] =
158 ".. function:: difference(other)\n"
159 "\n"
160 "   Returns a quaternion representing the rotational difference.\n"
161 "\n"
162 "   :arg other: second quaternion.\n"
163 "   :type other: :class:`Quaternion`\n"
164 "   :return: the rotational difference between the two quat rotations.\n"
165 "   :rtype: :class:`Quaternion`\n";
166
167 static PyObject *Quaternion_Difference(QuaternionObject * self, QuaternionObject * value)
168 {
169         float quat[4], tempQuat[4];
170         double dot = 0.0f;
171         int x;
172
173         if (!QuaternionObject_Check(value)) {
174                 PyErr_SetString( PyExc_TypeError, "quat.difference(value): expected a quaternion argument" );
175                 return NULL;
176         }
177
178         if(!BaseMath_ReadCallback(self) || !BaseMath_ReadCallback(value))
179                 return NULL;
180
181         tempQuat[0] = self->quat[0];
182         tempQuat[1] = - self->quat[1];
183         tempQuat[2] = - self->quat[2];
184         tempQuat[3] = - self->quat[3];
185
186         dot = sqrt(tempQuat[0] * tempQuat[0] + tempQuat[1] *  tempQuat[1] +
187                                tempQuat[2] * tempQuat[2] + tempQuat[3] * tempQuat[3]);
188
189         for(x = 0; x < 4; x++) {
190                 tempQuat[x] /= (float)(dot * dot);
191         }
192         mul_qt_qtqt(quat, tempQuat, value->quat);
193         return newQuaternionObject(quat, Py_NEW, NULL);
194 }
195
196 static char Quaternion_Slerp_doc[] =
197 ".. function:: slerp(other, factor)\n"
198 "\n"
199 "   Returns the interpolation of two quaternions.\n"
200 "\n"
201 "   :arg other: value to interpolate with.\n"
202 "   :type other: :class:`Quaternion`\n"
203 "   :arg factor: The interpolation value in [0.0, 1.0].\n"
204 "   :type factor: float\n"
205 "   :return: The interpolated rotation.\n"
206 "   :rtype: :class:`Quaternion`\n";
207
208 static PyObject *Quaternion_Slerp(QuaternionObject *self, PyObject *args)
209 {
210         QuaternionObject *value;
211         float quat[4], fac;
212
213         if(!PyArg_ParseTuple(args, "O!f:slerp", &quaternion_Type, &value, &fac)) {
214                 PyErr_SetString(PyExc_TypeError, "quat.slerp(): expected Quaternion types and float");
215                 return NULL;
216         }
217
218         if(!BaseMath_ReadCallback(self) || !BaseMath_ReadCallback(value))
219                 return NULL;
220
221         if(fac > 1.0f || fac < 0.0f) {
222                 PyErr_SetString(PyExc_AttributeError, "quat.slerp(): interpolation factor must be between 0.0 and 1.0");
223                 return NULL;
224         }
225
226         interp_qt_qtqt(quat, self->quat, value->quat, fac);
227
228         return newQuaternionObject(quat, Py_NEW, NULL);
229 }
230
231 //----------------------------Quaternion.normalize()----------------
232 //normalize the axis of rotation of [theta,vector]
233 static char Quaternion_Normalize_doc[] =
234 ".. function:: normalize()\n"
235 "\n"
236 "   Normalize the quaternion.\n"
237 "\n"
238 "   :return: an instance of itself.\n"
239 "   :rtype: :class:`Quaternion`\n";
240
241 static PyObject *Quaternion_Normalize(QuaternionObject * self)
242 {
243         if(!BaseMath_ReadCallback(self))
244                 return NULL;
245
246         normalize_qt(self->quat);
247
248         BaseMath_WriteCallback(self);
249         Py_INCREF(self);
250         return (PyObject*)self;
251 }
252 //----------------------------Quaternion.inverse()------------------
253 static char Quaternion_Inverse_doc[] =
254 ".. function:: inverse()\n"
255 "\n"
256 "   Set the quaternion to its inverse.\n"
257 "\n"
258 "   :return: an instance of itself.\n"
259 "   :rtype: :class:`Quaternion`\n";
260
261 static PyObject *Quaternion_Inverse(QuaternionObject * self)
262 {
263         if(!BaseMath_ReadCallback(self))
264                 return NULL;
265
266         invert_qt(self->quat);
267
268         BaseMath_WriteCallback(self);
269         Py_INCREF(self);
270         return (PyObject*)self;
271 }
272 //----------------------------Quaternion.identity()-----------------
273 static char Quaternion_Identity_doc[] =
274 ".. function:: identity()\n"
275 "\n"
276 "   Set the quaternion to an identity quaternion.\n"
277 "\n"
278 "   :return: an instance of itself.\n"
279 "   :rtype: :class:`Quaternion`\n";
280
281 static PyObject *Quaternion_Identity(QuaternionObject * self)
282 {
283         if(!BaseMath_ReadCallback(self))
284                 return NULL;
285
286         unit_qt(self->quat);
287
288         BaseMath_WriteCallback(self);
289         Py_INCREF(self);
290         return (PyObject*)self;
291 }
292 //----------------------------Quaternion.negate()-------------------
293 static char Quaternion_Negate_doc[] =
294 ".. function:: negate()\n"
295 "\n"
296 "   Set the quaternion to its negative.\n"
297 "\n"
298 "   :return: an instance of itself.\n"
299 "   :rtype: :class:`Quaternion`\n";
300
301 static PyObject *Quaternion_Negate(QuaternionObject * self)
302 {
303         if(!BaseMath_ReadCallback(self))
304                 return NULL;
305
306         mul_qt_fl(self->quat, -1.0f);
307
308         BaseMath_WriteCallback(self);
309         Py_INCREF(self);
310         return (PyObject*)self;
311 }
312 //----------------------------Quaternion.conjugate()----------------
313 static char Quaternion_Conjugate_doc[] =
314 ".. function:: conjugate()\n"
315 "\n"
316 "   Set the quaternion to its conjugate (negate x, y, z).\n"
317 "\n"
318 "   :return: an instance of itself.\n"
319 "   :rtype: :class:`Quaternion`\n";
320
321 static PyObject *Quaternion_Conjugate(QuaternionObject * self)
322 {
323         if(!BaseMath_ReadCallback(self))
324                 return NULL;
325
326         conjugate_qt(self->quat);
327
328         BaseMath_WriteCallback(self);
329         Py_INCREF(self);
330         return (PyObject*)self;
331 }
332 //----------------------------Quaternion.copy()----------------
333 static char Quaternion_copy_doc[] =
334 ".. function:: copy()\n"
335 "\n"
336 "   Returns a copy of this quaternion.\n"
337 "\n"
338 "   :return: A copy of the quaternion.\n"
339 "   :rtype: :class:`Quaternion`\n"
340 "\n"
341 "   .. note:: use this to get a copy of a wrapped quaternion with no reference to the original data.\n";
342
343 static PyObject *Quaternion_copy(QuaternionObject * self)
344 {
345         if(!BaseMath_ReadCallback(self))
346                 return NULL;
347
348         return newQuaternionObject(self->quat, Py_NEW, Py_TYPE(self));
349 }
350
351 //----------------------------print object (internal)--------------
352 //print the object to screen
353 static PyObject *Quaternion_repr(QuaternionObject * self)
354 {
355         char str[64];
356
357         if(!BaseMath_ReadCallback(self))
358                 return NULL;
359
360         sprintf(str, "[%.6f, %.6f, %.6f, %.6f](quaternion)", self->quat[0], self->quat[1], self->quat[2], self->quat[3]);
361         return PyUnicode_FromString(str);
362 }
363 //------------------------tp_richcmpr
364 //returns -1 execption, 0 false, 1 true
365 static PyObject* Quaternion_richcmpr(PyObject *objectA, PyObject *objectB, int comparison_type)
366 {
367         QuaternionObject *quatA = NULL, *quatB = NULL;
368         int result = 0;
369
370         if(QuaternionObject_Check(objectA)) {
371                 quatA = (QuaternionObject*)objectA;
372                 if(!BaseMath_ReadCallback(quatA))
373                         return NULL;
374         }
375         if(QuaternionObject_Check(objectB)) {
376                 quatB = (QuaternionObject*)objectB;
377                 if(!BaseMath_ReadCallback(quatB))
378                         return NULL;
379         }
380
381         if (!quatA || !quatB){
382                 if (comparison_type == Py_NE){
383                         Py_RETURN_TRUE;
384                 }else{
385                         Py_RETURN_FALSE;
386                 }
387         }
388
389         switch (comparison_type){
390                 case Py_EQ:
391                         result = EXPP_VectorsAreEqual(quatA->quat, quatB->quat, 4, 1);
392                         break;
393                 case Py_NE:
394                         result = EXPP_VectorsAreEqual(quatA->quat, quatB->quat, 4, 1);
395                         if (result == 0){
396                                 result = 1;
397                         }else{
398                                 result = 0;
399                         }
400                         break;
401                 default:
402                         printf("The result of the comparison could not be evaluated");
403                         break;
404         }
405         if (result == 1){
406                 Py_RETURN_TRUE;
407         }else{
408                 Py_RETURN_FALSE;
409         }
410 }
411
412 //---------------------SEQUENCE PROTOCOLS------------------------
413 //----------------------------len(object)------------------------
414 //sequence length
415 static int Quaternion_len(QuaternionObject * self)
416 {
417         return 4;
418 }
419 //----------------------------object[]---------------------------
420 //sequence accessor (get)
421 static PyObject *Quaternion_item(QuaternionObject * self, int i)
422 {
423         if(i<0) i= 4-i;
424
425         if(i < 0 || i >= 4) {
426                 PyErr_SetString(PyExc_IndexError, "quaternion[attribute]: array index out of range\n");
427                 return NULL;
428         }
429
430         if(!BaseMath_ReadIndexCallback(self, i))
431                 return NULL;
432
433         return PyFloat_FromDouble(self->quat[i]);
434
435 }
436 //----------------------------object[]-------------------------
437 //sequence accessor (set)
438 static int Quaternion_ass_item(QuaternionObject * self, int i, PyObject * ob)
439 {
440         float scalar= (float)PyFloat_AsDouble(ob);
441         if(scalar==-1.0f && PyErr_Occurred()) { /* parsed item not a number */
442                 PyErr_SetString(PyExc_TypeError, "quaternion[index] = x: index argument not a number\n");
443                 return -1;
444         }
445
446         if(i<0) i= 4-i;
447
448         if(i < 0 || i >= 4){
449                 PyErr_SetString(PyExc_IndexError, "quaternion[attribute] = x: array assignment index out of range\n");
450                 return -1;
451         }
452         self->quat[i] = scalar;
453
454         if(!BaseMath_WriteIndexCallback(self, i))
455                 return -1;
456
457         return 0;
458 }
459 //----------------------------object[z:y]------------------------
460 //sequence slice (get)
461 static PyObject *Quaternion_slice(QuaternionObject * self, int begin, int end)
462 {
463         PyObject *list = NULL;
464         int count;
465
466         if(!BaseMath_ReadCallback(self))
467                 return NULL;
468
469         CLAMP(begin, 0, 4);
470         if (end<0) end= 5+end;
471         CLAMP(end, 0, 4);
472         begin = MIN2(begin,end);
473
474         list = PyList_New(end - begin);
475         for(count = begin; count < end; count++) {
476                 PyList_SetItem(list, count - begin,
477                                 PyFloat_FromDouble(self->quat[count]));
478         }
479
480         return list;
481 }
482 //----------------------------object[z:y]------------------------
483 //sequence slice (set)
484 static int Quaternion_ass_slice(QuaternionObject * self, int begin, int end, PyObject * seq)
485 {
486         int i, y, size = 0;
487         float quat[4];
488         PyObject *q;
489
490         if(!BaseMath_ReadCallback(self))
491                 return -1;
492
493         CLAMP(begin, 0, 4);
494         if (end<0) end= 5+end;
495         CLAMP(end, 0, 4);
496         begin = MIN2(begin,end);
497
498         size = PySequence_Length(seq);
499         if(size != (end - begin)){
500                 PyErr_SetString(PyExc_TypeError, "quaternion[begin:end] = []: size mismatch in slice assignment\n");
501                 return -1;
502         }
503
504         for (i = 0; i < size; i++) {
505                 q = PySequence_GetItem(seq, i);
506                 if (q == NULL) { // Failed to read sequence
507                         PyErr_SetString(PyExc_RuntimeError, "quaternion[begin:end] = []: unable to read sequence\n");
508                         return -1;
509                 }
510
511                 quat[i]= (float)PyFloat_AsDouble(q);
512                 Py_DECREF(q);
513
514                 if(quat[i]==-1.0f && PyErr_Occurred()) { /* parsed item not a number */
515                         PyErr_SetString(PyExc_TypeError, "quaternion[begin:end] = []: sequence argument not a number\n");
516                         return -1;
517                 }
518         }
519         //parsed well - now set in vector
520         for(y = 0; y < size; y++)
521                 self->quat[begin + y] = quat[y];
522
523         BaseMath_WriteCallback(self);
524         return 0;
525 }
526 //------------------------NUMERIC PROTOCOLS----------------------
527 //------------------------obj + obj------------------------------
528 //addition
529 static PyObject *Quaternion_add(PyObject * q1, PyObject * q2)
530 {
531         float quat[4];
532         QuaternionObject *quat1 = NULL, *quat2 = NULL;
533
534         if(!QuaternionObject_Check(q1) || !QuaternionObject_Check(q2)) {
535                 PyErr_SetString(PyExc_AttributeError, "Quaternion addition: arguments not valid for this operation....\n");
536                 return NULL;
537         }
538         quat1 = (QuaternionObject*)q1;
539         quat2 = (QuaternionObject*)q2;
540         
541         if(!BaseMath_ReadCallback(quat1) || !BaseMath_ReadCallback(quat2))
542                 return NULL;
543
544         add_qt_qtqt(quat, quat1->quat, quat2->quat, 1.0f);
545         return newQuaternionObject(quat, Py_NEW, NULL);
546 }
547 //------------------------obj - obj------------------------------
548 //subtraction
549 static PyObject *Quaternion_sub(PyObject * q1, PyObject * q2)
550 {
551         int x;
552         float quat[4];
553         QuaternionObject *quat1 = NULL, *quat2 = NULL;
554
555         if(!QuaternionObject_Check(q1) || !QuaternionObject_Check(q2)) {
556                 PyErr_SetString(PyExc_AttributeError, "Quaternion addition: arguments not valid for this operation....\n");
557                 return NULL;
558         }
559         
560         quat1 = (QuaternionObject*)q1;
561         quat2 = (QuaternionObject*)q2;
562         
563         if(!BaseMath_ReadCallback(quat1) || !BaseMath_ReadCallback(quat2))
564                 return NULL;
565
566         for(x = 0; x < 4; x++) {
567                 quat[x] = quat1->quat[x] - quat2->quat[x];
568         }
569
570         return newQuaternionObject(quat, Py_NEW, NULL);
571 }
572 //------------------------obj * obj------------------------------
573 //mulplication
574 static PyObject *Quaternion_mul(PyObject * q1, PyObject * q2)
575 {
576         float quat[4], scalar;
577         QuaternionObject *quat1 = NULL, *quat2 = NULL;
578         VectorObject *vec = NULL;
579
580         if(QuaternionObject_Check(q1)) {
581                 quat1 = (QuaternionObject*)q1;
582                 if(!BaseMath_ReadCallback(quat1))
583                         return NULL;
584         }
585         if(QuaternionObject_Check(q2)) {
586                 quat2 = (QuaternionObject*)q2;
587                 if(!BaseMath_ReadCallback(quat2))
588                         return NULL;
589         }
590
591         if(quat1 && quat2) { /* QUAT*QUAT (dot product) */
592                 return PyFloat_FromDouble(dot_qtqt(quat1->quat, quat2->quat));
593         }
594         
595         /* the only case this can happen (for a supported type is "FLOAT*QUAT" ) */
596         if(!QuaternionObject_Check(q1)) {
597                 scalar= PyFloat_AsDouble(q1);
598                 if ((scalar == -1.0 && PyErr_Occurred())==0) { /* FLOAT*QUAT */
599                         QUATCOPY(quat, quat2->quat);
600                         mul_qt_fl(quat, scalar);
601                         return newQuaternionObject(quat, Py_NEW, NULL);
602                 }
603                 PyErr_SetString(PyExc_TypeError, "Quaternion multiplication: val * quat, val is not an acceptable type");
604                 return NULL;
605         }
606         else { /* QUAT*SOMETHING */
607                 if(VectorObject_Check(q2)){  /* QUAT*VEC */
608                         vec = (VectorObject*)q2;
609                         if(vec->size != 3){
610                                 PyErr_SetString(PyExc_TypeError, "Quaternion multiplication: only 3D vector rotations currently supported\n");
611                                 return NULL;
612                         }
613                         return quat_rotation((PyObject*)quat1, (PyObject*)vec); /* vector updating done inside the func */
614                 }
615                 
616                 scalar= PyFloat_AsDouble(q2);
617                 if ((scalar == -1.0 && PyErr_Occurred())==0) { /* QUAT*FLOAT */
618                         QUATCOPY(quat, quat1->quat);
619                         mul_qt_fl(quat, scalar);
620                         return newQuaternionObject(quat, Py_NEW, NULL);
621                 }
622         }
623         
624         PyErr_SetString(PyExc_TypeError, "Quaternion multiplication: arguments not acceptable for this operation\n");
625         return NULL;
626 }
627
628 //-----------------PROTOCOL DECLARATIONS--------------------------
629 static PySequenceMethods Quaternion_SeqMethods = {
630         (lenfunc) Quaternion_len,                                       /* sq_length */
631         (binaryfunc) 0,                                                         /* sq_concat */
632         (ssizeargfunc) 0,                                                               /* sq_repeat */
633         (ssizeargfunc) Quaternion_item,                         /* sq_item */
634         (ssizessizeargfunc) Quaternion_slice,                   /* sq_slice */
635         (ssizeobjargproc) Quaternion_ass_item,          /* sq_ass_item */
636         (ssizessizeobjargproc) Quaternion_ass_slice,    /* sq_ass_slice */
637 };
638
639 static PyNumberMethods Quaternion_NumMethods = {
640                 (binaryfunc)    Quaternion_add, /*nb_add*/
641                 (binaryfunc)    Quaternion_sub, /*nb_subtract*/
642                 (binaryfunc)    Quaternion_mul, /*nb_multiply*/
643                 0,                                                      /*nb_remainder*/
644                 0,                                                      /*nb_divmod*/
645                 0,                                                      /*nb_power*/
646                 (unaryfunc)     0,      /*nb_negative*/
647                 (unaryfunc)     0,      /*tp_positive*/
648                 (unaryfunc)     0,      /*tp_absolute*/
649                 (inquiry)       0,      /*tp_bool*/
650                 (unaryfunc)     0,      /*nb_invert*/
651                 0,                              /*nb_lshift*/
652                 (binaryfunc)0,  /*nb_rshift*/
653                 0,                              /*nb_and*/
654                 0,                              /*nb_xor*/
655                 0,                              /*nb_or*/
656                 0,                              /*nb_int*/
657                 0,                              /*nb_reserved*/
658                 0,                              /*nb_float*/
659                 0,                              /* nb_inplace_add */
660                 0,                              /* nb_inplace_subtract */
661                 0,                              /* nb_inplace_multiply */
662                 0,                              /* nb_inplace_remainder */
663                 0,                              /* nb_inplace_power */
664                 0,                              /* nb_inplace_lshift */
665                 0,                              /* nb_inplace_rshift */
666                 0,                              /* nb_inplace_and */
667                 0,                              /* nb_inplace_xor */
668                 0,                              /* nb_inplace_or */
669                 0,                              /* nb_floor_divide */
670                 0,                              /* nb_true_divide */
671                 0,                              /* nb_inplace_floor_divide */
672                 0,                              /* nb_inplace_true_divide */
673                 0,                              /* nb_index */
674 };
675
676 static PyObject *Quaternion_getAxis( QuaternionObject * self, void *type )
677 {
678         return Quaternion_item(self, GET_INT_FROM_POINTER(type));
679 }
680
681 static int Quaternion_setAxis( QuaternionObject * self, PyObject * value, void * type )
682 {
683         return Quaternion_ass_item(self, GET_INT_FROM_POINTER(type), value);
684 }
685
686 static PyObject *Quaternion_getMagnitude( QuaternionObject * self, void *type )
687 {
688         return PyFloat_FromDouble(sqrt(dot_qtqt(self->quat, self->quat)));
689 }
690
691 static PyObject *Quaternion_getAngle( QuaternionObject * self, void *type )
692 {
693         return PyFloat_FromDouble(2.0 * (saacos(self->quat[0])));
694 }
695
696 static PyObject *Quaternion_getAxisVec( QuaternionObject * self, void *type )
697 {
698         int i;
699         float vec[3];
700         double mag = self->quat[0] * (Py_PI / 180);
701         mag = 2 * (saacos(mag));
702         mag = sin(mag / 2);
703         for(i = 0; i < 3; i++)
704                 vec[i] = (float)(self->quat[i + 1] / mag);
705         
706         normalize_v3(vec);
707         //If the axis of rotation is 0,0,0 set it to 1,0,0 - for zero-degree rotations
708         if( EXPP_FloatsAreEqual(vec[0], 0.0f, 10) &&
709                 EXPP_FloatsAreEqual(vec[1], 0.0f, 10) &&
710                 EXPP_FloatsAreEqual(vec[2], 0.0f, 10) ){
711                 vec[0] = 1.0f;
712         }
713         return (PyObject *) newVectorObject(vec, 3, Py_NEW, NULL);
714 }
715
716 //----------------------------------Mathutils.Quaternion() --------------
717 static PyObject *Quaternion_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
718 {
719         PyObject *listObject = NULL, *n, *q;
720         int size, i;
721         float quat[4];
722         double angle = 0.0f;
723
724         size = PyTuple_GET_SIZE(args);
725         if (size == 1 || size == 2) { //seq?
726                 listObject = PyTuple_GET_ITEM(args, 0);
727                 if (PySequence_Check(listObject)) {
728                         size = PySequence_Length(listObject);
729                         if ((size == 4 && PySequence_Length(args) !=1) ||
730                                 (size == 3 && PySequence_Length(args) !=2) || (size >4 || size < 3)) {
731                                 // invalid args/size
732                                 PyErr_SetString(PyExc_AttributeError, "Mathutils.Quaternion(): 4d numeric sequence expected or 3d vector and number\n");
733                                 return NULL;
734                         }
735                         if(size == 3){ //get angle in axis/angle
736                                 n = PySequence_GetItem(args, 1);
737                                 if(n == NULL) { // parsed item not a number or getItem fail
738                                         PyErr_SetString(PyExc_TypeError, "Mathutils.Quaternion(): 4d numeric sequence expected or 3d vector and number\n");
739                                         return NULL;
740                                 }
741
742                                 angle = PyFloat_AsDouble(n);
743                                 Py_DECREF(n);
744
745                                 if (angle==-1 && PyErr_Occurred()) {
746                                         PyErr_SetString(PyExc_TypeError, "Mathutils.Quaternion(): 4d numeric sequence expected or 3d vector and number\n");
747                                         return NULL;
748                                 }
749                         }
750                 }else{
751                         listObject = PyTuple_GET_ITEM(args, 1);
752                         if (size>1 && PySequence_Check(listObject)) {
753                                 size = PySequence_Length(listObject);
754                                 if (size != 3) {
755                                         // invalid args/size
756                                         PyErr_SetString(PyExc_AttributeError, "Mathutils.Quaternion(): 4d numeric sequence expected or 3d vector and number\n");
757                                         return NULL;
758                                 }
759                                 angle = PyFloat_AsDouble(PyTuple_GET_ITEM(args, 0));
760
761                                 if (angle==-1 && PyErr_Occurred()) {
762                                         PyErr_SetString(PyExc_TypeError, "Mathutils.Quaternion(): 4d numeric sequence expected or 3d vector and number\n");
763                                         return NULL;
764                                 }
765                         } else { // argument was not a sequence
766                                 PyErr_SetString(PyExc_TypeError, "Mathutils.Quaternion(): 4d numeric sequence expected or 3d vector and number\n");
767                                 return NULL;
768                         }
769                 }
770         } else if (size == 0) { //returns a new empty quat
771                 return newQuaternionObject(NULL, Py_NEW, NULL);
772         } else {
773                 listObject = args;
774         }
775
776         if (size == 3) { // invalid quat size
777                 if(PySequence_Length(args) != 2){
778                         PyErr_SetString(PyExc_AttributeError, "Mathutils.Quaternion(): 4d numeric sequence expected or 3d vector and number\n");
779                         return NULL;
780                 }
781         }else{
782                 if(size != 4){
783                         PyErr_SetString(PyExc_AttributeError, "Mathutils.Quaternion(): 4d numeric sequence expected or 3d vector and number\n");
784                         return NULL;
785                 }
786         }
787
788         for (i=0; i<size; i++) { //parse
789                 q = PySequence_GetItem(listObject, i);
790                 if (q == NULL) { // Failed to read sequence
791                         PyErr_SetString(PyExc_RuntimeError, "Mathutils.Quaternion(): 4d numeric sequence expected or 3d vector and number\n");
792                         return NULL;
793                 }
794
795                 quat[i] = PyFloat_AsDouble(q);
796                 Py_DECREF(q);
797
798                 if (quat[i]==-1 && PyErr_Occurred()) {
799                         PyErr_SetString(PyExc_TypeError, "Mathutils.Quaternion(): 4d numeric sequence expected or 3d vector and number\n");
800                         return NULL;
801                 }
802         }
803
804         if(size == 3) //calculate the quat based on axis/angle
805                 axis_angle_to_quat(quat, quat, angle);
806
807         return newQuaternionObject(quat, Py_NEW, NULL);
808 }
809
810
811 //-----------------------METHOD DEFINITIONS ----------------------
812 static struct PyMethodDef Quaternion_methods[] = {
813         {"identity", (PyCFunction) Quaternion_Identity, METH_NOARGS, Quaternion_Identity_doc},
814         {"negate", (PyCFunction) Quaternion_Negate, METH_NOARGS, Quaternion_Negate_doc},
815         {"conjugate", (PyCFunction) Quaternion_Conjugate, METH_NOARGS, Quaternion_Conjugate_doc},
816         {"inverse", (PyCFunction) Quaternion_Inverse, METH_NOARGS, Quaternion_Inverse_doc},
817         {"normalize", (PyCFunction) Quaternion_Normalize, METH_NOARGS, Quaternion_Normalize_doc},
818         {"to_euler", (PyCFunction) Quaternion_ToEuler, METH_VARARGS, Quaternion_ToEuler_doc},
819         {"to_matrix", (PyCFunction) Quaternion_ToMatrix, METH_NOARGS, Quaternion_ToMatrix_doc},
820         {"cross", (PyCFunction) Quaternion_Cross, METH_O, Quaternion_Cross_doc},
821         {"dot", (PyCFunction) Quaternion_Dot, METH_O, Quaternion_Dot_doc},
822         {"difference", (PyCFunction) Quaternion_Difference, METH_O, Quaternion_Difference_doc},
823         {"slerp", (PyCFunction) Quaternion_Slerp, METH_VARARGS, Quaternion_Slerp_doc},
824         {"__copy__", (PyCFunction) Quaternion_copy, METH_NOARGS, Quaternion_copy_doc},
825         {"copy", (PyCFunction) Quaternion_copy, METH_NOARGS, Quaternion_copy_doc},
826         {NULL, NULL, 0, NULL}
827 };
828
829 /*****************************************************************************/
830 /* Python attributes get/set structure:                                      */
831 /*****************************************************************************/
832 static PyGetSetDef Quaternion_getseters[] = {
833         {"w", (getter)Quaternion_getAxis, (setter)Quaternion_setAxis, "Quaternion W value. **type** float", (void *)0},
834         {"x", (getter)Quaternion_getAxis, (setter)Quaternion_setAxis, "Quaternion X axis. **type** float", (void *)1},
835         {"y", (getter)Quaternion_getAxis, (setter)Quaternion_setAxis, "Quaternion Y axis. **type** float", (void *)2},
836         {"z", (getter)Quaternion_getAxis, (setter)Quaternion_setAxis, "Quaternion Z axis. **type** float", (void *)3},
837         {"magnitude", (getter)Quaternion_getMagnitude, (setter)NULL, "Size of the quaternion (readonly). **type** float", NULL},
838         {"angle", (getter)Quaternion_getAngle, (setter)NULL, "angle of the quaternion (readonly). **type** float", NULL},
839         {"axis",(getter)Quaternion_getAxisVec, (setter)NULL, "quaternion axis as a vector (readonly). **type** :class:`Vector`", NULL},
840         {"is_wrapped", (getter)BaseMathObject_getWrapped, (setter)NULL, BaseMathObject_Wrapped_doc, NULL},
841         {"_owner", (getter)BaseMathObject_getOwner, (setter)NULL, BaseMathObject_Owner_doc, NULL},
842         {NULL,NULL,NULL,NULL,NULL}  /* Sentinel */
843 };
844
845 //------------------PY_OBECT DEFINITION--------------------------
846 static char quaternion_doc[] =
847 "This object gives access to Quaternions in Blender.";
848
849 PyTypeObject quaternion_Type = {
850         PyVarObject_HEAD_INIT(NULL, 0)
851         "quaternion",                                           //tp_name
852         sizeof(QuaternionObject),                       //tp_basicsize
853         0,                                                              //tp_itemsize
854         (destructor)BaseMathObject_dealloc,             //tp_dealloc
855         0,                                                              //tp_print
856         0,                                                              //tp_getattr
857         0,                                                              //tp_setattr
858         0,                                                              //tp_compare
859         (reprfunc) Quaternion_repr,                     //tp_repr
860         &Quaternion_NumMethods,                         //tp_as_number
861         &Quaternion_SeqMethods,                         //tp_as_sequence
862         0,                                                              //tp_as_mapping
863         0,                                                              //tp_hash
864         0,                                                              //tp_call
865         0,                                                              //tp_str
866         0,                                                              //tp_getattro
867         0,                                                              //tp_setattro
868         0,                                                              //tp_as_buffer
869         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, //tp_flags
870         quaternion_doc, //tp_doc
871         0,                                                              //tp_traverse
872         0,                                                              //tp_clear
873         (richcmpfunc)Quaternion_richcmpr,       //tp_richcompare
874         0,                                                              //tp_weaklistoffset
875         0,                                                              //tp_iter
876         0,                                                              //tp_iternext
877         Quaternion_methods,                             //tp_methods
878         0,                                                              //tp_members
879         Quaternion_getseters,                   //tp_getset
880         0,                                                              //tp_base
881         0,                                                              //tp_dict
882         0,                                                              //tp_descr_get
883         0,                                                              //tp_descr_set
884         0,                                                              //tp_dictoffset
885         0,                                                              //tp_init
886         0,                                                              //tp_alloc
887         Quaternion_new,                                 //tp_new
888         0,                                                              //tp_free
889         0,                                                              //tp_is_gc
890         0,                                                              //tp_bases
891         0,                                                              //tp_mro
892         0,                                                              //tp_cache
893         0,                                                              //tp_subclasses
894         0,                                                              //tp_weaklist
895         0                                                               //tp_del
896 };
897 //------------------------newQuaternionObject (internal)-------------
898 //creates a new quaternion object
899 /*pass Py_WRAP - if vector is a WRAPPER for data allocated by BLENDER
900  (i.e. it was allocated elsewhere by MEM_mallocN())
901   pass Py_NEW - if vector is not a WRAPPER and managed by PYTHON
902  (i.e. it must be created here with PyMEM_malloc())*/
903 PyObject *newQuaternionObject(float *quat, int type, PyTypeObject *base_type)
904 {
905         QuaternionObject *self;
906         
907         if(base_type)   self = (QuaternionObject *)base_type->tp_alloc(base_type, 0);
908         else                    self = PyObject_NEW(QuaternionObject, &quaternion_Type);
909
910         /* init callbacks as NULL */
911         self->cb_user= NULL;
912         self->cb_type= self->cb_subtype= 0;
913
914         if(type == Py_WRAP){
915                 self->quat = quat;
916                 self->wrapped = Py_WRAP;
917         }else if (type == Py_NEW){
918                 self->quat = PyMem_Malloc(4 * sizeof(float));
919                 if(!quat) { //new empty
920                         unit_qt(self->quat);
921                 }else{
922                         QUATCOPY(self->quat, quat);
923                 }
924                 self->wrapped = Py_NEW;
925         }else{ //bad type
926                 return NULL;
927         }
928         return (PyObject *) self;
929 }
930
931 PyObject *newQuaternionObject_cb(PyObject *cb_user, int cb_type, int cb_subtype)
932 {
933         QuaternionObject *self= (QuaternionObject *)newQuaternionObject(NULL, Py_NEW, NULL);
934         if(self) {
935                 Py_INCREF(cb_user);
936                 self->cb_user=                  cb_user;
937                 self->cb_type=                  (unsigned char)cb_type;
938                 self->cb_subtype=               (unsigned char)cb_subtype;
939         }
940
941         return (PyObject *)self;
942 }
943