指向多边形的内部或边界

时间:2014-04-30 03:43:26

标签: c++ algorithm computational-geometry boundary point-in-polygon

我正在使用http://www.ecse.rpi.edu/~wrf/Research/Short_Notes/pnpoly.html中的算法, 但是当输入点在边界时,该算法对我来说是错误的。任何人都能帮助我解决边界案件吗? 任何帮助表示赞赏。

这是主要功能

#include <iostream>
#include <Polygon.h>
using namespace std;

int main()
{
    vector<Point> v;
    //v.push_back(make_pair(3.0,3.0));
    v.push_back(make_pair(1.0,1.0));
    v.push_back(make_pair(1.0,5.0));
    v.push_back(make_pair(5.0,5.0));
    v.push_back(make_pair(5.0,1.0));
    Polygon *p = new Polygon(v);
    cout << "A: " << p->IsInside(make_pair(1.0,3.0)) << endl;
    cout << "B: " << p->IsInside(make_pair(3.0,1.0)) << endl;
    cout << "C: " << p->IsInside(make_pair(5.0,3.0)) << endl;
    cout << "D: " << p->IsInside(make_pair(3.0,5.0)) << endl;
    delete p;
    return 0;
}

这是检查功能

bool Polygon::IsInside(Point p)
{
    /*determine whether a point is inside a polygon or not
     *  polygon's vertices need to be sorted counterclockwise
     *  source :
     *      http://www.ecse.rpi.edu/~wrf/Research/Short_Notes/pnpoly.html
    */
    bool ans = false;
    for(size_t c=0,d=this->vertices.size()-1; c<this->vertices.size(); d=c++)
    {
        if( ((this->vertices[c].y > p.y) != (this->vertices[d].y > p.y)) &&
            (p.x < (this->vertices[d].x - this->vertices[c].x) * (p.y - this->vertices[c].y) /
                (this->vertices[d].y - this->vertices[c].y) + this->vertices[c].x) )
           ans = !ans;
    }
    return ans;
}

1 个答案:

答案 0 :(得分:0)

从网站文档: “PNPOLY将平面划分为多边形内的点并指向多边形外部。边界上的点被分类为内部或外部....” 请再次阅读网站上提供的文档。它可以回答您的问题。 最后,您可能不得不忍受浮点计算的模糊性。

相关问题