因此,我根据礼品包装算法的示例编写了以下代码,用于查找一组点的凸包:
std::vector<sf::Vector2f> convexHull(const std::vector<sf::Vector2f>& _shape)
{
std::vector<sf::Vector2f> returnValue;
returnValue.push_back(leftmostPoint(_shape));
for (std::vector<sf::Vector2f>::const_iterator it = _shape.begin(), end = _shape.end(); it != end; ++it)
{
if (elementIncludedInVector(*it, returnValue)) continue;
bool allPointWereToTheLeft = true;
for (std::vector<sf::Vector2f>::const_iterator it1 = _shape.begin(); it1 != end; ++it1)
{
if (*it1 == *it || elementIncludedInVector(*it1, returnValue)) continue;
if (pointPositionRelativeToLine(returnValue.back(), *it, *it1) > 0.0f)
{
allPointWereToTheLeft = false;
break;
}
}
if (allPointWereToTheLeft)
{
returnValue.push_back(*it);
it = _shape.begin();
}
}
return returnValue;
}
这是我确定第三点位于直线哪一侧的函数:
float pointPositionRelativeToLine(const sf::Vector2f& A, const sf::Vector2f& B, const sf::Vector2f& C)
{
return (B.x - A.x)*(C.y - A.y) - (B.y - A.y)*(C.x - A.x);
}
返回负数表示点在一侧,正数在另一侧,0 表示三个点共线。现在,问题是:如何修改上述代码,使其即使在 _shape 中存在共线点时也能正常工作?