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