c++实现二维多边形均值重心坐标(代码可能有冗余,未优化代码!):
关于三维中均值重心坐标的实现可参考我的另一篇博客:均值重心坐标Mean Value Coordinates In 3D代码实现
/*
/// @brief mean value coordinates in 2D
/// @details
/// @param[in] p,postiveity
/// @return
/// @attention
*/
VectorXd MyPolygon::meanValueCoordinates(Vector2d &p, bool &postiveity)
{
postiveity = true;
int numOfV = this->getNumberOfVertices();
VectorXd mvc_coor = VectorXd::Zero(numOfV);
VectorXd tanalpha = VectorXd::Zero(numOfV);
MatrixXd temp = MatrixXd::Zero(2, numOfV);
MatrixXd unit_v = MatrixXd::Zero(2, numOfV);
for (int i = 0; i < numOfV; ++i)
{
temp.col(i) = this->vertices.col(i) - p;
unit_v.col(i) = temp.col(i).normalized();
}
for (int i = 0; i < numOfV; ++i)
{
//Vector3d cor = Vector3d(unit_v(0, i), unit_v(1, i), 0).cross(Vector3d(unit_v(0, (i + 1) % numOfV), unit_v(1, (i + 1) % numOfV), 0));
//tanalpha[i] = (1 - unit_v.col(i).dot(unit_v.col((i + 1) % numOfV))) / (cor.norm())*(2 * (cor.dot(Vector3d(0, 0, 1)) < 0) - 1);
tanalpha[i] = (1 - unit_v(0, (i + 1) % numOfV)*unit_v(0, i) - unit_v(1, (i + 1) % numOfV)*unit_v(1, i)) / (unit_v(0, (i + 1) % numOfV)*unit_v(1, i) - unit_v(0, i)*unit_v(1, (i + 1) % numOfV));
}
for (int i = 0; i < numOfV; ++i)
{
mvc_coor[i] = (tanalpha[i] + tanalpha[(i - 1 + numOfV) % numOfV]) / temp.col(i).norm();
}
mvc_coor /= mvc_coor.sum();
postiveity = mvc_coor.minCoeff() >= 0;
cout << mvc_coor << endl;
return mvc_coor;
}
如有任何疑问或建议欢迎下方留言 :-)