Blender V2.61 - r43446

mathutils.c

Go to the documentation of this file.
00001 /* 
00002  * ***** BEGIN GPL LICENSE BLOCK *****
00003  *
00004  * This program is free software; you can redistribute it and/or
00005  * modify it under the terms of the GNU General Public License
00006  * as published by the Free Software Foundation; either version 2
00007  * of the License, or (at your option) any later version.
00008  *
00009  * This program is distributed in the hope that it will be useful,
00010  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00011  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00012  * GNU General Public License for more details.
00013  *
00014  * You should have received a copy of the GNU General Public License
00015  * along with this program; if not, write to the Free Software Foundation,
00016  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
00017  *
00018  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
00019  * All rights reserved.
00020  *
00021  * This is a new part of Blender.
00022  *
00023  * Contributor(s): Joseph Gilbert, Campbell Barton
00024  *
00025  * ***** END GPL LICENSE BLOCK *****
00026  */
00027 
00032 #include <Python.h>
00033 
00034 #include "mathutils.h"
00035 
00036 #include "BLI_math.h"
00037 #include "BLI_utildefines.h"
00038 #include "BLI_dynstr.h"
00039 
00040 PyDoc_STRVAR(M_Mathutils_doc,
00041 "This module provides access to matrices, eulers, quaternions and vectors."
00042 );
00043 static int mathutils_array_parse_fast(float *array,
00044                                       int size,
00045                                       PyObject *value_fast,
00046                                       const char *error_prefix)
00047 {
00048     PyObject *item;
00049 
00050     int i;
00051 
00052     i = size;
00053     do {
00054         i--;
00055         if ( ((array[i] = PyFloat_AsDouble((item = PySequence_Fast_GET_ITEM(value_fast, i)))) == -1.0f) &&
00056              PyErr_Occurred())
00057         {
00058             PyErr_Format(PyExc_TypeError,
00059                          "%.200s: sequence index %d expected a number, "
00060                          "found '%.200s' type, ",
00061                          error_prefix, i, Py_TYPE(item)->tp_name);
00062             Py_DECREF(value_fast);
00063             return -1;
00064         }
00065     } while (i);
00066 
00067     Py_XDECREF(value_fast);
00068     return size;
00069 }
00070 
00071 /* helper functionm returns length of the 'value', -1 on error */
00072 int mathutils_array_parse(float *array, int array_min, int array_max, PyObject *value, const char *error_prefix)
00073 {
00074     int size;
00075 
00076 #if 1 /* approx 6x speedup for mathutils types */
00077 
00078     if ( (size = VectorObject_Check(value)     ? ((VectorObject *)value)->size : 0) ||
00079          (size = EulerObject_Check(value)      ? 3 : 0) ||
00080          (size = QuaternionObject_Check(value) ? 4 : 0) ||
00081          (size = ColorObject_Check(value)      ? 3 : 0))
00082     {
00083         if (BaseMath_ReadCallback((BaseMathObject *)value) == -1) {
00084             return -1;
00085         }
00086 
00087         if (size > array_max || size < array_min) {
00088             if (array_max == array_min) {
00089                 PyErr_Format(PyExc_ValueError,
00090                              "%.200s: sequence size is %d, expected %d",
00091                              error_prefix, size, array_max);
00092             }
00093             else {
00094                 PyErr_Format(PyExc_ValueError,
00095                              "%.200s: sequence size is %d, expected [%d - %d]",
00096                              error_prefix, size, array_min, array_max);
00097             }
00098             return -1;
00099         }
00100 
00101         memcpy(array, ((BaseMathObject *)value)->data, size * sizeof(float));
00102         return size;
00103     }
00104     else
00105 #endif
00106     {
00107         PyObject *value_fast = NULL;
00108 
00109         /* non list/tuple cases */
00110         if (!(value_fast = PySequence_Fast(value, error_prefix))) {
00111             /* PySequence_Fast sets the error */
00112             return -1;
00113         }
00114 
00115         size = PySequence_Fast_GET_SIZE(value_fast);
00116 
00117         if (size > array_max || size < array_min) {
00118             if (array_max == array_min) {
00119                 PyErr_Format(PyExc_ValueError,
00120                              "%.200s: sequence size is %d, expected %d",
00121                              error_prefix, size, array_max);
00122             }
00123             else {
00124                 PyErr_Format(PyExc_ValueError,
00125                              "%.200s: sequence size is %d, expected [%d - %d]",
00126                              error_prefix, size, array_min, array_max);
00127             }
00128             Py_DECREF(value_fast);
00129             return -1;
00130         }
00131 
00132         return mathutils_array_parse_fast(array, size, value_fast, error_prefix);
00133     }
00134 }
00135 
00136 int mathutils_array_parse_alloc(float **array, int array_min, PyObject *value, const char *error_prefix)
00137 {
00138     int size;
00139 
00140 #if 1 /* approx 6x speedup for mathutils types */
00141 
00142     if ( (size = VectorObject_Check(value)     ? ((VectorObject *)value)->size : 0) ||
00143          (size = EulerObject_Check(value)      ? 3 : 0) ||
00144          (size = QuaternionObject_Check(value) ? 4 : 0) ||
00145          (size = ColorObject_Check(value)      ? 3 : 0))
00146     {
00147         if (BaseMath_ReadCallback((BaseMathObject *)value) == -1) {
00148             return -1;
00149         }
00150 
00151         if (size < array_min) {
00152             PyErr_Format(PyExc_ValueError,
00153                          "%.200s: sequence size is %d, expected > %d",
00154                          error_prefix, size, array_min);
00155             return -1;
00156         }
00157         
00158         *array = PyMem_Malloc(size * sizeof(float));
00159         memcpy(*array, ((BaseMathObject *)value)->data, size * sizeof(float));
00160         return size;
00161     }
00162     else
00163 #endif
00164     {
00165         PyObject *value_fast = NULL;
00166         //*array = NULL;
00167 
00168         /* non list/tuple cases */
00169         if (!(value_fast = PySequence_Fast(value, error_prefix))) {
00170             /* PySequence_Fast sets the error */
00171             return -1;
00172         }
00173 
00174         size = PySequence_Fast_GET_SIZE(value_fast);
00175 
00176         if (size < array_min) {
00177             PyErr_Format(PyExc_ValueError,
00178                          "%.200s: sequence size is %d, expected > %d",
00179                          error_prefix, size, array_min);
00180             return -1;
00181         }
00182 
00183         *array = PyMem_Malloc(size * sizeof(float));
00184 
00185         return mathutils_array_parse_fast(*array, size, value_fast, error_prefix);
00186     }
00187 }
00188 
00189 int mathutils_any_to_rotmat(float rmat[3][3], PyObject *value, const char *error_prefix)
00190 {
00191     if (EulerObject_Check(value)) {
00192         if (BaseMath_ReadCallback((BaseMathObject *)value) == -1) {
00193             return -1;
00194         }
00195         else {
00196             eulO_to_mat3(rmat, ((EulerObject *)value)->eul, ((EulerObject *)value)->order);
00197             return 0;
00198         }
00199     }
00200     else if (QuaternionObject_Check(value)) {
00201         if (BaseMath_ReadCallback((BaseMathObject *)value) == -1) {
00202             return -1;
00203         }
00204         else {
00205             float tquat[4];
00206             normalize_qt_qt(tquat, ((QuaternionObject *)value)->quat);
00207             quat_to_mat3(rmat, tquat);
00208             return 0;
00209         }
00210     }
00211     else if (MatrixObject_Check(value)) {
00212         if (BaseMath_ReadCallback((BaseMathObject *)value) == -1) {
00213             return -1;
00214         }
00215         else if (((MatrixObject *)value)->num_row < 3 || ((MatrixObject *)value)->num_col < 3) {
00216             PyErr_Format(PyExc_ValueError,
00217                          "%.200s: matrix must have minimum 3x3 dimensions",
00218                          error_prefix);
00219             return -1;
00220         }
00221         else {
00222             matrix_as_3x3(rmat, (MatrixObject *)value);
00223             normalize_m3(rmat);
00224             return 0;
00225         }
00226     }
00227     else {
00228         PyErr_Format(PyExc_TypeError,
00229                      "%.200s: expected a Euler, Quaternion or Matrix type, "
00230                      "found %.200s", error_prefix, Py_TYPE(value)->tp_name);
00231         return -1;
00232     }
00233 }
00234 
00235 
00236 //----------------------------------MATRIX FUNCTIONS--------------------
00237 
00238 
00239 /* Utility functions */
00240 
00241 // LomontRRDCompare4, Ever Faster Float Comparisons by Randy Dillon
00242 #define SIGNMASK(i) (-(int)(((unsigned int)(i))>>31))
00243 
00244 int EXPP_FloatsAreEqual(float af, float bf, int maxDiff)
00245 {   // solid, fast routine across all platforms
00246     // with constant time behavior
00247     int ai = *(int *)(&af);
00248     int bi = *(int *)(&bf);
00249     int test = SIGNMASK(ai^bi);
00250     int diff, v1, v2;
00251 
00252     assert((0 == test) || (0xFFFFFFFF == test));
00253     diff = (ai ^ (test & 0x7fffffff)) - bi;
00254     v1 = maxDiff + diff;
00255     v2 = maxDiff - diff;
00256     return (v1|v2) >= 0;
00257 }
00258 
00259 /*---------------------- EXPP_VectorsAreEqual -------------------------
00260   Builds on EXPP_FloatsAreEqual to test vectors */
00261 int EXPP_VectorsAreEqual(float *vecA, float *vecB, int size, int floatSteps)
00262 {
00263     int x;
00264     for (x = 0; x < size; x++) {
00265         if (EXPP_FloatsAreEqual(vecA[x], vecB[x], floatSteps) == 0)
00266             return 0;
00267     }
00268     return 1;
00269 }
00270 
00271 /* dynstr as python string utility funcions, frees 'ds'! */
00272 PyObject *mathutils_dynstr_to_py(struct DynStr *ds)
00273 {
00274     const int ds_len = BLI_dynstr_get_len(ds); /* space for \0 */
00275     char *ds_buf     = PyMem_Malloc(ds_len + 1);
00276     PyObject *ret;
00277     BLI_dynstr_get_cstring_ex(ds, ds_buf);
00278     BLI_dynstr_free(ds);
00279     ret = PyUnicode_FromStringAndSize(ds_buf, ds_len);
00280     PyMem_Free(ds_buf);
00281     return ret;
00282 }
00283 
00284 /* Mathutils Callbacks */
00285 
00286 /* for mathutils internal use only, eventually should re-alloc but to start with we only have a few users */
00287 static Mathutils_Callback *mathutils_callbacks[8] = {NULL};
00288 
00289 int Mathutils_RegisterCallback(Mathutils_Callback *cb)
00290 {
00291     int i;
00292     
00293     /* find the first free slot */
00294     for (i = 0; mathutils_callbacks[i]; i++) {
00295         if (mathutils_callbacks[i] == cb) /* already registered? */
00296             return i;
00297     }
00298     
00299     mathutils_callbacks[i] = cb;
00300     return i;
00301 }
00302 
00303 /* use macros to check for NULL */
00304 int _BaseMathObject_ReadCallback(BaseMathObject *self)
00305 {
00306     Mathutils_Callback *cb = mathutils_callbacks[self->cb_type];
00307     if (cb->get(self, self->cb_subtype) != -1)
00308         return 0;
00309 
00310     if (!PyErr_Occurred()) {
00311         PyErr_Format(PyExc_RuntimeError,
00312                      "%s read, user has become invalid",
00313                      Py_TYPE(self)->tp_name);
00314     }
00315     return -1;
00316 }
00317 
00318 int _BaseMathObject_WriteCallback(BaseMathObject *self)
00319 {
00320     Mathutils_Callback *cb = mathutils_callbacks[self->cb_type];
00321     if (cb->set(self, self->cb_subtype) != -1)
00322         return 0;
00323 
00324     if (!PyErr_Occurred()) {
00325         PyErr_Format(PyExc_RuntimeError,
00326                      "%s write, user has become invalid",
00327                      Py_TYPE(self)->tp_name);
00328     }
00329     return -1;
00330 }
00331 
00332 int _BaseMathObject_ReadIndexCallback(BaseMathObject *self, int index)
00333 {
00334     Mathutils_Callback *cb = mathutils_callbacks[self->cb_type];
00335     if (cb->get_index(self, self->cb_subtype, index) != -1)
00336         return 0;
00337 
00338     if (!PyErr_Occurred()) {
00339         PyErr_Format(PyExc_RuntimeError,
00340                      "%s read index, user has become invalid",
00341                      Py_TYPE(self)->tp_name);
00342     }
00343     return -1;
00344 }
00345 
00346 int _BaseMathObject_WriteIndexCallback(BaseMathObject *self, int index)
00347 {
00348     Mathutils_Callback *cb = mathutils_callbacks[self->cb_type];
00349     if (cb->set_index(self, self->cb_subtype, index) != -1)
00350         return 0;
00351 
00352     if (!PyErr_Occurred()) {
00353         PyErr_Format(PyExc_RuntimeError,
00354                      "%s write index, user has become invalid",
00355                      Py_TYPE(self)->tp_name);
00356     }
00357     return -1;
00358 }
00359 
00360 /* BaseMathObject generic functions for all mathutils types */
00361 char BaseMathObject_owner_doc[] = "The item this is wrapping or None  (readonly).";
00362 PyObject *BaseMathObject_owner_get(BaseMathObject *self, void *UNUSED(closure))
00363 {
00364     PyObject *ret = self->cb_user ? self->cb_user : Py_None;
00365     Py_INCREF(ret);
00366     return ret;
00367 }
00368 
00369 char BaseMathObject_is_wrapped_doc[] = "True when this object wraps external data (readonly).\n\n:type: boolean";
00370 PyObject *BaseMathObject_is_wrapped_get(BaseMathObject *self, void *UNUSED(closure))
00371 {
00372     return PyBool_FromLong((self->wrapped == Py_WRAP) ? 1:0);
00373 }
00374 
00375 int BaseMathObject_traverse(BaseMathObject *self, visitproc visit, void *arg)
00376 {
00377     Py_VISIT(self->cb_user);
00378     return 0;
00379 }
00380 
00381 int BaseMathObject_clear(BaseMathObject *self)
00382 {
00383     Py_CLEAR(self->cb_user);
00384     return 0;
00385 }
00386 
00387 void BaseMathObject_dealloc(BaseMathObject *self)
00388 {
00389     /* only free non wrapped */
00390     if (self->wrapped != Py_WRAP) {
00391         PyMem_Free(self->data);
00392     }
00393 
00394     if (self->cb_user) {
00395         PyObject_GC_UnTrack(self);
00396         BaseMathObject_clear(self);
00397     }
00398 
00399     Py_TYPE(self)->tp_free(self); // PyObject_DEL(self); // breaks subtypes
00400 }
00401 
00402 /*----------------------------MODULE INIT-------------------------*/
00403 static struct PyMethodDef M_Mathutils_methods[] = {
00404     {NULL, NULL, 0, NULL}
00405 };
00406 
00407 static struct PyModuleDef M_Mathutils_module_def = {
00408     PyModuleDef_HEAD_INIT,
00409     "mathutils",  /* m_name */
00410     M_Mathutils_doc,  /* m_doc */
00411     0,  /* m_size */
00412     M_Mathutils_methods,  /* m_methods */
00413     NULL,  /* m_reload */
00414     NULL,  /* m_traverse */
00415     NULL,  /* m_clear */
00416     NULL,  /* m_free */
00417 };
00418 
00419 PyMODINIT_FUNC PyInit_mathutils(void)
00420 {
00421     PyObject *submodule;
00422     PyObject *item;
00423     PyObject *sys_modules = PyThreadState_GET()->interp->modules;
00424 
00425     if (PyType_Ready(&vector_Type) < 0)
00426         return NULL;
00427     if (PyType_Ready(&matrix_Type) < 0)
00428         return NULL;
00429     if (PyType_Ready(&matrix_access_Type) < 0)
00430         return NULL;
00431     if (PyType_Ready(&euler_Type) < 0)
00432         return NULL;
00433     if (PyType_Ready(&quaternion_Type) < 0)
00434         return NULL;
00435     if (PyType_Ready(&color_Type) < 0)
00436         return NULL;
00437 
00438     submodule = PyModule_Create(&M_Mathutils_module_def);
00439     
00440     /* each type has its own new() function */
00441     PyModule_AddObject(submodule, "Vector",     (PyObject *)&vector_Type);
00442     PyModule_AddObject(submodule, "Matrix",     (PyObject *)&matrix_Type);
00443     PyModule_AddObject(submodule, "Euler",      (PyObject *)&euler_Type);
00444     PyModule_AddObject(submodule, "Quaternion", (PyObject *)&quaternion_Type);
00445     PyModule_AddObject(submodule, "Color",      (PyObject *)&color_Type);
00446     
00447     /* submodule */
00448     PyModule_AddObject(submodule, "geometry",       (item = PyInit_mathutils_geometry()));
00449     /* XXX, python doesnt do imports with this usefully yet
00450      * 'from mathutils.geometry import PolyFill'
00451      * ...fails without this. */
00452     PyDict_SetItemString(sys_modules, "mathutils.geometry", item);
00453     Py_INCREF(item);
00454 
00455     /* Noise submodule */
00456     PyModule_AddObject(submodule, "noise",      (item = PyInit_mathutils_noise()));
00457     PyDict_SetItemString(sys_modules, "mathutils.noise", item);
00458     Py_INCREF(item);
00459 
00460     mathutils_matrix_row_cb_index = Mathutils_RegisterCallback(&mathutils_matrix_row_cb);
00461     mathutils_matrix_col_cb_index = Mathutils_RegisterCallback(&mathutils_matrix_col_cb);
00462     mathutils_matrix_translation_cb_index = Mathutils_RegisterCallback(&mathutils_matrix_translation_cb);
00463 
00464     return submodule;
00465 }