LJ Archive

Listing 1. inpoly.c

/* 1=inside, 0=outside                 */
int
/* is target point inside a 2D polygon? */
inpoly(
/* polygon points, [0]=x, [1]=y         */
unsigned int poly[][2],
/* number of points in polygon          */
int npoints,
/* x (horizontal) of target point       */
unsigned int xt,
/* y (vertical) of target point         */
unsigned int yt)
{
     unsigned int xnew,ynew;
     unsigned int xold,yold;
     unsigned int x1,y1;
     unsigned int x2,y2;
     int i;
     int inside=0;

     if (npoints < 3) {
          return(0);
     }
     xold=poly[npoints-1][0];
     yold=poly[npoints-1][1];
     for (i=0 ; i < npoints ; i++) {
          xnew=poly[i][0];
          ynew=poly[i][1];
          if (xnew > xold) {
               x1=xold;
               x2=xnew;
               y1=yold;
               y2=ynew;
          }
          else {
               x1=xnew;
               x2=xold;
               y1=ynew;
               y2=yold;
          }
          if ((xnew < xt) == (xt <= xold)
           /* edge "open" at one end */
           && ((long)yt-(long)y1)*(long)(x2-x1)
            < ((long)y2-(long)y1)*(long)(xt-x1)) {
               inside=!inside;
          }
          xold=xnew;
          yold=ynew;
     }
     return(inside);
}
LJ Archive