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