PyAPI RNA/BGE
[blender.git] / source / blender / python / generic / euler.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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, 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_arithb.h"
32 #include "BKE_utildefines.h"
33 #include "BLI_blenlib.h"
34
35
36 //-------------------------DOC STRINGS ---------------------------
37 static char Euler_Zero_doc[] = "() - set all values in the euler to 0";
38 static char Euler_Unique_doc[] ="() - sets the euler rotation a unique shortest arc rotation - tests for gimbal lock";
39 static char Euler_ToMatrix_doc[] =      "() - returns a rotation matrix representing the euler rotation";
40 static char Euler_ToQuat_doc[] = "() - returns a quaternion representing the euler rotation";
41 static char Euler_Rotate_doc[] = "() - rotate a euler by certain amount around an axis of rotation";
42 static char Euler_copy_doc[] = "() - returns a copy of the euler.";
43 static char Euler_MakeCompatible_doc[] = "(euler) - Make this user compatible with another (no axis flipping).";
44
45 static PyObject *Euler_Zero( EulerObject * self );
46 static PyObject *Euler_Unique( EulerObject * self );
47 static PyObject *Euler_ToMatrix( EulerObject * self );
48 static PyObject *Euler_ToQuat( EulerObject * self );
49 static PyObject *Euler_Rotate( EulerObject * self, PyObject *args );
50 static PyObject *Euler_MakeCompatible( EulerObject * self, EulerObject *value );
51 static PyObject *Euler_copy( EulerObject * self, PyObject *args );
52
53 //-----------------------METHOD DEFINITIONS ----------------------
54 static struct PyMethodDef Euler_methods[] = {
55         {"zero", (PyCFunction) Euler_Zero, METH_NOARGS, Euler_Zero_doc},
56         {"unique", (PyCFunction) Euler_Unique, METH_NOARGS, Euler_Unique_doc},
57         {"toMatrix", (PyCFunction) Euler_ToMatrix, METH_NOARGS, Euler_ToMatrix_doc},
58         {"toQuat", (PyCFunction) Euler_ToQuat, METH_NOARGS, Euler_ToQuat_doc},
59         {"rotate", (PyCFunction) Euler_Rotate, METH_VARARGS, Euler_Rotate_doc},
60         {"makeCompatible", (PyCFunction) Euler_MakeCompatible, METH_O, Euler_MakeCompatible_doc},
61         {"__copy__", (PyCFunction) Euler_copy, METH_VARARGS, Euler_copy_doc},
62         {"copy", (PyCFunction) Euler_copy, METH_VARARGS, Euler_copy_doc},
63         {NULL, NULL, 0, NULL}
64 };
65
66 //----------------------------------Mathutils.Euler() -------------------
67 //makes a new euler for you to play with
68 static PyObject *Euler_new(PyObject * self, PyObject * args)
69 {
70
71         PyObject *listObject = NULL;
72         int size, i;
73         float eul[3], scalar;
74         PyObject *e;
75
76         size = PyTuple_GET_SIZE(args);
77         if (size == 1) {
78                 listObject = PyTuple_GET_ITEM(args, 0);
79                 if (PySequence_Check(listObject)) {
80                         size = PySequence_Length(listObject);
81                 } else { // Single argument was not a sequence
82                         PyErr_SetString(PyExc_TypeError, "Mathutils.Euler(): 3d numeric sequence expected\n");
83                         return NULL;
84                 }
85         } else if (size == 0) {
86                 //returns a new empty 3d euler
87                 return newEulerObject(NULL, Py_NEW); 
88         } else {
89                 listObject = args;
90         }
91
92         if (size != 3) { // Invalid euler size
93                 PyErr_SetString(PyExc_AttributeError, "Mathutils.Euler(): 3d numeric sequence expected\n");
94                 return NULL;
95         }
96
97         for (i=0; i<size; i++) {
98                 e = PySequence_GetItem(listObject, i);
99                 if (e == NULL) { // Failed to read sequence
100                         Py_DECREF(listObject);
101                         PyErr_SetString(PyExc_RuntimeError, "Mathutils.Euler(): 3d numeric sequence expected\n");
102                         return NULL;
103                 }
104
105                 scalar= (float)PyFloat_AsDouble(e);
106                 Py_DECREF(e);
107                 
108                 if(scalar==-1 && PyErr_Occurred()) { // parsed item is not a number
109                         PyErr_SetString(PyExc_TypeError, "Mathutils.Euler(): 3d numeric sequence expected\n");
110                         return NULL;
111                 }
112
113                 eul[i]= scalar;
114         }
115         return newEulerObject(eul, Py_NEW);
116 }
117
118 //-----------------------------METHODS----------------------------
119 //----------------------------Euler.toQuat()----------------------
120 //return a quaternion representation of the euler
121 static PyObject *Euler_ToQuat(EulerObject * self)
122 {
123         float eul[3], quat[4];
124         int x;
125
126         if(!BaseMath_ReadCallback(self))
127                 return NULL;
128
129         for(x = 0; x < 3; x++) {
130                 eul[x] = self->eul[x] * ((float)Py_PI / 180);
131         }
132         EulToQuat(eul, quat);
133         return newQuaternionObject(quat, Py_NEW);
134 }
135 //----------------------------Euler.toMatrix()---------------------
136 //return a matrix representation of the euler
137 static PyObject *Euler_ToMatrix(EulerObject * self)
138 {
139         float eul[3];
140         float mat[9] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f};
141         int x;
142
143         if(!BaseMath_ReadCallback(self))
144                 return NULL;
145
146         for(x = 0; x < 3; x++) {
147                 eul[x] = self->eul[x] * ((float)Py_PI / 180);
148         }
149         EulToMat3(eul, (float (*)[3]) mat);
150         return newMatrixObject(mat, 3, 3 , Py_NEW);
151 }
152 //----------------------------Euler.unique()-----------------------
153 //sets the x,y,z values to a unique euler rotation
154 static PyObject *Euler_Unique(EulerObject * self)
155 {
156         double heading, pitch, bank;
157         double pi2 =  Py_PI * 2.0f;
158         double piO2 = Py_PI / 2.0f;
159         double Opi2 = 1.0f / pi2;
160
161         if(!BaseMath_ReadCallback(self))
162                 return NULL;
163
164         //radians
165         heading = self->eul[0] * (float)Py_PI / 180;
166         pitch = self->eul[1] * (float)Py_PI / 180;
167         bank = self->eul[2] * (float)Py_PI / 180;
168
169         //wrap heading in +180 / -180
170         pitch += Py_PI;
171         pitch -= floor(pitch * Opi2) * pi2;
172         pitch -= Py_PI;
173
174
175         if(pitch < -piO2) {
176                 pitch = -Py_PI - pitch;
177                 heading += Py_PI;
178                 bank += Py_PI;
179         } else if(pitch > piO2) {
180                 pitch = Py_PI - pitch;
181                 heading += Py_PI;
182                 bank += Py_PI;
183         }
184         //gimbal lock test
185         if(fabs(pitch) > piO2 - 1e-4) {
186                 heading += bank;
187                 bank = 0.0f;
188         } else {
189                 bank += Py_PI;
190                 bank -= (floor(bank * Opi2)) * pi2;
191                 bank -= Py_PI;
192         }
193
194         heading += Py_PI;
195         heading -= (floor(heading * Opi2)) * pi2;
196         heading -= Py_PI;
197
198         //back to degrees
199         self->eul[0] = (float)(heading * 180 / (float)Py_PI);
200         self->eul[1] = (float)(pitch * 180 / (float)Py_PI);
201         self->eul[2] = (float)(bank * 180 / (float)Py_PI);
202
203         BaseMath_WriteCallback(self);
204         Py_INCREF(self);
205         return (PyObject *)self;
206 }
207 //----------------------------Euler.zero()-------------------------
208 //sets the euler to 0,0,0
209 static PyObject *Euler_Zero(EulerObject * self)
210 {
211         self->eul[0] = 0.0;
212         self->eul[1] = 0.0;
213         self->eul[2] = 0.0;
214
215         BaseMath_WriteCallback(self);
216         Py_INCREF(self);
217         return (PyObject *)self;
218 }
219 //----------------------------Euler.rotate()-----------------------
220 //rotates a euler a certain amount and returns the result
221 //should return a unique euler rotation (i.e. no 720 degree pitches :)
222 static PyObject *Euler_Rotate(EulerObject * self, PyObject *args)
223 {
224         float angle = 0.0f;
225         char *axis;
226         int x;
227
228         if(!PyArg_ParseTuple(args, "fs", &angle, &axis)){
229                 PyErr_SetString(PyExc_TypeError, "euler.rotate():expected angle (float) and axis (x,y,z)");
230                 return NULL;
231         }
232         if(!STREQ3(axis,"x","y","z")){
233                 PyErr_SetString(PyExc_TypeError, "euler.rotate(): expected axis to be 'x', 'y' or 'z'");
234                 return NULL;
235         }
236
237         if(!BaseMath_ReadCallback(self))
238                 return NULL;
239
240         //covert to radians
241         angle *= ((float)Py_PI / 180);
242         for(x = 0; x < 3; x++) {
243                 self->eul[x] *= ((float)Py_PI / 180);
244         }
245         euler_rot(self->eul, angle, *axis);
246         //convert back from radians
247         for(x = 0; x < 3; x++) {
248                 self->eul[x] *= (180 / (float)Py_PI);
249         }
250
251         BaseMath_WriteCallback(self);
252         Py_INCREF(self);
253         return (PyObject *)self;
254 }
255
256 static PyObject *Euler_MakeCompatible(EulerObject * self, EulerObject *value)
257 {
258         float eul_from_rad[3];
259         int x;
260         
261         if(!EulerObject_Check(value)) {
262                 PyErr_SetString(PyExc_TypeError, "euler.makeCompatible(euler):expected a single euler argument.");
263                 return NULL;
264         }
265         
266         if(!BaseMath_ReadCallback(self) || !BaseMath_ReadCallback(value))
267                 return NULL;
268
269         //covert to radians
270         for(x = 0; x < 3; x++) {
271                 self->eul[x] = self->eul[x] * ((float)Py_PI / 180);
272                 eul_from_rad[x] = value->eul[x] * ((float)Py_PI / 180);
273         }
274         compatible_eul(self->eul, eul_from_rad);
275         //convert back from radians
276         for(x = 0; x < 3; x++) {
277                 self->eul[x] *= (180 / (float)Py_PI);
278         }
279         
280         BaseMath_WriteCallback(self);
281         Py_INCREF(self);
282         return (PyObject *)self;
283 }
284
285 //----------------------------Euler.rotate()-----------------------
286 // return a copy of the euler
287 static PyObject *Euler_copy(EulerObject * self, PyObject *args)
288 {
289         if(!BaseMath_ReadCallback(self))
290                 return NULL;
291
292         return newEulerObject(self->eul, Py_NEW);
293 }
294
295 //----------------------------print object (internal)--------------
296 //print the object to screen
297 static PyObject *Euler_repr(EulerObject * self)
298 {
299         char str[64];
300
301         if(!BaseMath_ReadCallback(self))
302                 return NULL;
303
304         sprintf(str, "[%.6f, %.6f, %.6f](euler)", self->eul[0], self->eul[1], self->eul[2]);
305         return PyUnicode_FromString(str);
306 }
307 //------------------------tp_richcmpr
308 //returns -1 execption, 0 false, 1 true
309 static PyObject* Euler_richcmpr(PyObject *objectA, PyObject *objectB, int comparison_type)
310 {
311         EulerObject *eulA = NULL, *eulB = NULL;
312         int result = 0;
313
314         if(EulerObject_Check(objectA)) {
315                 eulA = (EulerObject*)objectA;
316                 if(!BaseMath_ReadCallback(eulA))
317                         return NULL;
318         }
319         if(EulerObject_Check(objectB)) {
320                 eulB = (EulerObject*)objectB;
321                 if(!BaseMath_ReadCallback(eulB))
322                         return NULL;
323         }
324
325         if (!eulA || !eulB){
326                 if (comparison_type == Py_NE){
327                         Py_RETURN_TRUE;
328                 }else{
329                         Py_RETURN_FALSE;
330                 }
331         }
332         eulA = (EulerObject*)objectA;
333         eulB = (EulerObject*)objectB;
334
335         switch (comparison_type){
336                 case Py_EQ:
337                         result = EXPP_VectorsAreEqual(eulA->eul, eulB->eul, 3, 1);
338                         break;
339                 case Py_NE:
340                         result = EXPP_VectorsAreEqual(eulA->eul, eulB->eul, 3, 1);
341                         if (result == 0){
342                                 result = 1;
343                         }else{
344                                 result = 0;
345                         }
346                         break;
347                 default:
348                         printf("The result of the comparison could not be evaluated");
349                         break;
350         }
351         if (result == 1){
352                 Py_RETURN_TRUE;
353         }else{
354                 Py_RETURN_FALSE;
355         }
356 }
357 //------------------------tp_doc
358 static char EulerObject_doc[] = "This is a wrapper for euler objects.";
359 //---------------------SEQUENCE PROTOCOLS------------------------
360 //----------------------------len(object)------------------------
361 //sequence length
362 static int Euler_len(EulerObject * self)
363 {
364         return 3;
365 }
366 //----------------------------object[]---------------------------
367 //sequence accessor (get)
368 static PyObject *Euler_item(EulerObject * self, int i)
369 {
370         if(i<0) i= 3-i;
371         
372         if(i < 0 || i >= 3) {
373                 PyErr_SetString(PyExc_IndexError, "euler[attribute]: array index out of range");
374                 return NULL;
375         }
376
377         if(!BaseMath_ReadIndexCallback(self, i))
378                 return NULL;
379
380         return PyFloat_FromDouble(self->eul[i]);
381
382 }
383 //----------------------------object[]-------------------------
384 //sequence accessor (set)
385 static int Euler_ass_item(EulerObject * self, int i, PyObject * value)
386 {
387         float f = PyFloat_AsDouble(value);
388
389         if(f == -1 && PyErr_Occurred()) { // parsed item not a number
390                 PyErr_SetString(PyExc_TypeError, "euler[attribute] = x: argument not a number");
391                 return -1;
392         }
393
394         if(i<0) i= 3-i;
395         
396         if(i < 0 || i >= 3){
397                 PyErr_SetString(PyExc_IndexError, "euler[attribute] = x: array assignment index out of range\n");
398                 return -1;
399         }
400         
401         self->eul[i] = f;
402
403         if(!BaseMath_WriteIndexCallback(self, i))
404                 return -1;
405
406         return 0;
407 }
408 //----------------------------object[z:y]------------------------
409 //sequence slice (get)
410 static PyObject *Euler_slice(EulerObject * self, int begin, int end)
411 {
412         PyObject *list = NULL;
413         int count;
414
415         if(!BaseMath_ReadCallback(self))
416                 return NULL;
417
418         CLAMP(begin, 0, 3);
419         if (end<0) end= 4+end;
420         CLAMP(end, 0, 3);
421         begin = MIN2(begin,end);
422
423         list = PyList_New(end - begin);
424         for(count = begin; count < end; count++) {
425                 PyList_SetItem(list, count - begin,
426                                 PyFloat_FromDouble(self->eul[count]));
427         }
428
429         return list;
430 }
431 //----------------------------object[z:y]------------------------
432 //sequence slice (set)
433 static int Euler_ass_slice(EulerObject * self, int begin, int end,
434                              PyObject * seq)
435 {
436         int i, y, size = 0;
437         float eul[3];
438         PyObject *e;
439
440         if(!BaseMath_ReadCallback(self))
441                 return NULL;
442
443         CLAMP(begin, 0, 3);
444         if (end<0) end= 4+end;
445         CLAMP(end, 0, 3);
446         begin = MIN2(begin,end);
447
448         size = PySequence_Length(seq);
449         if(size != (end - begin)){
450                 PyErr_SetString(PyExc_TypeError, "euler[begin:end] = []: size mismatch in slice assignment");
451                 return -1;
452         }
453
454         for (i = 0; i < size; i++) {
455                 e = PySequence_GetItem(seq, i);
456                 if (e == NULL) { // Failed to read sequence
457                         PyErr_SetString(PyExc_RuntimeError, "euler[begin:end] = []: unable to read sequence");
458                         return -1;
459                 }
460
461                 eul[i] = (float)PyFloat_AsDouble(e);
462                 Py_DECREF(e);
463
464                 if(eul[i]==-1 && PyErr_Occurred()) { // parsed item not a number
465                         PyErr_SetString(PyExc_TypeError, "euler[begin:end] = []: sequence argument not a number");
466                         return -1;
467                 }
468         }
469         //parsed well - now set in vector
470         for(y = 0; y < 3; y++){
471                 self->eul[begin + y] = eul[y];
472         }
473
474         BaseMath_WriteCallback(self);
475         return 0;
476 }
477 //-----------------PROTCOL DECLARATIONS--------------------------
478 static PySequenceMethods Euler_SeqMethods = {
479         (inquiry) Euler_len,                                            /* sq_length */
480         (binaryfunc) 0,                                                         /* sq_concat */
481         (ssizeargfunc) 0,                                                               /* sq_repeat */
482         (ssizeargfunc) Euler_item,                                      /* sq_item */
483         (ssizessizeargfunc) Euler_slice,                                /* sq_slice */
484         (ssizeobjargproc) Euler_ass_item,                               /* sq_ass_item */
485         (ssizessizeobjargproc) Euler_ass_slice,                 /* sq_ass_slice */
486 };
487
488
489 /*
490  * vector axis, vector.x/y/z/w
491  */
492         
493 static PyObject *Euler_getAxis( EulerObject * self, void *type )
494 {
495         return Euler_item(self, GET_INT_FROM_POINTER(type));
496 }
497
498 static int Euler_setAxis( EulerObject * self, PyObject * value, void * type )
499 {
500         return Euler_ass_item(self, GET_INT_FROM_POINTER(type), value);
501 }
502
503 /*****************************************************************************/
504 /* Python attributes get/set structure:                                      */
505 /*****************************************************************************/
506 static PyGetSetDef Euler_getseters[] = {
507         {"x", (getter)Euler_getAxis, (setter)Euler_setAxis, "Euler X axis", (void *)0},
508         {"y", (getter)Euler_getAxis, (setter)Euler_setAxis, "Euler Y axis", (void *)1},
509         {"z", (getter)Euler_getAxis, (setter)Euler_setAxis, "Euler Z axis", (void *)2},
510
511         {"wrapped", (getter)BaseMathObject_getWrapped, (setter)NULL, "True when this wraps blenders internal data", NULL},
512         {"__owner__", (getter)BaseMathObject_getOwner, (setter)NULL, "Read only owner for vectors that depend on another object", NULL},
513         {NULL,NULL,NULL,NULL,NULL}  /* Sentinel */
514 };
515
516 //------------------PY_OBECT DEFINITION--------------------------
517 PyTypeObject euler_Type = {
518 #if (PY_VERSION_HEX >= 0x02060000)
519         PyVarObject_HEAD_INIT(NULL, 0)
520 #else
521         /* python 2.5 and below */
522         PyObject_HEAD_INIT( NULL )  /* required py macro */
523         0,                          /* ob_size */
524 #endif
525         "euler",                                                //tp_name
526         sizeof(EulerObject),                    //tp_basicsize
527         0,                                                              //tp_itemsize
528         (destructor)BaseMathObject_dealloc,             //tp_dealloc
529         0,                                                              //tp_print
530         0,                                                              //tp_getattr
531         0,                                                              //tp_setattr
532         0,                                                              //tp_compare
533         (reprfunc) Euler_repr,                  //tp_repr
534         0,                              //tp_as_number
535         &Euler_SeqMethods,                              //tp_as_sequence
536         0,                                                              //tp_as_mapping
537         0,                                                              //tp_hash
538         0,                                                              //tp_call
539         0,                                                              //tp_str
540         0,                                                              //tp_getattro
541         0,                                                              //tp_setattro
542         0,                                                              //tp_as_buffer
543         Py_TPFLAGS_DEFAULT,                             //tp_flags
544         EulerObject_doc,                                //tp_doc
545         0,                                                              //tp_traverse
546         0,                                                              //tp_clear
547         (richcmpfunc)Euler_richcmpr,    //tp_richcompare
548         0,                                                              //tp_weaklistoffset
549         0,                                                              //tp_iter
550         0,                                                              //tp_iternext
551         Euler_methods,                                  //tp_methods
552         0,                                                              //tp_members
553         Euler_getseters,                                //tp_getset
554         0,                                                              //tp_base
555         0,                                                              //tp_dict
556         0,                                                              //tp_descr_get
557         0,                                                              //tp_descr_set
558         0,                                                              //tp_dictoffset
559         0,                                                              //tp_init
560         0,                                                              //tp_alloc
561         Euler_new,                                              //tp_new
562         0,                                                              //tp_free
563         0,                                                              //tp_is_gc
564         0,                                                              //tp_bases
565         0,                                                              //tp_mro
566         0,                                                              //tp_cache
567         0,                                                              //tp_subclasses
568         0,                                                              //tp_weaklist
569         0                                                               //tp_del
570 };
571 //------------------------newEulerObject (internal)-------------
572 //creates a new euler object
573 /*pass Py_WRAP - if vector is a WRAPPER for data allocated by BLENDER
574  (i.e. it was allocated elsewhere by MEM_mallocN())
575   pass Py_NEW - if vector is not a WRAPPER and managed by PYTHON
576  (i.e. it must be created here with PyMEM_malloc())*/
577 PyObject *newEulerObject(float *eul, int type)
578 {
579         EulerObject *self;
580         int x;
581
582         self = PyObject_NEW(EulerObject, &euler_Type);
583
584         /* init callbacks as NULL */
585         self->cb_user= NULL;
586         self->cb_type= self->cb_subtype= 0;
587
588         if(type == Py_WRAP){
589                 self->eul = eul;
590                 self->wrapped = Py_WRAP;
591         }else if (type == Py_NEW){
592                 self->eul = PyMem_Malloc(3 * sizeof(float));
593                 if(!eul) { //new empty
594                         for(x = 0; x < 3; x++) {
595                                 self->eul[x] = 0.0f;
596                         }
597                 }else{
598                         VECCOPY(self->eul, eul);
599                 }
600                 self->wrapped = Py_NEW;
601         }else{ //bad type
602                 return NULL;
603         }
604         return (PyObject *)self;
605 }
606
607 PyObject *newEulerObject_cb(PyObject *cb_user, int cb_type, int cb_subtype)
608 {
609         EulerObject *self= (EulerObject *)newEulerObject(NULL, Py_NEW);
610         if(self) {
611                 Py_INCREF(cb_user);
612                 self->cb_user=                  cb_user;
613                 self->cb_type=                  (unsigned char)cb_type;
614                 self->cb_subtype=               (unsigned char)cb_subtype;
615         }
616
617         return self;
618 }