6a7f54d6f81d4d958c2a86ee74ca48b9b51ca834
[blender.git] / source / blender / python / mathutils / mathutils.c
1 /* 
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
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.
8  *
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.
13  *
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.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * This is a new part of Blender.
22  *
23  * Contributor(s): Joseph Gilbert, Campbell Barton
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/python/mathutils/mathutils.c
29  *  \ingroup pymathutils
30  */
31
32 #include <Python.h>
33
34 #include "mathutils.h"
35
36 #include "BLI_math.h"
37 #include "BLI_utildefines.h"
38
39 PyDoc_STRVAR(M_Mathutils_doc,
40 "This module provides access to matrices, eulers, quaternions and vectors."
41 );
42 static int mathutils_array_parse_fast(float *array,
43                                       int size,
44                                       PyObject *value_fast,
45                                                                           const char *error_prefix)
46 {
47         PyObject *item;
48
49         int i;
50
51         i= size;
52         do {
53                 i--;
54                 if ( ((array[i]= PyFloat_AsDouble((item= PySequence_Fast_GET_ITEM(value_fast, i)))) == -1.0f) &&
55                      PyErr_Occurred())
56                 {
57                         PyErr_Format(PyExc_TypeError,
58                                      "%.200s: sequence index %d expected a number, "
59                                      "found '%.200s' type, ",
60                                      error_prefix, i, Py_TYPE(item)->tp_name);
61                         Py_DECREF(value_fast);
62                         return -1;
63                 }
64         } while (i);
65
66         Py_XDECREF(value_fast);
67         return size;
68 }
69
70 /* helper functionm returns length of the 'value', -1 on error */
71 int mathutils_array_parse(float *array, int array_min, int array_max, PyObject *value, const char *error_prefix)
72 {
73         int size;
74
75 #if 1 /* approx 6x speedup for mathutils types */
76
77         if (    (size= VectorObject_Check(value)     ? ((VectorObject *)value)->size : 0) ||
78                 (size= EulerObject_Check(value)      ? 3 : 0) ||
79                 (size= QuaternionObject_Check(value) ? 4 : 0) ||
80                 (size= ColorObject_Check(value)      ? 3 : 0))
81         {
82                 if (BaseMath_ReadCallback((BaseMathObject *)value) == -1) {
83                         return -1;
84                 }
85
86                 if (size > array_max || size < array_min) {
87                         if (array_max == array_min)     {
88                                 PyErr_Format(PyExc_ValueError,
89                                              "%.200s: sequence size is %d, expected %d",
90                                              error_prefix, size, array_max);
91                         }
92                         else {
93                                 PyErr_Format(PyExc_ValueError,
94                                              "%.200s: sequence size is %d, expected [%d - %d]",
95                                              error_prefix, size, array_min, array_max);
96                         }
97                         return -1;
98                 }
99
100                 memcpy(array, ((BaseMathObject *)value)->data, size * sizeof(float));
101                 return size;
102         }
103         else
104 #endif
105         {
106                 PyObject *value_fast= NULL;
107
108                 /* non list/tuple cases */
109                 if (!(value_fast=PySequence_Fast(value, error_prefix))) {
110                         /* PySequence_Fast sets the error */
111                         return -1;
112                 }
113
114                 size= PySequence_Fast_GET_SIZE(value_fast);
115
116                 if (size > array_max || size < array_min) {
117                         if (array_max == array_min)     {
118                                 PyErr_Format(PyExc_ValueError,
119                                                          "%.200s: sequence size is %d, expected %d",
120                                                          error_prefix, size, array_max);
121                         }
122                         else {
123                                 PyErr_Format(PyExc_ValueError,
124                                                          "%.200s: sequence size is %d, expected [%d - %d]",
125                                                          error_prefix, size, array_min, array_max);
126                         }
127                         Py_DECREF(value_fast);
128                         return -1;
129                 }
130
131                 return mathutils_array_parse_fast(array, size, value_fast, error_prefix);
132         }
133 }
134
135 int mathutils_array_parse_alloc(float **array, int array_min, PyObject *value, const char *error_prefix)
136 {
137         int size;
138
139 #if 1 /* approx 6x speedup for mathutils types */
140
141         if (    (size= VectorObject_Check(value)     ? ((VectorObject *)value)->size : 0) ||
142                 (size= EulerObject_Check(value)      ? 3 : 0) ||
143                 (size= QuaternionObject_Check(value) ? 4 : 0) ||
144                 (size= ColorObject_Check(value)      ? 3 : 0))
145         {
146                 if (BaseMath_ReadCallback((BaseMathObject *)value) == -1) {
147                         return -1;
148                 }
149
150                 if (size < array_min) {
151                         PyErr_Format(PyExc_ValueError,
152                                      "%.200s: sequence size is %d, expected > %d",
153                                      error_prefix, size, array_min);
154                         return -1;
155                 }
156                 
157                 *array= PyMem_Malloc(size * sizeof(float));
158                 memcpy(*array, ((BaseMathObject *)value)->data, size * sizeof(float));
159                 return size;
160         }
161         else
162 #endif
163         {
164                 PyObject *value_fast= NULL;
165                 //*array= NULL;
166
167                 /* non list/tuple cases */
168                 if (!(value_fast=PySequence_Fast(value, error_prefix))) {
169                         /* PySequence_Fast sets the error */
170                         return -1;
171                 }
172
173                 size= PySequence_Fast_GET_SIZE(value_fast);
174
175                 if (size < array_min) {
176                         PyErr_Format(PyExc_ValueError,
177                                      "%.200s: sequence size is %d, expected > %d",
178                                      error_prefix, size, array_min);
179                         return -1;
180                 }
181
182                 *array= PyMem_Malloc(size * sizeof(float));
183
184                 return mathutils_array_parse_fast(*array, size, value_fast, error_prefix);
185         }
186 }
187
188 int mathutils_any_to_rotmat(float rmat[3][3], PyObject *value, const char *error_prefix)
189 {
190         if (EulerObject_Check(value)) {
191                 if (BaseMath_ReadCallback((BaseMathObject *)value) == -1) {
192                         return -1;
193                 }
194                 else {
195                         eulO_to_mat3(rmat, ((EulerObject *)value)->eul, ((EulerObject *)value)->order);
196                         return 0;
197                 }
198         }
199         else if (QuaternionObject_Check(value)) {
200                 if (BaseMath_ReadCallback((BaseMathObject *)value) == -1) {
201                         return -1;
202                 }
203                 else {
204                         float tquat[4];
205                         normalize_qt_qt(tquat, ((QuaternionObject *)value)->quat);
206                         quat_to_mat3(rmat, tquat);
207                         return 0;
208                 }
209         }
210         else if (MatrixObject_Check(value)) {
211                 if (BaseMath_ReadCallback((BaseMathObject *)value) == -1) {
212                         return -1;
213                 }
214                 else if (((MatrixObject *)value)->col_size < 3 || ((MatrixObject *)value)->row_size < 3) {
215                         PyErr_Format(PyExc_ValueError,
216                                      "%.200s: matrix must have minimum 3x3 dimensions",
217                                      error_prefix);
218                         return -1;
219                 }
220                 else {
221                         matrix_as_3x3(rmat, (MatrixObject *)value);
222                         normalize_m3(rmat);
223                         return 0;
224                 }
225         }
226         else {
227                 PyErr_Format(PyExc_TypeError,
228                              "%.200s: expected a Euler, Quaternion or Matrix type, "
229                              "found %.200s", error_prefix, Py_TYPE(value)->tp_name);
230                 return -1;
231         }
232 }
233
234
235 //----------------------------------MATRIX FUNCTIONS--------------------
236
237
238 /* Utility functions */
239
240 // LomontRRDCompare4, Ever Faster Float Comparisons by Randy Dillon
241 #define SIGNMASK(i) (-(int)(((unsigned int)(i))>>31))
242
243 int EXPP_FloatsAreEqual(float af, float bf, int maxDiff)
244 {       // solid, fast routine across all platforms
245         // with constant time behavior
246         int ai = *(int *)(&af);
247         int bi = *(int *)(&bf);
248         int test = SIGNMASK(ai^bi);
249         int diff, v1, v2;
250
251         assert((0 == test) || (0xFFFFFFFF == test));
252         diff = (ai ^ (test & 0x7fffffff)) - bi;
253         v1 = maxDiff + diff;
254         v2 = maxDiff - diff;
255         return (v1|v2) >= 0;
256 }
257
258 /*---------------------- EXPP_VectorsAreEqual -------------------------
259   Builds on EXPP_FloatsAreEqual to test vectors */
260 int EXPP_VectorsAreEqual(float *vecA, float *vecB, int size, int floatSteps)
261 {
262         int x;
263         for (x=0; x< size; x++) {
264                 if (EXPP_FloatsAreEqual(vecA[x], vecB[x], floatSteps) == 0)
265                         return 0;
266         }
267         return 1;
268 }
269
270
271 /* Mathutils Callbacks */
272
273 /* for mathutils internal use only, eventually should re-alloc but to start with we only have a few users */
274 static Mathutils_Callback *mathutils_callbacks[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
275
276 int Mathutils_RegisterCallback(Mathutils_Callback *cb)
277 {
278         int i;
279         
280         /* find the first free slot */
281         for (i= 0; mathutils_callbacks[i]; i++) {
282                 if (mathutils_callbacks[i]==cb) /* already registered? */
283                         return i;
284         }
285         
286         mathutils_callbacks[i] = cb;
287         return i;
288 }
289
290 /* use macros to check for NULL */
291 int _BaseMathObject_ReadCallback(BaseMathObject *self)
292 {
293         Mathutils_Callback *cb= mathutils_callbacks[self->cb_type];
294         if (cb->get(self, self->cb_subtype) != -1)
295                 return 0;
296
297         if (!PyErr_Occurred()) {
298                 PyErr_Format(PyExc_RuntimeError,
299                              "%s read, user has become invalid",
300                              Py_TYPE(self)->tp_name);
301         }
302         return -1;
303 }
304
305 int _BaseMathObject_WriteCallback(BaseMathObject *self)
306 {
307         Mathutils_Callback *cb= mathutils_callbacks[self->cb_type];
308         if (cb->set(self, self->cb_subtype) != -1)
309                 return 0;
310
311         if (!PyErr_Occurred()) {
312                 PyErr_Format(PyExc_RuntimeError,
313                              "%s write, user has become invalid",
314                              Py_TYPE(self)->tp_name);
315         }
316         return -1;
317 }
318
319 int _BaseMathObject_ReadIndexCallback(BaseMathObject *self, int index)
320 {
321         Mathutils_Callback *cb= mathutils_callbacks[self->cb_type];
322         if (cb->get_index(self, self->cb_subtype, index) != -1)
323                 return 0;
324
325         if (!PyErr_Occurred()) {
326                 PyErr_Format(PyExc_RuntimeError,
327                              "%s read index, user has become invalid",
328                              Py_TYPE(self)->tp_name);
329         }
330         return -1;
331 }
332
333 int _BaseMathObject_WriteIndexCallback(BaseMathObject *self, int index)
334 {
335         Mathutils_Callback *cb= mathutils_callbacks[self->cb_type];
336         if (cb->set_index(self, self->cb_subtype, index) != -1)
337                 return 0;
338
339         if (!PyErr_Occurred()) {
340                 PyErr_Format(PyExc_RuntimeError,
341                              "%s write index, user has become invalid",
342                              Py_TYPE(self)->tp_name);
343         }
344         return -1;
345 }
346
347 /* BaseMathObject generic functions for all mathutils types */
348 char BaseMathObject_Owner_doc[] = "The item this is wrapping or None  (readonly).";
349 PyObject *BaseMathObject_getOwner(BaseMathObject *self, void *UNUSED(closure))
350 {
351         PyObject *ret= self->cb_user ? self->cb_user : Py_None;
352         Py_INCREF(ret);
353         return ret;
354 }
355
356 char BaseMathObject_Wrapped_doc[] = "True when this object wraps external data (readonly).\n\n:type: boolean";
357 PyObject *BaseMathObject_getWrapped(BaseMathObject *self, void *UNUSED(closure))
358 {
359         return PyBool_FromLong((self->wrapped == Py_WRAP) ? 1:0);
360 }
361
362 int BaseMathObject_traverse(BaseMathObject *self, visitproc visit, void *arg)
363 {
364         Py_VISIT(self->cb_user);
365         return 0;
366 }
367
368 int BaseMathObject_clear(BaseMathObject *self)
369 {
370         Py_CLEAR(self->cb_user);
371         return 0;
372 }
373
374 void BaseMathObject_dealloc(BaseMathObject *self)
375 {
376         /* only free non wrapped */
377         if (self->wrapped != Py_WRAP) {
378                 PyMem_Free(self->data);
379         }
380
381         if (self->cb_user) {
382                 PyObject_GC_UnTrack(self);
383                 BaseMathObject_clear(self);
384         }
385
386         Py_TYPE(self)->tp_free(self); // PyObject_DEL(self); // breaks subtypes
387 }
388
389 /*----------------------------MODULE INIT-------------------------*/
390 static struct PyMethodDef M_Mathutils_methods[] = {
391         {NULL, NULL, 0, NULL}
392 };
393
394 static struct PyModuleDef M_Mathutils_module_def = {
395         PyModuleDef_HEAD_INIT,
396         "mathutils",  /* m_name */
397         M_Mathutils_doc,  /* m_doc */
398         0,  /* m_size */
399         M_Mathutils_methods,  /* m_methods */
400         NULL,  /* m_reload */
401         NULL,  /* m_traverse */
402         NULL,  /* m_clear */
403         NULL,  /* m_free */
404 };
405
406 PyMODINIT_FUNC PyInit_mathutils(void)
407 {
408         PyObject *submodule;
409         PyObject *item;
410         PyObject *sys_modules= PyThreadState_GET()->interp->modules;
411
412         if (PyType_Ready(&vector_Type) < 0)
413                 return NULL;
414         if (PyType_Ready(&matrix_Type) < 0)
415                 return NULL;    
416         if (PyType_Ready(&euler_Type) < 0)
417                 return NULL;
418         if (PyType_Ready(&quaternion_Type) < 0)
419                 return NULL;
420         if (PyType_Ready(&color_Type) < 0)
421                 return NULL;
422
423         submodule = PyModule_Create(&M_Mathutils_module_def);
424         
425         /* each type has its own new() function */
426         PyModule_AddObject(submodule, "Vector",         (PyObject *)&vector_Type);
427         PyModule_AddObject(submodule, "Matrix",         (PyObject *)&matrix_Type);
428         PyModule_AddObject(submodule, "Euler",          (PyObject *)&euler_Type);
429         PyModule_AddObject(submodule, "Quaternion",     (PyObject *)&quaternion_Type);
430         PyModule_AddObject(submodule, "Color",          (PyObject *)&color_Type);
431         
432         /* submodule */
433         PyModule_AddObject(submodule, "geometry",               (item=PyInit_mathutils_geometry()));
434         /* XXX, python doesnt do imports with this usefully yet
435          * 'from mathutils.geometry import PolyFill'
436          * ...fails without this. */
437         PyDict_SetItemString(sys_modules, "mathutils.geometry", item);
438         Py_INCREF(item);
439
440         /* Noise submodule */
441         PyModule_AddObject(submodule, "noise",          (item=PyInit_mathutils_noise()));
442         PyDict_SetItemString(sys_modules, "mathutils.noise", item);
443         Py_INCREF(item);
444
445         mathutils_matrix_vector_cb_index= Mathutils_RegisterCallback(&mathutils_matrix_vector_cb);
446
447         return submodule;
448 }