pole_in_poly.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*!
  2. \file lib/gis/pole_in_poly.c
  3. \brief GIS Library - Pole in polygon
  4. (C) 2001-2009 by the GRASS Development Team
  5. This program is free software under the GNU General Public License
  6. (>=v2). Read the file COPYING that comes with GRASS for details.
  7. \author CERL
  8. */
  9. #include <grass/gis.h>
  10. static void mystats(double, double, double, double, double *, double *);
  11. /*!
  12. * \brief Check if pole is in polygon
  13. *
  14. * For latitude-longitude coordinates, this routine determines if the polygon
  15. * defined by the <i>n</i> coordinate vertices <i>x,y</i> contains one of the
  16. * poles.
  17. *
  18. * <b>Note:</b> Use this routine only if the projection is PROJECTION_LL.
  19. *
  20. * \param x array of x coordinates
  21. * \param y array of y coordinates
  22. * \param n number of coordinates
  23. *
  24. * \return -1 if it contains the south pole
  25. * \return 1 if it contains the north pole
  26. * \return 0 if it contains neither pole.
  27. */
  28. int G_pole_in_polygon(const double *x, const double *y, int n)
  29. {
  30. int i;
  31. double len, area, total_len, total_area;
  32. if (n <= 1)
  33. return 0;
  34. mystats(x[n - 1], y[n - 1], x[0], y[0], &total_len, &total_area);
  35. for (i = 1; i < n; i++) {
  36. mystats(x[i - 1], y[i - 1], x[i], y[i], &len, &area);
  37. total_len += len;
  38. total_area += area;
  39. }
  40. /* if polygon contains a pole then the x-coordinate length of
  41. * the perimeter should compute to 0, otherwise it should be about 360
  42. * (or -360, depending on the direction of perimeter traversal)
  43. *
  44. * instead of checking for exactly 0, check from -1 to 1 to avoid
  45. * roundoff error.
  46. */
  47. if (total_len < 1.0 && total_len > -1.0)
  48. return 0;
  49. return total_area >= 0.0 ? 1 : -1;
  50. }
  51. static void mystats(double x0, double y0, double x1, double y1, double *len,
  52. double *area)
  53. {
  54. if (x1 > x0)
  55. while (x1 - x0 > 180)
  56. x0 += 360;
  57. else if (x0 > x1)
  58. while (x0 - x1 > 180)
  59. x0 -= 360;
  60. *len = x0 - x1;
  61. if (x0 > x1)
  62. *area = (x0 - x1) * (y0 + y1) / 2.0;
  63. else
  64. *area = (x1 - x0) * (y1 + y0) / 2.0;
  65. }