Converting polygon coordinates from Double to Long for use with the Clipper library

I have two polygons with their vertices stored as double coordinates. I would like to find the intersecting area of ​​these polygons, so I look at the Clipper library (C ++ version). The problem is that Clipper only works with integer math (it uses a long type).

Is there a way that I can safely convert both my polygons with the same scale factor, convert their coordinates to Longs, execute the intersection algorithm with Clipper, and scale the resulting intersection polygon with the same ratio and convert it back to Double without too much loss of accuracy ?

I can’t figure out how to do this.

+7
c ++ casting polygon data-conversion clipperlib
source share
1 answer

You can use a simple factor to convert between two:

/* 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); } } 

Note that the more you make the scale, the higher your accuracy will be, but it also reduces the range. In fact, this converts a floating point number to a fixed point number.

Finally, you should be able to find code for calculating intersections between line segments using floating point math, so I wonder why you want to use Clipper specifically.

+6
source share

All Articles