source: trunk/anuga_core/source/anuga/utilities/polygon_ext.c @ 8028

Last change on this file since 8028 was 8028, checked in by habili, 13 years ago

added _polygon_triangle_overlap to determine if a polygon and a triangle overlap.

File size: 22.8 KB
Line 
1// Python - C extension for polygon module.
2//
3// To compile (Python2.3):
4//  gcc -c polygon_ext.c -I/usr/include/python2.3 -o polygon_ext.o -Wall -O
5//  gcc -shared polygon_ext.o  -o polygon_ext.so
6//
7// See the module polygon.py
8//
9//
10// Ole Nielsen, GA 2004
11//
12// NOTE: We use long* instead of int* for numeric arrays as this will work both
13//       for 64 as well as 32 bit systems
14
15
16#include "Python.h"
17#include "numpy/arrayobject.h"
18#include "math.h"
19
20#include "util_ext.h"
21
22#define YES 1
23#define NO 0
24
25
26double dist(double x,
27            double y) {
28 
29  return sqrt(x*x + y*y);
30}
31
32
33int __point_on_line(double x, double y,
34                    double x0, double y0,
35                    double x1, double y1,
36                    double rtol,
37                    double atol) {
38  /*Determine whether a point is on a line segment
39
40    Input: x, y, x0, x0, x1, y1: where
41        point is given by x, y
42        line is given by (x0, y0) and (x1, y1)
43
44  */
45
46  double a0, a1, a_normal0, a_normal1, b0, b1, len_a, len_b;
47  double nominator, denominator;
48  int is_parallel;
49
50  a0 = x - x0;
51  a1 = y - y0;
52
53  a_normal0 = a1;
54  a_normal1 = -a0;
55
56  b0 = x1 - x0;
57  b1 = y1 - y0;
58
59  nominator = fabs(a_normal0*b0 + a_normal1*b1);
60  denominator = b0*b0 + b1*b1;
61 
62  // Determine if line is parallel to point vector up to a tolerance
63  is_parallel = 0;
64  if (denominator == 0.0) {
65    // Use absolute tolerance
66    if (nominator <= atol) {
67      is_parallel = 1;
68    }
69  } else {
70    // Denominator is positive - use relative tolerance
71    if (nominator/denominator <= rtol) {
72      is_parallel = 1;
73    }   
74  }
75   
76  if (is_parallel) {
77    // Point is somewhere on the infinite extension of the line
78    // subject to specified absolute tolerance
79
80    len_a = dist(a0, a1); //sqrt(a0*a0 + a1*a1);
81    len_b = dist(b0, b1); //sqrt(b0*b0 + b1*b1);
82
83    if (a0*b0 + a1*b1 >= 0 && len_a <= len_b) {
84      return 1;
85    } else {
86      return 0;
87    }
88  } else {
89    return 0;
90  }
91}
92
93
94//  public domain function by Darel Rex Finley, 2006
95//  http://www.alienryderflex.com/intersect/
96//
97//  Determines the intersection point of the line segment defined by points A and B
98//  with the line segment defined by points C and D.
99//
100//  Returns YES if the intersection point was found, and stores that point in X,Y.
101//  Returns NO if there is no determinable intersection point, in which case X,Y will
102//  be unmodified.
103
104int __line_segment_intersection(
105        double Ax, double Ay,
106        double Bx, double By,
107        double Cx, double Cy,
108        double Dx, double Dy,
109        double *X, double *Y) {
110
111    double distAB, theCos, theSin, newX, ABpos;
112
113    //  Fail if either line segment is zero-length.
114    if ( (Ax == Bx && Ay == By) || (Cx == Dx && Cy == Dy) ) return NO ;
115
116    //  Fail if the segments share an end-point.
117    if ( (Ax == Cx && Ay == Cy) || (Bx == Cx && By == Cy)
118            || (Ax == Dx && Ay == Dy) || (Bx == Dx && By == Dy) ) {
119        return NO;
120    }
121
122    //  (1) Translate the system so that point A is on the origin.
123    Bx -= Ax;
124    By -= Ay;
125    Cx -= Ax;
126    Cy -= Ay;
127    Dx -= Ax;
128    Dy -= Ay;
129
130    //  Discover the length of segment A-B.
131    distAB = sqrt(Bx * Bx + By * By);
132
133    //  (2) Rotate the system so that point B is on the positive X axis.
134    theCos = Bx / distAB;
135    theSin = By / distAB;
136    newX = Cx * theCos + Cy*theSin;
137    Cy = Cy * theCos - Cx*theSin;
138    Cx = newX;
139    newX = Dx * theCos + Dy*theSin;
140    Dy = Dy * theCos - Dx*theSin;
141    Dx = newX;
142
143    //  Fail if segment C-D doesn't cross line A-B.
144    if ( (Cy < 0. && Dy < 0.) || (Cy >= 0. && Dy >= 0.) ) return NO;
145
146    //  (3) Discover the position of the intersection point along line A-B.
147    ABpos = Dx + (Cx - Dx) * Dy / (Dy - Cy);
148
149    //  Fail if segment C-D crosses line A-B outside of segment A-B.
150    if (ABpos < 0. || ABpos > distAB) return NO;
151
152    //  (4) Apply the discovered position to line A-B in the original coordinate system.
153    *X = Ax + ABpos*theCos;
154    *Y = Ay + ABpos*theSin;
155
156    //  Success.
157    return YES;
158}
159
160/*
161WORK IN PROGRESS TO OPTIMISE INTERSECTION
162int __intersection(double x0, double y0,
163                   double x1, double y1) {
164
165
166    x0 = line0[0,0]; y0 = line0[0,1]
167    x1 = line0[1,0]; y1 = line0[1,1]
168
169    x2 = line1[0,0]; y2 = line1[0,1]
170    x3 = line1[1,0]; y3 = line1[1,1]
171
172    denom = (y3-y2)*(x1-x0) - (x3-x2)*(y1-y0)
173    u0 = (x3-x2)*(y0-y2) - (y3-y2)*(x0-x2)
174    u1 = (x2-x0)*(y1-y0) - (y2-y0)*(x1-x0)
175       
176    if allclose(denom, 0.0):
177        # Lines are parallel - check if they coincide on a shared a segment
178
179        if allclose( [u0, u1], 0.0 ):
180            # We now know that the lines if continued coincide
181            # The remaining check will establish if the finite lines share a segment
182
183            line0_starts_on_line1 = line0_ends_on_line1 =\
184            line1_starts_on_line0 = line1_ends_on_line0 = False
185               
186            if point_on_line([x0, y0], line1):
187                line0_starts_on_line1 = True
188
189            if point_on_line([x1, y1], line1):
190                line0_ends_on_line1 = True
191 
192            if point_on_line([x2, y2], line0):
193                line1_starts_on_line0 = True
194
195            if point_on_line([x3, y3], line0):
196                line1_ends_on_line0 = True                               
197
198            if not(line0_starts_on_line1 or line0_ends_on_line1\
199               or line1_starts_on_line0 or line1_ends_on_line0):
200                # Lines are parallel and would coincide if extended, but not as they are.
201                return 3, None
202
203
204            # One line fully included in the other. Use direction of included line
205            if line0_starts_on_line1 and line0_ends_on_line1:
206                # Shared segment is line0 fully included in line1
207                segment = array([[x0, y0], [x1, y1]])               
208
209            if line1_starts_on_line0 and line1_ends_on_line0:
210                # Shared segment is line1 fully included in line0
211                segment = array([[x2, y2], [x3, y3]])
212           
213
214            # Overlap with lines are oriented the same way
215            if line0_starts_on_line1 and line1_ends_on_line0:
216                # Shared segment from line0 start to line 1 end
217                segment = array([[x0, y0], [x3, y3]])
218
219            if line1_starts_on_line0 and line0_ends_on_line1:
220                # Shared segment from line1 start to line 0 end
221                segment = array([[x2, y2], [x1, y1]])                               
222
223
224            # Overlap in opposite directions - use direction of line0
225            if line0_starts_on_line1 and line1_starts_on_line0:
226                # Shared segment from line0 start to line 1 end
227                segment = array([[x0, y0], [x2, y2]])
228
229            if line0_ends_on_line1 and line1_ends_on_line0:
230                # Shared segment from line0 start to line 1 end
231                segment = array([[x3, y3], [x1, y1]])               
232
233               
234            return 2, segment
235        else:
236            # Lines are parallel but they do not coincide
237            return 4, None #FIXME (Ole): Add distance here instead of None
238           
239    else:
240        # Lines are not parallel or coinciding
241        u0 = u0/denom
242        u1 = u1/denom       
243
244        x = x0 + u0*(x1-x0)
245        y = y0 + u0*(y1-y0)
246
247        # Sanity check - can be removed to speed up if needed
248        assert allclose(x, x2 + u1*(x3-x2))
249        assert allclose(y, y2 + u1*(y3-y2))       
250
251        # Check if point found lies within given line segments
252        if 0.0 <= u0 <= 1.0 and 0.0 <= u1 <= 1.0:
253            # We have intersection
254
255            return 1, array([x, y])
256        else:
257            # No intersection
258            return 0, None
259
260
261}
262*/
263
264
265
266int __interpolate_polyline(int number_of_nodes,
267                           int number_of_points,
268                           double* data,
269                           double* polyline_nodes,
270                           long* gauge_neighbour_id,
271                           double* interpolation_points,                               
272                           double* interpolated_values,
273                           double rtol,
274                           double atol) {
275                           
276  int j, i, neighbour_id;
277  double x0, y0, x1, y1, x, y;
278  double segment_len, segment_delta, slope, alpha;
279
280  for (j=0; j<number_of_nodes; j++) { 
281
282    neighbour_id = gauge_neighbour_id[j];
283       
284    // FIXME(Ole): I am convinced that gauge_neighbour_id can be discarded, but need to check with John J.
285    // Keep it for now (17 Jan 2009)
286    // When gone, we can simply interpolate between neighbouring nodes, i.e. neighbour_id = j+1.
287    // and the test below becomes something like: if j < number_of_nodes... 
288       
289    if (neighbour_id >= 0) {
290      x0 = polyline_nodes[2*j];
291      y0 = polyline_nodes[2*j+1];
292     
293      x1 = polyline_nodes[2*neighbour_id];
294      y1 = polyline_nodes[2*neighbour_id+1];     
295     
296           
297      segment_len = dist(x1-x0, y1-y0);
298      segment_delta = data[neighbour_id] - data[j];           
299      slope = segment_delta/segment_len;
300           
301      for (i=0; i<number_of_points; i++) {               
302        x = interpolation_points[2*i];
303        y = interpolation_points[2*i+1];       
304       
305        if (__point_on_line(x, y, x0, y0, x1, y1, rtol, atol)) {
306          alpha = dist(x-x0, y-y0);
307          interpolated_values[i] = slope*alpha + data[j];
308        }
309      }
310    }
311  }
312                           
313  return 0;                         
314}                                                     
315
316
317int __polygon_triangle_overlap(double* polygon,
318                               double* triangle)
319{
320    int i, ii, j, jj;
321    double p0_x, p0_y, p1_x, p1_y, pp_x, pp_y;
322    double t0_x, t0_y, t1_x, t1_y, tp_x, tp_y;
323    double u_x, u_y, v_x, v_y, w_x, w_y;
324    double u_dot_tp, v_dot_tp, v_dot_pp, w_dot_pp;
325    double a, b;
326   
327    p0_x = polygon[0];
328    p0_y = polygon[1];
329   
330    for (i = 1; i < 5; i++)
331    {
332        ii = i%4;
333       
334        p1_x = polygon[2*ii];
335        p1_y = polygon[2*ii + 1];
336       
337        pp_x = -(p1_y - p0_y);
338        pp_y = p1_x - p0_x;
339 
340        t0_x = triangle[0];
341        t0_y = triangle[1];
342 
343        for (j = 1; j < 4; j++)
344        {
345            jj = j%3;
346                     
347            t1_x = triangle[2*jj];
348            t1_y = triangle[2*jj + 1];
349           
350            tp_x = -(t1_y - t0_y); //perpendicular to triangle vector
351            tp_y = t1_x - t0_x;
352       
353            u_x = p1_x - p0_x;
354            u_y = p1_y - p0_y;
355            v_x = t0_x - p0_x;
356            v_y = t0_y - p0_y;
357            w_x = t1_x - t0_x;
358            w_y = t1_y - t0_y;
359
360            u_dot_tp = (u_x*tp_x) + (u_y*tp_y);
361           
362            if (u_dot_tp != 0.0f) //Vectors are not parallel
363            {
364                v_dot_tp = (v_x*tp_x) + (v_y*tp_y);
365                v_dot_pp = (v_x*pp_x) + (v_y*pp_y);
366                w_dot_pp = (w_x*pp_x) + (w_y*pp_y);
367               
368                a = v_dot_tp/u_dot_tp;
369                b = v_dot_pp/w_dot_pp;
370               
371                if (a >= 0.0f && a <= 1.0f)
372                {
373                    return 1; //overlap
374                }
375               
376                if (b >= 0.0f && b <= 1.0f)
377                {
378                    return 1; //overlap
379                }
380            }
381           
382            t0_x = t1_x;
383            t0_y = t1_y;
384        }
385       
386        p0_x = p1_x;
387        p0_y = p1_y;
388    }
389
390    return 0; //no overlap
391}
392                               
393
394
395int __is_inside_triangle(double* point,
396                         double* triangle,
397                         int closed,
398                         double rtol,
399                         double atol) {
400                         
401  double vx, vy, v0x, v0y, v1x, v1y;
402  double a00, a10, a01, a11, b0, b1;
403  double denom, alpha, beta;
404 
405  double x, y; // Point coordinates
406  int i, j, res;
407
408  x = point[0];
409  y = point[1];
410 
411  // Quickly reject points that are clearly outside
412  if ((x < triangle[0]) && 
413      (x < triangle[2]) && 
414      (x < triangle[4])) return 0;       
415     
416  if ((x > triangle[0]) && 
417      (x > triangle[2]) && 
418      (x > triangle[4])) return 0;             
419 
420  if ((y < triangle[1]) && 
421      (y < triangle[3]) && 
422      (y < triangle[5])) return 0;       
423     
424  if ((y > triangle[1]) && 
425      (y > triangle[3]) && 
426      (y > triangle[5])) return 0;             
427 
428 
429  // v0 = C-A
430  v0x = triangle[4]-triangle[0]; 
431  v0y = triangle[5]-triangle[1];
432 
433  // v1 = B-A   
434  v1x = triangle[2]-triangle[0]; 
435  v1y = triangle[3]-triangle[1];
436
437  // First check if point lies wholly inside triangle
438  a00 = v0x*v0x + v0y*v0y; // innerproduct(v0, v0)
439  a01 = v0x*v1x + v0y*v1y; // innerproduct(v0, v1)
440  a10 = a01;               // innerproduct(v1, v0)
441  a11 = v1x*v1x + v1y*v1y; // innerproduct(v1, v1)
442   
443  denom = a11*a00 - a01*a10;
444
445  if (fabs(denom) > 0.0) {
446    // v = point-A 
447    vx = x - triangle[0]; 
448    vy = y - triangle[1];     
449   
450    b0 = v0x*vx + v0y*vy; // innerproduct(v0, v)       
451    b1 = v1x*vx + v1y*vy; // innerproduct(v1, v)           
452   
453    alpha = (b0*a11 - b1*a01)/denom;
454    beta = (b1*a00 - b0*a10)/denom;       
455   
456    if ((alpha > 0.0) && (beta > 0.0) && (alpha+beta < 1.0)) return 1;
457  }
458
459  if (closed) {
460    // Check if point lies on one of the edges
461       
462    for (i=0; i<3; i++) {
463      j = (i+1) % 3; // Circular index into triangle array
464      res = __point_on_line(x, y,
465                            triangle[2*i], triangle[2*i+1], 
466                            triangle[2*j], triangle[2*j+1],                         
467                            rtol, atol);
468      if (res) return 1;
469    }
470  }
471               
472  // Default return if point is outside triangle                         
473  return 0;                                             
474}                                                                             
475
476
477int __separate_points_by_polygon(int M,     // Number of points
478                                 int N,     // Number of polygon vertices
479                                 double* points,
480                                 double* polygon,
481                                 long* indices,  // M-Array for storage indices
482                                 int closed,
483                                 int verbose) {
484
485  double minpx, maxpx, minpy, maxpy, x, y, px_i, py_i, px_j, py_j, rtol=0.0, atol=0.0;
486  int i, j, k, outside_index, inside_index, inside;
487
488  // Find min and max of poly used for optimisation when points
489  // are far away from polygon
490 
491  // FIXME(Ole): Pass in rtol and atol from Python
492
493  minpx = polygon[0]; maxpx = minpx;
494  minpy = polygon[1]; maxpy = minpy;
495
496  for (i=0; i<N; i++) {
497    px_i = polygon[2*i];
498    py_i = polygon[2*i + 1];
499
500    if (px_i < minpx) minpx = px_i;
501    if (px_i > maxpx) maxpx = px_i;
502    if (py_i < minpy) minpy = py_i;
503    if (py_i > maxpy) maxpy = py_i;
504  }
505
506  // Begin main loop (for each point)
507  inside_index = 0;    // Keep track of points inside
508  outside_index = M-1; // Keep track of points outside (starting from end)   
509  if (verbose){
510     printf("Separating %d points\n", M);
511  } 
512  for (k=0; k<M; k++) {
513    if (verbose){
514      if (k %((M+10)/10)==0) printf("Doing %d of %d\n", k, M);
515    }
516   
517    x = points[2*k];
518    y = points[2*k + 1];
519
520    inside = 0;
521
522    // Optimisation
523    if ((x > maxpx) || (x < minpx) || (y > maxpy) || (y < minpy)) {
524      // Nothing
525    } else {   
526      // Check polygon
527      for (i=0; i<N; i++) {
528        j = (i+1)%N;
529
530        px_i = polygon[2*i];
531        py_i = polygon[2*i+1];
532        px_j = polygon[2*j];
533        py_j = polygon[2*j+1];
534
535        // Check for case where point is contained in line segment
536        if (__point_on_line(x, y, px_i, py_i, px_j, py_j, rtol, atol)) {
537          if (closed == 1) {
538            inside = 1;
539          } else {
540            inside = 0;
541          }
542          break;
543        } else {
544          //Check if truly inside polygon
545          if ( ((py_i < y) && (py_j >= y)) ||
546               ((py_j < y) && (py_i >= y)) ) {
547            if (px_i + (y-py_i)/(py_j-py_i)*(px_j-px_i) < x)
548              inside = 1-inside;
549          }
550        }
551      }
552    } 
553    if (inside == 1) {
554      indices[inside_index] = k;
555      inside_index += 1;
556    } else {
557      indices[outside_index] = k;
558      outside_index -= 1;   
559    }
560  } // End k
561
562  return inside_index;
563}
564
565
566
567// Gateways to Python
568PyObject *_point_on_line(PyObject *self, PyObject *args) {
569  //
570  // point_on_line(x, y, x0, y0, x1, y1)
571  //
572
573  double x, y, x0, y0, x1, y1, rtol, atol;
574  int res;
575  PyObject *result;
576
577  // Convert Python arguments to C
578  if (!PyArg_ParseTuple(args, "dddddddd", &x, &y, &x0, &y0, &x1, &y1, &rtol, &atol)) {
579    PyErr_SetString(PyExc_RuntimeError, 
580                    "point_on_line could not parse input");   
581    return NULL;
582  }
583
584
585  // Call underlying routine
586  res = __point_on_line(x, y, x0, y0, x1, y1, rtol, atol);
587
588  // Return values a and b
589  result = Py_BuildValue("i", res);
590  return result;
591}
592
593
594
595// Gateways to Python
596PyObject *_interpolate_polyline(PyObject *self, PyObject *args) {
597  //
598  // _interpolate_polyline(data, polyline_nodes, gauge_neighbour_id, interpolation_points
599  //                       interpolated_values):
600  //
601
602 
603  PyArrayObject
604    *data,
605    *polyline_nodes,
606    *gauge_neighbour_id,
607    *interpolation_points,
608    *interpolated_values;
609
610  double rtol, atol; 
611  int number_of_nodes, number_of_points, res;
612 
613  // Convert Python arguments to C
614  if (!PyArg_ParseTuple(args, "OOOOOdd",
615                        &data,
616                        &polyline_nodes,
617                        &gauge_neighbour_id,
618                        &interpolation_points,
619                        &interpolated_values,
620                        &rtol,
621                        &atol)) {
622   
623    PyErr_SetString(PyExc_RuntimeError, 
624                    "_interpolate_polyline could not parse input");
625    return NULL;
626  }
627
628  // check that numpy array objects arrays are C contiguous memory
629  CHECK_C_CONTIG(data);
630  CHECK_C_CONTIG(polyline_nodes);
631  CHECK_C_CONTIG(gauge_neighbour_id);
632  CHECK_C_CONTIG(interpolation_points);
633  CHECK_C_CONTIG(interpolated_values);
634
635  number_of_nodes = polyline_nodes -> dimensions[0];  // Number of nodes in polyline
636  number_of_points = interpolation_points -> dimensions[0];   //Number of points
637 
638
639  // Call underlying routine
640  res = __interpolate_polyline(number_of_nodes,
641                               number_of_points,
642                               (double*) data -> data,
643                               (double*) polyline_nodes -> data,
644                               (long*) gauge_neighbour_id -> data,
645                               (double*) interpolation_points -> data,                         
646                               (double*) interpolated_values -> data,
647                               rtol,
648                               atol);                                                 
649
650  // Return
651  return Py_BuildValue(""); 
652}
653
654
655PyObject *_polygon_triangle_overlap(PyObject *self, PyObject *args) {
656  //
657  // _polygon_triangle_overlap(polygon, triangle)
658  //
659
660 
661  PyArrayObject
662    *polygon,
663    *triangle;
664   
665    int res;
666
667  PyObject *result;
668     
669  // Convert Python arguments to C
670  if (!PyArg_ParseTuple(args, "OO",
671                        &polygon,
672                        &triangle)) {
673   
674    PyErr_SetString(PyExc_RuntimeError, 
675                    "_polygon_triangle_overlap could not parse input");
676    return NULL;
677  }
678
679  // Call underlying routine
680  res = __polygon_triangle_overlap((double*) polygon->data,
681                             (double*) triangle -> data);                                                     
682
683
684  // Return result
685  result = Py_BuildValue("i", res);
686  return result; 
687}
688
689     
690PyObject *_is_inside_triangle(PyObject *self, PyObject *args) {
691  //
692  // _is_inside_triangle(point, triangle, int(closed), rtol, atol)
693  //
694
695 
696  PyArrayObject
697    *point,
698    *triangle;
699
700  double rtol, atol; 
701  int closed, res;
702
703  PyObject *result;
704     
705  // Convert Python arguments to C
706  if (!PyArg_ParseTuple(args, "OOidd",
707                        &point,
708                        &triangle,
709                        &closed,
710                        &rtol,
711                        &atol)) {
712   
713    PyErr_SetString(PyExc_RuntimeError, 
714                    "_is_inside_triangle could not parse input");
715    return NULL;
716  }
717
718  // Call underlying routine
719  res = __is_inside_triangle((double*) point -> data,
720                             (double*) triangle -> data,
721                             closed,
722                             rtol,
723                             atol);                                                   
724
725
726  // Return result
727  result = Py_BuildValue("i", res);
728  return result; 
729}
730     
731
732
733/*
734PyObject *_intersection(PyObject *self, PyObject *args) {
735  //
736  // intersection(x0, y0, x1, y1)
737  //
738
739  double x, y, x0, y0, x1, y1;
740  int res;
741  PyObject *result;
742
743  // Convert Python arguments to C
744  if (!PyArg_ParseTuple(args, "dddddd", &x, &y, &x0, &y0, &x1, &y1)) {
745    PyErr_SetString(PyExc_RuntimeError,
746                    "point_on_line could not parse input");   
747    return NULL;
748  }
749
750
751  // Call underlying routine
752  res = __intersection(x, y, x0, y0, x1, y1);
753
754  // Return values a and b
755  result = Py_BuildValue("i", res);
756  return result;
757}
758*/
759
760
761PyObject *_separate_points_by_polygon(PyObject *self, PyObject *args) {
762  //def separate_points_by_polygon(points, polygon, closed, verbose, one_point):
763  //  """Determine whether points are inside or outside a polygon
764  //
765  //  Input:
766  //     point - Tuple of (x, y) coordinates, or list of tuples
767  //     polygon - list of vertices of polygon
768  //     closed - (optional) determine whether points on boundary should be
769  //     regarded as belonging to the polygon (closed = True)
770  //     or not (closed = False)
771
772  //
773  //  Output:
774  //     indices: array of same length as points with indices of points falling
775  //     inside the polygon listed from the beginning and indices of points
776  //     falling outside listed from the end.
777  //     
778  //     count: count of points falling inside the polygon
779  //     
780  //     The indices of points inside are obtained as indices[:count]
781  //     The indices of points outside are obtained as indices[count:]       
782  //
783  //  Examples:
784  //     separate_polygon( [[0.5, 0.5], [1, -0.5], [0.3, 0.2]] )
785  //     will return the indices [0, 2, 1] as only the first and the last point
786  //     is inside the unit square
787  //
788  //  Remarks:
789  //     The vertices may be listed clockwise or counterclockwise and
790  //     the first point may optionally be repeated.
791  //     Polygons do not need to be convex.
792  //     Polygons can have holes in them and points inside a hole is
793  //     regarded as being outside the polygon.
794  //
795  //
796  //  Algorithm is based on work by Darel Finley,
797  //  http://www.alienryderflex.com/polygon/
798  //
799  //
800
801  PyArrayObject
802    *points,
803    *polygon,
804    *indices;
805
806  int closed, verbose; //Flags
807  int count, M, N;
808
809  // Convert Python arguments to C
810  if (!PyArg_ParseTuple(args, "OOOii",
811                        &points,
812                        &polygon,
813                        &indices,
814                        &closed,
815                        &verbose)) {
816   
817
818    PyErr_SetString(PyExc_RuntimeError, 
819                    "separate_points_by_polygon could not parse input");
820    return NULL;
821  }
822
823  // check that points, polygon and indices arrays are C contiguous
824  CHECK_C_CONTIG(points);
825  CHECK_C_CONTIG(polygon);
826  CHECK_C_CONTIG(indices);
827
828  M = points -> dimensions[0];   //Number of points
829  N = polygon -> dimensions[0];  //Number of vertices in polygon
830
831  //FIXME (Ole): This isn't send to Python's sys.stdout
832  if (verbose) printf("Got %d points and %d polygon vertices\n", M, N);
833 
834  //Call underlying routine
835  count = __separate_points_by_polygon(M, N,
836                                       (double*) points -> data,
837                                       (double*) polygon -> data,
838                                       (long*) indices -> data,
839                                       closed, verbose);
840 
841  //NOTE: return number of points inside..
842  return Py_BuildValue("i", count);
843}
844
845
846
847// Method table for python module
848static struct PyMethodDef MethodTable[] = {
849  /* The cast of the function is necessary since PyCFunction values
850   * only take two PyObject* parameters, and rotate() takes
851   * three.
852   */
853
854  {"_point_on_line", _point_on_line, METH_VARARGS, "Print out"},
855  //{"_intersection", _intersection, METH_VARARGS, "Print out"}, 
856  {"_separate_points_by_polygon", _separate_points_by_polygon, 
857                                 METH_VARARGS, "Print out"},
858  {"_interpolate_polyline", _interpolate_polyline, 
859                                 METH_VARARGS, "Print out"},                             
860  {"_is_inside_triangle", _is_inside_triangle, 
861                                 METH_VARARGS, "Print out"},
862  {NULL, NULL, 0, NULL}   /* sentinel */
863};
864
865
866
867// Module initialisation
868void initpolygon_ext(void){
869  Py_InitModule("polygon_ext", MethodTable);
870
871  import_array();     //Necessary for handling of NumPY structures
872}
873
874
875
Note: See TracBrowser for help on using the repository browser.