Cycles / HSV Separator and Combine node:
[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 "   :arg no_flip: Always return an intersection on the directon defined bt line_a -> line_b\n"
572 "   :type no_flip: :boolean\n"
573 "   :return: The point of intersection or None when not found\n"
574 "   :rtype: :class:`mathutils.Vector` or None\n"
575 );
576 static PyObject *M_Geometry_intersect_line_plane(PyObject *UNUSED(self), PyObject *args)
577 {
578         VectorObject *line_a, *line_b, *plane_co, *plane_no;
579         int no_flip = 0;
580         float isect[3];
581         if (!PyArg_ParseTuple(args, "O!O!O!O!|i:intersect_line_plane",
582                               &vector_Type, &line_a,
583                               &vector_Type, &line_b,
584                               &vector_Type, &plane_co,
585                               &vector_Type, &plane_no,
586                               &no_flip))
587         {
588                 return NULL;
589         }
590
591         if (BaseMath_ReadCallback(line_a) == -1 ||
592             BaseMath_ReadCallback(line_b) == -1 ||
593             BaseMath_ReadCallback(plane_co) == -1 ||
594             BaseMath_ReadCallback(plane_no) == -1)
595         {
596                 return NULL;
597         }
598
599         if (ELEM4(2, line_a->size, line_b->size, plane_co->size, plane_no->size)) {
600                 PyErr_SetString(PyExc_ValueError,
601                                 "geometry.intersect_line_plane(...): "
602                                 " can't use 2D Vectors");
603                 return NULL;
604         }
605
606         if (isect_line_plane_v3(isect, line_a->vec, line_b->vec, plane_co->vec, plane_no->vec, no_flip) == 1) {
607                 return Vector_CreatePyObject(isect, 3, Py_NEW, NULL);
608         }
609         else {
610                 Py_RETURN_NONE;
611         }
612 }
613
614 PyDoc_STRVAR(M_Geometry_intersect_plane_plane_doc,
615 ".. function:: intersect_plane_plane(plane_a_co, plane_a_no, plane_b_co, plane_b_no)\n"
616 "\n"
617 "   Return the intersection between two planes\n"
618 "\n"
619 "   :arg plane_a_co: Point on the first plane\n"
620 "   :type plane_a_co: :class:`mathutils.Vector`\n"
621 "   :arg plane_a_no: Normal of the first plane\n"
622 "   :type plane_a_no: :class:`mathutils.Vector`\n"
623 "   :arg plane_b_co: Point on the second plane\n"
624 "   :type plane_b_co: :class:`mathutils.Vector`\n"
625 "   :arg plane_b_no: Normal of the second plane\n"
626 "   :type plane_b_no: :class:`mathutils.Vector`\n"
627 "   :return: The line of the intersection represented as a point and a vector\n"
628 "   :rtype: tuple pair of :class:`mathutils.Vector`\n"
629 );
630 static PyObject *M_Geometry_intersect_plane_plane(PyObject *UNUSED(self), PyObject *args)
631 {
632         PyObject *ret;
633         VectorObject *plane_a_co, *plane_a_no, *plane_b_co, *plane_b_no;
634
635         float isect_co[3];
636         float isect_no[3];
637
638         if (!PyArg_ParseTuple(args, "O!O!O!O!|i:intersect_plane_plane",
639                               &vector_Type, &plane_a_co,
640                               &vector_Type, &plane_a_no,
641                               &vector_Type, &plane_b_co,
642                               &vector_Type, &plane_b_no))
643         {
644                 return NULL;
645         }
646
647         if (BaseMath_ReadCallback(plane_a_co) == -1 ||
648             BaseMath_ReadCallback(plane_a_no) == -1 ||
649             BaseMath_ReadCallback(plane_b_co) == -1 ||
650             BaseMath_ReadCallback(plane_b_no) == -1)
651         {
652                 return NULL;
653         }
654
655         if (ELEM4(2, plane_a_co->size, plane_a_no->size, plane_b_co->size, plane_b_no->size)) {
656                 PyErr_SetString(PyExc_ValueError,
657                                 "geometry.intersect_plane_plane(...): "
658                                 " can't use 2D Vectors");
659                 return NULL;
660         }
661
662         isect_plane_plane_v3(isect_co, isect_no,
663                              plane_a_co->vec, plane_a_no->vec,
664                              plane_b_co->vec, plane_b_no->vec);
665
666         normalize_v3(isect_no);
667
668         ret = PyTuple_New(2);
669         PyTuple_SET_ITEM(ret, 0, Vector_CreatePyObject(isect_co, 3, Py_NEW, NULL));
670         PyTuple_SET_ITEM(ret, 1, Vector_CreatePyObject(isect_no, 3, Py_NEW, NULL));
671         return ret;
672 }
673
674 PyDoc_STRVAR(M_Geometry_intersect_line_sphere_doc,
675 ".. function:: intersect_line_sphere(line_a, line_b, sphere_co, sphere_radius, clip=True)\n"
676 "\n"
677 "   Takes a lines (as 2 vectors), a sphere as a point and a radius and\n"
678 "   returns the intersection\n"
679 "\n"
680 "   :arg line_a: First point of the first line\n"
681 "   :type line_a: :class:`mathutils.Vector`\n"
682 "   :arg line_b: Second point of the first line\n"
683 "   :type line_b: :class:`mathutils.Vector`\n"
684 "   :arg sphere_co: The center of the sphere\n"
685 "   :type sphere_co: :class:`mathutils.Vector`\n"
686 "   :arg sphere_radius: Radius of the sphere\n"
687 "   :type sphere_radius: sphere_radius\n"
688 "   :return: The intersection points as a pair of vectors or None when there is no intersection\n"
689 "   :rtype: A tuple pair containing :class:`mathutils.Vector` or None\n"
690 );
691 static PyObject *M_Geometry_intersect_line_sphere(PyObject *UNUSED(self), PyObject *args)
692 {
693         VectorObject *line_a, *line_b, *sphere_co;
694         float sphere_radius;
695         int clip = TRUE;
696
697         float isect_a[3];
698         float isect_b[3];
699
700         if (!PyArg_ParseTuple(args, "O!O!O!f|i:intersect_line_sphere",
701                               &vector_Type, &line_a,
702                               &vector_Type, &line_b,
703                               &vector_Type, &sphere_co,
704                               &sphere_radius, &clip))
705         {
706                 return NULL;
707         }
708
709         if (BaseMath_ReadCallback(line_a) == -1 ||
710             BaseMath_ReadCallback(line_b) == -1 ||
711             BaseMath_ReadCallback(sphere_co) == -1)
712         {
713                 return NULL;
714         }
715
716         if (ELEM3(2, line_a->size, line_b->size, sphere_co->size)) {
717                 PyErr_SetString(PyExc_ValueError,
718                                 "geometry.intersect_line_sphere(...): "
719                                 " can't use 2D Vectors");
720                 return NULL;
721         }
722         else {
723                 bool use_a = true;
724                 bool use_b = true;
725                 float lambda;
726
727                 PyObject *ret = PyTuple_New(2);
728
729                 switch (isect_line_sphere_v3(line_a->vec, line_b->vec, sphere_co->vec, sphere_radius, isect_a, isect_b)) {
730                         case 1:
731                                 if (!(!clip || (((lambda = line_point_factor_v3(isect_a, line_a->vec, line_b->vec)) >= 0.0f) && (lambda <= 1.0f)))) use_a = FALSE;
732                                 use_b = false;
733                                 break;
734                         case 2:
735                                 if (!(!clip || (((lambda = line_point_factor_v3(isect_a, line_a->vec, line_b->vec)) >= 0.0f) && (lambda <= 1.0f)))) use_a = FALSE;
736                                 if (!(!clip || (((lambda = line_point_factor_v3(isect_b, line_a->vec, line_b->vec)) >= 0.0f) && (lambda <= 1.0f)))) use_b = FALSE;
737                                 break;
738                         default:
739                                 use_a = false;
740                                 use_b = false;
741                                 break;
742                 }
743
744                 if (use_a) { PyTuple_SET_ITEM(ret, 0,  Vector_CreatePyObject(isect_a, 3, Py_NEW, NULL)); }
745                 else       { PyTuple_SET_ITEM(ret, 0,  Py_None); Py_INCREF(Py_None); }
746
747                 if (use_b) { PyTuple_SET_ITEM(ret, 1,  Vector_CreatePyObject(isect_b, 3, Py_NEW, NULL)); }
748                 else       { PyTuple_SET_ITEM(ret, 1,  Py_None); Py_INCREF(Py_None); }
749
750                 return ret;
751         }
752 }
753
754 /* keep in sync with M_Geometry_intersect_line_sphere */
755 PyDoc_STRVAR(M_Geometry_intersect_line_sphere_2d_doc,
756 ".. function:: intersect_line_sphere_2d(line_a, line_b, sphere_co, sphere_radius, clip=True)\n"
757 "\n"
758 "   Takes a lines (as 2 vectors), a sphere as a point and a radius and\n"
759 "   returns the intersection\n"
760 "\n"
761 "   :arg line_a: First point of the first line\n"
762 "   :type line_a: :class:`mathutils.Vector`\n"
763 "   :arg line_b: Second point of the first line\n"
764 "   :type line_b: :class:`mathutils.Vector`\n"
765 "   :arg sphere_co: The center of the sphere\n"
766 "   :type sphere_co: :class:`mathutils.Vector`\n"
767 "   :arg sphere_radius: Radius of the sphere\n"
768 "   :type sphere_radius: sphere_radius\n"
769 "   :return: The intersection points as a pair of vectors or None when there is no intersection\n"
770 "   :rtype: A tuple pair containing :class:`mathutils.Vector` or None\n"
771 );
772 static PyObject *M_Geometry_intersect_line_sphere_2d(PyObject *UNUSED(self), PyObject *args)
773 {
774         VectorObject *line_a, *line_b, *sphere_co;
775         float sphere_radius;
776         int clip = TRUE;
777
778         float isect_a[2];
779         float isect_b[2];
780
781         if (!PyArg_ParseTuple(args, "O!O!O!f|i:intersect_line_sphere_2d",
782                               &vector_Type, &line_a,
783                               &vector_Type, &line_b,
784                               &vector_Type, &sphere_co,
785                               &sphere_radius, &clip))
786         {
787                 return NULL;
788         }
789
790         if (BaseMath_ReadCallback(line_a) == -1 ||
791             BaseMath_ReadCallback(line_b) == -1 ||
792             BaseMath_ReadCallback(sphere_co) == -1)
793         {
794                 return NULL;
795         }
796         else {
797                 bool use_a = true;
798                 bool use_b = true;
799                 float lambda;
800
801                 PyObject *ret = PyTuple_New(2);
802
803                 switch (isect_line_sphere_v2(line_a->vec, line_b->vec, sphere_co->vec, sphere_radius, isect_a, isect_b)) {
804                         case 1:
805                                 if (!(!clip || (((lambda = line_point_factor_v2(isect_a, line_a->vec, line_b->vec)) >= 0.0f) && (lambda <= 1.0f)))) use_a = false;
806                                 use_b = FALSE;
807                                 break;
808                         case 2:
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                                 if (!(!clip || (((lambda = line_point_factor_v2(isect_b, line_a->vec, line_b->vec)) >= 0.0f) && (lambda <= 1.0f)))) use_b = false;
811                                 break;
812                         default:
813                                 use_a = false;
814                                 use_b = false;
815                                 break;
816                 }
817
818                 if (use_a) { PyTuple_SET_ITEM(ret, 0,  Vector_CreatePyObject(isect_a, 2, Py_NEW, NULL)); }
819                 else       { PyTuple_SET_ITEM(ret, 0,  Py_None); Py_INCREF(Py_None); }
820
821                 if (use_b) { PyTuple_SET_ITEM(ret, 1,  Vector_CreatePyObject(isect_b, 2, Py_NEW, NULL)); }
822                 else       { PyTuple_SET_ITEM(ret, 1,  Py_None); Py_INCREF(Py_None); }
823
824                 return ret;
825         }
826 }
827
828 PyDoc_STRVAR(M_Geometry_intersect_point_line_doc,
829 ".. function:: intersect_point_line(pt, line_p1, line_p2)\n"
830 "\n"
831 "   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"
832 "\n"
833 "   :arg pt: Point\n"
834 "   :type pt: :class:`mathutils.Vector`\n"
835 "   :arg line_p1: First point of the line\n"
836 "   :type line_p1: :class:`mathutils.Vector`\n"
837 "   :arg line_p1: Second point of the line\n"
838 "   :type line_p1: :class:`mathutils.Vector`\n"
839 "   :rtype: (:class:`mathutils.Vector`, float)\n"
840 );
841 static PyObject *M_Geometry_intersect_point_line(PyObject *UNUSED(self), PyObject *args)
842 {
843         VectorObject *pt, *line_1, *line_2;
844         float pt_in[3], pt_out[3], l1[3], l2[3];
845         float lambda;
846         PyObject *ret;
847         int size = 2;
848         
849         if (!PyArg_ParseTuple(args, "O!O!O!:intersect_point_line",
850                               &vector_Type, &pt,
851                               &vector_Type, &line_1,
852                               &vector_Type, &line_2))
853         {
854                 return NULL;
855         }
856
857         if (BaseMath_ReadCallback(pt) == -1 ||
858             BaseMath_ReadCallback(line_1) == -1 ||
859             BaseMath_ReadCallback(line_2) == -1)
860         {
861                 return NULL;
862         }
863
864         /* accept 2d verts */
865         if (pt->size >= 3)     { copy_v3_v3(pt_in, pt->vec); size = 3; }
866         else                   { copy_v2_v2(pt_in, pt->vec); pt_in[2] = 0.0f; }
867         
868         if (line_1->size >= 3) { copy_v3_v3(l1, line_1->vec); size = 3; }
869         else                   { copy_v2_v2(l1, line_1->vec); l1[2] = 0.0f; }
870         
871         if (line_2->size >= 3) { copy_v3_v3(l2, line_2->vec); size = 3; }
872         else                   { copy_v2_v2(l2, line_2->vec); l2[2] = 0.0f; }
873         
874         /* do the calculation */
875         lambda = closest_to_line_v3(pt_out, pt_in, l1, l2);
876         
877         ret = PyTuple_New(2);
878         PyTuple_SET_ITEM(ret, 0, Vector_CreatePyObject(pt_out, size, Py_NEW, NULL));
879         PyTuple_SET_ITEM(ret, 1, PyFloat_FromDouble(lambda));
880         return ret;
881 }
882
883 PyDoc_STRVAR(M_Geometry_intersect_point_tri_2d_doc,
884 ".. function:: intersect_point_tri_2d(pt, tri_p1, tri_p2, tri_p3)\n"
885 "\n"
886 "   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"
887 "\n"
888 "   :arg pt: Point\n"
889 "   :type v1: :class:`mathutils.Vector`\n"
890 "   :arg tri_p1: First point of the triangle\n"
891 "   :type tri_p1: :class:`mathutils.Vector`\n"
892 "   :arg tri_p2: Second point of the triangle\n"
893 "   :type tri_p2: :class:`mathutils.Vector`\n"
894 "   :arg tri_p3: Third point of the triangle\n"
895 "   :type tri_p3: :class:`mathutils.Vector`\n"
896 "   :rtype: int\n"
897 );
898 static PyObject *M_Geometry_intersect_point_tri_2d(PyObject *UNUSED(self), PyObject *args)
899 {
900         VectorObject *pt_vec, *tri_p1, *tri_p2, *tri_p3;
901         
902         if (!PyArg_ParseTuple(args, "O!O!O!O!:intersect_point_tri_2d",
903                               &vector_Type, &pt_vec,
904                               &vector_Type, &tri_p1,
905                               &vector_Type, &tri_p2,
906                               &vector_Type, &tri_p3))
907         {
908                 return NULL;
909         }
910         
911         if (BaseMath_ReadCallback(pt_vec) == -1 ||
912             BaseMath_ReadCallback(tri_p1) == -1 ||
913             BaseMath_ReadCallback(tri_p2) == -1 ||
914             BaseMath_ReadCallback(tri_p3) == -1)
915         {
916                 return NULL;
917         }
918
919         return PyLong_FromLong(isect_point_tri_v2(pt_vec->vec, tri_p1->vec, tri_p2->vec, tri_p3->vec));
920 }
921
922 PyDoc_STRVAR(M_Geometry_intersect_point_quad_2d_doc,
923 ".. function:: intersect_point_quad_2d(pt, quad_p1, quad_p2, quad_p3, quad_p4)\n"
924 "\n"
925 "   Takes 5 vectors (using only the x and y coordinates): one is the point and the next 4 define the quad, \n"
926 "   only the x and y are used from the vectors. Returns 1 if the point is within the quad, otherwise 0.\n"
927 "   Works only with convex quads without singular edges."
928 "\n"
929 "   :arg pt: Point\n"
930 "   :type pt: :class:`mathutils.Vector`\n"
931 "   :arg quad_p1: First point of the quad\n"
932 "   :type quad_p1: :class:`mathutils.Vector`\n"
933 "   :arg quad_p2: Second point of the quad\n"
934 "   :type quad_p2: :class:`mathutils.Vector`\n"
935 "   :arg quad_p3: Third point of the quad\n"
936 "   :type quad_p3: :class:`mathutils.Vector`\n"
937 "   :arg quad_p4: Forth point of the quad\n"
938 "   :type quad_p4: :class:`mathutils.Vector`\n"
939 "   :rtype: int\n"
940 );
941 static PyObject *M_Geometry_intersect_point_quad_2d(PyObject *UNUSED(self), PyObject *args)
942 {
943         VectorObject *pt_vec, *quad_p1, *quad_p2, *quad_p3, *quad_p4;
944         
945         if (!PyArg_ParseTuple(args, "O!O!O!O!O!:intersect_point_quad_2d",
946                               &vector_Type, &pt_vec,
947                               &vector_Type, &quad_p1,
948                               &vector_Type, &quad_p2,
949                               &vector_Type, &quad_p3,
950                               &vector_Type, &quad_p4))
951         {
952                 return NULL;
953         }
954
955         if (BaseMath_ReadCallback(pt_vec)  == -1 ||
956             BaseMath_ReadCallback(quad_p1) == -1 ||
957             BaseMath_ReadCallback(quad_p2) == -1 ||
958             BaseMath_ReadCallback(quad_p3) == -1 ||
959             BaseMath_ReadCallback(quad_p4) == -1)
960         {
961                 return NULL;
962         }
963
964         return PyLong_FromLong(isect_point_quad_v2(pt_vec->vec, quad_p1->vec, quad_p2->vec, quad_p3->vec, quad_p4->vec));
965 }
966
967 PyDoc_STRVAR(M_Geometry_distance_point_to_plane_doc,
968 ".. function:: distance_point_to_plane(pt, plane_co, plane_no)\n"
969 "\n"
970 "   Returns the signed distance between a point and a plane "
971 "   (negative when below the normal).\n"
972 "\n"
973 "   :arg pt: Point\n"
974 "   :type pt: :class:`mathutils.Vector`\n"
975 "   :arg plane_co: First point of the quad\n"
976 "   :type plane_co: :class:`mathutils.Vector`\n"
977 "   :arg plane_no: Second point of the quad\n"
978 "   :type plane_no: :class:`mathutils.Vector`\n"
979 "   :rtype: float\n"
980 );
981 static PyObject *M_Geometry_distance_point_to_plane(PyObject *UNUSED(self), PyObject *args)
982 {
983         VectorObject *pt, *plene_co, *plane_no;
984
985         if (!PyArg_ParseTuple(args, "O!O!O!:distance_point_to_plane",
986                               &vector_Type, &pt,
987                               &vector_Type, &plene_co,
988                               &vector_Type, &plane_no))
989         {
990                 return NULL;
991         }
992
993         if (BaseMath_ReadCallback(pt) == -1 ||
994             BaseMath_ReadCallback(plene_co) == -1 ||
995             BaseMath_ReadCallback(plane_no) == -1)
996         {
997                 return NULL;
998         }
999
1000         return PyFloat_FromDouble(dist_to_plane_v3(pt->vec, plene_co->vec, plane_no->vec));
1001 }
1002
1003 PyDoc_STRVAR(M_Geometry_barycentric_transform_doc,
1004 ".. function:: barycentric_transform(point, tri_a1, tri_a2, tri_a3, tri_b1, tri_b2, tri_b3)\n"
1005 "\n"
1006 "   Return a transformed point, the transformation is defined by 2 triangles.\n"
1007 "\n"
1008 "   :arg point: The point to transform.\n"
1009 "   :type point: :class:`mathutils.Vector`\n"
1010 "   :arg tri_a1: source triangle vertex.\n"
1011 "   :type tri_a1: :class:`mathutils.Vector`\n"
1012 "   :arg tri_a2: source triangle vertex.\n"
1013 "   :type tri_a2: :class:`mathutils.Vector`\n"
1014 "   :arg tri_a3: source triangle vertex.\n"
1015 "   :type tri_a3: :class:`mathutils.Vector`\n"
1016 "   :arg tri_a1: target triangle vertex.\n"
1017 "   :type tri_a1: :class:`mathutils.Vector`\n"
1018 "   :arg tri_a2: target triangle vertex.\n"
1019 "   :type tri_a2: :class:`mathutils.Vector`\n"
1020 "   :arg tri_a3: target triangle vertex.\n"
1021 "   :type tri_a3: :class:`mathutils.Vector`\n"
1022 "   :return: The transformed point\n"
1023 "   :rtype: :class:`mathutils.Vector`'s\n"
1024 );
1025 static PyObject *M_Geometry_barycentric_transform(PyObject *UNUSED(self), PyObject *args)
1026 {
1027         VectorObject *vec_pt;
1028         VectorObject *vec_t1_tar, *vec_t2_tar, *vec_t3_tar;
1029         VectorObject *vec_t1_src, *vec_t2_src, *vec_t3_src;
1030         float vec[3];
1031
1032         if (!PyArg_ParseTuple(args, "O!O!O!O!O!O!O!:barycentric_transform",
1033                               &vector_Type, &vec_pt,
1034                               &vector_Type, &vec_t1_src,
1035                               &vector_Type, &vec_t2_src,
1036                               &vector_Type, &vec_t3_src,
1037                               &vector_Type, &vec_t1_tar,
1038                               &vector_Type, &vec_t2_tar,
1039                               &vector_Type, &vec_t3_tar))
1040         {
1041                 return NULL;
1042         }
1043
1044         if (vec_pt->size != 3 ||
1045             vec_t1_src->size != 3 ||
1046             vec_t2_src->size != 3 ||
1047             vec_t3_src->size != 3 ||
1048             vec_t1_tar->size != 3 ||
1049             vec_t2_tar->size != 3 ||
1050             vec_t3_tar->size != 3)
1051         {
1052                 PyErr_SetString(PyExc_ValueError,
1053                                 "One of more of the vector arguments wasn't a 3D vector");
1054                 return NULL;
1055         }
1056
1057         barycentric_transform(vec, vec_pt->vec,
1058                               vec_t1_tar->vec, vec_t2_tar->vec, vec_t3_tar->vec,
1059                               vec_t1_src->vec, vec_t2_src->vec, vec_t3_src->vec);
1060
1061         return Vector_CreatePyObject(vec, 3, Py_NEW, NULL);
1062 }
1063
1064 PyDoc_STRVAR(M_Geometry_points_in_planes_doc,
1065 ".. function:: points_in_planes(planes)\n"
1066 "\n"
1067 "   Returns a list of points inside all planes given and a list of index values for the planes used.\n"
1068 "\n"
1069 "   :arg planes: List of planes (4D vectors).\n"
1070 "   :type planes: list of :class:`mathutils.Vector`\n"
1071 "   :return: two lists, once containing the vertices inside the planes, another containing the plane indicies used\n"
1072 "   :rtype: pair of lists\n"
1073 );
1074 /* note: this function could be optimized by some spatial structure */
1075 static PyObject *M_Geometry_points_in_planes(PyObject *UNUSED(self), PyObject *args)
1076 {
1077         PyObject *py_planes;
1078         float (*planes)[4];
1079         unsigned int planes_len;
1080
1081         if (!PyArg_ParseTuple(args, "O:points_in_planes",
1082                               &py_planes))
1083         {
1084                 return NULL;
1085         }
1086
1087         if ((planes_len = mathutils_array_parse_alloc_v((float **)&planes, 4, py_planes, "points_in_planes")) == -1) {
1088                 return NULL;
1089         }
1090         else {
1091                 /* note, this could be refactored into plain C easy - py bits are noted */
1092                 const float eps = 0.0001f;
1093                 const unsigned int len = (unsigned int)planes_len;
1094                 unsigned int i, j, k, l;
1095
1096                 float n1n2[3], n2n3[3], n3n1[3];
1097                 float potentialVertex[3];
1098                 char *planes_used = PyMem_Malloc(sizeof(char) * len);
1099
1100                 /* python */
1101                 PyObject *py_verts = PyList_New(0);
1102                 PyObject *py_plene_index = PyList_New(0);
1103
1104                 memset(planes_used, 0, sizeof(char) * len);
1105
1106                 for (i = 0; i < len; i++) {
1107                         const float *N1 = planes[i];
1108                         for (j = i + 1; j < len; j++) {
1109                                 const float *N2 = planes[j];
1110                                 cross_v3_v3v3(n1n2, N1, N2);
1111                                 if (len_squared_v3(n1n2) > eps) {
1112                                         for (k = j + 1; k < len; k++) {
1113                                                 const float *N3 = planes[k];
1114                                                 cross_v3_v3v3(n2n3, N2, N3);
1115                                                 if (len_squared_v3(n2n3) > eps) {
1116                                                         cross_v3_v3v3(n3n1, N3, N1);
1117                                                         if (len_squared_v3(n3n1) > eps) {
1118                                                                 const float quotient = dot_v3v3(N1, n2n3);
1119                                                                 if (fabsf(quotient) > eps) {
1120                                                                         /* potentialVertex = (n2n3 * N1[3] + n3n1 * N2[3] + n1n2 * N3[3]) * (-1.0 / quotient); */
1121                                                                         const float quotient_ninv = -1.0f / quotient;
1122                                                                         potentialVertex[0] = ((n2n3[0] * N1[3]) + (n3n1[0] * N2[3]) + (n1n2[0] * N3[3])) * quotient_ninv;
1123                                                                         potentialVertex[1] = ((n2n3[1] * N1[3]) + (n3n1[1] * N2[3]) + (n1n2[1] * N3[3])) * quotient_ninv;
1124                                                                         potentialVertex[2] = ((n2n3[2] * N1[3]) + (n3n1[2] * N2[3]) + (n1n2[2] * N3[3])) * quotient_ninv;
1125                                                                         for (l = 0; l < len; l++) {
1126                                                                                 const float *NP = planes[l];
1127                                                                                 if ((dot_v3v3(NP, potentialVertex) + NP[3]) > 0.000001f) {
1128                                                                                         break;
1129                                                                                 }
1130                                                                         }
1131
1132                                                                         if (l == len) { /* ok */
1133                                                                                 /* python */
1134                                                                                 PyObject *item = Vector_CreatePyObject(potentialVertex, 3, Py_NEW, NULL);
1135                                                                                 PyList_Append(py_verts, item);
1136                                                                                 Py_DECREF(item);
1137
1138                                                                                 planes_used[i] = planes_used[j] = planes_used[k] = TRUE;
1139                                                                         }
1140                                                                 }
1141                                                         }
1142                                                 }
1143                                         }
1144                                 }
1145                         }
1146                 }
1147
1148                 PyMem_Free(planes);
1149
1150                 /* now make a list of used planes */
1151                 for (i = 0; i < len; i++) {
1152                         if (planes_used[i]) {
1153                                 PyObject *item = PyLong_FromLong(i);
1154                                 PyList_Append(py_plene_index, item);
1155                                 Py_DECREF(item);
1156                         }
1157                 }
1158                 PyMem_Free(planes_used);
1159
1160                 {
1161                         PyObject *ret = PyTuple_New(2);
1162                         PyTuple_SET_ITEM(ret, 0, py_verts);
1163                         PyTuple_SET_ITEM(ret, 1, py_plene_index);
1164                         return ret;
1165                 }
1166         }
1167 }
1168
1169 #ifndef MATH_STANDALONE
1170
1171 PyDoc_STRVAR(M_Geometry_interpolate_bezier_doc,
1172 ".. function:: interpolate_bezier(knot1, handle1, handle2, knot2, resolution)\n"
1173 "\n"
1174 "   Interpolate a bezier spline segment.\n"
1175 "\n"
1176 "   :arg knot1: First bezier spline point.\n"
1177 "   :type knot1: :class:`mathutils.Vector`\n"
1178 "   :arg handle1: First bezier spline handle.\n"
1179 "   :type handle1: :class:`mathutils.Vector`\n"
1180 "   :arg handle2: Second bezier spline handle.\n"
1181 "   :type handle2: :class:`mathutils.Vector`\n"
1182 "   :arg knot2: Second bezier spline point.\n"
1183 "   :type knot2: :class:`mathutils.Vector`\n"
1184 "   :arg resolution: Number of points to return.\n"
1185 "   :type resolution: int\n"
1186 "   :return: The interpolated points\n"
1187 "   :rtype: list of :class:`mathutils.Vector`'s\n"
1188 );
1189 static PyObject *M_Geometry_interpolate_bezier(PyObject *UNUSED(self), PyObject *args)
1190 {
1191         VectorObject *vec_k1, *vec_h1, *vec_k2, *vec_h2;
1192         int resolu;
1193         int dims;
1194         int i;
1195         float *coord_array, *fp;
1196         PyObject *list;
1197
1198         float k1[4] = {0.0, 0.0, 0.0, 0.0};
1199         float h1[4] = {0.0, 0.0, 0.0, 0.0};
1200         float k2[4] = {0.0, 0.0, 0.0, 0.0};
1201         float h2[4] = {0.0, 0.0, 0.0, 0.0};
1202
1203
1204         if (!PyArg_ParseTuple(args, "O!O!O!O!i:interpolate_bezier",
1205                               &vector_Type, &vec_k1,
1206                               &vector_Type, &vec_h1,
1207                               &vector_Type, &vec_h2,
1208                               &vector_Type, &vec_k2, &resolu))
1209         {
1210                 return NULL;
1211         }
1212
1213         if (resolu <= 1) {
1214                 PyErr_SetString(PyExc_ValueError,
1215                                 "resolution must be 2 or over");
1216                 return NULL;
1217         }
1218
1219         if (BaseMath_ReadCallback(vec_k1) == -1 ||
1220             BaseMath_ReadCallback(vec_h1) == -1 ||
1221             BaseMath_ReadCallback(vec_k2) == -1 ||
1222             BaseMath_ReadCallback(vec_h2) == -1)
1223         {
1224                 return NULL;
1225         }
1226
1227         dims = max_iiii(vec_k1->size, vec_h1->size, vec_h2->size, vec_k2->size);
1228
1229         for (i = 0; i < vec_k1->size; i++) k1[i] = vec_k1->vec[i];
1230         for (i = 0; i < vec_h1->size; i++) h1[i] = vec_h1->vec[i];
1231         for (i = 0; i < vec_k2->size; i++) k2[i] = vec_k2->vec[i];
1232         for (i = 0; i < vec_h2->size; i++) h2[i] = vec_h2->vec[i];
1233
1234         coord_array = MEM_callocN(dims * (resolu) * sizeof(float), "interpolate_bezier");
1235         for (i = 0; i < dims; i++) {
1236                 BKE_curve_forward_diff_bezier(k1[i], h1[i], h2[i], k2[i], coord_array + i, resolu - 1, sizeof(float) * dims);
1237         }
1238
1239         list = PyList_New(resolu);
1240         fp = coord_array;
1241         for (i = 0; i < resolu; i++, fp = fp + dims) {
1242                 PyList_SET_ITEM(list, i, Vector_CreatePyObject(fp, dims, Py_NEW, NULL));
1243         }
1244         MEM_freeN(coord_array);
1245         return list;
1246 }
1247
1248
1249 PyDoc_STRVAR(M_Geometry_tessellate_polygon_doc,
1250 ".. function:: tessellate_polygon(veclist_list)\n"
1251 "\n"
1252 "   Takes a list of polylines (each point a vector) and returns the point indices for a polyline filled with triangles.\n"
1253 "\n"
1254 "   :arg veclist_list: list of polylines\n"
1255 "   :rtype: list\n"
1256 );
1257 /* PolyFill function, uses Blenders scanfill to fill multiple poly lines */
1258 static PyObject *M_Geometry_tessellate_polygon(PyObject *UNUSED(self), PyObject *polyLineSeq)
1259 {
1260         PyObject *tri_list; /*return this list of tri's */
1261         PyObject *polyLine, *polyVec;
1262         int i, len_polylines, len_polypoints, ls_error = 0;
1263
1264         /* display listbase */
1265         ListBase dispbase = {NULL, NULL};
1266         DispList *dl;
1267         float *fp; /*pointer to the array of malloced dl->verts to set the points from the vectors */
1268         int index, *dl_face, totpoints = 0;
1269
1270         if (!PySequence_Check(polyLineSeq)) {
1271                 PyErr_SetString(PyExc_TypeError,
1272                                 "expected a sequence of poly lines");
1273                 return NULL;
1274         }
1275
1276         len_polylines = PySequence_Size(polyLineSeq);
1277
1278         for (i = 0; i < len_polylines; i++) {
1279                 polyLine = PySequence_GetItem(polyLineSeq, i);
1280                 if (!PySequence_Check(polyLine)) {
1281                         BKE_displist_free(&dispbase);
1282                         Py_XDECREF(polyLine); /* may be null so use Py_XDECREF*/
1283                         PyErr_SetString(PyExc_TypeError,
1284                                         "One or more of the polylines is not a sequence of mathutils.Vector's");
1285                         return NULL;
1286                 }
1287
1288                 len_polypoints = PySequence_Size(polyLine);
1289                 if (len_polypoints > 0) { /* don't bother adding edges as polylines */
1290 #if 0
1291                         if (EXPP_check_sequence_consistency(polyLine, &vector_Type) != 1) {
1292                                 freedisplist(&dispbase);
1293                                 Py_DECREF(polyLine);
1294                                 PyErr_SetString(PyExc_TypeError,
1295                                                 "A point in one of the polylines is not a mathutils.Vector type");
1296                                 return NULL;
1297                         }
1298 #endif
1299                         dl = MEM_callocN(sizeof(DispList), "poly disp");
1300                         BLI_addtail(&dispbase, dl);
1301                         dl->type = DL_INDEX3;
1302                         dl->nr = len_polypoints;
1303                         dl->type = DL_POLY;
1304                         dl->parts = 1; /* no faces, 1 edge loop */
1305                         dl->col = 0; /* no material */
1306                         dl->verts = fp = MEM_callocN(sizeof(float) * 3 * len_polypoints, "dl verts");
1307                         dl->index = MEM_callocN(sizeof(int) * 3 * len_polypoints, "dl index");
1308
1309                         for (index = 0; index < len_polypoints; index++, fp += 3) {
1310                                 polyVec = PySequence_GetItem(polyLine, index);
1311                                 if (VectorObject_Check(polyVec)) {
1312
1313                                         if (BaseMath_ReadCallback((VectorObject *)polyVec) == -1)
1314                                                 ls_error = 1;
1315
1316                                         fp[0] = ((VectorObject *)polyVec)->vec[0];
1317                                         fp[1] = ((VectorObject *)polyVec)->vec[1];
1318                                         if (((VectorObject *)polyVec)->size > 2)
1319                                                 fp[2] = ((VectorObject *)polyVec)->vec[2];
1320                                         else
1321                                                 fp[2] = 0.0f;  /* if its a 2d vector then set the z to be zero */
1322                                 }
1323                                 else {
1324                                         ls_error = 1;
1325                                 }
1326
1327                                 totpoints++;
1328                                 Py_DECREF(polyVec);
1329                         }
1330                 }
1331                 Py_DECREF(polyLine);
1332         }
1333
1334         if (ls_error) {
1335                 BKE_displist_free(&dispbase); /* possible some dl was allocated */
1336                 PyErr_SetString(PyExc_TypeError,
1337                                 "A point in one of the polylines "
1338                                 "is not a mathutils.Vector type");
1339                 return NULL;
1340         }
1341         else if (totpoints) {
1342                 /* now make the list to return */
1343                 /* TODO, add normal arg */
1344                 BKE_displist_fill(&dispbase, &dispbase, NULL, false);
1345
1346                 /* The faces are stored in a new DisplayList
1347                  * thats added to the head of the listbase */
1348                 dl = dispbase.first;
1349
1350                 tri_list = PyList_New(dl->parts);
1351                 if (!tri_list) {
1352                         BKE_displist_free(&dispbase);
1353                         PyErr_SetString(PyExc_RuntimeError,
1354                                         "failed to make a new list");
1355                         return NULL;
1356                 }
1357
1358                 index = 0;
1359                 dl_face = dl->index;
1360                 while (index < dl->parts) {
1361                         PyList_SET_ITEM(tri_list, index, Py_BuildValue("iii", dl_face[0], dl_face[1], dl_face[2]));
1362                         dl_face += 3;
1363                         index++;
1364                 }
1365                 BKE_displist_free(&dispbase);
1366         }
1367         else {
1368                 /* no points, do this so scripts don't barf */
1369                 BKE_displist_free(&dispbase); /* possible some dl was allocated */
1370                 tri_list = PyList_New(0);
1371         }
1372
1373         return tri_list;
1374 }
1375
1376
1377 static int boxPack_FromPyObject(PyObject *value, BoxPack **boxarray)
1378 {
1379         Py_ssize_t len, i;
1380         PyObject *list_item, *item_1, *item_2;
1381         BoxPack *box;
1382
1383
1384         /* Error checking must already be done */
1385         if (!PyList_Check(value)) {
1386                 PyErr_SetString(PyExc_TypeError,
1387                                 "can only back a list of [x, y, w, h]");
1388                 return -1;
1389         }
1390
1391         len = PyList_GET_SIZE(value);
1392
1393         *boxarray = MEM_mallocN(len * sizeof(BoxPack), "BoxPack box");
1394
1395
1396         for (i = 0; i < len; i++) {
1397                 list_item = PyList_GET_ITEM(value, i);
1398                 if (!PyList_Check(list_item) || PyList_GET_SIZE(list_item) < 4) {
1399                         MEM_freeN(*boxarray);
1400                         PyErr_SetString(PyExc_TypeError,
1401                                         "can only pack a list of [x, y, w, h]");
1402                         return -1;
1403                 }
1404
1405                 box = (*boxarray) + i;
1406
1407                 item_1 = PyList_GET_ITEM(list_item, 2);
1408                 item_2 = PyList_GET_ITEM(list_item, 3);
1409
1410                 box->w =  (float)PyFloat_AsDouble(item_1);
1411                 box->h =  (float)PyFloat_AsDouble(item_2);
1412                 box->index = i;
1413
1414                 /* accounts for error case too and overwrites with own error */
1415                 if (box->w < 0.0f || box->h < 0.0f) {
1416                         MEM_freeN(*boxarray);
1417                         PyErr_SetString(PyExc_TypeError,
1418                                         "error parsing width and height values from list: "
1419                                         "[x, y, w, h], not numbers or below zero");
1420                         return -1;
1421                 }
1422
1423                 /* verts will be added later */
1424         }
1425         return 0;
1426 }
1427
1428 static void boxPack_ToPyObject(PyObject *value, BoxPack **boxarray)
1429 {
1430         Py_ssize_t len, i;
1431         PyObject *list_item;
1432         BoxPack *box;
1433
1434         len = PyList_GET_SIZE(value);
1435
1436         for (i = 0; i < len; i++) {
1437                 box = (*boxarray) + i;
1438                 list_item = PyList_GET_ITEM(value, box->index);
1439                 PyList_SET_ITEM(list_item, 0, PyFloat_FromDouble(box->x));
1440                 PyList_SET_ITEM(list_item, 1, PyFloat_FromDouble(box->y));
1441         }
1442         MEM_freeN(*boxarray);
1443 }
1444
1445 PyDoc_STRVAR(M_Geometry_box_pack_2d_doc,
1446 ".. function:: box_pack_2d(boxes)\n"
1447 "\n"
1448 "   Returns the normal of the 3D tri or quad.\n"
1449 "\n"
1450 "   :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"
1451 "   :type boxes: list\n"
1452 "   :return: the width and height of the packed bounding box\n"
1453 "   :rtype: tuple, pair of floats\n"
1454 );
1455 static PyObject *M_Geometry_box_pack_2d(PyObject *UNUSED(self), PyObject *boxlist)
1456 {
1457         float tot_width = 0.0f, tot_height = 0.0f;
1458         Py_ssize_t len;
1459
1460         PyObject *ret;
1461
1462         if (!PyList_Check(boxlist)) {
1463                 PyErr_SetString(PyExc_TypeError,
1464                                 "expected a list of boxes [[x, y, w, h], ... ]");
1465                 return NULL;
1466         }
1467
1468         len = PyList_GET_SIZE(boxlist);
1469         if (len) {
1470                 BoxPack *boxarray = NULL;
1471                 if (boxPack_FromPyObject(boxlist, &boxarray) == -1) {
1472                         return NULL; /* exception set */
1473                 }
1474
1475                 /* Non Python function */
1476                 BLI_box_pack_2D(boxarray, len, &tot_width, &tot_height);
1477
1478                 boxPack_ToPyObject(boxlist, &boxarray);
1479         }
1480
1481         ret = PyTuple_New(2);
1482         PyTuple_SET_ITEM(ret, 0, PyFloat_FromDouble(tot_width));
1483         PyTuple_SET_ITEM(ret, 1, PyFloat_FromDouble(tot_width));
1484         return ret;
1485 }
1486
1487 #endif /* MATH_STANDALONE */
1488
1489
1490 static PyMethodDef M_Geometry_methods[] = {
1491         {"intersect_ray_tri", (PyCFunction) M_Geometry_intersect_ray_tri, METH_VARARGS, M_Geometry_intersect_ray_tri_doc},
1492         {"intersect_point_line", (PyCFunction) M_Geometry_intersect_point_line, METH_VARARGS, M_Geometry_intersect_point_line_doc},
1493         {"intersect_point_tri_2d", (PyCFunction) M_Geometry_intersect_point_tri_2d, METH_VARARGS, M_Geometry_intersect_point_tri_2d_doc},
1494         {"intersect_point_quad_2d", (PyCFunction) M_Geometry_intersect_point_quad_2d, METH_VARARGS, M_Geometry_intersect_point_quad_2d_doc},
1495         {"intersect_line_line", (PyCFunction) M_Geometry_intersect_line_line, METH_VARARGS, M_Geometry_intersect_line_line_doc},
1496         {"intersect_line_line_2d", (PyCFunction) M_Geometry_intersect_line_line_2d, METH_VARARGS, M_Geometry_intersect_line_line_2d_doc},
1497         {"intersect_line_plane", (PyCFunction) M_Geometry_intersect_line_plane, METH_VARARGS, M_Geometry_intersect_line_plane_doc},
1498         {"intersect_plane_plane", (PyCFunction) M_Geometry_intersect_plane_plane, METH_VARARGS, M_Geometry_intersect_plane_plane_doc},
1499         {"intersect_line_sphere", (PyCFunction) M_Geometry_intersect_line_sphere, METH_VARARGS, M_Geometry_intersect_line_sphere_doc},
1500         {"intersect_line_sphere_2d", (PyCFunction) M_Geometry_intersect_line_sphere_2d, METH_VARARGS, M_Geometry_intersect_line_sphere_2d_doc},
1501         {"distance_point_to_plane", (PyCFunction) M_Geometry_distance_point_to_plane, METH_VARARGS, M_Geometry_distance_point_to_plane_doc},
1502         {"intersect_sphere_sphere_2d", (PyCFunction) M_Geometry_intersect_sphere_sphere_2d, METH_VARARGS, M_Geometry_intersect_sphere_sphere_2d_doc},
1503         {"area_tri", (PyCFunction) M_Geometry_area_tri, METH_VARARGS, M_Geometry_area_tri_doc},
1504         {"volume_tetrahedron", (PyCFunction) M_Geometry_volume_tetrahedron, METH_VARARGS, M_Geometry_volume_tetrahedron_doc},
1505         {"normal", (PyCFunction) M_Geometry_normal, METH_VARARGS, M_Geometry_normal_doc},
1506         {"barycentric_transform", (PyCFunction) M_Geometry_barycentric_transform, METH_VARARGS, M_Geometry_barycentric_transform_doc},
1507         {"points_in_planes", (PyCFunction) M_Geometry_points_in_planes, METH_VARARGS, M_Geometry_points_in_planes_doc},
1508 #ifndef MATH_STANDALONE
1509         {"interpolate_bezier", (PyCFunction) M_Geometry_interpolate_bezier, METH_VARARGS, M_Geometry_interpolate_bezier_doc},
1510         {"tessellate_polygon", (PyCFunction) M_Geometry_tessellate_polygon, METH_O, M_Geometry_tessellate_polygon_doc},
1511         {"box_pack_2d", (PyCFunction) M_Geometry_box_pack_2d, METH_O, M_Geometry_box_pack_2d_doc},
1512 #endif
1513         {NULL, NULL, 0, NULL}
1514 };
1515
1516 static struct PyModuleDef M_Geometry_module_def = {
1517         PyModuleDef_HEAD_INIT,
1518         "mathutils.geometry",  /* m_name */
1519         M_Geometry_doc,  /* m_doc */
1520         0,  /* m_size */
1521         M_Geometry_methods,  /* m_methods */
1522         NULL,  /* m_reload */
1523         NULL,  /* m_traverse */
1524         NULL,  /* m_clear */
1525         NULL,  /* m_free */
1526 };
1527
1528 /*----------------------------MODULE INIT-------------------------*/
1529 PyMODINIT_FUNC PyInit_mathutils_geometry(void)
1530 {
1531         PyObject *submodule = PyModule_Create(&M_Geometry_module_def);
1532         return submodule;
1533 }