ifdef out dynstr so mathutils can be compiled as an external module again.
[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 #ifndef MATH_STANDALONE
40 #  include "BLI_dynstr.h"
41 #endif
42
43 PyDoc_STRVAR(M_Mathutils_doc,
44 "This module provides access to matrices, eulers, quaternions and vectors."
45 );
46 static int mathutils_array_parse_fast(float *array,
47                                       int size,
48                                       PyObject *value_fast,
49                                       const char *error_prefix)
50 {
51         PyObject *item;
52
53         int i;
54
55         i = size;
56         do {
57                 i--;
58                 if (((array[i] = PyFloat_AsDouble((item = PySequence_Fast_GET_ITEM(value_fast, i)))) == -1.0f) &&
59                     PyErr_Occurred())
60                 {
61                         PyErr_Format(PyExc_TypeError,
62                                      "%.200s: sequence index %d expected a number, "
63                                      "found '%.200s' type, ",
64                                      error_prefix, i, Py_TYPE(item)->tp_name);
65                         Py_DECREF(value_fast);
66                         return -1;
67                 }
68         } while (i);
69
70         Py_XDECREF(value_fast);
71         return size;
72 }
73
74 /* helper functionm returns length of the 'value', -1 on error */
75 int mathutils_array_parse(float *array, int array_min, int array_max, PyObject *value, const char *error_prefix)
76 {
77         int size;
78
79 #if 1 /* approx 6x speedup for mathutils types */
80
81         if ((size = VectorObject_Check(value)     ? ((VectorObject *)value)->size : 0) ||
82             (size = EulerObject_Check(value)      ? 3 : 0) ||
83             (size = QuaternionObject_Check(value) ? 4 : 0) ||
84             (size = ColorObject_Check(value)      ? 3 : 0))
85         {
86                 if (BaseMath_ReadCallback((BaseMathObject *)value) == -1) {
87                         return -1;
88                 }
89
90                 if (size > array_max || size < array_min) {
91                         if (array_max == array_min) {
92                                 PyErr_Format(PyExc_ValueError,
93                                              "%.200s: sequence size is %d, expected %d",
94                                              error_prefix, size, array_max);
95                         }
96                         else {
97                                 PyErr_Format(PyExc_ValueError,
98                                              "%.200s: sequence size is %d, expected [%d - %d]",
99                                              error_prefix, size, array_min, array_max);
100                         }
101                         return -1;
102                 }
103
104                 memcpy(array, ((BaseMathObject *)value)->data, size * sizeof(float));
105                 return size;
106         }
107         else
108 #endif
109         {
110                 PyObject *value_fast = NULL;
111
112                 /* non list/tuple cases */
113                 if (!(value_fast = PySequence_Fast(value, error_prefix))) {
114                         /* PySequence_Fast sets the error */
115                         return -1;
116                 }
117
118                 size = PySequence_Fast_GET_SIZE(value_fast);
119
120                 if (size > array_max || size < array_min) {
121                         if (array_max == array_min) {
122                                 PyErr_Format(PyExc_ValueError,
123                                              "%.200s: sequence size is %d, expected %d",
124                                              error_prefix, size, array_max);
125                         }
126                         else {
127                                 PyErr_Format(PyExc_ValueError,
128                                              "%.200s: sequence size is %d, expected [%d - %d]",
129                                              error_prefix, size, array_min, array_max);
130                         }
131                         Py_DECREF(value_fast);
132                         return -1;
133                 }
134
135                 return mathutils_array_parse_fast(array, size, value_fast, error_prefix);
136         }
137 }
138
139 /* on error, -1 is returned and no allocation is made */
140 int mathutils_array_parse_alloc(float **array, int array_min, PyObject *value, const char *error_prefix)
141 {
142         int size;
143
144 #if 1 /* approx 6x speedup for mathutils types */
145
146         if ((size = VectorObject_Check(value)     ? ((VectorObject *)value)->size : 0) ||
147             (size = EulerObject_Check(value)      ? 3 : 0) ||
148             (size = QuaternionObject_Check(value) ? 4 : 0) ||
149             (size = ColorObject_Check(value)      ? 3 : 0))
150         {
151                 if (BaseMath_ReadCallback((BaseMathObject *)value) == -1) {
152                         return -1;
153                 }
154
155                 if (size < array_min) {
156                         PyErr_Format(PyExc_ValueError,
157                                      "%.200s: sequence size is %d, expected > %d",
158                                      error_prefix, size, array_min);
159                         return -1;
160                 }
161                 
162                 *array = PyMem_Malloc(size * sizeof(float));
163                 memcpy(*array, ((BaseMathObject *)value)->data, size * sizeof(float));
164                 return size;
165         }
166         else
167 #endif
168         {
169                 PyObject *value_fast = NULL;
170                 // *array = NULL;
171                 int ret;
172
173                 /* non list/tuple cases */
174                 if (!(value_fast = PySequence_Fast(value, error_prefix))) {
175                         /* PySequence_Fast sets the error */
176                         return -1;
177                 }
178
179                 size = PySequence_Fast_GET_SIZE(value_fast);
180
181                 if (size < array_min) {
182                         PyErr_Format(PyExc_ValueError,
183                                      "%.200s: sequence size is %d, expected > %d",
184                                      error_prefix, size, array_min);
185                         return -1;
186                 }
187
188                 *array = PyMem_Malloc(size * sizeof(float));
189
190                 ret = mathutils_array_parse_fast(*array, size, value_fast, error_prefix);
191
192                 if (ret == -1) {
193                         PyMem_Free(*array);
194                 }
195
196                 return ret;
197         }
198 }
199
200 /* parse an array of vectors */
201 int mathutils_array_parse_alloc_v(float **array, int array_dim, PyObject *value, const char *error_prefix)
202 {
203         PyObject *value_fast = NULL;
204         int i, size;
205
206         /* non list/tuple cases */
207         if (!(value_fast = PySequence_Fast(value, error_prefix))) {
208                 /* PySequence_Fast sets the error */
209                 return -1;
210         }
211
212         size = PySequence_Fast_GET_SIZE(value_fast);
213
214         if (size != 0) {
215                 float *fp;
216
217                 fp = *array = PyMem_Malloc(size * array_dim * sizeof(float));
218
219                 for (i = 0; i < size; i++, fp += array_dim) {
220                         PyObject *item = PySequence_Fast_GET_ITEM(value, i);
221
222                         if (mathutils_array_parse(fp, array_dim, array_dim, item, error_prefix) == -1) {
223                                 PyMem_Free(*array);
224                                 *array = NULL;
225                                 size = -1;
226                                 break;
227                         }
228                 }
229         }
230
231         Py_DECREF(value_fast);
232         return size;
233 }
234
235 int mathutils_any_to_rotmat(float rmat[3][3], PyObject *value, const char *error_prefix)
236 {
237         if (EulerObject_Check(value)) {
238                 if (BaseMath_ReadCallback((BaseMathObject *)value) == -1) {
239                         return -1;
240                 }
241                 else {
242                         eulO_to_mat3(rmat, ((EulerObject *)value)->eul, ((EulerObject *)value)->order);
243                         return 0;
244                 }
245         }
246         else if (QuaternionObject_Check(value)) {
247                 if (BaseMath_ReadCallback((BaseMathObject *)value) == -1) {
248                         return -1;
249                 }
250                 else {
251                         float tquat[4];
252                         normalize_qt_qt(tquat, ((QuaternionObject *)value)->quat);
253                         quat_to_mat3(rmat, tquat);
254                         return 0;
255                 }
256         }
257         else if (MatrixObject_Check(value)) {
258                 if (BaseMath_ReadCallback((BaseMathObject *)value) == -1) {
259                         return -1;
260                 }
261                 else if (((MatrixObject *)value)->num_row < 3 || ((MatrixObject *)value)->num_col < 3) {
262                         PyErr_Format(PyExc_ValueError,
263                                      "%.200s: matrix must have minimum 3x3 dimensions",
264                                      error_prefix);
265                         return -1;
266                 }
267                 else {
268                         matrix_as_3x3(rmat, (MatrixObject *)value);
269                         normalize_m3(rmat);
270                         return 0;
271                 }
272         }
273         else {
274                 PyErr_Format(PyExc_TypeError,
275                              "%.200s: expected a Euler, Quaternion or Matrix type, "
276                              "found %.200s", error_prefix, Py_TYPE(value)->tp_name);
277                 return -1;
278         }
279 }
280
281
282 /* ----------------------------------MATRIX FUNCTIONS-------------------- */
283
284
285 /* Utility functions */
286
287 /* LomontRRDCompare4, Ever Faster Float Comparisons by Randy Dillon */
288 #define SIGNMASK(i) (-(int)(((unsigned int)(i)) >> 31))
289
290 int EXPP_FloatsAreEqual(float af, float bf, int maxDiff)
291 {
292         /* solid, fast routine across all platforms
293          * with constant time behavior */
294         int ai = *(int *)(&af);
295         int bi = *(int *)(&bf);
296         int test = SIGNMASK(ai ^ bi);
297         int diff, v1, v2;
298
299         assert((0 == test) || (0xFFFFFFFF == test));
300         diff = (ai ^ (test & 0x7fffffff)) - bi;
301         v1 = maxDiff + diff;
302         v2 = maxDiff - diff;
303         return (v1 | v2) >= 0;
304 }
305
306 /*---------------------- EXPP_VectorsAreEqual -------------------------
307  * Builds on EXPP_FloatsAreEqual to test vectors */
308 int EXPP_VectorsAreEqual(const float *vecA, const float *vecB, int size, int floatSteps)
309 {
310         int x;
311         for (x = 0; x < size; x++) {
312                 if (EXPP_FloatsAreEqual(vecA[x], vecB[x], floatSteps) == 0)
313                         return 0;
314         }
315         return 1;
316 }
317
318 #ifndef MATH_STANDALONE
319 /* dynstr as python string utility funcions, frees 'ds'! */
320 PyObject *mathutils_dynstr_to_py(struct DynStr *ds)
321 {
322         const int ds_len = BLI_dynstr_get_len(ds); /* space for \0 */
323         char *ds_buf     = PyMem_Malloc(ds_len + 1);
324         PyObject *ret;
325         BLI_dynstr_get_cstring_ex(ds, ds_buf);
326         BLI_dynstr_free(ds);
327         ret = PyUnicode_FromStringAndSize(ds_buf, ds_len);
328         PyMem_Free(ds_buf);
329         return ret;
330 }
331 #endif
332
333 /* silly function, we dont use arg. just check its compatible with __deepcopy__ */
334 int mathutils_deepcopy_args_check(PyObject *args)
335 {
336         PyObject *dummy_pydict;
337         return PyArg_ParseTuple(args, "|O!:__deepcopy__", &PyDict_Type, &dummy_pydict) != 0;
338 }
339
340 /* Mathutils Callbacks */
341
342 /* for mathutils internal use only, eventually should re-alloc but to start with we only have a few users */
343 #define MATHUTILS_TOT_CB 10
344 static Mathutils_Callback *mathutils_callbacks[MATHUTILS_TOT_CB] = {NULL};
345
346 unsigned char Mathutils_RegisterCallback(Mathutils_Callback *cb)
347 {
348         unsigned char i;
349         
350         /* find the first free slot */
351         for (i = 0; mathutils_callbacks[i]; i++) {
352                 if (mathutils_callbacks[i] == cb) /* already registered? */
353                         return i;
354         }
355
356         BLI_assert(i + 1 < MATHUTILS_TOT_CB);
357
358         mathutils_callbacks[i] = cb;
359         return i;
360 }
361
362 /* use macros to check for NULL */
363 int _BaseMathObject_ReadCallback(BaseMathObject *self)
364 {
365         Mathutils_Callback *cb = mathutils_callbacks[self->cb_type];
366         if (LIKELY(cb->get(self, self->cb_subtype) != -1)) {
367                 return 0;
368         }
369
370         if (!PyErr_Occurred()) {
371                 PyErr_Format(PyExc_RuntimeError,
372                              "%s read, user has become invalid",
373                              Py_TYPE(self)->tp_name);
374         }
375         return -1;
376 }
377
378 int _BaseMathObject_WriteCallback(BaseMathObject *self)
379 {
380         Mathutils_Callback *cb = mathutils_callbacks[self->cb_type];
381         if (LIKELY(cb->set(self, self->cb_subtype) != -1)) {
382                 return 0;
383         }
384
385         if (!PyErr_Occurred()) {
386                 PyErr_Format(PyExc_RuntimeError,
387                              "%s write, user has become invalid",
388                              Py_TYPE(self)->tp_name);
389         }
390         return -1;
391 }
392
393 int _BaseMathObject_ReadIndexCallback(BaseMathObject *self, int index)
394 {
395         Mathutils_Callback *cb = mathutils_callbacks[self->cb_type];
396         if (LIKELY(cb->get_index(self, self->cb_subtype, index) != -1)) {
397                 return 0;
398         }
399
400         if (!PyErr_Occurred()) {
401                 PyErr_Format(PyExc_RuntimeError,
402                              "%s read index, user has become invalid",
403                              Py_TYPE(self)->tp_name);
404         }
405         return -1;
406 }
407
408 int _BaseMathObject_WriteIndexCallback(BaseMathObject *self, int index)
409 {
410         Mathutils_Callback *cb = mathutils_callbacks[self->cb_type];
411         if (LIKELY(cb->set_index(self, self->cb_subtype, index) != -1)) {
412                 return 0;
413         }
414
415         if (!PyErr_Occurred()) {
416                 PyErr_Format(PyExc_RuntimeError,
417                              "%s write index, user has become invalid",
418                              Py_TYPE(self)->tp_name);
419         }
420         return -1;
421 }
422
423 /* BaseMathObject generic functions for all mathutils types */
424 char BaseMathObject_owner_doc[] = "The item this is wrapping or None  (read-only).";
425 PyObject *BaseMathObject_owner_get(BaseMathObject *self, void *UNUSED(closure))
426 {
427         PyObject *ret = self->cb_user ? self->cb_user : Py_None;
428         Py_INCREF(ret);
429         return ret;
430 }
431
432 char BaseMathObject_is_wrapped_doc[] = "True when this object wraps external data (read-only).\n\n:type: boolean";
433 PyObject *BaseMathObject_is_wrapped_get(BaseMathObject *self, void *UNUSED(closure))
434 {
435         return PyBool_FromLong((self->wrapped == Py_WRAP) ? 1 : 0);
436 }
437
438 int BaseMathObject_traverse(BaseMathObject *self, visitproc visit, void *arg)
439 {
440         Py_VISIT(self->cb_user);
441         return 0;
442 }
443
444 int BaseMathObject_clear(BaseMathObject *self)
445 {
446         Py_CLEAR(self->cb_user);
447         return 0;
448 }
449
450 void BaseMathObject_dealloc(BaseMathObject *self)
451 {
452         /* only free non wrapped */
453         if (self->wrapped != Py_WRAP) {
454                 PyMem_Free(self->data);
455         }
456
457         if (self->cb_user) {
458                 PyObject_GC_UnTrack(self);
459                 BaseMathObject_clear(self);
460         }
461
462         Py_TYPE(self)->tp_free(self); // PyObject_DEL(self); // breaks subtypes
463 }
464
465 /*----------------------------MODULE INIT-------------------------*/
466 static struct PyMethodDef M_Mathutils_methods[] = {
467         {NULL, NULL, 0, NULL}
468 };
469
470 static struct PyModuleDef M_Mathutils_module_def = {
471         PyModuleDef_HEAD_INIT,
472         "mathutils",  /* m_name */
473         M_Mathutils_doc,  /* m_doc */
474         0,  /* m_size */
475         M_Mathutils_methods,  /* m_methods */
476         NULL,  /* m_reload */
477         NULL,  /* m_traverse */
478         NULL,  /* m_clear */
479         NULL,  /* m_free */
480 };
481
482 PyMODINIT_FUNC PyInit_mathutils(void)
483 {
484         PyObject *mod;
485         PyObject *submodule;
486         PyObject *sys_modules = PyThreadState_GET()->interp->modules;
487
488         if (PyType_Ready(&vector_Type) < 0)
489                 return NULL;
490         if (PyType_Ready(&matrix_Type) < 0)
491                 return NULL;
492         if (PyType_Ready(&matrix_access_Type) < 0)
493                 return NULL;
494         if (PyType_Ready(&euler_Type) < 0)
495                 return NULL;
496         if (PyType_Ready(&quaternion_Type) < 0)
497                 return NULL;
498         if (PyType_Ready(&color_Type) < 0)
499                 return NULL;
500
501         mod = PyModule_Create(&M_Mathutils_module_def);
502         
503         /* each type has its own new() function */
504         PyModule_AddObject(mod, vector_Type.tp_name,     (PyObject *)&vector_Type);
505         PyModule_AddObject(mod, matrix_Type.tp_name,     (PyObject *)&matrix_Type);
506         PyModule_AddObject(mod, euler_Type.tp_name,      (PyObject *)&euler_Type);
507         PyModule_AddObject(mod, quaternion_Type.tp_name, (PyObject *)&quaternion_Type);
508         PyModule_AddObject(mod, color_Type.tp_name,      (PyObject *)&color_Type);
509         
510         /* submodule */
511         PyModule_AddObject(mod, "geometry",       (submodule = PyInit_mathutils_geometry()));
512         /* XXX, python doesnt do imports with this usefully yet
513          * 'from mathutils.geometry import PolyFill'
514          * ...fails without this. */
515         PyDict_SetItemString(sys_modules, PyModule_GetName(submodule), submodule);
516         Py_INCREF(submodule);
517
518         /* Noise submodule */
519         PyModule_AddObject(mod, "noise", (submodule = PyInit_mathutils_noise()));
520         PyDict_SetItemString(sys_modules, PyModule_GetName(submodule), submodule);
521         Py_INCREF(submodule);
522
523         mathutils_matrix_row_cb_index = Mathutils_RegisterCallback(&mathutils_matrix_row_cb);
524         mathutils_matrix_col_cb_index = Mathutils_RegisterCallback(&mathutils_matrix_col_cb);
525         mathutils_matrix_translation_cb_index = Mathutils_RegisterCallback(&mathutils_matrix_translation_cb);
526
527         return mod;
528 }