2 * ***** BEGIN GPL LICENSE BLOCK *****
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version 2
7 * of the License, or (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software Foundation,
16 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19 * All rights reserved.
22 * Contributor(s): Joseph Gilbert
24 * ***** END GPL LICENSE BLOCK *****
27 /** \file blender/python/mathutils/mathutils_Quaternion.c
28 * \ingroup pymathutils
34 #include "mathutils.h"
37 #include "BLI_utildefines.h"
38 #include "BLI_dynstr.h"
42 static PyObject *quat__apply_to_copy(PyNoArgsFunction quat_func, QuaternionObject *self);
43 static void quat__axis_angle_sanitize(float axis[3], float *angle);
44 static PyObject *Quaternion_copy(QuaternionObject *self);
46 //-----------------------------METHODS------------------------------
48 /* note: BaseMath_ReadCallback must be called beforehand */
49 static PyObject *Quaternion_to_tuple_ext(QuaternionObject *self, int ndigits)
54 ret = PyTuple_New(QUAT_SIZE);
57 for (i = 0; i < QUAT_SIZE; i++) {
58 PyTuple_SET_ITEM(ret, i, PyFloat_FromDouble(double_round((double)self->quat[i], ndigits)));
62 for (i = 0; i < QUAT_SIZE; i++) {
63 PyTuple_SET_ITEM(ret, i, PyFloat_FromDouble(self->quat[i]));
70 PyDoc_STRVAR(Quaternion_to_euler_doc,
71 ".. method:: to_euler(order, euler_compat)\n"
73 " Return Euler representation of the quaternion.\n"
75 " :arg order: Optional rotation order argument in\n"
76 " ['XYZ', 'XZY', 'YXZ', 'YZX', 'ZXY', 'ZYX'].\n"
77 " :type order: string\n"
78 " :arg euler_compat: Optional euler argument the new euler will be made\n"
79 " compatible with (no axis flipping between them).\n"
80 " Useful for converting a series of matrices to animation curves.\n"
81 " :type euler_compat: :class:`Euler`\n"
82 " :return: Euler representation of the quaternion.\n"
83 " :rtype: :class:`Euler`\n"
85 static PyObject *Quaternion_to_euler(QuaternionObject *self, PyObject *args)
89 const char *order_str = NULL;
90 short order = EULER_ORDER_XYZ;
91 EulerObject *eul_compat = NULL;
93 if (!PyArg_ParseTuple(args, "|sO!:to_euler", &order_str, &euler_Type, &eul_compat))
96 if (BaseMath_ReadCallback(self) == -1)
100 order = euler_order_from_string(order_str, "Matrix.to_euler()");
106 normalize_qt_qt(tquat, self->quat);
111 if (BaseMath_ReadCallback(eul_compat) == -1)
114 quat_to_mat3(mat, tquat);
116 if (order == EULER_ORDER_XYZ) mat3_to_compatible_eul(eul, eul_compat->eul, mat);
117 else mat3_to_compatible_eulO(eul, eul_compat->eul, order, mat);
120 if (order == EULER_ORDER_XYZ) quat_to_eul(eul, tquat);
121 else quat_to_eulO(eul, order, tquat);
124 return Euler_CreatePyObject(eul, order, Py_NEW, NULL);
126 //----------------------------Quaternion.toMatrix()------------------
127 PyDoc_STRVAR(Quaternion_to_matrix_doc,
128 ".. method:: to_matrix()\n"
130 " Return a matrix representation of the quaternion.\n"
132 " :return: A 3x3 rotation matrix representation of the quaternion.\n"
133 " :rtype: :class:`Matrix`\n"
135 static PyObject *Quaternion_to_matrix(QuaternionObject *self)
137 float mat[9]; /* all values are set */
139 if (BaseMath_ReadCallback(self) == -1)
142 quat_to_mat3((float (*)[3])mat, self->quat);
143 return Matrix_CreatePyObject(mat, 3, 3, Py_NEW, NULL);
146 //----------------------------Quaternion.toMatrix()------------------
147 PyDoc_STRVAR(Quaternion_to_axis_angle_doc,
148 ".. method:: to_axis_angle()\n"
150 " Return the axis, angle representation of the quaternion.\n"
152 " :return: axis, angle.\n"
153 " :rtype: (:class:`Vector`, float) pair\n"
155 static PyObject *Quaternion_to_axis_angle(QuaternionObject *self)
164 if (BaseMath_ReadCallback(self) == -1)
167 normalize_qt_qt(tquat, self->quat);
168 quat_to_axis_angle(axis, &angle, tquat);
170 quat__axis_angle_sanitize(axis, &angle);
172 ret = PyTuple_New(2);
173 PyTuple_SET_ITEM(ret, 0, Vector_CreatePyObject(axis, 3, Py_NEW, NULL));
174 PyTuple_SET_ITEM(ret, 1, PyFloat_FromDouble(angle));
179 //----------------------------Quaternion.cross(other)------------------
180 PyDoc_STRVAR(Quaternion_cross_doc,
181 ".. method:: cross(other)\n"
183 " Return the cross product of this quaternion and another.\n"
185 " :arg other: The other quaternion to perform the cross product with.\n"
186 " :type other: :class:`Quaternion`\n"
187 " :return: The cross product.\n"
188 " :rtype: :class:`Quaternion`\n"
190 static PyObject *Quaternion_cross(QuaternionObject *self, PyObject *value)
192 float quat[QUAT_SIZE], tquat[QUAT_SIZE];
194 if (BaseMath_ReadCallback(self) == -1)
197 if (mathutils_array_parse(tquat, QUAT_SIZE, QUAT_SIZE, value,
198 "Quaternion.cross(other), invalid 'other' arg") == -1) {
202 mul_qt_qtqt(quat, self->quat, tquat);
203 return Quaternion_CreatePyObject(quat, Py_NEW, Py_TYPE(self));
206 //----------------------------Quaternion.dot(other)------------------
207 PyDoc_STRVAR(Quaternion_dot_doc,
208 ".. method:: dot(other)\n"
210 " Return the dot product of this quaternion and another.\n"
212 " :arg other: The other quaternion to perform the dot product with.\n"
213 " :type other: :class:`Quaternion`\n"
214 " :return: The dot product.\n"
215 " :rtype: :class:`Quaternion`\n"
217 static PyObject *Quaternion_dot(QuaternionObject *self, PyObject *value)
219 float tquat[QUAT_SIZE];
221 if (BaseMath_ReadCallback(self) == -1)
224 if (mathutils_array_parse(tquat, QUAT_SIZE, QUAT_SIZE, value,
225 "Quaternion.dot(other), invalid 'other' arg") == -1)
230 return PyFloat_FromDouble(dot_qtqt(self->quat, tquat));
233 PyDoc_STRVAR(Quaternion_rotation_difference_doc,
234 ".. function:: rotation_difference(other)\n"
236 " Returns a quaternion representing the rotational difference.\n"
238 " :arg other: second quaternion.\n"
239 " :type other: :class:`Quaternion`\n"
240 " :return: the rotational difference between the two quat rotations.\n"
241 " :rtype: :class:`Quaternion`\n"
243 static PyObject *Quaternion_rotation_difference(QuaternionObject *self, PyObject *value)
245 float tquat[QUAT_SIZE], quat[QUAT_SIZE];
247 if (BaseMath_ReadCallback(self) == -1)
250 if (mathutils_array_parse(tquat, QUAT_SIZE, QUAT_SIZE, value,
251 "Quaternion.difference(other), invalid 'other' arg") == -1)
256 rotation_between_quats_to_quat(quat, self->quat, tquat);
258 return Quaternion_CreatePyObject(quat, Py_NEW, Py_TYPE(self));
261 PyDoc_STRVAR(Quaternion_slerp_doc,
262 ".. function:: slerp(other, factor)\n"
264 " Returns the interpolation of two quaternions.\n"
266 " :arg other: value to interpolate with.\n"
267 " :type other: :class:`Quaternion`\n"
268 " :arg factor: The interpolation value in [0.0, 1.0].\n"
269 " :type factor: float\n"
270 " :return: The interpolated rotation.\n"
271 " :rtype: :class:`Quaternion`\n"
273 static PyObject *Quaternion_slerp(QuaternionObject *self, PyObject *args)
276 float tquat[QUAT_SIZE], quat[QUAT_SIZE], fac;
278 if (!PyArg_ParseTuple(args, "Of:slerp", &value, &fac)) {
279 PyErr_SetString(PyExc_TypeError,
281 "expected Quaternion types and float");
285 if (BaseMath_ReadCallback(self) == -1)
288 if (mathutils_array_parse(tquat, QUAT_SIZE, QUAT_SIZE, value,
289 "Quaternion.slerp(other), invalid 'other' arg") == -1)
294 if (fac > 1.0f || fac < 0.0f) {
295 PyErr_SetString(PyExc_ValueError,
297 "interpolation factor must be between 0.0 and 1.0");
301 interp_qt_qtqt(quat, self->quat, tquat, fac);
303 return Quaternion_CreatePyObject(quat, Py_NEW, Py_TYPE(self));
306 PyDoc_STRVAR(Quaternion_rotate_doc,
307 ".. method:: rotate(other)\n"
309 " Rotates the quaternion a by another mathutils value.\n"
311 " :arg other: rotation component of mathutils value\n"
312 " :type other: :class:`Euler`, :class:`Quaternion` or :class:`Matrix`\n"
314 static PyObject *Quaternion_rotate(QuaternionObject *self, PyObject *value)
316 float self_rmat[3][3], other_rmat[3][3], rmat[3][3];
317 float tquat[4], length;
319 if (BaseMath_ReadCallback(self) == -1)
322 if (mathutils_any_to_rotmat(other_rmat, value, "Quaternion.rotate(value)") == -1)
325 length = normalize_qt_qt(tquat, self->quat);
326 quat_to_mat3(self_rmat, tquat);
327 mul_m3_m3m3(rmat, other_rmat, self_rmat);
329 mat3_to_quat(self->quat, rmat);
330 mul_qt_fl(self->quat, length); /* maintain length after rotating */
332 (void)BaseMath_WriteCallback(self);
336 //----------------------------Quaternion.normalize()----------------
337 //normalize the axis of rotation of [theta, vector]
338 PyDoc_STRVAR(Quaternion_normalize_doc,
339 ".. function:: normalize()\n"
341 " Normalize the quaternion.\n"
343 static PyObject *Quaternion_normalize(QuaternionObject *self)
345 if (BaseMath_ReadCallback(self) == -1)
348 normalize_qt(self->quat);
350 (void)BaseMath_WriteCallback(self);
353 PyDoc_STRVAR(Quaternion_normalized_doc,
354 ".. function:: normalized()\n"
356 " Return a new normalized quaternion.\n"
358 " :return: a normalized copy.\n"
359 " :rtype: :class:`Quaternion`\n"
361 static PyObject *Quaternion_normalized(QuaternionObject *self)
363 return quat__apply_to_copy((PyNoArgsFunction)Quaternion_normalize, self);
366 //----------------------------Quaternion.invert()------------------
367 PyDoc_STRVAR(Quaternion_invert_doc,
368 ".. function:: invert()\n"
370 " Set the quaternion to its inverse.\n"
372 static PyObject *Quaternion_invert(QuaternionObject *self)
374 if (BaseMath_ReadCallback(self) == -1)
377 invert_qt(self->quat);
379 (void)BaseMath_WriteCallback(self);
382 PyDoc_STRVAR(Quaternion_inverted_doc,
383 ".. function:: inverted()\n"
385 " Return a new, inverted quaternion.\n"
387 " :return: the inverted value.\n"
388 " :rtype: :class:`Quaternion`\n"
390 static PyObject *Quaternion_inverted(QuaternionObject *self)
392 return quat__apply_to_copy((PyNoArgsFunction)Quaternion_invert, self);
395 //----------------------------Quaternion.identity()-----------------
396 PyDoc_STRVAR(Quaternion_identity_doc,
397 ".. function:: identity()\n"
399 " Set the quaternion to an identity quaternion.\n"
401 " :return: an instance of itself.\n"
402 " :rtype: :class:`Quaternion`\n"
404 static PyObject *Quaternion_identity(QuaternionObject *self)
406 if (BaseMath_ReadCallback(self) == -1)
411 (void)BaseMath_WriteCallback(self);
414 //----------------------------Quaternion.negate()-------------------
415 PyDoc_STRVAR(Quaternion_negate_doc,
416 ".. function:: negate()\n"
418 " Set the quaternion to its negative.\n"
420 " :return: an instance of itself.\n"
421 " :rtype: :class:`Quaternion`\n"
423 static PyObject *Quaternion_negate(QuaternionObject *self)
425 if (BaseMath_ReadCallback(self) == -1)
428 mul_qt_fl(self->quat, -1.0f);
430 (void)BaseMath_WriteCallback(self);
433 //----------------------------Quaternion.conjugate()----------------
434 PyDoc_STRVAR(Quaternion_conjugate_doc,
435 ".. function:: conjugate()\n"
437 " Set the quaternion to its conjugate (negate x, y, z).\n"
439 static PyObject *Quaternion_conjugate(QuaternionObject *self)
441 if (BaseMath_ReadCallback(self) == -1)
444 conjugate_qt(self->quat);
446 (void)BaseMath_WriteCallback(self);
449 PyDoc_STRVAR(Quaternion_conjugated_doc,
450 ".. function:: conjugated()\n"
452 " Return a new conjugated quaternion.\n"
454 " :return: a new quaternion.\n"
455 " :rtype: :class:`Quaternion`\n"
457 static PyObject *Quaternion_conjugated(QuaternionObject *self)
459 return quat__apply_to_copy((PyNoArgsFunction)Quaternion_conjugate, self);
462 //----------------------------Quaternion.copy()----------------
463 PyDoc_STRVAR(Quaternion_copy_doc,
464 ".. function:: copy()\n"
466 " Returns a copy of this quaternion.\n"
468 " :return: A copy of the quaternion.\n"
469 " :rtype: :class:`Quaternion`\n"
471 " .. note:: use this to get a copy of a wrapped quaternion with\n"
472 " no reference to the original data.\n"
474 static PyObject *Quaternion_copy(QuaternionObject *self)
476 if (BaseMath_ReadCallback(self) == -1)
479 return Quaternion_CreatePyObject(self->quat, Py_NEW, Py_TYPE(self));
482 //----------------------------print object (internal)--------------
483 //print the object to screen
484 static PyObject *Quaternion_repr(QuaternionObject *self)
486 PyObject *ret, *tuple;
488 if (BaseMath_ReadCallback(self) == -1)
491 tuple = Quaternion_to_tuple_ext(self, -1);
493 ret = PyUnicode_FromFormat("Quaternion(%R)", tuple);
499 static PyObject *Quaternion_str(QuaternionObject *self)
503 if (BaseMath_ReadCallback(self) == -1)
506 ds = BLI_dynstr_new();
508 BLI_dynstr_appendf(ds, "<Quaternion (w=%.4f, x=%.4f, y=%.4f, z=%.4f)>",
509 self->quat[0], self->quat[1], self->quat[2], self->quat[3]);
511 return mathutils_dynstr_to_py(ds); /* frees ds */
514 static PyObject *Quaternion_richcmpr(PyObject *a, PyObject *b, int op)
517 int ok = -1; /* zero is true */
519 if (QuaternionObject_Check(a) && QuaternionObject_Check(b)) {
520 QuaternionObject *quatA = (QuaternionObject *)a;
521 QuaternionObject *quatB = (QuaternionObject *)b;
523 if (BaseMath_ReadCallback(quatA) == -1 || BaseMath_ReadCallback(quatB) == -1)
526 ok = (EXPP_VectorsAreEqual(quatA->quat, quatB->quat, QUAT_SIZE, 1)) ? 0 : -1;
531 ok = !ok; /* pass through */
533 res = ok ? Py_False : Py_True;
540 res = Py_NotImplemented;
547 return Py_INCREF(res), res;
550 //---------------------SEQUENCE PROTOCOLS------------------------
551 //----------------------------len(object)------------------------
553 static int Quaternion_len(QuaternionObject *UNUSED(self))
557 //----------------------------object[]---------------------------
558 //sequence accessor (get)
559 static PyObject *Quaternion_item(QuaternionObject *self, int i)
561 if (i < 0) i = QUAT_SIZE-i;
563 if (i < 0 || i >= QUAT_SIZE) {
564 PyErr_SetString(PyExc_IndexError,
565 "quaternion[attribute]: "
566 "array index out of range");
570 if (BaseMath_ReadIndexCallback(self, i) == -1)
573 return PyFloat_FromDouble(self->quat[i]);
576 //----------------------------object[]-------------------------
577 //sequence accessor (set)
578 static int Quaternion_ass_item(QuaternionObject *self, int i, PyObject *ob)
580 float scalar = (float)PyFloat_AsDouble(ob);
581 if (scalar == -1.0f && PyErr_Occurred()) { /* parsed item not a number */
582 PyErr_SetString(PyExc_TypeError,
583 "quaternion[index] = x: "
584 "index argument not a number");
588 if (i < 0) i = QUAT_SIZE-i;
590 if (i < 0 || i >= QUAT_SIZE) {
591 PyErr_SetString(PyExc_IndexError,
592 "quaternion[attribute] = x: "
593 "array assignment index out of range");
596 self->quat[i] = scalar;
598 if (BaseMath_WriteIndexCallback(self, i) == -1)
603 //----------------------------object[z:y]------------------------
604 //sequence slice (get)
605 static PyObject *Quaternion_slice(QuaternionObject *self, int begin, int end)
610 if (BaseMath_ReadCallback(self) == -1)
613 CLAMP(begin, 0, QUAT_SIZE);
614 if (end < 0) end = (QUAT_SIZE + 1) + end;
615 CLAMP(end, 0, QUAT_SIZE);
616 begin = MIN2(begin, end);
618 tuple = PyTuple_New(end - begin);
619 for (count = begin; count < end; count++) {
620 PyTuple_SET_ITEM(tuple, count - begin, PyFloat_FromDouble(self->quat[count]));
625 //----------------------------object[z:y]------------------------
626 //sequence slice (set)
627 static int Quaternion_ass_slice(QuaternionObject *self, int begin, int end, PyObject *seq)
630 float quat[QUAT_SIZE];
632 if (BaseMath_ReadCallback(self) == -1)
635 CLAMP(begin, 0, QUAT_SIZE);
636 if (end < 0) end = (QUAT_SIZE + 1) + end;
637 CLAMP(end, 0, QUAT_SIZE);
638 begin = MIN2(begin, end);
640 if ((size = mathutils_array_parse(quat, 0, QUAT_SIZE, seq, "mathutils.Quaternion[begin:end] = []")) == -1)
643 if (size != (end - begin)) {
644 PyErr_SetString(PyExc_ValueError,
645 "quaternion[begin:end] = []: "
646 "size mismatch in slice assignment");
650 /* parsed well - now set in vector */
651 for (i = 0; i < size; i++)
652 self->quat[begin + i] = quat[i];
654 (void)BaseMath_WriteCallback(self);
659 static PyObject *Quaternion_subscript(QuaternionObject *self, PyObject *item)
661 if (PyIndex_Check(item)) {
663 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
664 if (i == -1 && PyErr_Occurred())
668 return Quaternion_item(self, i);
670 else if (PySlice_Check(item)) {
671 Py_ssize_t start, stop, step, slicelength;
673 if (PySlice_GetIndicesEx((void *)item, QUAT_SIZE, &start, &stop, &step, &slicelength) < 0)
676 if (slicelength <= 0) {
677 return PyTuple_New(0);
679 else if (step == 1) {
680 return Quaternion_slice(self, start, stop);
683 PyErr_SetString(PyExc_IndexError,
684 "slice steps not supported with quaternions");
689 PyErr_Format(PyExc_TypeError,
690 "quaternion indices must be integers, not %.200s",
691 Py_TYPE(item)->tp_name);
697 static int Quaternion_ass_subscript(QuaternionObject *self, PyObject *item, PyObject *value)
699 if (PyIndex_Check(item)) {
700 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
701 if (i == -1 && PyErr_Occurred())
705 return Quaternion_ass_item(self, i, value);
707 else if (PySlice_Check(item)) {
708 Py_ssize_t start, stop, step, slicelength;
710 if (PySlice_GetIndicesEx((void *)item, QUAT_SIZE, &start, &stop, &step, &slicelength) < 0)
714 return Quaternion_ass_slice(self, start, stop, value);
716 PyErr_SetString(PyExc_IndexError,
717 "slice steps not supported with quaternion");
722 PyErr_Format(PyExc_TypeError,
723 "quaternion indices must be integers, not %.200s",
724 Py_TYPE(item)->tp_name);
729 //------------------------NUMERIC PROTOCOLS----------------------
730 //------------------------obj + obj------------------------------
732 static PyObject *Quaternion_add(PyObject *q1, PyObject *q2)
734 float quat[QUAT_SIZE];
735 QuaternionObject *quat1 = NULL, *quat2 = NULL;
737 if (!QuaternionObject_Check(q1) || !QuaternionObject_Check(q2)) {
738 PyErr_Format(PyExc_TypeError,
739 "Quaternion addition: (%s + %s) "
740 "invalid type for this operation",
741 Py_TYPE(q1)->tp_name, Py_TYPE(q2)->tp_name);
744 quat1 = (QuaternionObject*)q1;
745 quat2 = (QuaternionObject*)q2;
747 if (BaseMath_ReadCallback(quat1) == -1 || BaseMath_ReadCallback(quat2) == -1)
750 add_qt_qtqt(quat, quat1->quat, quat2->quat, 1.0f);
751 return Quaternion_CreatePyObject(quat, Py_NEW, Py_TYPE(q1));
753 //------------------------obj - obj------------------------------
755 static PyObject *Quaternion_sub(PyObject *q1, PyObject *q2)
758 float quat[QUAT_SIZE];
759 QuaternionObject *quat1 = NULL, *quat2 = NULL;
761 if (!QuaternionObject_Check(q1) || !QuaternionObject_Check(q2)) {
762 PyErr_Format(PyExc_TypeError,
763 "Quaternion subtraction: (%s - %s) "
764 "invalid type for this operation",
765 Py_TYPE(q1)->tp_name, Py_TYPE(q2)->tp_name);
769 quat1 = (QuaternionObject*)q1;
770 quat2 = (QuaternionObject*)q2;
772 if (BaseMath_ReadCallback(quat1) == -1 || BaseMath_ReadCallback(quat2) == -1)
775 for (x = 0; x < QUAT_SIZE; x++) {
776 quat[x] = quat1->quat[x] - quat2->quat[x];
779 return Quaternion_CreatePyObject(quat, Py_NEW, Py_TYPE(q1));
782 static PyObject *quat_mul_float(QuaternionObject *quat, const float scalar)
785 copy_qt_qt(tquat, quat->quat);
786 mul_qt_fl(tquat, scalar);
787 return Quaternion_CreatePyObject(tquat, Py_NEW, Py_TYPE(quat));
790 //------------------------obj * obj------------------------------
792 static PyObject *Quaternion_mul(PyObject *q1, PyObject *q2)
794 float quat[QUAT_SIZE], scalar;
795 QuaternionObject *quat1 = NULL, *quat2 = NULL;
797 if (QuaternionObject_Check(q1)) {
798 quat1 = (QuaternionObject*)q1;
799 if (BaseMath_ReadCallback(quat1) == -1)
802 if (QuaternionObject_Check(q2)) {
803 quat2 = (QuaternionObject*)q2;
804 if (BaseMath_ReadCallback(quat2) == -1)
808 if (quat1 && quat2) { /* QUAT*QUAT (cross product) */
809 mul_qt_qtqt(quat, quat1->quat, quat2->quat);
810 return Quaternion_CreatePyObject(quat, Py_NEW, Py_TYPE(q1));
812 /* the only case this can happen (for a supported type is "FLOAT*QUAT") */
813 else if (quat2) { /* FLOAT*QUAT */
814 if (((scalar = PyFloat_AsDouble(q1)) == -1.0f && PyErr_Occurred()) == 0) {
815 return quat_mul_float(quat2, scalar);
820 if (VectorObject_Check(q2)) {
821 VectorObject *vec2 = (VectorObject *)q2;
824 if (vec2->size != 3) {
825 PyErr_SetString(PyExc_ValueError,
826 "Vector multiplication: "
827 "only 3D vector rotations (with quats) "
828 "currently supported");
831 if (BaseMath_ReadCallback(vec2) == -1) {
835 copy_v3_v3(tvec, vec2->vec);
836 mul_qt_v3(quat1->quat, tvec);
838 return Vector_CreatePyObject(tvec, 3, Py_NEW, Py_TYPE(vec2));
841 else if ((((scalar = PyFloat_AsDouble(q2)) == -1.0f && PyErr_Occurred()) == 0)) {
842 return quat_mul_float(quat1, scalar);
846 BLI_assert(!"internal error");
849 PyErr_Format(PyExc_TypeError,
850 "Quaternion multiplication: "
851 "not supported between '%.200s' and '%.200s' types",
852 Py_TYPE(q1)->tp_name, Py_TYPE(q2)->tp_name);
857 returns the negative of this object*/
858 static PyObject *Quaternion_neg(QuaternionObject *self)
860 float tquat[QUAT_SIZE];
862 if (BaseMath_ReadCallback(self) == -1)
865 negate_v4_v4(tquat, self->quat);
866 return Quaternion_CreatePyObject(tquat, Py_NEW, Py_TYPE(self));
870 //-----------------PROTOCOL DECLARATIONS--------------------------
871 static PySequenceMethods Quaternion_SeqMethods = {
872 (lenfunc) Quaternion_len, /* sq_length */
873 (binaryfunc) NULL, /* sq_concat */
874 (ssizeargfunc) NULL, /* sq_repeat */
875 (ssizeargfunc) Quaternion_item, /* sq_item */
876 (ssizessizeargfunc) NULL, /* sq_slice, deprecated */
877 (ssizeobjargproc) Quaternion_ass_item, /* sq_ass_item */
878 (ssizessizeobjargproc) NULL, /* sq_ass_slice, deprecated */
879 (objobjproc) NULL, /* sq_contains */
880 (binaryfunc) NULL, /* sq_inplace_concat */
881 (ssizeargfunc) NULL, /* sq_inplace_repeat */
884 static PyMappingMethods Quaternion_AsMapping = {
885 (lenfunc)Quaternion_len,
886 (binaryfunc)Quaternion_subscript,
887 (objobjargproc)Quaternion_ass_subscript
890 static PyNumberMethods Quaternion_NumMethods = {
891 (binaryfunc) Quaternion_add, /*nb_add*/
892 (binaryfunc) Quaternion_sub, /*nb_subtract*/
893 (binaryfunc) Quaternion_mul, /*nb_multiply*/
894 NULL, /*nb_remainder*/
897 (unaryfunc) Quaternion_neg, /*nb_negative*/
898 (unaryfunc) 0, /*tp_positive*/
899 (unaryfunc) 0, /*tp_absolute*/
900 (inquiry) 0, /*tp_bool*/
901 (unaryfunc) 0, /*nb_invert*/
903 (binaryfunc)0, /*nb_rshift*/
908 NULL, /*nb_reserved*/
910 NULL, /* nb_inplace_add */
911 NULL, /* nb_inplace_subtract */
912 NULL, /* nb_inplace_multiply */
913 NULL, /* nb_inplace_remainder */
914 NULL, /* nb_inplace_power */
915 NULL, /* nb_inplace_lshift */
916 NULL, /* nb_inplace_rshift */
917 NULL, /* nb_inplace_and */
918 NULL, /* nb_inplace_xor */
919 NULL, /* nb_inplace_or */
920 NULL, /* nb_floor_divide */
921 NULL, /* nb_true_divide */
922 NULL, /* nb_inplace_floor_divide */
923 NULL, /* nb_inplace_true_divide */
927 PyDoc_STRVAR(Quaternion_axis_doc,
928 "Quaternion axis value.\n\n:type: float"
930 static PyObject *Quaternion_axis_get(QuaternionObject *self, void *type)
932 return Quaternion_item(self, GET_INT_FROM_POINTER(type));
935 static int Quaternion_axis_set(QuaternionObject *self, PyObject *value, void *type)
937 return Quaternion_ass_item(self, GET_INT_FROM_POINTER(type), value);
940 PyDoc_STRVAR(Quaternion_magnitude_doc,
941 "Size of the quaternion (readonly).\n\n:type: float"
943 static PyObject *Quaternion_magnitude_get(QuaternionObject *self, void *UNUSED(closure))
945 if (BaseMath_ReadCallback(self) == -1)
948 return PyFloat_FromDouble(sqrt(dot_qtqt(self->quat, self->quat)));
951 PyDoc_STRVAR(Quaternion_angle_doc,
952 "Angle of the quaternion.\n\n:type: float"
954 static PyObject *Quaternion_angle_get(QuaternionObject *self, void *UNUSED(closure))
959 if (BaseMath_ReadCallback(self) == -1)
962 normalize_qt_qt(tquat, self->quat);
964 angle = 2.0f * saacos(tquat[0]);
966 quat__axis_angle_sanitize(NULL, &angle);
968 return PyFloat_FromDouble(angle);
971 static int Quaternion_angle_set(QuaternionObject *self, PyObject *value, void *UNUSED(closure))
976 float axis[3], angle_dummy;
979 if (BaseMath_ReadCallback(self) == -1)
982 len = normalize_qt_qt(tquat, self->quat);
983 quat_to_axis_angle(axis, &angle_dummy, tquat);
985 angle = PyFloat_AsDouble(value);
987 if (angle == -1.0f && PyErr_Occurred()) { /* parsed item not a number */
988 PyErr_SetString(PyExc_TypeError,
989 "Quaternion.angle = value: float expected");
993 angle = angle_wrap_rad(angle);
995 quat__axis_angle_sanitize(axis, &angle);
997 axis_angle_to_quat(self->quat, axis, angle);
998 mul_qt_fl(self->quat, len);
1000 if (BaseMath_WriteCallback(self) == -1)
1006 PyDoc_STRVAR(Quaternion_axis_vector_doc,
1007 "Quaternion axis as a vector.\n\n:type: :class:`Vector`"
1009 static PyObject *Quaternion_axis_vector_get(QuaternionObject *self, void *UNUSED(closure))
1016 if (BaseMath_ReadCallback(self) == -1)
1019 normalize_qt_qt(tquat, self->quat);
1020 quat_to_axis_angle(axis, &angle_dummy, tquat);
1022 quat__axis_angle_sanitize(axis, NULL);
1024 return Vector_CreatePyObject(axis, 3, Py_NEW, NULL);
1027 static int Quaternion_axis_vector_set(QuaternionObject *self, PyObject *value, void *UNUSED(closure))
1035 if (BaseMath_ReadCallback(self) == -1)
1038 len = normalize_qt_qt(tquat, self->quat);
1039 quat_to_axis_angle(axis, &angle, tquat); /* axis value is unused */
1041 if (mathutils_array_parse(axis, 3, 3, value, "quat.axis = other") == -1)
1044 quat__axis_angle_sanitize(axis, &angle);
1046 axis_angle_to_quat(self->quat, axis, angle);
1047 mul_qt_fl(self->quat, len);
1049 if (BaseMath_WriteCallback(self) == -1)
1055 //----------------------------------mathutils.Quaternion() --------------
1056 static PyObject *Quaternion_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1058 PyObject *seq = NULL;
1059 double angle = 0.0f;
1060 float quat[QUAT_SIZE] = {0.0f, 0.0f, 0.0f, 0.0f};
1062 if (kwds && PyDict_Size(kwds)) {
1063 PyErr_SetString(PyExc_TypeError,
1064 "mathutils.Quaternion(): "
1065 "takes no keyword args");
1069 if (!PyArg_ParseTuple(args, "|Od:mathutils.Quaternion", &seq, &angle))
1072 switch (PyTuple_GET_SIZE(args)) {
1076 if (mathutils_array_parse(quat, QUAT_SIZE, QUAT_SIZE, seq, "mathutils.Quaternion()") == -1)
1080 if (mathutils_array_parse(quat, 3, 3, seq, "mathutils.Quaternion()") == -1)
1082 angle = angle_wrap_rad(angle); /* clamp because of precision issues */
1083 axis_angle_to_quat(quat, quat, angle);
1085 /* PyArg_ParseTuple assures no more then 2 */
1087 return Quaternion_CreatePyObject(quat, Py_NEW, type);
1090 static PyObject *quat__apply_to_copy(PyNoArgsFunction quat_func, QuaternionObject *self)
1092 PyObject *ret = Quaternion_copy(self);
1093 PyObject *ret_dummy = quat_func(ret);
1095 Py_DECREF(ret_dummy);
1104 /* axis vector suffers from precission errors, use this function to ensure */
1105 static void quat__axis_angle_sanitize(float axis[3], float *angle)
1108 if ( !finite(axis[0]) ||
1116 else if ( EXPP_FloatsAreEqual(axis[0], 0.0f, 10) &&
1117 EXPP_FloatsAreEqual(axis[1], 0.0f, 10) &&
1118 EXPP_FloatsAreEqual(axis[2], 0.0f, 10))
1125 if (!finite(*angle)) {
1131 //-----------------------METHOD DEFINITIONS ----------------------
1132 static struct PyMethodDef Quaternion_methods[] = {
1134 {"identity", (PyCFunction) Quaternion_identity, METH_NOARGS, Quaternion_identity_doc},
1135 {"negate", (PyCFunction) Quaternion_negate, METH_NOARGS, Quaternion_negate_doc},
1137 /* operate on original or copy */
1138 {"conjugate", (PyCFunction) Quaternion_conjugate, METH_NOARGS, Quaternion_conjugate_doc},
1139 {"conjugated", (PyCFunction) Quaternion_conjugated, METH_NOARGS, Quaternion_conjugated_doc},
1141 {"invert", (PyCFunction) Quaternion_invert, METH_NOARGS, Quaternion_invert_doc},
1142 {"inverted", (PyCFunction) Quaternion_inverted, METH_NOARGS, Quaternion_inverted_doc},
1144 {"normalize", (PyCFunction) Quaternion_normalize, METH_NOARGS, Quaternion_normalize_doc},
1145 {"normalized", (PyCFunction) Quaternion_normalized, METH_NOARGS, Quaternion_normalized_doc},
1147 /* return converted representation */
1148 {"to_euler", (PyCFunction) Quaternion_to_euler, METH_VARARGS, Quaternion_to_euler_doc},
1149 {"to_matrix", (PyCFunction) Quaternion_to_matrix, METH_NOARGS, Quaternion_to_matrix_doc},
1150 {"to_axis_angle", (PyCFunction) Quaternion_to_axis_angle, METH_NOARGS, Quaternion_to_axis_angle_doc},
1152 /* operation between 2 or more types */
1153 {"cross", (PyCFunction) Quaternion_cross, METH_O, Quaternion_cross_doc},
1154 {"dot", (PyCFunction) Quaternion_dot, METH_O, Quaternion_dot_doc},
1155 {"rotation_difference", (PyCFunction) Quaternion_rotation_difference, METH_O, Quaternion_rotation_difference_doc},
1156 {"slerp", (PyCFunction) Quaternion_slerp, METH_VARARGS, Quaternion_slerp_doc},
1157 {"rotate", (PyCFunction) Quaternion_rotate, METH_O, Quaternion_rotate_doc},
1159 {"__copy__", (PyCFunction) Quaternion_copy, METH_NOARGS, Quaternion_copy_doc},
1160 {"copy", (PyCFunction) Quaternion_copy, METH_NOARGS, Quaternion_copy_doc},
1161 {NULL, NULL, 0, NULL}
1164 /*****************************************************************************/
1165 /* Python attributes get/set structure: */
1166 /*****************************************************************************/
1167 static PyGetSetDef Quaternion_getseters[] = {
1168 {(char *)"w", (getter)Quaternion_axis_get, (setter)Quaternion_axis_set, Quaternion_axis_doc, (void *)0},
1169 {(char *)"x", (getter)Quaternion_axis_get, (setter)Quaternion_axis_set, Quaternion_axis_doc, (void *)1},
1170 {(char *)"y", (getter)Quaternion_axis_get, (setter)Quaternion_axis_set, Quaternion_axis_doc, (void *)2},
1171 {(char *)"z", (getter)Quaternion_axis_get, (setter)Quaternion_axis_set, Quaternion_axis_doc, (void *)3},
1172 {(char *)"magnitude", (getter)Quaternion_magnitude_get, (setter)NULL, Quaternion_magnitude_doc, NULL},
1173 {(char *)"angle", (getter)Quaternion_angle_get, (setter)Quaternion_angle_set, Quaternion_angle_doc, NULL},
1174 {(char *)"axis",(getter)Quaternion_axis_vector_get, (setter)Quaternion_axis_vector_set, Quaternion_axis_vector_doc, NULL},
1175 {(char *)"is_wrapped", (getter)BaseMathObject_is_wrapped_get, (setter)NULL, BaseMathObject_is_wrapped_doc, NULL},
1176 {(char *)"owner", (getter)BaseMathObject_owner_get, (setter)NULL, BaseMathObject_owner_doc, NULL},
1177 {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
1180 //------------------PY_OBECT DEFINITION--------------------------
1181 PyDoc_STRVAR(quaternion_doc,
1182 "This object gives access to Quaternions in Blender."
1184 PyTypeObject quaternion_Type = {
1185 PyVarObject_HEAD_INIT(NULL, 0)
1186 "mathutils.Quaternion", //tp_name
1187 sizeof(QuaternionObject), //tp_basicsize
1189 (destructor)BaseMathObject_dealloc, //tp_dealloc
1194 (reprfunc) Quaternion_repr, //tp_repr
1195 &Quaternion_NumMethods, //tp_as_number
1196 &Quaternion_SeqMethods, //tp_as_sequence
1197 &Quaternion_AsMapping, //tp_as_mapping
1200 (reprfunc) Quaternion_str, //tp_str
1203 NULL, //tp_as_buffer
1204 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, //tp_flags
1205 quaternion_doc, //tp_doc
1206 (traverseproc)BaseMathObject_traverse, //tp_traverse
1207 (inquiry)BaseMathObject_clear, //tp_clear
1208 (richcmpfunc)Quaternion_richcmpr, //tp_richcompare
1209 0, //tp_weaklistoffset
1212 Quaternion_methods, //tp_methods
1214 Quaternion_getseters, //tp_getset
1217 NULL, //tp_descr_get
1218 NULL, //tp_descr_set
1222 Quaternion_new, //tp_new
1228 NULL, //tp_subclasses
1232 //------------------------Quaternion_CreatePyObject (internal)-------------
1233 //creates a new quaternion object
1234 /*pass Py_WRAP - if vector is a WRAPPER for data allocated by BLENDER
1235 (i.e. it was allocated elsewhere by MEM_mallocN())
1236 pass Py_NEW - if vector is not a WRAPPER and managed by PYTHON
1237 (i.e. it must be created here with PyMEM_malloc())*/
1238 PyObject *Quaternion_CreatePyObject(float *quat, int type, PyTypeObject *base_type)
1240 QuaternionObject *self;
1242 self = base_type ? (QuaternionObject *)base_type->tp_alloc(base_type, 0) :
1243 (QuaternionObject *)PyObject_GC_New(QuaternionObject, &quaternion_Type);
1246 /* init callbacks as NULL */
1247 self->cb_user = NULL;
1248 self->cb_type = self->cb_subtype = 0;
1250 if (type == Py_WRAP) {
1252 self->wrapped = Py_WRAP;
1254 else if (type == Py_NEW) {
1255 self->quat = PyMem_Malloc(QUAT_SIZE * sizeof(float));
1256 if (!quat) { //new empty
1257 unit_qt(self->quat);
1260 copy_qt_qt(self->quat, quat);
1262 self->wrapped = Py_NEW;
1265 Py_FatalError("Quaternion(): invalid type!");
1268 return (PyObject *) self;
1271 PyObject *Quaternion_CreatePyObject_cb(PyObject *cb_user, int cb_type, int cb_subtype)
1273 QuaternionObject *self = (QuaternionObject *)Quaternion_CreatePyObject(NULL, Py_NEW, NULL);
1276 self->cb_user = cb_user;
1277 self->cb_type = (unsigned char)cb_type;
1278 self->cb_subtype = (unsigned char)cb_subtype;
1279 PyObject_GC_Track(self);
1282 return (PyObject *)self;