cleanup: style
[blender.git] / source / blender / python / mathutils / mathutils_geometry.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): Joseph Gilbert, Campbell Barton
19  *
20  * ***** END GPL LICENSE BLOCK *****
21  */
22
23 /** \file blender/python/mathutils/mathutils_geometry.c
24  *  \ingroup pymathutils
25  */
26
27
28 #include <Python.h>
29
30 #include "mathutils.h"
31 #include "mathutils_geometry.h"
32
33 /* Used for PolyFill */
34 #ifndef MATH_STANDALONE /* define when building outside blender */
35 #  include "MEM_guardedalloc.h"
36 #  include "BLI_blenlib.h"
37 #  include "BLI_boxpack2d.h"
38 #  include "BLI_convexhull2d.h"
39 #  include "BKE_displist.h"
40 #  include "BKE_curve.h"
41 #endif
42
43 #include "BLI_math.h"
44 #include "BLI_utildefines.h"
45
46 /*-------------------------DOC STRINGS ---------------------------*/
47 PyDoc_STRVAR(M_Geometry_doc,
48 "The Blender geometry module"
49 );
50
51 /* ---------------------------------INTERSECTION FUNCTIONS-------------------- */
52
53 PyDoc_STRVAR(M_Geometry_intersect_ray_tri_doc,
54 ".. function:: intersect_ray_tri(v1, v2, v3, ray, orig, clip=True)\n"
55 "\n"
56 "   Returns the intersection between a ray and a triangle, if possible, returns None otherwise.\n"
57 "\n"
58 "   :arg v1: Point1\n"
59 "   :type v1: :class:`mathutils.Vector`\n"
60 "   :arg v2: Point2\n"
61 "   :type v2: :class:`mathutils.Vector`\n"
62 "   :arg v3: Point3\n"
63 "   :type v3: :class:`mathutils.Vector`\n"
64 "   :arg ray: Direction of the projection\n"
65 "   :type ray: :class:`mathutils.Vector`\n"
66 "   :arg orig: Origin\n"
67 "   :type orig: :class:`mathutils.Vector`\n"
68 "   :arg clip: When False, don't restrict the intersection to the area of the triangle, use the infinite plane defined by the triangle.\n"
69 "   :type clip: boolean\n"
70 "   :return: The point of intersection or None if no intersection is found\n"
71 "   :rtype: :class:`mathutils.Vector` or None\n"
72 );
73 static PyObject *M_Geometry_intersect_ray_tri(PyObject *UNUSED(self), PyObject *args)
74 {
75         const char *error_prefix = "intersect_ray_tri";
76         PyObject *py_ray, *py_ray_off, *py_tri[3];
77         float dir[3], orig[3], tri[3][3], e1[3], e2[3], pvec[3], tvec[3], qvec[3];
78         float det, inv_det, u, v, t;
79         int clip = 1;
80         int i;
81
82         if (!PyArg_ParseTuple(
83                 args, "OOOOO|i:intersect_ray_tri",
84                 UNPACK3_EX(&, py_tri, ), &py_ray, &py_ray_off, &clip))
85         {
86                 return NULL;
87         }
88
89         if (((mathutils_array_parse(dir, 3, 3, py_ray, error_prefix) != -1) &&
90              (mathutils_array_parse(orig, 3, 3, py_ray_off, error_prefix) != -1)) == 0)
91         {
92                 return NULL;
93         }
94
95         for (i = 0; i < ARRAY_SIZE(tri); i++) {
96                 if (mathutils_array_parse(tri[i], 2, 2 | MU_ARRAY_SPILL, py_tri[i], error_prefix) == -1) {
97                         return NULL;
98                 }
99         }
100
101         normalize_v3(dir);
102
103         /* find vectors for two edges sharing v1 */
104         sub_v3_v3v3(e1, tri[1], tri[0]);
105         sub_v3_v3v3(e2, tri[2], tri[0]);
106
107         /* begin calculating determinant - also used to calculated U parameter */
108         cross_v3_v3v3(pvec, dir, e2);
109
110         /* if determinant is near zero, ray lies in plane of triangle */
111         det = dot_v3v3(e1, pvec);
112
113         if (det > -0.000001f && det < 0.000001f) {
114                 Py_RETURN_NONE;
115         }
116
117         inv_det = 1.0f / det;
118
119         /* calculate distance from v1 to ray origin */
120         sub_v3_v3v3(tvec, orig, tri[0]);
121
122         /* calculate U parameter and test bounds */
123         u = dot_v3v3(tvec, pvec) * inv_det;
124         if (clip && (u < 0.0f || u > 1.0f)) {
125                 Py_RETURN_NONE;
126         }
127
128         /* prepare to test the V parameter */
129         cross_v3_v3v3(qvec, tvec, e1);
130
131         /* calculate V parameter and test bounds */
132         v = dot_v3v3(dir, qvec) * inv_det;
133
134         if (clip && (v < 0.0f || u + v > 1.0f)) {
135                 Py_RETURN_NONE;
136         }
137
138         /* calculate t, ray intersects triangle */
139         t = dot_v3v3(e2, qvec) * inv_det;
140
141         /* ray hit behind */
142         if (t < 0.0f) {
143                 Py_RETURN_NONE;
144         }
145
146         mul_v3_fl(dir, t);
147         add_v3_v3v3(pvec, orig, dir);
148
149         return Vector_CreatePyObject(pvec, 3, Py_NEW, NULL);
150 }
151
152 /* Line-Line intersection using algorithm from mathworld.wolfram.com */
153
154 PyDoc_STRVAR(M_Geometry_intersect_line_line_doc,
155 ".. function:: intersect_line_line(v1, v2, v3, v4)\n"
156 "\n"
157 "   Returns a tuple with the points on each line respectively closest to the other.\n"
158 "\n"
159 "   :arg v1: First point of the first line\n"
160 "   :type v1: :class:`mathutils.Vector`\n"
161 "   :arg v2: Second point of the first line\n"
162 "   :type v2: :class:`mathutils.Vector`\n"
163 "   :arg v3: First point of the second line\n"
164 "   :type v3: :class:`mathutils.Vector`\n"
165 "   :arg v4: Second point of the second line\n"
166 "   :type v4: :class:`mathutils.Vector`\n"
167 "   :rtype: tuple of :class:`mathutils.Vector`'s\n"
168 );
169 static PyObject *M_Geometry_intersect_line_line(PyObject *UNUSED(self), PyObject *args)
170 {
171         const char *error_prefix = "intersect_line_line";
172         PyObject *tuple;
173         PyObject *py_lines[4];
174         float lines[4][3], i1[3], i2[3];
175         int len;
176         int result;
177
178         if (!PyArg_ParseTuple(
179                 args, "OOOO:intersect_line_line",
180                 UNPACK4_EX(&, py_lines, )))
181         {
182                 return NULL;
183         }
184
185         if ((((len = mathutils_array_parse(lines[0], 2, 3, py_lines[0], error_prefix)) != -1) &&
186              (mathutils_array_parse(lines[1], len, len, py_lines[1], error_prefix) != -1) &&
187              (mathutils_array_parse(lines[2], len, len, py_lines[2], error_prefix) != -1) &&
188              (mathutils_array_parse(lines[3], len, len, py_lines[3], error_prefix) != -1)) == 0)
189         {
190                 return NULL;
191         }
192
193         if (len == 2) {
194                 lines[0][2] = lines[1][2] = lines[2][2] = lines[3][2] = 0.0f;
195         }
196
197         result = isect_line_line_v3(UNPACK4(lines), i1, i2);
198         /* The return-code isnt exposed,
199          * this way we can check know how close the lines are. */
200         if (result == 1) {
201                 closest_to_line_v3(i2, i1, lines[2], lines[3]);
202         }
203
204         if (result == 0) {
205                 /* colinear */
206                 Py_RETURN_NONE;
207         }
208         else {
209                 tuple = PyTuple_New(2);
210                 PyTuple_SET_ITEM(tuple, 0, Vector_CreatePyObject(i1, len, Py_NEW, NULL));
211                 PyTuple_SET_ITEM(tuple, 1, Vector_CreatePyObject(i2, len, Py_NEW, NULL));
212                 return tuple;
213         }
214 }
215
216 /* Line-Line intersection using algorithm from mathworld.wolfram.com */
217
218 PyDoc_STRVAR(M_Geometry_intersect_sphere_sphere_2d_doc,
219 ".. function:: intersect_sphere_sphere_2d(p_a, radius_a, p_b, radius_b)\n"
220 "\n"
221 "   Returns 2 points on between intersecting circles.\n"
222 "\n"
223 "   :arg p_a: Center of the first circle\n"
224 "   :type p_a: :class:`mathutils.Vector`\n"
225 "   :arg radius_a: Radius of the first circle\n"
226 "   :type radius_a: float\n"
227 "   :arg p_b: Center of the second circle\n"
228 "   :type p_b: :class:`mathutils.Vector`\n"
229 "   :arg radius_b: Radius of the second circle\n"
230 "   :type radius_b: float\n"
231 "   :rtype: tuple of :class:`mathutils.Vector`'s or None when there is no intersection\n"
232 );
233 static PyObject *M_Geometry_intersect_sphere_sphere_2d(PyObject *UNUSED(self), PyObject *args)
234 {
235         const char *error_prefix = "intersect_sphere_sphere_2d";
236         PyObject *ret;
237         PyObject *py_v_a, *py_v_b;
238         float v_a[2], v_b[2];
239         float rad_a, rad_b;
240         float v_ab[2];
241         float dist;
242
243         if (!PyArg_ParseTuple(
244                 args, "OfOf:intersect_sphere_sphere_2d",
245                 &py_v_a, &rad_a,
246                 &py_v_b, &rad_b))
247         {
248                 return NULL;
249         }
250
251         if (((mathutils_array_parse(v_a, 2, 2, py_v_a, error_prefix) != -1) &&
252              (mathutils_array_parse(v_b, 2, 2, py_v_b, error_prefix) != -1)) == 0)
253         {
254                 return NULL;
255         }
256
257         ret = PyTuple_New(2);
258
259         sub_v2_v2v2(v_ab, v_b, v_a);
260         dist = len_v2(v_ab);
261
262         if (/* out of range */
263             (dist > rad_a + rad_b) ||
264             /* fully-contained in the other */
265             (dist < fabsf(rad_a - rad_b)) ||
266             /* co-incident */
267             (dist < FLT_EPSILON))
268         {
269                 /* out of range */
270                 PyTuple_SET_ITEM(ret, 0,  Py_None); Py_INCREF(Py_None);
271                 PyTuple_SET_ITEM(ret, 1,  Py_None); Py_INCREF(Py_None);
272         }
273         else {
274                 const float dist_delta = ((rad_a * rad_a) - (rad_b * rad_b) + (dist * dist)) / (2.0f * dist);
275                 const float h = powf(fabsf((rad_a * rad_a) - (dist_delta * dist_delta)), 0.5f);
276                 float i_cent[2];
277                 float i1[2], i2[2];
278
279                 i_cent[0] = v_a[0] + ((v_ab[0] * dist_delta) / dist);
280                 i_cent[1] = v_a[1] + ((v_ab[1] * dist_delta) / dist);
281
282                 i1[0] = i_cent[0] + h * v_ab[1] / dist;
283                 i1[1] = i_cent[1] - h * v_ab[0] / dist;
284
285                 i2[0] = i_cent[0] - h * v_ab[1] / dist;
286                 i2[1] = i_cent[1] + h * v_ab[0] / dist;
287
288                 PyTuple_SET_ITEM(ret, 0, Vector_CreatePyObject(i1, 2, Py_NEW, NULL));
289                 PyTuple_SET_ITEM(ret, 1, Vector_CreatePyObject(i2, 2, Py_NEW, NULL));
290         }
291
292         return ret;
293 }
294
295 PyDoc_STRVAR(M_Geometry_normal_doc,
296 ".. function:: normal(vectors)\n"
297 "\n"
298 "   Returns the normal of a 3D polygon.\n"
299 "\n"
300 "   :arg vectors: Vectors to calculate normals with\n"
301 "   :type vectors: sequence of 3 or more 3d vector\n"
302 "   :rtype: :class:`mathutils.Vector`\n"
303 );
304 static PyObject *M_Geometry_normal(PyObject *UNUSED(self), PyObject *args)
305 {
306         float (*coords)[3];
307         int coords_len;
308         float n[3];
309         PyObject *ret = NULL;
310
311         /* use */
312         if (PyTuple_GET_SIZE(args) == 1) {
313                 args = PyTuple_GET_ITEM(args, 0);
314         }
315
316         if ((coords_len = mathutils_array_parse_alloc_v((float **)&coords, 3 | MU_ARRAY_SPILL, args, "normal")) == -1) {
317                 return NULL;
318         }
319
320         if (coords_len < 3) {
321                 PyErr_SetString(PyExc_ValueError,
322                                 "Expected 3 or more vectors");
323                 goto finally;
324         }
325
326         normal_poly_v3(n, (const float (*)[3])coords, coords_len);
327         ret = Vector_CreatePyObject(n, 3, Py_NEW, NULL);
328
329 finally:
330         PyMem_Free(coords);
331         return ret;
332 }
333
334 /* --------------------------------- AREA FUNCTIONS-------------------- */
335
336 PyDoc_STRVAR(M_Geometry_area_tri_doc,
337 ".. function:: area_tri(v1, v2, v3)\n"
338 "\n"
339 "   Returns the area size of the 2D or 3D triangle defined.\n"
340 "\n"
341 "   :arg v1: Point1\n"
342 "   :type v1: :class:`mathutils.Vector`\n"
343 "   :arg v2: Point2\n"
344 "   :type v2: :class:`mathutils.Vector`\n"
345 "   :arg v3: Point3\n"
346 "   :type v3: :class:`mathutils.Vector`\n"
347 "   :rtype: float\n"
348 );
349 static PyObject *M_Geometry_area_tri(PyObject *UNUSED(self), PyObject *args)
350 {
351         const char *error_prefix = "area_tri";
352         PyObject *py_tri[3];
353         float tri[3][3];
354         int len;
355
356         if (!PyArg_ParseTuple(
357                 args, "OOO:area_tri",
358                 UNPACK3_EX(&, py_tri, )))
359         {
360                 return NULL;
361         }
362
363         if ((((len = mathutils_array_parse(tri[0], 2, 3, py_tri[0], error_prefix)) != -1) &&
364              (mathutils_array_parse(tri[1], len, len, py_tri[1], error_prefix) != -1) &&
365              (mathutils_array_parse(tri[2], len, len, py_tri[2], error_prefix) != -1)) == 0)
366         {
367                 return NULL;
368         }
369
370         return PyFloat_FromDouble((len == 3 ? area_tri_v3 : area_tri_v2)(UNPACK3(tri)));
371 }
372
373 PyDoc_STRVAR(M_Geometry_volume_tetrahedron_doc,
374 ".. function:: volume_tetrahedron(v1, v2, v3, v4)\n"
375 "\n"
376 "   Return the volume formed by a tetrahedron (points can be in any order).\n"
377 "\n"
378 "   :arg v1: Point1\n"
379 "   :type v1: :class:`mathutils.Vector`\n"
380 "   :arg v2: Point2\n"
381 "   :type v2: :class:`mathutils.Vector`\n"
382 "   :arg v3: Point3\n"
383 "   :type v3: :class:`mathutils.Vector`\n"
384 "   :arg v4: Point4\n"
385 "   :type v4: :class:`mathutils.Vector`\n"
386 "   :rtype: float\n"
387 );
388 static PyObject *M_Geometry_volume_tetrahedron(PyObject *UNUSED(self), PyObject *args)
389 {
390         const char *error_prefix = "volume_tetrahedron";
391         PyObject *py_tet[4];
392         float tet[4][3];
393         int i;
394
395         if (!PyArg_ParseTuple(
396                 args, "OOOO:volume_tetrahedron",
397                 UNPACK4_EX(&, py_tet, )))
398         {
399                 return NULL;
400         }
401
402         for (i = 0; i < ARRAY_SIZE(tet); i++) {
403                 if (mathutils_array_parse(tet[i], 3, 3 | MU_ARRAY_SPILL, py_tet[i], error_prefix) == -1) {
404                         return NULL;
405                 }
406         }
407
408         return PyFloat_FromDouble(volume_tetrahedron_v3(UNPACK4(tet)));
409 }
410
411 PyDoc_STRVAR(M_Geometry_intersect_line_line_2d_doc,
412 ".. function:: intersect_line_line_2d(lineA_p1, lineA_p2, lineB_p1, lineB_p2)\n"
413 "\n"
414 "   Takes 2 lines (as 4 vectors) and returns a vector for their point of intersection or None.\n"
415 "\n"
416 "   :arg lineA_p1: First point of the first line\n"
417 "   :type lineA_p1: :class:`mathutils.Vector`\n"
418 "   :arg lineA_p2: Second point of the first line\n"
419 "   :type lineA_p2: :class:`mathutils.Vector`\n"
420 "   :arg lineB_p1: First point of the second line\n"
421 "   :type lineB_p1: :class:`mathutils.Vector`\n"
422 "   :arg lineB_p2: Second point of the second line\n"
423 "   :type lineB_p2: :class:`mathutils.Vector`\n"
424 "   :return: The point of intersection or None when not found\n"
425 "   :rtype: :class:`mathutils.Vector` or None\n"
426 );
427 static PyObject *M_Geometry_intersect_line_line_2d(PyObject *UNUSED(self), PyObject *args)
428 {
429         const char *error_prefix = "intersect_line_line_2d";
430         PyObject *py_lines[4];
431         float lines[4][2];
432         float vi[2];
433         int i;
434
435         if (!PyArg_ParseTuple(
436                 args, "OOOO:intersect_line_line_2d",
437                 UNPACK4_EX(&, py_lines, )))
438         {
439                 return NULL;
440         }
441
442         for (i = 0; i < ARRAY_SIZE(lines); i++) {
443                 if (mathutils_array_parse(lines[i], 2, 2 | MU_ARRAY_SPILL, py_lines[i], error_prefix) == -1) {
444                         return NULL;
445                 }
446         }
447
448         if (isect_seg_seg_v2_point(UNPACK4(lines), vi) == 1) {
449                 return Vector_CreatePyObject(vi, 2, Py_NEW, NULL);
450         }
451         else {
452                 Py_RETURN_NONE;
453         }
454 }
455
456
457 PyDoc_STRVAR(M_Geometry_intersect_line_plane_doc,
458 ".. function:: intersect_line_plane(line_a, line_b, plane_co, plane_no, no_flip=False)\n"
459 "\n"
460 "   Calculate the intersection between a line (as 2 vectors) and a plane.\n"
461 "   Returns a vector for the intersection or None.\n"
462 "\n"
463 "   :arg line_a: First point of the first line\n"
464 "   :type line_a: :class:`mathutils.Vector`\n"
465 "   :arg line_b: Second point of the first line\n"
466 "   :type line_b: :class:`mathutils.Vector`\n"
467 "   :arg plane_co: A point on the plane\n"
468 "   :type plane_co: :class:`mathutils.Vector`\n"
469 "   :arg plane_no: The direction the plane is facing\n"
470 "   :type plane_no: :class:`mathutils.Vector`\n"
471 "   :return: The point of intersection or None when not found\n"
472 "   :rtype: :class:`mathutils.Vector` or None\n"
473 );
474 static PyObject *M_Geometry_intersect_line_plane(PyObject *UNUSED(self), PyObject *args)
475 {
476         const char *error_prefix = "intersect_line_plane";
477         PyObject *py_line_a, *py_line_b, *py_plane_co, *py_plane_no;
478         float line_a[3], line_b[3], plane_co[3], plane_no[3];
479         float isect[3];
480         int no_flip = false;
481
482         if (!PyArg_ParseTuple(
483                 args, "OOOO|i:intersect_line_plane",
484                 &py_line_a, &py_line_b, &py_plane_co, &py_plane_no,
485                 &no_flip))
486         {
487                 return NULL;
488         }
489
490         if (((mathutils_array_parse(line_a, 3, 3 | MU_ARRAY_SPILL, py_line_a, error_prefix) != -1) &&
491              (mathutils_array_parse(line_b, 3, 3 | MU_ARRAY_SPILL, py_line_b, error_prefix) != -1) &&
492              (mathutils_array_parse(plane_co, 3, 3 | MU_ARRAY_SPILL, py_plane_co, error_prefix) != -1) &&
493              (mathutils_array_parse(plane_no, 3, 3 | MU_ARRAY_SPILL, py_plane_no, error_prefix) != -1)) == 0)
494         {
495                 return NULL;
496         }
497
498         /* TODO: implements no_flip */
499         if (isect_line_plane_v3(isect, line_a, line_b, plane_co, plane_no) == 1) {
500                 return Vector_CreatePyObject(isect, 3, Py_NEW, NULL);
501         }
502         else {
503                 Py_RETURN_NONE;
504         }
505 }
506
507 PyDoc_STRVAR(M_Geometry_intersect_plane_plane_doc,
508 ".. function:: intersect_plane_plane(plane_a_co, plane_a_no, plane_b_co, plane_b_no)\n"
509 "\n"
510 "   Return the intersection between two planes\n"
511 "\n"
512 "   :arg plane_a_co: Point on the first plane\n"
513 "   :type plane_a_co: :class:`mathutils.Vector`\n"
514 "   :arg plane_a_no: Normal of the first plane\n"
515 "   :type plane_a_no: :class:`mathutils.Vector`\n"
516 "   :arg plane_b_co: Point on the second plane\n"
517 "   :type plane_b_co: :class:`mathutils.Vector`\n"
518 "   :arg plane_b_no: Normal of the second plane\n"
519 "   :type plane_b_no: :class:`mathutils.Vector`\n"
520 "   :return: The line of the intersection represented as a point and a vector\n"
521 "   :rtype: tuple pair of :class:`mathutils.Vector` or None if the intersection can't be calculated\n"
522 );
523 static PyObject *M_Geometry_intersect_plane_plane(PyObject *UNUSED(self), PyObject *args)
524 {
525         const char *error_prefix = "intersect_plane_plane";
526         PyObject *ret, *ret_co, *ret_no;
527         PyObject *py_plane_a_co, *py_plane_a_no, *py_plane_b_co, *py_plane_b_no;
528         float plane_a_co[3], plane_a_no[3], plane_b_co[3], plane_b_no[3];
529
530         float isect_co[3];
531         float isect_no[3];
532
533         if (!PyArg_ParseTuple(
534                 args, "OOOO:intersect_plane_plane",
535                 &plane_a_co, &plane_a_no, &plane_b_co, &plane_b_no))
536         {
537                 return NULL;
538         }
539
540         if (((mathutils_array_parse(plane_a_co, 3, 3 | MU_ARRAY_SPILL, py_plane_a_co, error_prefix) != -1) &&
541              (mathutils_array_parse(plane_a_no, 3, 3 | MU_ARRAY_SPILL, py_plane_a_no, error_prefix) != -1) &&
542              (mathutils_array_parse(plane_b_co, 3, 3 | MU_ARRAY_SPILL, py_plane_b_co, error_prefix) != -1) &&
543              (mathutils_array_parse(plane_b_no, 3, 3 | MU_ARRAY_SPILL, py_plane_b_no, error_prefix) != -1)) == 0)
544         {
545                 return NULL;
546         }
547
548         if (isect_plane_plane_v3(isect_co, isect_no,
549                                  plane_a_co, plane_a_no,
550                                  plane_b_co, plane_b_no))
551         {
552                 normalize_v3(isect_no);
553
554                 ret_co = Vector_CreatePyObject(isect_co, 3, Py_NEW, NULL);
555                 ret_no = Vector_CreatePyObject(isect_no, 3, Py_NEW, NULL);
556         }
557         else {
558                 ret_co = Py_None;
559                 ret_no = Py_None;
560
561                 Py_INCREF(ret_co);
562                 Py_INCREF(ret_no);
563         }
564
565         ret = PyTuple_New(2);
566         PyTuple_SET_ITEM(ret, 0, ret_co);
567         PyTuple_SET_ITEM(ret, 1, ret_no);
568         return ret;
569 }
570
571 PyDoc_STRVAR(M_Geometry_intersect_line_sphere_doc,
572 ".. function:: intersect_line_sphere(line_a, line_b, sphere_co, sphere_radius, clip=True)\n"
573 "\n"
574 "   Takes a line (as 2 points) and a sphere (as a point and a radius) and\n"
575 "   returns the intersection\n"
576 "\n"
577 "   :arg line_a: First point of the line\n"
578 "   :type line_a: :class:`mathutils.Vector`\n"
579 "   :arg line_b: Second point of the line\n"
580 "   :type line_b: :class:`mathutils.Vector`\n"
581 "   :arg sphere_co: The center of the sphere\n"
582 "   :type sphere_co: :class:`mathutils.Vector`\n"
583 "   :arg sphere_radius: Radius of the sphere\n"
584 "   :type sphere_radius: sphere_radius\n"
585 "   :return: The intersection points as a pair of vectors or None when there is no intersection\n"
586 "   :rtype: A tuple pair containing :class:`mathutils.Vector` or None\n"
587 );
588 static PyObject *M_Geometry_intersect_line_sphere(PyObject *UNUSED(self), PyObject *args)
589 {
590         const char *error_prefix = "intersect_line_sphere";
591         PyObject *py_line_a, *py_line_b, *py_sphere_co;
592         float line_a[3], line_b[3], sphere_co[3];
593         float sphere_radius;
594         int clip = true;
595
596         float isect_a[3];
597         float isect_b[3];
598
599         if (!PyArg_ParseTuple(
600                 args, "OOOf|i:intersect_line_sphere",
601                 &py_line_a, &py_line_b, &py_sphere_co, &sphere_radius, &clip))
602         {
603                 return NULL;
604         }
605
606         if (((mathutils_array_parse(line_a, 3, 3 | MU_ARRAY_SPILL, py_line_a, error_prefix) != -1) &&
607              (mathutils_array_parse(line_b, 3, 3 | MU_ARRAY_SPILL, py_line_b, error_prefix) != -1) &&
608              (mathutils_array_parse(sphere_co, 3, 3 | MU_ARRAY_SPILL, py_sphere_co, error_prefix) != -1)) == 0)
609         {
610                 return NULL;
611         }
612         else {
613                 bool use_a = true;
614                 bool use_b = true;
615                 float lambda;
616
617                 PyObject *ret = PyTuple_New(2);
618
619                 switch (isect_line_sphere_v3(line_a, line_b, sphere_co, sphere_radius, isect_a, isect_b)) {
620                         case 1:
621                                 if (!(!clip || (((lambda = line_point_factor_v3(isect_a, line_a, line_b)) >= 0.0f) && (lambda <= 1.0f)))) use_a = false;
622                                 use_b = false;
623                                 break;
624                         case 2:
625                                 if (!(!clip || (((lambda = line_point_factor_v3(isect_a, line_a, line_b)) >= 0.0f) && (lambda <= 1.0f)))) use_a = false;
626                                 if (!(!clip || (((lambda = line_point_factor_v3(isect_b, line_a, line_b)) >= 0.0f) && (lambda <= 1.0f)))) use_b = false;
627                                 break;
628                         default:
629                                 use_a = false;
630                                 use_b = false;
631                                 break;
632                 }
633
634                 if (use_a) { PyTuple_SET_ITEM(ret, 0,  Vector_CreatePyObject(isect_a, 3, Py_NEW, NULL)); }
635                 else       { PyTuple_SET_ITEM(ret, 0,  Py_None); Py_INCREF(Py_None); }
636
637                 if (use_b) { PyTuple_SET_ITEM(ret, 1,  Vector_CreatePyObject(isect_b, 3, Py_NEW, NULL)); }
638                 else       { PyTuple_SET_ITEM(ret, 1,  Py_None); Py_INCREF(Py_None); }
639
640                 return ret;
641         }
642 }
643
644 /* keep in sync with M_Geometry_intersect_line_sphere */
645 PyDoc_STRVAR(M_Geometry_intersect_line_sphere_2d_doc,
646 ".. function:: intersect_line_sphere_2d(line_a, line_b, sphere_co, sphere_radius, clip=True)\n"
647 "\n"
648 "   Takes a line (as 2 points) and a sphere (as a point and a radius) and\n"
649 "   returns the intersection\n"
650 "\n"
651 "   :arg line_a: First point of the line\n"
652 "   :type line_a: :class:`mathutils.Vector`\n"
653 "   :arg line_b: Second point of the line\n"
654 "   :type line_b: :class:`mathutils.Vector`\n"
655 "   :arg sphere_co: The center of the sphere\n"
656 "   :type sphere_co: :class:`mathutils.Vector`\n"
657 "   :arg sphere_radius: Radius of the sphere\n"
658 "   :type sphere_radius: sphere_radius\n"
659 "   :return: The intersection points as a pair of vectors or None when there is no intersection\n"
660 "   :rtype: A tuple pair containing :class:`mathutils.Vector` or None\n"
661 );
662 static PyObject *M_Geometry_intersect_line_sphere_2d(PyObject *UNUSED(self), PyObject *args)
663 {
664         const char *error_prefix = "intersect_line_sphere_2d";
665         PyObject *py_line_a, *py_line_b, *py_sphere_co;
666         float line_a[2], line_b[2], sphere_co[2];
667         float sphere_radius;
668         int clip = true;
669
670         float isect_a[2];
671         float isect_b[2];
672
673         if (!PyArg_ParseTuple(
674                 args, "OOOf|i:intersect_line_sphere_2d",
675                 &py_line_a, &py_line_b, &py_sphere_co, &sphere_radius, &clip))
676         {
677                 return NULL;
678         }
679
680         if (((mathutils_array_parse(line_a, 2, 2 | MU_ARRAY_SPILL, py_line_a, error_prefix) != -1) &&
681              (mathutils_array_parse(line_b, 2, 2 | MU_ARRAY_SPILL, py_line_b, error_prefix) != -1) &&
682              (mathutils_array_parse(sphere_co, 2, 2 | MU_ARRAY_SPILL, py_sphere_co, error_prefix) != -1)) == 0)
683         {
684                 return NULL;
685         }
686         else {
687                 bool use_a = true;
688                 bool use_b = true;
689                 float lambda;
690
691                 PyObject *ret = PyTuple_New(2);
692
693                 switch (isect_line_sphere_v2(line_a, line_b, sphere_co, sphere_radius, isect_a, isect_b)) {
694                         case 1:
695                                 if (!(!clip || (((lambda = line_point_factor_v2(isect_a, line_a, line_b)) >= 0.0f) && (lambda <= 1.0f)))) use_a = false;
696                                 use_b = false;
697                                 break;
698                         case 2:
699                                 if (!(!clip || (((lambda = line_point_factor_v2(isect_a, line_a, line_b)) >= 0.0f) && (lambda <= 1.0f)))) use_a = false;
700                                 if (!(!clip || (((lambda = line_point_factor_v2(isect_b, line_a, line_b)) >= 0.0f) && (lambda <= 1.0f)))) use_b = false;
701                                 break;
702                         default:
703                                 use_a = false;
704                                 use_b = false;
705                                 break;
706                 }
707
708                 if (use_a) { PyTuple_SET_ITEM(ret, 0,  Vector_CreatePyObject(isect_a, 2, Py_NEW, NULL)); }
709                 else       { PyTuple_SET_ITEM(ret, 0,  Py_None); Py_INCREF(Py_None); }
710
711                 if (use_b) { PyTuple_SET_ITEM(ret, 1,  Vector_CreatePyObject(isect_b, 2, Py_NEW, NULL)); }
712                 else       { PyTuple_SET_ITEM(ret, 1,  Py_None); Py_INCREF(Py_None); }
713
714                 return ret;
715         }
716 }
717
718 PyDoc_STRVAR(M_Geometry_intersect_point_line_doc,
719 ".. function:: intersect_point_line(pt, line_p1, line_p2)\n"
720 "\n"
721 "   Takes a point and a line and returns a tuple with the closest point on the line and its distance from the first point of the line as a percentage of the length of the line.\n"
722 "\n"
723 "   :arg pt: Point\n"
724 "   :type pt: :class:`mathutils.Vector`\n"
725 "   :arg line_p1: First point of the line\n"
726 "   :type line_p1: :class:`mathutils.Vector`\n"
727 "   :arg line_p1: Second point of the line\n"
728 "   :type line_p1: :class:`mathutils.Vector`\n"
729 "   :rtype: (:class:`mathutils.Vector`, float)\n"
730 );
731 static PyObject *M_Geometry_intersect_point_line(PyObject *UNUSED(self), PyObject *args)
732 {
733         const char *error_prefix = "intersect_point_line";
734         PyObject *py_pt, *py_line_a, *py_line_b;
735         float pt[3], pt_out[3], line_a[3], line_b[3];
736         float lambda;
737         PyObject *ret;
738         int size = 2;
739         
740         if (!PyArg_ParseTuple(
741                 args, "OOO:intersect_point_line",
742                 &py_pt, &py_line_a, &py_line_b))
743         {
744                 return NULL;
745         }
746
747         /* accept 2d verts */
748         if (((mathutils_array_parse(pt, 2, 3 | MU_ARRAY_SPILL | MU_ARRAY_ZERO, py_pt, error_prefix) != -1) &&
749              (mathutils_array_parse(line_a, 2, 3 | MU_ARRAY_SPILL | MU_ARRAY_ZERO, py_line_a, error_prefix) != -1) &&
750              (mathutils_array_parse(line_b, 3, 3 | MU_ARRAY_SPILL | MU_ARRAY_ZERO, py_line_b, error_prefix) != -1)) == 0)
751         {
752                 return NULL;
753         }
754
755         /* do the calculation */
756         lambda = closest_to_line_v3(pt_out, pt, line_a, line_b);
757         
758         ret = PyTuple_New(2);
759         PyTuple_SET_ITEM(ret, 0, Vector_CreatePyObject(pt_out, size, Py_NEW, NULL));
760         PyTuple_SET_ITEM(ret, 1, PyFloat_FromDouble(lambda));
761         return ret;
762 }
763
764 PyDoc_STRVAR(M_Geometry_intersect_point_tri_doc,
765 ".. function:: intersect_point_tri(pt, tri_p1, tri_p2, tri_p3)\n"
766 "\n"
767 "   Takes 4 vectors: one is the point and the next 3 define the triangle.\n"
768 "\n"
769 "   :arg pt: Point\n"
770 "   :type pt: :class:`mathutils.Vector`\n"
771 "   :arg tri_p1: First point of the triangle\n"
772 "   :type tri_p1: :class:`mathutils.Vector`\n"
773 "   :arg tri_p2: Second point of the triangle\n"
774 "   :type tri_p2: :class:`mathutils.Vector`\n"
775 "   :arg tri_p3: Third point of the triangle\n"
776 "   :type tri_p3: :class:`mathutils.Vector`\n"
777 "   :return: Point on the triangles plane or None if its outside the triangle\n"
778 "   :rtype: :class:`mathutils.Vector` or None\n"
779 );
780 static PyObject *M_Geometry_intersect_point_tri(PyObject *UNUSED(self), PyObject *args)
781 {
782         const char *error_prefix = "intersect_point_tri";
783         PyObject *py_pt, *py_tri[3];
784         float pt[3], tri[3][3];
785         float vi[3];
786         int i;
787
788         if (!PyArg_ParseTuple(
789                 args, "OOOO:intersect_point_tri",
790                 &py_pt, UNPACK3_EX(&, py_tri, )))
791         {
792                 return NULL;
793         }
794
795         if (mathutils_array_parse(pt, 3, 3 | MU_ARRAY_SPILL, py_pt, error_prefix) == -1) {
796                 return NULL;
797         }
798         for (i = 0; i < ARRAY_SIZE(tri); i++) {
799                 if (mathutils_array_parse(tri[i], 3, 3 | MU_ARRAY_SPILL, py_tri[i], error_prefix) == -1) {
800                         return NULL;
801                 }
802         }
803
804         if (isect_point_tri_v3(pt, UNPACK3(tri), vi)) {
805                 return Vector_CreatePyObject(vi, 3, Py_NEW, NULL);
806         }
807         else {
808                 Py_RETURN_NONE;
809         }
810 }
811
812 PyDoc_STRVAR(M_Geometry_intersect_point_tri_2d_doc,
813 ".. function:: intersect_point_tri_2d(pt, tri_p1, tri_p2, tri_p3)\n"
814 "\n"
815 "   Takes 4 vectors (using only the x and y coordinates): one is the point and the next 3 define the triangle. Returns 1 if the point is within the triangle, otherwise 0.\n"
816 "\n"
817 "   :arg pt: Point\n"
818 "   :type pt: :class:`mathutils.Vector`\n"
819 "   :arg tri_p1: First point of the triangle\n"
820 "   :type tri_p1: :class:`mathutils.Vector`\n"
821 "   :arg tri_p2: Second point of the triangle\n"
822 "   :type tri_p2: :class:`mathutils.Vector`\n"
823 "   :arg tri_p3: Third point of the triangle\n"
824 "   :type tri_p3: :class:`mathutils.Vector`\n"
825 "   :rtype: int\n"
826 );
827 static PyObject *M_Geometry_intersect_point_tri_2d(PyObject *UNUSED(self), PyObject *args)
828 {
829         const char *error_prefix = "intersect_point_tri_2d";
830         PyObject *py_pt, *py_tri[3];
831         float pt[2], tri[3][2];
832         int i;
833
834         if (!PyArg_ParseTuple(
835                 args, "OOOO:intersect_point_tri_2d",
836                 &py_pt, UNPACK3_EX(&, py_tri, )))
837         {
838                 return NULL;
839         }
840
841         if (mathutils_array_parse(pt, 2, 2 | MU_ARRAY_SPILL, py_pt, error_prefix) == -1) {
842                 return NULL;
843         }
844         for (i = 0; i < ARRAY_SIZE(tri); i++) {
845                 if (mathutils_array_parse(tri[i], 2, 2 | MU_ARRAY_SPILL, py_tri[i], error_prefix) == -1) {
846                         return NULL;
847                 }
848         }
849
850         return PyLong_FromLong(isect_point_tri_v2(pt, UNPACK3(tri)));
851 }
852
853 PyDoc_STRVAR(M_Geometry_intersect_point_quad_2d_doc,
854 ".. function:: intersect_point_quad_2d(pt, quad_p1, quad_p2, quad_p3, quad_p4)\n"
855 "\n"
856 "   Takes 5 vectors (using only the x and y coordinates): one is the point and the next 4 define the quad, \n"
857 "   only the x and y are used from the vectors. Returns 1 if the point is within the quad, otherwise 0.\n"
858 "   Works only with convex quads without singular edges."
859 "\n"
860 "   :arg pt: Point\n"
861 "   :type pt: :class:`mathutils.Vector`\n"
862 "   :arg quad_p1: First point of the quad\n"
863 "   :type quad_p1: :class:`mathutils.Vector`\n"
864 "   :arg quad_p2: Second point of the quad\n"
865 "   :type quad_p2: :class:`mathutils.Vector`\n"
866 "   :arg quad_p3: Third point of the quad\n"
867 "   :type quad_p3: :class:`mathutils.Vector`\n"
868 "   :arg quad_p4: Forth point of the quad\n"
869 "   :type quad_p4: :class:`mathutils.Vector`\n"
870 "   :rtype: int\n"
871 );
872 static PyObject *M_Geometry_intersect_point_quad_2d(PyObject *UNUSED(self), PyObject *args)
873 {
874         const char *error_prefix = "intersect_point_quad_2d";
875         PyObject *py_pt, *py_quad[4];
876         float pt[2], quad[4][2];
877         int i;
878         
879         if (!PyArg_ParseTuple(
880                 args, "OOOOO:intersect_point_quad_2d",
881                 &py_pt, UNPACK4_EX(&, py_quad, )))
882         {
883                 return NULL;
884         }
885
886         if (mathutils_array_parse(pt, 2, 2 | MU_ARRAY_SPILL, py_pt, error_prefix) == -1) {
887                 return NULL;
888         }
889         for (i = 0; i < ARRAY_SIZE(quad); i++) {
890                 if (mathutils_array_parse(quad[i], 2, 2 | MU_ARRAY_SPILL, py_quad[i], error_prefix) == -1) {
891                         return NULL;
892                 }
893         }
894
895         return PyLong_FromLong(isect_point_quad_v2(pt, UNPACK4(quad)));
896 }
897
898 PyDoc_STRVAR(M_Geometry_distance_point_to_plane_doc,
899 ".. function:: distance_point_to_plane(pt, plane_co, plane_no)\n"
900 "\n"
901 "   Returns the signed distance between a point and a plane "
902 "   (negative when below the normal).\n"
903 "\n"
904 "   :arg pt: Point\n"
905 "   :type pt: :class:`mathutils.Vector`\n"
906 "   :arg plane_co: A point on the plane\n"
907 "   :type plane_co: :class:`mathutils.Vector`\n"
908 "   :arg plane_no: The direction the plane is facing\n"
909 "   :type plane_no: :class:`mathutils.Vector`\n"
910 "   :rtype: float\n"
911 );
912 static PyObject *M_Geometry_distance_point_to_plane(PyObject *UNUSED(self), PyObject *args)
913 {
914         const char *error_prefix = "distance_point_to_plane";
915         PyObject *py_pt, *py_plane_co, *py_plane_no;
916         float pt[3], plane_co[3], plane_no[3];
917         float plane[4];
918
919         if (!PyArg_ParseTuple(
920                 args, "OOO:distance_point_to_plane",
921                 &py_pt, &py_plane_co, &py_plane_no))
922         {
923                 return NULL;
924         }
925
926         if (((mathutils_array_parse(pt,       3, 3 | MU_ARRAY_SPILL, py_pt,       error_prefix) != -1) &&
927              (mathutils_array_parse(plane_co, 3, 3 | MU_ARRAY_SPILL, py_plane_co, error_prefix) != -1) &&
928              (mathutils_array_parse(plane_no, 3, 3 | MU_ARRAY_SPILL, py_plane_no, error_prefix) != -1)) == 0)
929         {
930                 return NULL;
931         }
932
933         plane_from_point_normal_v3(plane, plane_co, plane_no);
934         return PyFloat_FromDouble(dist_signed_to_plane_v3(pt, plane));
935 }
936
937 PyDoc_STRVAR(M_Geometry_barycentric_transform_doc,
938 ".. function:: barycentric_transform(point, tri_a1, tri_a2, tri_a3, tri_b1, tri_b2, tri_b3)\n"
939 "\n"
940 "   Return a transformed point, the transformation is defined by 2 triangles.\n"
941 "\n"
942 "   :arg point: The point to transform.\n"
943 "   :type point: :class:`mathutils.Vector`\n"
944 "   :arg tri_a1: source triangle vertex.\n"
945 "   :type tri_a1: :class:`mathutils.Vector`\n"
946 "   :arg tri_a2: source triangle vertex.\n"
947 "   :type tri_a2: :class:`mathutils.Vector`\n"
948 "   :arg tri_a3: source triangle vertex.\n"
949 "   :type tri_a3: :class:`mathutils.Vector`\n"
950 "   :arg tri_a1: target triangle vertex.\n"
951 "   :type tri_a1: :class:`mathutils.Vector`\n"
952 "   :arg tri_a2: target triangle vertex.\n"
953 "   :type tri_a2: :class:`mathutils.Vector`\n"
954 "   :arg tri_a3: target triangle vertex.\n"
955 "   :type tri_a3: :class:`mathutils.Vector`\n"
956 "   :return: The transformed point\n"
957 "   :rtype: :class:`mathutils.Vector`'s\n"
958 );
959 static PyObject *M_Geometry_barycentric_transform(PyObject *UNUSED(self), PyObject *args)
960 {
961         const char *error_prefix = "barycentric_transform";
962         PyObject *py_pt_src, *py_tri_src[3], *py_tri_dst[3];
963         float pt_src[3], pt_dst[3], tri_src[3][3], tri_dst[3][3];
964         int i;
965
966         if (!PyArg_ParseTuple(
967                 args, "OOOOOOO:barycentric_transform",
968                 &py_pt_src,
969                 UNPACK3_EX(&, py_tri_src, ),
970                 UNPACK3_EX(&, py_tri_dst, )))
971         {
972                 return NULL;
973         }
974
975         if (mathutils_array_parse(pt_src, 2, 2 | MU_ARRAY_SPILL, py_pt_src, error_prefix) == -1) {
976                 return NULL;
977         }
978         for (i = 0; i < ARRAY_SIZE(tri_src); i++) {
979                 if (((mathutils_array_parse(tri_src[i], 3, 3 | MU_ARRAY_SPILL, py_tri_src[i], error_prefix) != -1) &&
980                      (mathutils_array_parse(tri_dst[i], 3, 3 | MU_ARRAY_SPILL, py_tri_dst[i], error_prefix) != -1)) == 0)
981                 {
982                         return NULL;
983                 }
984         }
985
986         transform_point_by_tri_v3(
987                 pt_dst, pt_src,
988                 UNPACK3(tri_dst),
989                 UNPACK3(tri_src));
990
991         return Vector_CreatePyObject(pt_dst, 3, Py_NEW, NULL);
992 }
993
994 PyDoc_STRVAR(M_Geometry_points_in_planes_doc,
995 ".. function:: points_in_planes(planes)\n"
996 "\n"
997 "   Returns a list of points inside all planes given and a list of index values for the planes used.\n"
998 "\n"
999 "   :arg planes: List of planes (4D vectors).\n"
1000 "   :type planes: list of :class:`mathutils.Vector`\n"
1001 "   :return: two lists, once containing the vertices inside the planes, another containing the plane indices used\n"
1002 "   :rtype: pair of lists\n"
1003 );
1004 /* note: this function could be optimized by some spatial structure */
1005 static PyObject *M_Geometry_points_in_planes(PyObject *UNUSED(self), PyObject *args)
1006 {
1007         PyObject *py_planes;
1008         float (*planes)[4];
1009         unsigned int planes_len;
1010
1011         if (!PyArg_ParseTuple(
1012                 args, "O:points_in_planes",
1013                 &py_planes))
1014         {
1015                 return NULL;
1016         }
1017
1018         if ((planes_len = mathutils_array_parse_alloc_v((float **)&planes, 4, py_planes, "points_in_planes")) == -1) {
1019                 return NULL;
1020         }
1021         else {
1022                 /* note, this could be refactored into plain C easy - py bits are noted */
1023                 const float eps = 0.0001f;
1024                 const unsigned int len = (unsigned int)planes_len;
1025                 unsigned int i, j, k, l;
1026
1027                 float n1n2[3], n2n3[3], n3n1[3];
1028                 float potentialVertex[3];
1029                 char *planes_used = PyMem_Malloc(sizeof(char) * len);
1030
1031                 /* python */
1032                 PyObject *py_verts = PyList_New(0);
1033                 PyObject *py_plane_index = PyList_New(0);
1034
1035                 memset(planes_used, 0, sizeof(char) * len);
1036
1037                 for (i = 0; i < len; i++) {
1038                         const float *N1 = planes[i];
1039                         for (j = i + 1; j < len; j++) {
1040                                 const float *N2 = planes[j];
1041                                 cross_v3_v3v3(n1n2, N1, N2);
1042                                 if (len_squared_v3(n1n2) > eps) {
1043                                         for (k = j + 1; k < len; k++) {
1044                                                 const float *N3 = planes[k];
1045                                                 cross_v3_v3v3(n2n3, N2, N3);
1046                                                 if (len_squared_v3(n2n3) > eps) {
1047                                                         cross_v3_v3v3(n3n1, N3, N1);
1048                                                         if (len_squared_v3(n3n1) > eps) {
1049                                                                 const float quotient = dot_v3v3(N1, n2n3);
1050                                                                 if (fabsf(quotient) > eps) {
1051                                                                         /* potentialVertex = (n2n3 * N1[3] + n3n1 * N2[3] + n1n2 * N3[3]) * (-1.0 / quotient); */
1052                                                                         const float quotient_ninv = -1.0f / quotient;
1053                                                                         potentialVertex[0] = ((n2n3[0] * N1[3]) + (n3n1[0] * N2[3]) + (n1n2[0] * N3[3])) * quotient_ninv;
1054                                                                         potentialVertex[1] = ((n2n3[1] * N1[3]) + (n3n1[1] * N2[3]) + (n1n2[1] * N3[3])) * quotient_ninv;
1055                                                                         potentialVertex[2] = ((n2n3[2] * N1[3]) + (n3n1[2] * N2[3]) + (n1n2[2] * N3[3])) * quotient_ninv;
1056                                                                         for (l = 0; l < len; l++) {
1057                                                                                 const float *NP = planes[l];
1058                                                                                 if ((dot_v3v3(NP, potentialVertex) + NP[3]) > 0.000001f) {
1059                                                                                         break;
1060                                                                                 }
1061                                                                         }
1062
1063                                                                         if (l == len) { /* ok */
1064                                                                                 /* python */
1065                                                                                 PyObject *item = Vector_CreatePyObject(potentialVertex, 3, Py_NEW, NULL);
1066                                                                                 PyList_Append(py_verts, item);
1067                                                                                 Py_DECREF(item);
1068
1069                                                                                 planes_used[i] = planes_used[j] = planes_used[k] = true;
1070                                                                         }
1071                                                                 }
1072                                                         }
1073                                                 }
1074                                         }
1075                                 }
1076                         }
1077                 }
1078
1079                 PyMem_Free(planes);
1080
1081                 /* now make a list of used planes */
1082                 for (i = 0; i < len; i++) {
1083                         if (planes_used[i]) {
1084                                 PyObject *item = PyLong_FromLong(i);
1085                                 PyList_Append(py_plane_index, item);
1086                                 Py_DECREF(item);
1087                         }
1088                 }
1089                 PyMem_Free(planes_used);
1090
1091                 {
1092                         PyObject *ret = PyTuple_New(2);
1093                         PyTuple_SET_ITEM(ret, 0, py_verts);
1094                         PyTuple_SET_ITEM(ret, 1, py_plane_index);
1095                         return ret;
1096                 }
1097         }
1098 }
1099
1100 #ifndef MATH_STANDALONE
1101
1102 PyDoc_STRVAR(M_Geometry_interpolate_bezier_doc,
1103 ".. function:: interpolate_bezier(knot1, handle1, handle2, knot2, resolution)\n"
1104 "\n"
1105 "   Interpolate a bezier spline segment.\n"
1106 "\n"
1107 "   :arg knot1: First bezier spline point.\n"
1108 "   :type knot1: :class:`mathutils.Vector`\n"
1109 "   :arg handle1: First bezier spline handle.\n"
1110 "   :type handle1: :class:`mathutils.Vector`\n"
1111 "   :arg handle2: Second bezier spline handle.\n"
1112 "   :type handle2: :class:`mathutils.Vector`\n"
1113 "   :arg knot2: Second bezier spline point.\n"
1114 "   :type knot2: :class:`mathutils.Vector`\n"
1115 "   :arg resolution: Number of points to return.\n"
1116 "   :type resolution: int\n"
1117 "   :return: The interpolated points\n"
1118 "   :rtype: list of :class:`mathutils.Vector`'s\n"
1119 );
1120 static PyObject *M_Geometry_interpolate_bezier(PyObject *UNUSED(self), PyObject *args)
1121 {
1122         const char *error_prefix = "interpolate_bezier";
1123         PyObject *py_data[4];
1124         float data[4][4] = {{0.0f}};
1125         int resolu;
1126         int dims = 0;
1127         int i;
1128         float *coord_array, *fp;
1129         PyObject *list;
1130
1131         if (!PyArg_ParseTuple(
1132                 args, "OOOOi:interpolate_bezier",
1133                 UNPACK4_EX(&, py_data, ), &resolu))
1134         {
1135                 return NULL;
1136         }
1137
1138         for (i = 0; i < 4; i++) {
1139                 int dims_tmp;
1140                 if ((((dims_tmp = mathutils_array_parse(data[i], 2, 2 | MU_ARRAY_SPILL, py_data[i], error_prefix)) == -1))) {
1141                         return NULL;
1142                 }
1143                 dims = max_ii(dims, dims_tmp);
1144         }
1145
1146         if (resolu <= 1) {
1147                 PyErr_SetString(PyExc_ValueError,
1148                                 "resolution must be 2 or over");
1149                 return NULL;
1150         }
1151
1152         coord_array = MEM_callocN(dims * (resolu) * sizeof(float), error_prefix);
1153         for (i = 0; i < dims; i++) {
1154                 BKE_curve_forward_diff_bezier(UNPACK4_EX(, data, [i]), coord_array + i, resolu - 1, sizeof(float) * dims);
1155         }
1156
1157         list = PyList_New(resolu);
1158         fp = coord_array;
1159         for (i = 0; i < resolu; i++, fp = fp + dims) {
1160                 PyList_SET_ITEM(list, i, Vector_CreatePyObject(fp, dims, Py_NEW, NULL));
1161         }
1162         MEM_freeN(coord_array);
1163         return list;
1164 }
1165
1166
1167 PyDoc_STRVAR(M_Geometry_tessellate_polygon_doc,
1168 ".. function:: tessellate_polygon(veclist_list)\n"
1169 "\n"
1170 "   Takes a list of polylines (each point a vector) and returns the point indices for a polyline filled with triangles.\n"
1171 "\n"
1172 "   :arg veclist_list: list of polylines\n"
1173 "   :rtype: list\n"
1174 );
1175 /* PolyFill function, uses Blenders scanfill to fill multiple poly lines */
1176 static PyObject *M_Geometry_tessellate_polygon(PyObject *UNUSED(self), PyObject *polyLineSeq)
1177 {
1178         PyObject *tri_list; /*return this list of tri's */
1179         PyObject *polyLine, *polyVec;
1180         int i, len_polylines, len_polypoints, ls_error = 0;
1181
1182         /* display listbase */
1183         ListBase dispbase = {NULL, NULL};
1184         DispList *dl;
1185         float *fp; /*pointer to the array of malloced dl->verts to set the points from the vectors */
1186         int index, *dl_face, totpoints = 0;
1187
1188         if (!PySequence_Check(polyLineSeq)) {
1189                 PyErr_SetString(PyExc_TypeError,
1190                                 "expected a sequence of poly lines");
1191                 return NULL;
1192         }
1193
1194         len_polylines = PySequence_Size(polyLineSeq);
1195
1196         for (i = 0; i < len_polylines; i++) {
1197                 polyLine = PySequence_GetItem(polyLineSeq, i);
1198                 if (!PySequence_Check(polyLine)) {
1199                         BKE_displist_free(&dispbase);
1200                         Py_XDECREF(polyLine); /* may be null so use Py_XDECREF*/
1201                         PyErr_SetString(PyExc_TypeError,
1202                                         "One or more of the polylines is not a sequence of mathutils.Vector's");
1203                         return NULL;
1204                 }
1205
1206                 len_polypoints = PySequence_Size(polyLine);
1207                 if (len_polypoints > 0) { /* don't bother adding edges as polylines */
1208 #if 0
1209                         if (EXPP_check_sequence_consistency(polyLine, &vector_Type) != 1) {
1210                                 freedisplist(&dispbase);
1211                                 Py_DECREF(polyLine);
1212                                 PyErr_SetString(PyExc_TypeError,
1213                                                 "A point in one of the polylines is not a mathutils.Vector type");
1214                                 return NULL;
1215                         }
1216 #endif
1217                         dl = MEM_callocN(sizeof(DispList), "poly disp");
1218                         BLI_addtail(&dispbase, dl);
1219                         dl->type = DL_INDEX3;
1220                         dl->nr = len_polypoints;
1221                         dl->type = DL_POLY;
1222                         dl->parts = 1; /* no faces, 1 edge loop */
1223                         dl->col = 0; /* no material */
1224                         dl->verts = fp = MEM_callocN(sizeof(float) * 3 * len_polypoints, "dl verts");
1225                         dl->index = MEM_callocN(sizeof(int) * 3 * len_polypoints, "dl index");
1226
1227                         for (index = 0; index < len_polypoints; index++, fp += 3) {
1228                                 polyVec = PySequence_GetItem(polyLine, index);
1229                                 if (VectorObject_Check(polyVec)) {
1230
1231                                         if (BaseMath_ReadCallback((VectorObject *)polyVec) == -1)
1232                                                 ls_error = 1;
1233
1234                                         fp[0] = ((VectorObject *)polyVec)->vec[0];
1235                                         fp[1] = ((VectorObject *)polyVec)->vec[1];
1236                                         if (((VectorObject *)polyVec)->size > 2)
1237                                                 fp[2] = ((VectorObject *)polyVec)->vec[2];
1238                                         else
1239                                                 fp[2] = 0.0f;  /* if its a 2d vector then set the z to be zero */
1240                                 }
1241                                 else {
1242                                         ls_error = 1;
1243                                 }
1244
1245                                 totpoints++;
1246                                 Py_DECREF(polyVec);
1247                         }
1248                 }
1249                 Py_DECREF(polyLine);
1250         }
1251
1252         if (ls_error) {
1253                 BKE_displist_free(&dispbase); /* possible some dl was allocated */
1254                 PyErr_SetString(PyExc_TypeError,
1255                                 "A point in one of the polylines "
1256                                 "is not a mathutils.Vector type");
1257                 return NULL;
1258         }
1259         else if (totpoints) {
1260                 /* now make the list to return */
1261                 /* TODO, add normal arg */
1262                 BKE_displist_fill(&dispbase, &dispbase, NULL, false);
1263
1264                 /* The faces are stored in a new DisplayList
1265                  * thats added to the head of the listbase */
1266                 dl = dispbase.first;
1267
1268                 tri_list = PyList_New(dl->parts);
1269                 if (!tri_list) {
1270                         BKE_displist_free(&dispbase);
1271                         PyErr_SetString(PyExc_RuntimeError,
1272                                         "failed to make a new list");
1273                         return NULL;
1274                 }
1275
1276                 index = 0;
1277                 dl_face = dl->index;
1278                 while (index < dl->parts) {
1279                         PyList_SET_ITEM(tri_list, index, Py_BuildValue("iii", dl_face[0], dl_face[1], dl_face[2]));
1280                         dl_face += 3;
1281                         index++;
1282                 }
1283                 BKE_displist_free(&dispbase);
1284         }
1285         else {
1286                 /* no points, do this so scripts don't barf */
1287                 BKE_displist_free(&dispbase); /* possible some dl was allocated */
1288                 tri_list = PyList_New(0);
1289         }
1290
1291         return tri_list;
1292 }
1293
1294
1295 static int boxPack_FromPyObject(PyObject *value, BoxPack **boxarray)
1296 {
1297         Py_ssize_t len, i;
1298         PyObject *list_item, *item_1, *item_2;
1299         BoxPack *box;
1300
1301
1302         /* Error checking must already be done */
1303         if (!PyList_Check(value)) {
1304                 PyErr_SetString(PyExc_TypeError,
1305                                 "can only back a list of [x, y, w, h]");
1306                 return -1;
1307         }
1308
1309         len = PyList_GET_SIZE(value);
1310
1311         *boxarray = MEM_mallocN(len * sizeof(BoxPack), "BoxPack box");
1312
1313
1314         for (i = 0; i < len; i++) {
1315                 list_item = PyList_GET_ITEM(value, i);
1316                 if (!PyList_Check(list_item) || PyList_GET_SIZE(list_item) < 4) {
1317                         MEM_freeN(*boxarray);
1318                         PyErr_SetString(PyExc_TypeError,
1319                                         "can only pack a list of [x, y, w, h]");
1320                         return -1;
1321                 }
1322
1323                 box = (*boxarray) + i;
1324
1325                 item_1 = PyList_GET_ITEM(list_item, 2);
1326                 item_2 = PyList_GET_ITEM(list_item, 3);
1327
1328                 box->w =  (float)PyFloat_AsDouble(item_1);
1329                 box->h =  (float)PyFloat_AsDouble(item_2);
1330                 box->index = i;
1331
1332                 /* accounts for error case too and overwrites with own error */
1333                 if (box->w < 0.0f || box->h < 0.0f) {
1334                         MEM_freeN(*boxarray);
1335                         PyErr_SetString(PyExc_TypeError,
1336                                         "error parsing width and height values from list: "
1337                                         "[x, y, w, h], not numbers or below zero");
1338                         return -1;
1339                 }
1340
1341                 /* verts will be added later */
1342         }
1343         return 0;
1344 }
1345
1346 static void boxPack_ToPyObject(PyObject *value, BoxPack **boxarray)
1347 {
1348         Py_ssize_t len, i;
1349         PyObject *list_item;
1350         BoxPack *box;
1351
1352         len = PyList_GET_SIZE(value);
1353
1354         for (i = 0; i < len; i++) {
1355                 box = (*boxarray) + i;
1356                 list_item = PyList_GET_ITEM(value, box->index);
1357                 PyList_SET_ITEM(list_item, 0, PyFloat_FromDouble(box->x));
1358                 PyList_SET_ITEM(list_item, 1, PyFloat_FromDouble(box->y));
1359         }
1360         MEM_freeN(*boxarray);
1361 }
1362
1363 PyDoc_STRVAR(M_Geometry_box_pack_2d_doc,
1364 ".. function:: box_pack_2d(boxes)\n"
1365 "\n"
1366 "   Returns the normal of the 3D tri or quad.\n"
1367 "\n"
1368 "   :arg boxes: list of boxes, each box is a list where the first 4 items are [x, y, width, height, ...] other items are ignored.\n"
1369 "   :type boxes: list\n"
1370 "   :return: the width and height of the packed bounding box\n"
1371 "   :rtype: tuple, pair of floats\n"
1372 );
1373 static PyObject *M_Geometry_box_pack_2d(PyObject *UNUSED(self), PyObject *boxlist)
1374 {
1375         float tot_width = 0.0f, tot_height = 0.0f;
1376         Py_ssize_t len;
1377
1378         PyObject *ret;
1379
1380         if (!PyList_Check(boxlist)) {
1381                 PyErr_SetString(PyExc_TypeError,
1382                                 "expected a list of boxes [[x, y, w, h], ... ]");
1383                 return NULL;
1384         }
1385
1386         len = PyList_GET_SIZE(boxlist);
1387         if (len) {
1388                 BoxPack *boxarray = NULL;
1389                 if (boxPack_FromPyObject(boxlist, &boxarray) == -1) {
1390                         return NULL; /* exception set */
1391                 }
1392
1393                 /* Non Python function */
1394                 BLI_box_pack_2d(boxarray, len, &tot_width, &tot_height);
1395
1396                 boxPack_ToPyObject(boxlist, &boxarray);
1397         }
1398
1399         ret = PyTuple_New(2);
1400         PyTuple_SET_ITEM(ret, 0, PyFloat_FromDouble(tot_width));
1401         PyTuple_SET_ITEM(ret, 1, PyFloat_FromDouble(tot_height));
1402         return ret;
1403 }
1404
1405 PyDoc_STRVAR(M_Geometry_box_fit_2d_doc,
1406 ".. function:: box_fit_2d(points)\n"
1407 "\n"
1408 "   Returns an angle that best fits the points to an axis aligned rectangle\n"
1409 "\n"
1410 "   :arg points: list of 2d points.\n"
1411 "   :type points: list\n"
1412 "   :return: angle\n"
1413 "   :rtype: float\n"
1414 );
1415 static PyObject *M_Geometry_box_fit_2d(PyObject *UNUSED(self), PyObject *pointlist)
1416 {
1417         float (*points)[2];
1418         Py_ssize_t len;
1419
1420         float angle = 0.0f;
1421
1422         len = mathutils_array_parse_alloc_v(((float **)&points), 2, pointlist, "box_fit_2d");
1423         if (len == -1) {
1424                 return NULL;
1425         }
1426
1427         if (len) {
1428                 /* Non Python function */
1429                 angle = BLI_convexhull_aabb_fit_points_2d((const float (*)[2])points, len);
1430
1431                 PyMem_Free(points);
1432         }
1433
1434
1435         return PyFloat_FromDouble(angle);
1436 }
1437
1438 PyDoc_STRVAR(M_Geometry_convex_hull_2d_doc,
1439 ".. function:: convex_hull_2d(points)\n"
1440 "\n"
1441 "   Returns a list of indices into the list given\n"
1442 "\n"
1443 "   :arg points: list of 2d points.\n"
1444 "   :type points: list\n"
1445 "   :return: a list of indices\n"
1446 "   :rtype: list of ints\n"
1447 );
1448 static PyObject *M_Geometry_convex_hull_2d(PyObject *UNUSED(self), PyObject *pointlist)
1449 {
1450         float (*points)[2];
1451         Py_ssize_t len;
1452
1453         PyObject *ret;
1454
1455         len = mathutils_array_parse_alloc_v(((float **)&points), 2, pointlist, "convex_hull_2d");
1456         if (len == -1) {
1457                 return NULL;
1458         }
1459
1460         if (len) {
1461                 int *index_map;
1462                 Py_ssize_t len_ret, i;
1463
1464                 index_map  = MEM_mallocN(sizeof(*index_map) * len * 2, __func__);
1465
1466                 /* Non Python function */
1467                 len_ret = BLI_convexhull_2d((const float (*)[2])points, len, index_map);
1468
1469                 ret = PyList_New(len_ret);
1470                 for (i = 0; i < len_ret; i++) {
1471                         PyList_SET_ITEM(ret, i, PyLong_FromLong(index_map[i]));
1472                 }
1473
1474                 MEM_freeN(index_map);
1475
1476                 PyMem_Free(points);
1477         }
1478         else {
1479                 ret = PyList_New(0);
1480         }
1481
1482
1483         return ret;
1484 }
1485
1486 #endif /* MATH_STANDALONE */
1487
1488
1489 static PyMethodDef M_Geometry_methods[] = {
1490         {"intersect_ray_tri", (PyCFunction) M_Geometry_intersect_ray_tri, METH_VARARGS, M_Geometry_intersect_ray_tri_doc},
1491         {"intersect_point_line", (PyCFunction) M_Geometry_intersect_point_line, METH_VARARGS, M_Geometry_intersect_point_line_doc},
1492         {"intersect_point_tri", (PyCFunction) M_Geometry_intersect_point_tri, METH_VARARGS, M_Geometry_intersect_point_tri_doc},
1493         {"intersect_point_tri_2d", (PyCFunction) M_Geometry_intersect_point_tri_2d, METH_VARARGS, M_Geometry_intersect_point_tri_2d_doc},
1494         {"intersect_point_quad_2d", (PyCFunction) M_Geometry_intersect_point_quad_2d, METH_VARARGS, M_Geometry_intersect_point_quad_2d_doc},
1495         {"intersect_line_line", (PyCFunction) M_Geometry_intersect_line_line, METH_VARARGS, M_Geometry_intersect_line_line_doc},
1496         {"intersect_line_line_2d", (PyCFunction) M_Geometry_intersect_line_line_2d, METH_VARARGS, M_Geometry_intersect_line_line_2d_doc},
1497         {"intersect_line_plane", (PyCFunction) M_Geometry_intersect_line_plane, METH_VARARGS, M_Geometry_intersect_line_plane_doc},
1498         {"intersect_plane_plane", (PyCFunction) M_Geometry_intersect_plane_plane, METH_VARARGS, M_Geometry_intersect_plane_plane_doc},
1499         {"intersect_line_sphere", (PyCFunction) M_Geometry_intersect_line_sphere, METH_VARARGS, M_Geometry_intersect_line_sphere_doc},
1500         {"intersect_line_sphere_2d", (PyCFunction) M_Geometry_intersect_line_sphere_2d, METH_VARARGS, M_Geometry_intersect_line_sphere_2d_doc},
1501         {"distance_point_to_plane", (PyCFunction) M_Geometry_distance_point_to_plane, METH_VARARGS, M_Geometry_distance_point_to_plane_doc},
1502         {"intersect_sphere_sphere_2d", (PyCFunction) M_Geometry_intersect_sphere_sphere_2d, METH_VARARGS, M_Geometry_intersect_sphere_sphere_2d_doc},
1503         {"area_tri", (PyCFunction) M_Geometry_area_tri, METH_VARARGS, M_Geometry_area_tri_doc},
1504         {"volume_tetrahedron", (PyCFunction) M_Geometry_volume_tetrahedron, METH_VARARGS, M_Geometry_volume_tetrahedron_doc},
1505         {"normal", (PyCFunction) M_Geometry_normal, METH_VARARGS, M_Geometry_normal_doc},
1506         {"barycentric_transform", (PyCFunction) M_Geometry_barycentric_transform, METH_VARARGS, M_Geometry_barycentric_transform_doc},
1507         {"points_in_planes", (PyCFunction) M_Geometry_points_in_planes, METH_VARARGS, M_Geometry_points_in_planes_doc},
1508 #ifndef MATH_STANDALONE
1509         {"interpolate_bezier", (PyCFunction) M_Geometry_interpolate_bezier, METH_VARARGS, M_Geometry_interpolate_bezier_doc},
1510         {"tessellate_polygon", (PyCFunction) M_Geometry_tessellate_polygon, METH_O, M_Geometry_tessellate_polygon_doc},
1511         {"convex_hull_2d", (PyCFunction) M_Geometry_convex_hull_2d, METH_O, M_Geometry_convex_hull_2d_doc},
1512         {"box_fit_2d", (PyCFunction) M_Geometry_box_fit_2d, METH_O, M_Geometry_box_fit_2d_doc},
1513         {"box_pack_2d", (PyCFunction) M_Geometry_box_pack_2d, METH_O, M_Geometry_box_pack_2d_doc},
1514 #endif
1515         {NULL, NULL, 0, NULL}
1516 };
1517
1518 static struct PyModuleDef M_Geometry_module_def = {
1519         PyModuleDef_HEAD_INIT,
1520         "mathutils.geometry",  /* m_name */
1521         M_Geometry_doc,  /* m_doc */
1522         0,  /* m_size */
1523         M_Geometry_methods,  /* m_methods */
1524         NULL,  /* m_reload */
1525         NULL,  /* m_traverse */
1526         NULL,  /* m_clear */
1527         NULL,  /* m_free */
1528 };
1529
1530 /*----------------------------MODULE INIT-------------------------*/
1531 PyMODINIT_FUNC PyInit_mathutils_geometry(void)
1532 {
1533         PyObject *submodule = PyModule_Create(&M_Geometry_module_def);
1534         return submodule;
1535 }