c++clipperlib

Intersection between line and Polygon using clipper library


I tried all the possibilities. But I am not getting an intersection point between line and polygon.

Paths clip(1), soln , pol(1);
clip[0] << IntPoint(1,1) << IntPoint(30,30) ;
pol[0] << IntPoint(10,10) << IntPoint(20, 10) << IntPoint(20,20) << 
IntPoint(10, 20) << IntPoint(10, 10);
Path line= clip[0];
Path poly = pol[0];
Clipper c;
c.AddPath(line, ptSubject, true);
c.AddPath(poly, ptClip, true);
c.Execute(ctIntersection, soln, pftNonZero, pftNonZero);
std::cout << soln.size() ;

Solution

    1. You're using the wrong override of Execute for open path intersections. When the subject is a line then the solution needs to be PolyTree and not Paths.

      ... when open paths are passed to a Clipper object, the user must use a PolyTree object as the solution parameter, otherwise an exception will be raised. [src]

    2. The line subject you're supposed to make open and not closed with the third parameter of AddPath.

      The function will return false if the path is invalid for clipping. A path is invalid for clipping when it has 2 vertices but is not an open path. [src]

    So change as follows:

    c.AddPath(line, ptSubject, false); // a line is open
    c.AddPath(poly, ptClip, true); // a polygon is closed
    PolyTree soln; // the solution is a tree
    c.Execute(ctIntersection, soln);