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