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