tom*_*sey 8 c++ casting polygon data-conversion clipperlib
我有两个多边形,它们的顶点存储为双坐标.我想找到这些多边形的交叉区域,所以我正在看Clipper库(C++版本).问题是,Clipper仅适用于整数数学(它使用Long类型).
有没有办法可以安全地转换具有相同比例因子的多边形,将它们的坐标转换为Longs,使用Clipper执行交点算法,然后使用相同的因子缩小生成的交叉点多边形,并将其转换回Double没有太多的精度损失?
我无法理解如何做到这一点.
您可以使用简单的乘数在两者之间进行转换:
/* Using power-of-two because it is exactly representable and makes
the scaling operation (not the rounding!) lossless. The value 1024
preserves roughly three decimal digits. */
double const scale = 1024.0;
// representable range
double const min_value = std::numeric_limits<long>::min() / scale;
double const max_value = std::numeric_limits<long>::max() / scale;
long
to_long(double v)
{
    if(v < 0)
    {
        if(v < min_value)
            throw out_of_range();
        return static_cast<long>(v * scale - 0.5);
    }
    else
    {
        if(v > max_value)
            throw out_of_range();
        return static_cast<long>(v * scale + 0.5);
    }
}
Run Code Online (Sandbox Code Playgroud)
请注意,刻度越大,精度越高,但也会降低范围.实际上,这会将浮点数转换为定点数.
最后,您应该能够轻松地使用浮点数学来定位代码来计算线段之间的交叉点,所以我想知道为什么要使用Clipper.