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