您的位置:首页 > 产品设计 > UI/UE

QuickHull 快速凸包

2016-05-24 19:54 330 查看
#include <algorithm>
#include <cmath>
#include <vector>
using namespace std;
struct Point
{
double x, y;
Point(double x = 0, double y = 0): x(x), y(y) {}
};
typedef Point Vector;
typedef vector<Point> Polygon;
double Cross(Vector A, Vector B)//
{
return A.x * B.y - A.y * B.x;
}
bool operator <(const Point &a, const Point &b)//
{
return a.x < b.x || (a.x == b.x && a.y < b.y);
}
double Dot(Vector A, Vector B)//
{
return A.x * B.x + A.y * B.y;
}
double Length(Vector A)//
{
return sqrt(Dot(A, A));
}
Vector operator -(Point A, Point B)//
{
return Vector(A.x - B.x , A.y - B.y);
}
bool OnLeft(Point A, Point B, Point p)
{
return Cross(A - B, p - A) > 0;
}
double DistanceToLine(Point p, Point A, Point B) //
{
Vector v1 = B - A, v2 = p - A;
return fabs(Cross(v1, v2)) / Length(v1);
}
void FindHull(const Polygon &Sk, const Point P, const Point Q, Polygon &hullPoints)
{
if (Sk.size() == 0) return;
Point C; Polygon S1, S2;
double furthestDistance = 0.0;
for (const auto &pt : Sk)
{
double distance = DistanceToLine(pt, P, Q);
if (distance > furthestDistance)
{
furthestDistance = distance;
C = pt;
}
}
hullPoints.push_back(C);
for (auto it = Sk.begin(); it != Sk.end(); ++it)
(OnLeft(P, Q, *it) ? S1 : S2).push_back(*it);
FindHull(S1, P, C, hullPoints);
FindHull(S2, C, Q, hullPoints);
}
void QuickHull(const Polygon &s, Polygon &hullPoints)
{
Polygon S1, S2;
Point A = s.front(); hullPoints.push_back(A);
Point B = s.back(); hullPoints.push_back(B);
for (auto it = s.begin() + 1; it != s.end() - 1; ++it)
(OnLeft(A, B, *it) ? S1 : S2).push_back(*it);
FindHull(S1, A, B, hullPoints);
FindHull(S2, B, A, hullPoints);
}


改造来自:https://github.com/abatilo/QuickHull/blob/master/qhull.h
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: