Advertisement
LinKin

Point In Polygon

Jun 26th, 2013
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.83 KB | None | 0 0
  1. /*
  2.  * Algorithm : Point in Polygon By ray shooting
  3.  *             Adapted from "Computational Geometry in C" (Second Edition)
  4.  * Complexity : O( N )
  5.  * Note : For each query point Pt, InPoly returns one of four char's:
  6.  *  i : Pt is strictly interior to Pl
  7.  *  o : Pt is strictly exterior to Pl
  8.  *  v : Pt is a vertex of Pl
  9.  *  e : Pt lies on the relative interior of an edge of Pl
  10.  *
  11. */
  12. #include<stdio.h>
  13. #include<math.h>
  14. #define X 0
  15. #define Y 1
  16. #define DIM 2
  17. typedef long POINT[DIM];   /* type integer point */
  18. char PointInPoly( POINT Pt,POINT *Pl, long N ){
  19.     long i,j,d;
  20.     long Rcross = 0; /* number of right edge/ray crossings */
  21.     long Lcross = 0; /* number of left edge/ray crossings */
  22.  
  23.     /* Shift so that Pt is the origin. Note this destroys the polygon.*/
  24.     for( i=0;i<N;i++ ){
  25.         for( d=0;d<DIM;d++ ) Pl[i][d] = Pl[i][d] - Pt[d];
  26.     }
  27.     /* For each edge e=(i-1,i), see if crosses ray. */
  28.     for( i=0;i<N;i++ ){
  29.         /* First see if Pt=(0,0) is a vertex. */
  30.         if( Pl[i][X]==0 and Pl[i][Y]==0 ) return 'v';
  31.         j = (i+N-1)%N;
  32.  
  33.         bool Rstrad = (Pl[i][Y]>0) != (Pl[j][Y]>0);
  34.         bool Lstrad = (Pl[i][Y]<0) != (Pl[j][Y]<0);
  35.  
  36.         /* if e "straddles" the x-axis... */
  37.         if( Rstrad or Lstrad ){
  38.             /* e straddles ray, so compute intersection with ray. */
  39.             double x = ( Pl[i][X]*(double)Pl[j][Y] - Pl[j][X]*(double)Pl[i][Y]) / (double)(Pl[j][Y]-Pl[i][Y]);
  40.             /* crosses ray if strictly positive intersection. */
  41.             if( Rstrad and x>0 ) Rcross++;
  42.             if( Lstrad and x<0 ) Lcross++;
  43.         }
  44.     }
  45.     /* Pt on the edge if left and right cross are not the same parity. */
  46.     if( (Rcross%2) != (Lcross%2) ) return 'e';
  47.     /* Pt inside iff an odd number of crossings. */
  48.     if( (Rcross%2) == 1 ) return 'i';
  49.     else return 'o';
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement