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