4 * ***** BEGIN GPL LICENSE BLOCK *****
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.
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.
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.
20 * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21 * All rights reserved.
24 * Contributor(s): Joseph Gilbert
26 * ***** END GPL LICENSE BLOCK *****
29 #include "mathutils.h"
32 #include "BLI_utildefines.h"
37 #include "BLO_sys_types.h"
42 //----------------------------------mathutils.Euler() -------------------
43 //makes a new euler for you to play with
44 static PyObject *Euler_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
47 char *order_str= NULL;
49 float eul[EULER_SIZE]= {0.0f, 0.0f, 0.0f};
50 short order= EULER_ORDER_XYZ;
52 if(kwds && PyDict_Size(kwds)) {
53 PyErr_SetString(PyExc_TypeError, "mathutils.Euler(): takes no keyword args");
57 if(!PyArg_ParseTuple(args, "|Os:mathutils.Euler", &seq, &order_str))
60 switch(PyTuple_GET_SIZE(args)) {
64 if((order=euler_order_from_string(order_str, "mathutils.Euler()")) == -1)
66 /* intentionally pass through */
68 if (mathutils_array_parse(eul, EULER_SIZE, EULER_SIZE, seq, "mathutils.Euler()") == -1)
72 return newEulerObject(eul, order, Py_NEW, type);
75 short euler_order_from_string(const char *str, const char *error_prefix)
77 if((str[0] && str[1] && str[2] && str[3]=='\0')) {
78 switch(*((int32_t *)str)) {
79 case 'X'|'Y'<<8|'Z'<<16: return EULER_ORDER_XYZ;
80 case 'X'|'Z'<<8|'Y'<<16: return EULER_ORDER_XZY;
81 case 'Y'|'X'<<8|'Z'<<16: return EULER_ORDER_YXZ;
82 case 'Y'|'Z'<<8|'X'<<16: return EULER_ORDER_YZX;
83 case 'Z'|'X'<<8|'Y'<<16: return EULER_ORDER_ZXY;
84 case 'Z'|'Y'<<8|'X'<<16: return EULER_ORDER_ZYX;
88 PyErr_Format(PyExc_TypeError, "%s: invalid euler order '%s'", error_prefix, str);
92 /* note: BaseMath_ReadCallback must be called beforehand */
93 static PyObject *Euler_ToTupleExt(EulerObject *self, int ndigits)
98 ret= PyTuple_New(EULER_SIZE);
101 for(i= 0; i < EULER_SIZE; i++) {
102 PyTuple_SET_ITEM(ret, i, PyFloat_FromDouble(double_round((double)self->eul[i], ndigits)));
106 for(i= 0; i < EULER_SIZE; i++) {
107 PyTuple_SET_ITEM(ret, i, PyFloat_FromDouble(self->eul[i]));
114 //-----------------------------METHODS----------------------------
115 //return a quaternion representation of the euler
117 static char Euler_ToQuat_doc[] =
118 ".. method:: to_quat()\n"
120 " Return a quaternion representation of the euler.\n"
122 " :return: Quaternion representation of the euler.\n"
123 " :rtype: :class:`Quaternion`\n";
125 static PyObject *Euler_ToQuat(EulerObject * self)
129 if(!BaseMath_ReadCallback(self))
132 if(self->order==EULER_ORDER_XYZ) eul_to_quat(quat, self->eul);
133 else eulO_to_quat(quat, self->eul, self->order);
135 return newQuaternionObject(quat, Py_NEW, NULL);
138 //return a matrix representation of the euler
139 static char Euler_ToMatrix_doc[] =
140 ".. method:: to_matrix()\n"
142 " Return a matrix representation of the euler.\n"
144 " :return: A 3x3 roation matrix representation of the euler.\n"
145 " :rtype: :class:`Matrix`\n";
147 static PyObject *Euler_ToMatrix(EulerObject * self)
149 float mat[9] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f};
151 if(!BaseMath_ReadCallback(self))
154 if(self->order==EULER_ORDER_XYZ) eul_to_mat3((float (*)[3])mat, self->eul);
155 else eulO_to_mat3((float (*)[3])mat, self->eul, self->order);
157 return newMatrixObject(mat, 3, 3 , Py_NEW, NULL);
160 //sets the x,y,z values to a unique euler rotation
161 // TODO, check if this works with rotation order!!!
162 static char Euler_Unique_doc[] =
163 ".. method:: unique()\n"
165 " Calculate a unique rotation for this euler. Avoids gimble lock.\n"
167 " :return: an instance of itself\n"
168 " :rtype: :class:`Euler`\n";
170 static PyObject *Euler_Unique(EulerObject * self)
172 #define PI_2 (Py_PI * 2.0)
173 #define PI_HALF (Py_PI / 2.0)
174 #define PI_INV (1.0 / Py_PI)
176 double heading, pitch, bank;
178 if(!BaseMath_ReadCallback(self))
181 heading = self->eul[0];
182 pitch = self->eul[1];
185 //wrap heading in +180 / -180
187 pitch -= floor(pitch * PI_INV) * PI_2;
191 if(pitch < -PI_HALF) {
192 pitch = -Py_PI - pitch;
195 } else if(pitch > PI_HALF) {
196 pitch = Py_PI - pitch;
201 if(fabs(pitch) > PI_HALF - 1e-4) {
206 bank -= (floor(bank * PI_INV)) * PI_2;
211 heading -= (floor(heading * PI_INV)) * PI_2;
214 (void)BaseMath_WriteCallback(self);
216 return (PyObject *)self;
219 //sets the euler to 0,0,0
220 static char Euler_Zero_doc[] =
221 ".. method:: zero()\n"
223 " Set all values to zero.\n"
225 " :return: an instance of itself\n"
226 " :rtype: :class:`Euler`\n";
228 static PyObject *Euler_Zero(EulerObject * self)
234 (void)BaseMath_WriteCallback(self);
236 return (PyObject *)self;
239 static char Euler_rotate_axis_doc[] =
240 ".. method:: rotate_axis(axis, angle)\n"
242 " Rotates the euler a certain amount and returning a unique euler rotation (no 720 degree pitches).\n"
244 " :arg axis: single character in ['X, 'Y', 'Z'].\n"
245 " :type axis: string\n"
246 " :arg angle: angle in radians.\n"
247 " :type angle: float\n"
248 " :return: an instance of itself\n"
249 " :rtype: :class:`Euler`";
251 static PyObject *Euler_rotate_axis(EulerObject * self, PyObject *args)
256 if(!PyArg_ParseTuple(args, "sf:rotate", &axis, &angle)){
257 PyErr_SetString(PyExc_TypeError, "euler.rotate(): expected angle (float) and axis (x,y,z)");
260 if(!(ELEM3(*axis, 'X', 'Y', 'Z') && axis[1]=='\0')){
261 PyErr_SetString(PyExc_TypeError, "euler.rotate(): expected axis to be 'X', 'Y' or 'Z'");
265 if(!BaseMath_ReadCallback(self))
268 if(self->order == EULER_ORDER_XYZ) rotate_eul(self->eul, *axis, angle);
269 else rotate_eulO(self->eul, self->order, *axis, angle);
271 (void)BaseMath_WriteCallback(self);
273 return (PyObject *)self;
276 static char Euler_MakeCompatible_doc[] =
277 ".. method:: make_compatible(other)\n"
279 " Make this euler compatible with another, so interpolating between them works as intended.\n"
281 " :arg other: make compatible with this rotation.\n"
282 " :type other: :class:`Euler`\n"
283 " :return: an instance of itself.\n"
284 " :rtype: :class:`Euler`\n"
286 " .. note:: the order of eulers must match or an exception is raised.\n";
288 static PyObject *Euler_MakeCompatible(EulerObject * self, EulerObject *value)
290 if(!EulerObject_Check(value)) {
291 PyErr_SetString(PyExc_TypeError, "euler.make_compatible(euler): expected a single euler argument");
295 if(!BaseMath_ReadCallback(self) || !BaseMath_ReadCallback(value))
298 if(self->order != value->order) {
299 PyErr_SetString(PyExc_ValueError, "euler.make_compatible(euler): rotation orders don't match");
303 compatible_eul(self->eul, value->eul);
305 (void)BaseMath_WriteCallback(self);
307 return (PyObject *)self;
310 //----------------------------Euler.rotate()-----------------------
311 // return a copy of the euler
313 static char Euler_copy_doc[] =
314 ".. function:: copy()\n"
316 " Returns a copy of this euler.\n"
318 " :return: A copy of the euler.\n"
319 " :rtype: :class:`Euler`\n"
321 " .. note:: use this to get a copy of a wrapped euler with no reference to the original data.\n";
323 static PyObject *Euler_copy(EulerObject *self)
325 if(!BaseMath_ReadCallback(self))
328 return newEulerObject(self->eul, self->order, Py_NEW, Py_TYPE(self));
331 //----------------------------print object (internal)--------------
332 //print the object to screen
334 static PyObject *Euler_repr(EulerObject * self)
336 PyObject *ret, *tuple;
338 if(!BaseMath_ReadCallback(self))
341 tuple= Euler_ToTupleExt(self, -1);
343 ret= PyUnicode_FromFormat("Euler(%R)", tuple);
349 //------------------------tp_richcmpr
350 //returns -1 execption, 0 false, 1 true
351 static PyObject* Euler_richcmpr(PyObject *objectA, PyObject *objectB, int comparison_type)
353 EulerObject *eulA = NULL, *eulB = NULL;
356 if(EulerObject_Check(objectA)) {
357 eulA = (EulerObject*)objectA;
358 if(!BaseMath_ReadCallback(eulA))
361 if(EulerObject_Check(objectB)) {
362 eulB = (EulerObject*)objectB;
363 if(!BaseMath_ReadCallback(eulB))
368 if (comparison_type == Py_NE){
374 eulA = (EulerObject*)objectA;
375 eulB = (EulerObject*)objectB;
377 switch (comparison_type){
379 result = EXPP_VectorsAreEqual(eulA->eul, eulB->eul, EULER_SIZE, 1);
382 result = !EXPP_VectorsAreEqual(eulA->eul, eulB->eul, EULER_SIZE, 1);
385 printf("The result of the comparison could not be evaluated");
395 //---------------------SEQUENCE PROTOCOLS------------------------
396 //----------------------------len(object)------------------------
398 static int Euler_len(EulerObject *UNUSED(self))
402 //----------------------------object[]---------------------------
403 //sequence accessor (get)
404 static PyObject *Euler_item(EulerObject * self, int i)
406 if(i<0) i= EULER_SIZE-i;
408 if(i < 0 || i >= EULER_SIZE) {
409 PyErr_SetString(PyExc_IndexError, "euler[attribute]: array index out of range");
413 if(!BaseMath_ReadIndexCallback(self, i))
416 return PyFloat_FromDouble(self->eul[i]);
419 //----------------------------object[]-------------------------
420 //sequence accessor (set)
421 static int Euler_ass_item(EulerObject * self, int i, PyObject *value)
423 float f = PyFloat_AsDouble(value);
425 if(f == -1 && PyErr_Occurred()) { // parsed item not a number
426 PyErr_SetString(PyExc_TypeError, "euler[attribute] = x: argument not a number");
430 if(i<0) i= EULER_SIZE-i;
432 if(i < 0 || i >= EULER_SIZE){
433 PyErr_SetString(PyExc_IndexError, "euler[attribute] = x: array assignment index out of range");
439 if(!BaseMath_WriteIndexCallback(self, i))
444 //----------------------------object[z:y]------------------------
445 //sequence slice (get)
446 static PyObject *Euler_slice(EulerObject * self, int begin, int end)
451 if(!BaseMath_ReadCallback(self))
454 CLAMP(begin, 0, EULER_SIZE);
455 if (end<0) end= (EULER_SIZE + 1) + end;
456 CLAMP(end, 0, EULER_SIZE);
457 begin= MIN2(begin, end);
459 tuple= PyTuple_New(end - begin);
460 for(count = begin; count < end; count++) {
461 PyTuple_SET_ITEM(tuple, count - begin, PyFloat_FromDouble(self->eul[count]));
466 //----------------------------object[z:y]------------------------
467 //sequence slice (set)
468 static int Euler_ass_slice(EulerObject * self, int begin, int end, PyObject * seq)
471 float eul[EULER_SIZE];
473 if(!BaseMath_ReadCallback(self))
476 CLAMP(begin, 0, EULER_SIZE);
477 if (end<0) end= (EULER_SIZE + 1) + end;
478 CLAMP(end, 0, EULER_SIZE);
479 begin = MIN2(begin,end);
481 if((size=mathutils_array_parse(eul, 0, EULER_SIZE, seq, "mathutils.Euler[begin:end] = []")) == -1)
484 if(size != (end - begin)){
485 PyErr_SetString(PyExc_TypeError, "euler[begin:end] = []: size mismatch in slice assignment");
489 for(i= 0; i < EULER_SIZE; i++)
490 self->eul[begin + i] = eul[i];
492 (void)BaseMath_WriteCallback(self);
496 static PyObject *Euler_subscript(EulerObject *self, PyObject *item)
498 if (PyIndex_Check(item)) {
500 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
501 if (i == -1 && PyErr_Occurred())
505 return Euler_item(self, i);
506 } else if (PySlice_Check(item)) {
507 Py_ssize_t start, stop, step, slicelength;
509 if (PySlice_GetIndicesEx((PySliceObject*)item, EULER_SIZE, &start, &stop, &step, &slicelength) < 0)
512 if (slicelength <= 0) {
513 return PyList_New(0);
515 else if (step == 1) {
516 return Euler_slice(self, start, stop);
519 PyErr_SetString(PyExc_TypeError, "slice steps not supported with eulers");
524 PyErr_Format(PyExc_TypeError, "euler indices must be integers, not %.200s", Py_TYPE(item)->tp_name);
530 static int Euler_ass_subscript(EulerObject *self, PyObject *item, PyObject *value)
532 if (PyIndex_Check(item)) {
533 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
534 if (i == -1 && PyErr_Occurred())
538 return Euler_ass_item(self, i, value);
540 else if (PySlice_Check(item)) {
541 Py_ssize_t start, stop, step, slicelength;
543 if (PySlice_GetIndicesEx((PySliceObject*)item, EULER_SIZE, &start, &stop, &step, &slicelength) < 0)
547 return Euler_ass_slice(self, start, stop, value);
549 PyErr_SetString(PyExc_TypeError, "slice steps not supported with euler");
554 PyErr_Format(PyExc_TypeError, "euler indices must be integers, not %.200s", Py_TYPE(item)->tp_name);
559 //-----------------PROTCOL DECLARATIONS--------------------------
560 static PySequenceMethods Euler_SeqMethods = {
561 (lenfunc) Euler_len, /* sq_length */
562 (binaryfunc) NULL, /* sq_concat */
563 (ssizeargfunc) NULL, /* sq_repeat */
564 (ssizeargfunc) Euler_item, /* sq_item */
565 (ssizessizeargfunc) NULL, /* sq_slice, deprecated */
566 (ssizeobjargproc) Euler_ass_item, /* sq_ass_item */
567 (ssizessizeobjargproc) NULL, /* sq_ass_slice, deprecated */
568 (objobjproc) NULL, /* sq_contains */
569 (binaryfunc) NULL, /* sq_inplace_concat */
570 (ssizeargfunc) NULL, /* sq_inplace_repeat */
573 static PyMappingMethods Euler_AsMapping = {
575 (binaryfunc)Euler_subscript,
576 (objobjargproc)Euler_ass_subscript
580 * euler axis, euler.x/y/z
582 static PyObject *Euler_getAxis(EulerObject *self, void *type )
584 return Euler_item(self, GET_INT_FROM_POINTER(type));
587 static int Euler_setAxis(EulerObject *self, PyObject *value, void *type)
589 return Euler_ass_item(self, GET_INT_FROM_POINTER(type), value);
593 static PyObject *Euler_getOrder(EulerObject *self, void *UNUSED(closure))
595 const char order[][4] = {"XYZ", "XZY", "YXZ", "YZX", "ZXY", "ZYX"};
597 if(!BaseMath_ReadCallback(self)) /* can read order too */
600 return PyUnicode_FromString(order[self->order-EULER_ORDER_XYZ]);
603 static int Euler_setOrder(EulerObject *self, PyObject *value, void *UNUSED(closure))
605 char *order_str= _PyUnicode_AsString(value);
606 short order= euler_order_from_string(order_str, "euler.order");
612 (void)BaseMath_WriteCallback(self); /* order can be written back */
616 /*****************************************************************************/
617 /* Python attributes get/set structure: */
618 /*****************************************************************************/
619 static PyGetSetDef Euler_getseters[] = {
620 {(char *)"x", (getter)Euler_getAxis, (setter)Euler_setAxis, (char *)"Euler X axis in radians.\n\n:type: float", (void *)0},
621 {(char *)"y", (getter)Euler_getAxis, (setter)Euler_setAxis, (char *)"Euler Y axis in radians.\n\n:type: float", (void *)1},
622 {(char *)"z", (getter)Euler_getAxis, (setter)Euler_setAxis, (char *)"Euler Z axis in radians.\n\n:type: float", (void *)2},
623 {(char *)"order", (getter)Euler_getOrder, (setter)Euler_setOrder, (char *)"Euler rotation order.\n\n:type: string in ['XYZ', 'XZY', 'YXZ', 'YZX', 'ZXY', 'ZYX']", (void *)NULL},
625 {(char *)"is_wrapped", (getter)BaseMathObject_getWrapped, (setter)NULL, (char *)BaseMathObject_Wrapped_doc, NULL},
626 {(char *)"owner", (getter)BaseMathObject_getOwner, (setter)NULL, (char *)BaseMathObject_Owner_doc, NULL},
627 {NULL,NULL,NULL,NULL,NULL} /* Sentinel */
631 //-----------------------METHOD DEFINITIONS ----------------------
632 static struct PyMethodDef Euler_methods[] = {
633 {"zero", (PyCFunction) Euler_Zero, METH_NOARGS, Euler_Zero_doc},
634 {"unique", (PyCFunction) Euler_Unique, METH_NOARGS, Euler_Unique_doc},
635 {"to_matrix", (PyCFunction) Euler_ToMatrix, METH_NOARGS, Euler_ToMatrix_doc},
636 {"to_quat", (PyCFunction) Euler_ToQuat, METH_NOARGS, Euler_ToQuat_doc},
637 {"rotate_axis", (PyCFunction) Euler_rotate_axis, METH_VARARGS, Euler_rotate_axis_doc},
638 {"make_compatible", (PyCFunction) Euler_MakeCompatible, METH_O, Euler_MakeCompatible_doc},
639 {"__copy__", (PyCFunction) Euler_copy, METH_NOARGS, Euler_copy_doc},
640 {"copy", (PyCFunction) Euler_copy, METH_NOARGS, Euler_copy_doc},
641 {NULL, NULL, 0, NULL}
644 //------------------PY_OBECT DEFINITION--------------------------
645 static char euler_doc[] =
646 "This object gives access to Eulers in Blender.";
648 PyTypeObject euler_Type = {
649 PyVarObject_HEAD_INIT(NULL, 0)
650 "mathutils.Euler", //tp_name
651 sizeof(EulerObject), //tp_basicsize
653 (destructor)BaseMathObject_dealloc, //tp_dealloc
658 (reprfunc) Euler_repr, //tp_repr
660 &Euler_SeqMethods, //tp_as_sequence
661 &Euler_AsMapping, //tp_as_mapping
668 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, //tp_flags
672 (richcmpfunc)Euler_richcmpr, //tp_richcompare
673 0, //tp_weaklistoffset
676 Euler_methods, //tp_methods
678 Euler_getseters, //tp_getset
696 //------------------------newEulerObject (internal)-------------
697 //creates a new euler object
698 /*pass Py_WRAP - if vector is a WRAPPER for data allocated by BLENDER
699 (i.e. it was allocated elsewhere by MEM_mallocN())
700 pass Py_NEW - if vector is not a WRAPPER and managed by PYTHON
701 (i.e. it must be created here with PyMEM_malloc())*/
702 PyObject *newEulerObject(float *eul, short order, int type, PyTypeObject *base_type)
706 if(base_type) self = (EulerObject *)base_type->tp_alloc(base_type, 0);
707 else self = PyObject_NEW(EulerObject, &euler_Type);
709 /* init callbacks as NULL */
711 self->cb_type= self->cb_subtype= 0;
713 if(type == Py_WRAP) {
715 self->wrapped = Py_WRAP;
717 else if (type == Py_NEW){
718 self->eul = PyMem_Malloc(EULER_SIZE * sizeof(float));
720 copy_v3_v3(self->eul, eul);
724 self->wrapped = Py_NEW;
731 return (PyObject *)self;
734 PyObject *newEulerObject_cb(PyObject *cb_user, short order, int cb_type, int cb_subtype)
736 EulerObject *self= (EulerObject *)newEulerObject(NULL, order, Py_NEW, NULL);
739 self->cb_user= cb_user;
740 self->cb_type= (unsigned char)cb_type;
741 self->cb_subtype= (unsigned char)cb_subtype;
744 return (PyObject *)self;