PyAPI: add utilities PyTuple_SET_ITEMS, Py_INCREF_RET
[blender.git] / source / blender / python / mathutils / mathutils_kdtree.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  * Contributor(s): Dan Eicher, Campbell Barton
19  *
20  * ***** END GPL LICENSE BLOCK *****
21  */
22
23 /** \file blender/python/mathutils/mathutils_kdtree.c
24  *  \ingroup mathutils
25  *
26  * This file defines the 'mathutils.kdtree' module, a general purpose module to access
27  * blenders kdtree for 3d spatial lookups.
28  */
29
30 #include <Python.h>
31
32 #include "MEM_guardedalloc.h"
33
34 #include "BLI_utildefines.h"
35 #include "BLI_kdtree.h"
36
37 #include "../generic/py_capi_utils.h"
38 #include "../generic/python_utildefines.h"
39
40 #include "mathutils.h"
41 #include "mathutils_kdtree.h"  /* own include */
42
43 #include "BLI_strict_flags.h"
44
45 typedef struct {
46         PyObject_HEAD
47         KDTree *obj;
48         unsigned int maxsize;
49         unsigned int count;
50         unsigned int count_balance;  /* size when we last balanced */
51 } PyKDTree;
52
53
54 /* -------------------------------------------------------------------- */
55 /* Utility helper functions */
56
57 static void kdtree_nearest_to_py_tuple(const KDTreeNearest *nearest, PyObject *py_retval)
58 {
59         BLI_assert(nearest->index >= 0);
60         BLI_assert(PyTuple_GET_SIZE(py_retval) == 3);
61
62         PyTuple_SET_ITEMS(py_retval,
63                 Vector_CreatePyObject((float *)nearest->co, 3, NULL),
64                 PyLong_FromLong(nearest->index),
65                 PyFloat_FromDouble(nearest->dist));
66 }
67
68 static PyObject *kdtree_nearest_to_py(const KDTreeNearest *nearest)
69 {
70         PyObject *py_retval;
71
72         py_retval = PyTuple_New(3);
73
74         kdtree_nearest_to_py_tuple(nearest, py_retval);
75
76         return py_retval;
77 }
78
79 static PyObject *kdtree_nearest_to_py_and_check(const KDTreeNearest *nearest)
80 {
81         PyObject *py_retval;
82
83         py_retval = PyTuple_New(3);
84
85         if (nearest->index != -1) {
86                 kdtree_nearest_to_py_tuple(nearest, py_retval);
87         }
88         else {
89                 PyC_Tuple_Fill(py_retval, Py_None);
90         }
91
92         return py_retval;
93 }
94
95
96 /* -------------------------------------------------------------------- */
97 /* KDTree */
98
99 /* annoying since arg parsing won't check overflow */
100 #define UINT_IS_NEG(n) ((n) > INT_MAX)
101
102 static int PyKDTree__tp_init(PyKDTree *self, PyObject *args, PyObject *kwargs)
103 {
104         unsigned int maxsize;
105         const char *keywords[] = {"size", NULL};
106
107         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "I:KDTree", (char **)keywords, &maxsize)) {
108                 return -1;
109         }
110
111         if (UINT_IS_NEG(maxsize)) {
112                 PyErr_SetString(PyExc_ValueError, "negative 'size' given");
113                 return -1;
114         }
115
116         self->obj = BLI_kdtree_new(maxsize);
117         self->maxsize = maxsize;
118         self->count = 0;
119         self->count_balance = 0;
120
121         return 0;
122 }
123
124 static void PyKDTree__tp_dealloc(PyKDTree *self)
125 {
126         BLI_kdtree_free(self->obj);
127         Py_TYPE(self)->tp_free((PyObject *)self);
128 }
129
130 PyDoc_STRVAR(py_kdtree_insert_doc,
131 ".. method:: insert(co, index)\n"
132 "\n"
133 "   Insert a point into the KDTree.\n"
134 "\n"
135 "   :arg co: Point 3d position.\n"
136 "   :type co: float triplet\n"
137 "   :arg index: The index of the point.\n"
138 "   :type index: int\n"
139 );
140 static PyObject *py_kdtree_insert(PyKDTree *self, PyObject *args, PyObject *kwargs)
141 {
142         PyObject *py_co;
143         float co[3];
144         int index;
145         const char *keywords[] = {"co", "index", NULL};
146
147         if (!PyArg_ParseTupleAndKeywords(args, kwargs, (char *) "Oi:insert", (char **)keywords,
148                                          &py_co, &index))
149         {
150                 return NULL;
151         }
152
153         if (mathutils_array_parse(co, 3, 3, py_co, "insert: invalid 'co' arg") == -1)
154                 return NULL;
155
156         if (index < 0) {
157                 PyErr_SetString(PyExc_ValueError, "negative index given");
158                 return NULL;
159         }
160
161         if (self->count >= self->maxsize) {
162                 PyErr_SetString(PyExc_RuntimeError, "Trying to insert more items than KDTree has room for");
163                 return NULL;
164         }
165
166         BLI_kdtree_insert(self->obj, index, co);
167         self->count++;
168
169         Py_RETURN_NONE;
170 }
171
172 PyDoc_STRVAR(py_kdtree_balance_doc,
173 ".. method:: balance()\n"
174 "\n"
175 "   Balance the tree.\n"
176 "\n"
177 ".. note::\n"
178 "\n"
179 "   This builds the entire tree, avoid calling after each insertion.\n"
180 );
181 static PyObject *py_kdtree_balance(PyKDTree *self)
182 {
183         BLI_kdtree_balance(self->obj);
184         self->count_balance = self->count;
185         Py_RETURN_NONE;
186 }
187
188 PyDoc_STRVAR(py_kdtree_find_doc,
189 ".. method:: find(co)\n"
190 "\n"
191 "   Find nearest point to ``co``.\n"
192 "\n"
193 "   :arg co: 3d coordinates.\n"
194 "   :type co: float triplet\n"
195 "   :return: Returns (:class:`Vector`, index, distance).\n"
196 "   :rtype: :class:`tuple`\n"
197 );
198 static PyObject *py_kdtree_find(PyKDTree *self, PyObject *args, PyObject *kwargs)
199 {
200         PyObject *py_co;
201         float co[3];
202         KDTreeNearest nearest;
203         const char *keywords[] = {"co", NULL};
204
205         if (!PyArg_ParseTupleAndKeywords(args, kwargs, (char *) "O:find", (char **)keywords,
206                                          &py_co))
207         {
208                 return NULL;
209         }
210
211         if (mathutils_array_parse(co, 3, 3, py_co, "find: invalid 'co' arg") == -1)
212                 return NULL;
213
214         if (self->count != self->count_balance) {
215                 PyErr_SetString(PyExc_RuntimeError, "KDTree must be balanced before calling find()");
216                 return NULL;
217         }
218
219
220         nearest.index = -1;
221
222         BLI_kdtree_find_nearest(self->obj, co, &nearest);
223
224         return kdtree_nearest_to_py_and_check(&nearest);
225 }
226
227 PyDoc_STRVAR(py_kdtree_find_n_doc,
228 ".. method:: find_n(co, n)\n"
229 "\n"
230 "   Find nearest ``n`` points to ``co``.\n"
231 "\n"
232 "   :arg co: 3d coordinates.\n"
233 "   :type co: float triplet\n"
234 "   :arg n: Number of points to find.\n"
235 "   :type n: int\n"
236 "   :return: Returns a list of tuples (:class:`Vector`, index, distance).\n"
237 "   :rtype: :class:`list`\n"
238 );
239 static PyObject *py_kdtree_find_n(PyKDTree *self, PyObject *args, PyObject *kwargs)
240 {
241         PyObject *py_list;
242         PyObject *py_co;
243         float co[3];
244         KDTreeNearest *nearest;
245         unsigned int n;
246         int i, found;
247         const char *keywords[] = {"co", "n", NULL};
248
249         if (!PyArg_ParseTupleAndKeywords(args, kwargs, (char *) "OI:find_n", (char **)keywords,
250                                          &py_co, &n))
251         {
252                 return NULL;
253         }
254
255         if (mathutils_array_parse(co, 3, 3, py_co, "find_n: invalid 'co' arg") == -1)
256                 return NULL;
257
258         if (UINT_IS_NEG(n)) {
259                 PyErr_SetString(PyExc_RuntimeError, "negative 'n' given");
260                 return NULL;
261         }
262
263         if (self->count != self->count_balance) {
264                 PyErr_SetString(PyExc_RuntimeError, "KDTree must be balanced before calling find_n()");
265                 return NULL;
266         }
267
268         nearest = MEM_mallocN(sizeof(KDTreeNearest) * n, __func__);
269
270         found = BLI_kdtree_find_nearest_n(self->obj, co, nearest, n);
271
272         py_list = PyList_New(found);
273
274         for (i = 0; i < found; i++) {
275                 PyList_SET_ITEM(py_list, i, kdtree_nearest_to_py(&nearest[i]));
276         }
277
278         MEM_freeN(nearest);
279
280         return py_list;
281 }
282
283 PyDoc_STRVAR(py_kdtree_find_range_doc,
284 ".. method:: find_range(co, radius)\n"
285 "\n"
286 "   Find all points within ``radius`` of ``co``.\n"
287 "\n"
288 "   :arg co: 3d coordinates.\n"
289 "   :type co: float triplet\n"
290 "   :arg radius: Distance to search for points.\n"
291 "   :type radius: float\n"
292 "   :return: Returns a list of tuples (:class:`Vector`, index, distance).\n"
293 "   :rtype: :class:`list`\n"
294 );
295 static PyObject *py_kdtree_find_range(PyKDTree *self, PyObject *args, PyObject *kwargs)
296 {
297         PyObject *py_list;
298         PyObject *py_co;
299         float co[3];
300         KDTreeNearest *nearest = NULL;
301         float radius;
302         int i, found;
303
304         const char *keywords[] = {"co", "radius", NULL};
305
306         if (!PyArg_ParseTupleAndKeywords(args, kwargs, (char *) "Of:find_range", (char **)keywords,
307                                          &py_co, &radius))
308         {
309                 return NULL;
310         }
311
312         if (mathutils_array_parse(co, 3, 3, py_co, "find_range: invalid 'co' arg") == -1)
313                 return NULL;
314
315         if (radius < 0.0f) {
316                 PyErr_SetString(PyExc_RuntimeError, "negative radius given");
317                 return NULL;
318         }
319
320         if (self->count != self->count_balance) {
321                 PyErr_SetString(PyExc_RuntimeError, "KDTree must be balanced before calling find_range()");
322                 return NULL;
323         }
324
325         found = BLI_kdtree_range_search(self->obj, co, &nearest, radius);
326
327         py_list = PyList_New(found);
328
329         for (i = 0; i < found; i++) {
330                 PyList_SET_ITEM(py_list, i, kdtree_nearest_to_py(&nearest[i]));
331         }
332
333         if (nearest) {
334                 MEM_freeN(nearest);
335         }
336
337         return py_list;
338 }
339
340
341 static PyMethodDef PyKDTree_methods[] = {
342         {"insert", (PyCFunction)py_kdtree_insert, METH_VARARGS | METH_KEYWORDS, py_kdtree_insert_doc},
343         {"balance", (PyCFunction)py_kdtree_balance, METH_NOARGS, py_kdtree_balance_doc},
344         {"find", (PyCFunction)py_kdtree_find, METH_VARARGS | METH_KEYWORDS, py_kdtree_find_doc},
345         {"find_n", (PyCFunction)py_kdtree_find_n, METH_VARARGS | METH_KEYWORDS, py_kdtree_find_n_doc},
346         {"find_range", (PyCFunction)py_kdtree_find_range, METH_VARARGS | METH_KEYWORDS, py_kdtree_find_range_doc},
347         {NULL, NULL, 0, NULL}
348 };
349
350 PyDoc_STRVAR(py_KDtree_doc,
351 "KdTree(size) -> new kd-tree initialized to hold ``size`` items.\n"
352 "\n"
353 ".. note::\n"
354 "\n"
355 "   :class:`KDTree.balance` must have been called before using any of the ``find`` methods.\n"
356 );
357 PyTypeObject PyKDTree_Type = {
358         PyVarObject_HEAD_INIT(NULL, 0)
359         "KDTree",                                    /* tp_name */
360         sizeof(PyKDTree),                            /* tp_basicsize */
361         0,                                           /* tp_itemsize */
362         /* methods */
363         (destructor)PyKDTree__tp_dealloc,            /* tp_dealloc */
364         NULL,                                        /* tp_print */
365         NULL,                                        /* tp_getattr */
366         NULL,                                        /* tp_setattr */
367         NULL,                                        /* tp_compare */
368         NULL,                                        /* tp_repr */
369         NULL,                                        /* tp_as_number */
370         NULL,                                        /* tp_as_sequence */
371         NULL,                                        /* tp_as_mapping */
372         NULL,                                        /* tp_hash */
373         NULL,                                        /* tp_call */
374         NULL,                                        /* tp_str */
375         NULL,                                        /* tp_getattro */
376         NULL,                                        /* tp_setattro */
377         NULL,                                        /* tp_as_buffer */
378         Py_TPFLAGS_DEFAULT,                          /* tp_flags */
379         py_KDtree_doc,                               /* Documentation string */
380         NULL,                                        /* tp_traverse */
381         NULL,                                        /* tp_clear */
382         NULL,                                        /* tp_richcompare */
383         0,                                           /* tp_weaklistoffset */
384         NULL,                                        /* tp_iter */
385         NULL,                                        /* tp_iternext */
386         (struct PyMethodDef *)PyKDTree_methods,      /* tp_methods */
387         NULL,                                        /* tp_members */
388         NULL,                                        /* tp_getset */
389         NULL,                                        /* tp_base */
390         NULL,                                        /* tp_dict */
391         NULL,                                        /* tp_descr_get */
392         NULL,                                        /* tp_descr_set */
393         0,                                           /* tp_dictoffset */
394         (initproc)PyKDTree__tp_init,                 /* tp_init */
395         (allocfunc)PyType_GenericAlloc,              /* tp_alloc */
396         (newfunc)PyType_GenericNew,                  /* tp_new */
397         (freefunc)0,                                 /* tp_free */
398         NULL,                                        /* tp_is_gc */
399         NULL,                                        /* tp_bases */
400         NULL,                                        /* tp_mro */
401         NULL,                                        /* tp_cache */
402         NULL,                                        /* tp_subclasses */
403         NULL,                                        /* tp_weaklist */
404         (destructor) NULL                            /* tp_del */
405 };
406
407 PyDoc_STRVAR(py_kdtree_doc,
408 "Generic 3-dimentional kd-tree to perform spatial searches."
409 );
410 static struct PyModuleDef kdtree_moduledef = {
411         PyModuleDef_HEAD_INIT,
412         "mathutils.kdtree",                          /* m_name */
413         py_kdtree_doc,                               /* m_doc */
414         0,                                           /* m_size */
415         NULL,                                        /* m_methods */
416         NULL,                                        /* m_reload */
417         NULL,                                        /* m_traverse */
418         NULL,                                        /* m_clear */
419         NULL                                         /* m_free */
420 };
421
422 PyMODINIT_FUNC PyInit_mathutils_kdtree(void)
423 {
424         PyObject *m = PyModule_Create(&kdtree_moduledef);
425
426         if (m == NULL) {
427                 return NULL;
428         }
429
430         /* Register the 'KDTree' class */
431         if (PyType_Ready(&PyKDTree_Type)) {
432                 return NULL;
433         }
434         PyModule_AddObject(m, "KDTree", (PyObject *) &PyKDTree_Type);
435
436         return m;
437 }