clipper.hpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. /*******************************************************************************
  2. * *
  3. * Author : Angus Johnson *
  4. * Version : 6.2.9 *
  5. * Date : 16 February 2015 *
  6. * Website : http://www.angusj.com *
  7. * Copyright : Angus Johnson 2010-2015 *
  8. * *
  9. * License: *
  10. * Use, modification & distribution is subject to Boost Software License Ver 1. *
  11. * http://www.boost.org/LICENSE_1_0.txt *
  12. * *
  13. * Attributions: *
  14. * The code in this library is an extension of Bala Vatti's clipping algorithm: *
  15. * "A generic solution to polygon clipping" *
  16. * Communications of the ACM, Vol 35, Issue 7 (July 1992) pp 56-63. *
  17. * http://portal.acm.org/citation.cfm?id=129906 *
  18. * *
  19. * Computer graphics and geometric modeling: implementation and algorithms *
  20. * By Max K. Agoston *
  21. * Springer; 1 edition (January 4, 2005) *
  22. * http://books.google.com/books?q=vatti+clipping+agoston *
  23. * *
  24. * See also: *
  25. * "Polygon Offsetting by Computing Winding Numbers" *
  26. * Paper no. DETC2005-85513 pp. 565-575 *
  27. * ASME 2005 International Design Engineering Technical Conferences *
  28. * and Computers and Information in Engineering Conference (IDETC/CIE2005) *
  29. * September 24-28, 2005 , Long Beach, California, USA *
  30. * http://www.me.berkeley.edu/~mcmains/pubs/DAC05OffsetPolygon.pdf *
  31. * *
  32. *******************************************************************************/
  33. #ifndef clipper_hpp
  34. #define clipper_hpp
  35. #include <inttypes.h>
  36. #define CLIPPER_VERSION "6.2.6"
  37. //use_xyz: adds a Z member to IntPoint. Adds a minor cost to perfomance.
  38. //#define use_xyz
  39. //use_lines: Enables line clipping. Adds a very minor cost to performance.
  40. #define use_lines
  41. //use_deprecated: Enables temporary support for the obsolete functions
  42. //#define use_deprecated
  43. #include <vector>
  44. #include <deque>
  45. #include <stdexcept>
  46. #include <cstring>
  47. #include <cstdlib>
  48. #include <ostream>
  49. #include <functional>
  50. #include <queue>
  51. namespace ClipperLib {
  52. enum ClipType { ctIntersection, ctUnion, ctDifference, ctXor };
  53. enum PolyType { ptSubject, ptClip };
  54. //By far the most widely used winding rules for polygon filling are
  55. //EvenOdd & NonZero (GDI, GDI+, XLib, OpenGL, Cairo, AGG, Quartz, SVG, Gr32)
  56. //Others rules include Positive, Negative and ABS_GTR_EQ_TWO (only in OpenGL)
  57. //see http://glprogramming.com/red/chapter11.html
  58. enum PolyFillType { pftEvenOdd, pftNonZero, pftPositive, pftNegative };
  59. // Point coordinate type
  60. typedef int64_t cInt;
  61. // Maximum cInt value to allow a cross product calculation using 32bit expressions.
  62. static cInt const loRange = 0x3FFFFFFF;
  63. // Maximum allowed cInt value.
  64. static cInt const hiRange = 0x3FFFFFFFFFFFFFFFLL;
  65. struct IntPoint {
  66. cInt X;
  67. cInt Y;
  68. #ifdef use_xyz
  69. cInt Z;
  70. IntPoint(cInt x = 0, cInt y = 0, cInt z = 0): X(x), Y(y), Z(z) {};
  71. #else
  72. IntPoint(cInt x = 0, cInt y = 0): X(x), Y(y) {};
  73. #endif
  74. friend inline bool operator== (const IntPoint& a, const IntPoint& b)
  75. {
  76. return a.X == b.X && a.Y == b.Y;
  77. }
  78. friend inline bool operator!= (const IntPoint& a, const IntPoint& b)
  79. {
  80. return a.X != b.X || a.Y != b.Y;
  81. }
  82. };
  83. //------------------------------------------------------------------------------
  84. typedef std::vector< IntPoint > Path;
  85. typedef std::vector< Path > Paths;
  86. inline Path& operator <<(Path& poly, const IntPoint& p) {poly.push_back(p); return poly;}
  87. inline Paths& operator <<(Paths& polys, const Path& p) {polys.push_back(p); return polys;}
  88. std::ostream& operator <<(std::ostream &s, const IntPoint &p);
  89. std::ostream& operator <<(std::ostream &s, const Path &p);
  90. std::ostream& operator <<(std::ostream &s, const Paths &p);
  91. struct DoublePoint
  92. {
  93. double X;
  94. double Y;
  95. DoublePoint(double x = 0, double y = 0) : X(x), Y(y) {}
  96. DoublePoint(IntPoint ip) : X((double)ip.X), Y((double)ip.Y) {}
  97. };
  98. //------------------------------------------------------------------------------
  99. #ifdef use_xyz
  100. typedef void (*ZFillCallback)(IntPoint& e1bot, IntPoint& e1top, IntPoint& e2bot, IntPoint& e2top, IntPoint& pt);
  101. #endif
  102. enum InitOptions {ioReverseSolution = 1, ioStrictlySimple = 2, ioPreserveCollinear = 4};
  103. enum JoinType {jtSquare, jtRound, jtMiter};
  104. enum EndType {etClosedPolygon, etClosedLine, etOpenButt, etOpenSquare, etOpenRound};
  105. class PolyNode;
  106. typedef std::vector< PolyNode* > PolyNodes;
  107. class PolyNode
  108. {
  109. public:
  110. PolyNode() : Childs(), Parent(0), Index(0), m_IsOpen(false) {}
  111. virtual ~PolyNode(){};
  112. Path Contour;
  113. PolyNodes Childs;
  114. PolyNode* Parent;
  115. // Traversal of the polygon tree in a depth first fashion.
  116. PolyNode* GetNext() const { return Childs.empty() ? GetNextSiblingUp() : Childs.front(); }
  117. bool IsHole() const;
  118. bool IsOpen() const { return m_IsOpen; }
  119. int ChildCount() const { return (int)Childs.size(); }
  120. private:
  121. unsigned Index; //node index in Parent.Childs
  122. bool m_IsOpen;
  123. JoinType m_jointype;
  124. EndType m_endtype;
  125. PolyNode* GetNextSiblingUp() const { return Parent ? ((Index == Parent->Childs.size() - 1) ? Parent->GetNextSiblingUp() : Parent->Childs[Index + 1]) : nullptr; }
  126. void AddChild(PolyNode& child);
  127. friend class Clipper; //to access Index
  128. friend class ClipperOffset;
  129. friend class PolyTree; //to implement the PolyTree::move operator
  130. };
  131. class PolyTree: public PolyNode
  132. {
  133. public:
  134. PolyTree() {}
  135. PolyTree(PolyTree &&src) { *this = std::move(src); }
  136. virtual ~PolyTree(){Clear();};
  137. PolyTree& operator=(PolyTree &&src) {
  138. AllNodes = std::move(src.AllNodes);
  139. Contour = std::move(src.Contour);
  140. Childs = std::move(src.Childs);
  141. Parent = nullptr;
  142. Index = src.Index;
  143. m_IsOpen = src.m_IsOpen;
  144. m_jointype = src.m_jointype;
  145. m_endtype = src.m_endtype;
  146. for (size_t i = 0; i < Childs.size(); ++ i)
  147. Childs[i]->Parent = this;
  148. return *this;
  149. }
  150. PolyNode* GetFirst() const { return Childs.empty() ? nullptr : Childs.front(); }
  151. void Clear() { AllNodes.clear(); Childs.clear(); }
  152. int Total() const;
  153. private:
  154. PolyTree(const PolyTree &src) = delete;
  155. PolyTree& operator=(const PolyTree &src) = delete;
  156. std::vector<PolyNode> AllNodes;
  157. friend class Clipper; //to access AllNodes
  158. };
  159. double Area(const Path &poly);
  160. inline bool Orientation(const Path &poly) { return Area(poly) >= 0; }
  161. int PointInPolygon(const IntPoint &pt, const Path &path);
  162. void SimplifyPolygon(const Path &in_poly, Paths &out_polys, PolyFillType fillType = pftEvenOdd);
  163. void SimplifyPolygons(const Paths &in_polys, Paths &out_polys, PolyFillType fillType = pftEvenOdd);
  164. void SimplifyPolygons(Paths &polys, PolyFillType fillType = pftEvenOdd);
  165. void CleanPolygon(const Path& in_poly, Path& out_poly, double distance = 1.415);
  166. void CleanPolygon(Path& poly, double distance = 1.415);
  167. void CleanPolygons(const Paths& in_polys, Paths& out_polys, double distance = 1.415);
  168. void CleanPolygons(Paths& polys, double distance = 1.415);
  169. void MinkowskiSum(const Path& pattern, const Path& path, Paths& solution, bool pathIsClosed);
  170. void MinkowskiSum(const Path& pattern, const Paths& paths, Paths& solution, bool pathIsClosed);
  171. void MinkowskiDiff(const Path& poly1, const Path& poly2, Paths& solution);
  172. void PolyTreeToPaths(const PolyTree& polytree, Paths& paths);
  173. void ClosedPathsFromPolyTree(const PolyTree& polytree, Paths& paths);
  174. void OpenPathsFromPolyTree(PolyTree& polytree, Paths& paths);
  175. void ReversePath(Path& p);
  176. void ReversePaths(Paths& p);
  177. struct IntRect { cInt left; cInt top; cInt right; cInt bottom; };
  178. //enums that are used internally ...
  179. enum EdgeSide { esLeft = 1, esRight = 2};
  180. // namespace Internal {
  181. //forward declarations (for stuff used internally) ...
  182. struct TEdge {
  183. // Bottom point of this edge (with minimum Y).
  184. IntPoint Bot;
  185. // Current position.
  186. IntPoint Curr;
  187. // Top point of this edge (with maximum Y).
  188. IntPoint Top;
  189. // Vector from Bot to Top.
  190. IntPoint Delta;
  191. // Slope (dx/dy). For horiontal edges, the slope is set to HORIZONTAL (-1.0E+40).
  192. double Dx;
  193. PolyType PolyTyp;
  194. EdgeSide Side;
  195. // Winding number delta. 1 or -1 depending on winding direction, 0 for open paths and flat closed paths.
  196. int WindDelta;
  197. int WindCnt;
  198. int WindCnt2; //winding count of the opposite polytype
  199. int OutIdx;
  200. // Next edge in the input path.
  201. TEdge *Next;
  202. // Previous edge in the input path.
  203. TEdge *Prev;
  204. // Next edge in the Local Minima List chain.
  205. TEdge *NextInLML;
  206. TEdge *NextInAEL;
  207. TEdge *PrevInAEL;
  208. TEdge *NextInSEL;
  209. TEdge *PrevInSEL;
  210. };
  211. struct IntersectNode {
  212. IntersectNode(TEdge *Edge1, TEdge *Edge2, IntPoint Pt) :
  213. Edge1(Edge1), Edge2(Edge2), Pt(Pt) {}
  214. TEdge *Edge1;
  215. TEdge *Edge2;
  216. IntPoint Pt;
  217. };
  218. struct LocalMinimum {
  219. cInt Y;
  220. TEdge *LeftBound;
  221. TEdge *RightBound;
  222. };
  223. // Point of an output polygon.
  224. // 36B on 64bit system without use_xyz.
  225. struct OutPt {
  226. // 4B
  227. int Idx;
  228. // 16B without use_xyz / 24B with use_xyz
  229. IntPoint Pt;
  230. // 4B on 32bit system, 8B on 64bit system
  231. OutPt *Next;
  232. // 4B on 32bit system, 8B on 64bit system
  233. OutPt *Prev;
  234. };
  235. struct OutRec;
  236. struct Join {
  237. Join(OutPt *OutPt1, OutPt *OutPt2, IntPoint OffPt) :
  238. OutPt1(OutPt1), OutPt2(OutPt2), OffPt(OffPt) {}
  239. OutPt *OutPt1;
  240. OutPt *OutPt2;
  241. IntPoint OffPt;
  242. };
  243. // }; // namespace Internal
  244. //------------------------------------------------------------------------------
  245. //ClipperBase is the ancestor to the Clipper class. It should not be
  246. //instantiated directly. This class simply abstracts the conversion of sets of
  247. //polygon coordinates into edge objects that are stored in a LocalMinima list.
  248. class ClipperBase
  249. {
  250. public:
  251. ClipperBase() : m_UseFullRange(false), m_HasOpenPaths(false) {}
  252. ~ClipperBase() { Clear(); }
  253. bool AddPath(const Path &pg, PolyType PolyTyp, bool Closed);
  254. bool AddPaths(const Paths &ppg, PolyType PolyTyp, bool Closed);
  255. void Clear();
  256. IntRect GetBounds();
  257. // By default, when three or more vertices are collinear in input polygons (subject or clip), the Clipper object removes the 'inner' vertices before clipping.
  258. // When enabled the PreserveCollinear property prevents this default behavior to allow these inner vertices to appear in the solution.
  259. bool PreserveCollinear() const {return m_PreserveCollinear;};
  260. void PreserveCollinear(bool value) {m_PreserveCollinear = value;};
  261. protected:
  262. bool AddPathInternal(const Path &pg, int highI, PolyType PolyTyp, bool Closed, TEdge* edges);
  263. TEdge* AddBoundsToLML(TEdge *e, bool IsClosed);
  264. void Reset();
  265. TEdge* ProcessBound(TEdge* E, bool IsClockwise);
  266. TEdge* DescendToMin(TEdge *&E);
  267. void AscendToMax(TEdge *&E, bool Appending, bool IsClosed);
  268. // Local minima (Y, left edge, right edge) sorted by ascending Y.
  269. std::vector<LocalMinimum> m_MinimaList;
  270. // True if the input polygons have abs values higher than loRange, but lower than hiRange.
  271. // False if the input polygons have abs values lower or equal to loRange.
  272. bool m_UseFullRange;
  273. // A vector of edges per each input path.
  274. std::vector<std::vector<TEdge>> m_edges;
  275. // Don't remove intermediate vertices of a collinear sequence of points.
  276. bool m_PreserveCollinear;
  277. // Is any of the paths inserted by AddPath() or AddPaths() open?
  278. bool m_HasOpenPaths;
  279. };
  280. //------------------------------------------------------------------------------
  281. class Clipper : public ClipperBase
  282. {
  283. public:
  284. Clipper(int initOptions = 0);
  285. ~Clipper() { Clear(); }
  286. void Clear() { ClipperBase::Clear(); DisposeAllOutRecs(); }
  287. bool Execute(ClipType clipType,
  288. Paths &solution,
  289. PolyFillType fillType = pftEvenOdd)
  290. { return Execute(clipType, solution, fillType, fillType); }
  291. bool Execute(ClipType clipType,
  292. Paths &solution,
  293. PolyFillType subjFillType,
  294. PolyFillType clipFillType);
  295. bool Execute(ClipType clipType,
  296. PolyTree &polytree,
  297. PolyFillType fillType = pftEvenOdd)
  298. { return Execute(clipType, polytree, fillType, fillType); }
  299. bool Execute(ClipType clipType,
  300. PolyTree &polytree,
  301. PolyFillType subjFillType,
  302. PolyFillType clipFillType);
  303. bool ReverseSolution() const { return m_ReverseOutput; };
  304. void ReverseSolution(bool value) {m_ReverseOutput = value;};
  305. bool StrictlySimple() const {return m_StrictSimple;};
  306. void StrictlySimple(bool value) {m_StrictSimple = value;};
  307. //set the callback function for z value filling on intersections (otherwise Z is 0)
  308. #ifdef use_xyz
  309. void ZFillFunction(ZFillCallback zFillFunc) { m_ZFill = zFillFunc; }
  310. #endif
  311. protected:
  312. void Reset();
  313. virtual bool ExecuteInternal();
  314. private:
  315. // Output polygons.
  316. std::vector<OutRec*> m_PolyOuts;
  317. // Output points, allocated by a continuous sets of m_OutPtsChunkSize.
  318. std::vector<OutPt*> m_OutPts;
  319. // List of free output points, to be used before taking a point from m_OutPts or allocating a new chunk.
  320. OutPt *m_OutPtsFree;
  321. size_t m_OutPtsChunkSize;
  322. size_t m_OutPtsChunkLast;
  323. std::vector<Join> m_Joins;
  324. std::vector<Join> m_GhostJoins;
  325. std::vector<IntersectNode> m_IntersectList;
  326. ClipType m_ClipType;
  327. // A priority queue (a binary heap) of Y coordinates.
  328. std::priority_queue<cInt> m_Scanbeam;
  329. // Maxima are collected by ProcessEdgesAtTopOfScanbeam(), consumed by ProcessHorizontal().
  330. std::vector<cInt> m_Maxima;
  331. TEdge *m_ActiveEdges;
  332. TEdge *m_SortedEdges;
  333. PolyFillType m_ClipFillType;
  334. PolyFillType m_SubjFillType;
  335. bool m_ReverseOutput;
  336. // Does the result go to a PolyTree or Paths?
  337. bool m_UsingPolyTree;
  338. bool m_StrictSimple;
  339. #ifdef use_xyz
  340. ZFillCallback m_ZFill; //custom callback
  341. #endif
  342. void SetWindingCount(TEdge& edge) const;
  343. bool IsEvenOddFillType(const TEdge& edge) const
  344. { return (edge.PolyTyp == ptSubject) ? m_SubjFillType == pftEvenOdd : m_ClipFillType == pftEvenOdd; }
  345. bool IsEvenOddAltFillType(const TEdge& edge) const
  346. { return (edge.PolyTyp == ptSubject) ? m_ClipFillType == pftEvenOdd : m_SubjFillType == pftEvenOdd; }
  347. void InsertLocalMinimaIntoAEL(const cInt botY);
  348. void InsertEdgeIntoAEL(TEdge *edge, TEdge* startEdge);
  349. void AddEdgeToSEL(TEdge *edge);
  350. void CopyAELToSEL();
  351. void DeleteFromSEL(TEdge *e);
  352. void DeleteFromAEL(TEdge *e);
  353. void UpdateEdgeIntoAEL(TEdge *&e);
  354. void SwapPositionsInSEL(TEdge *edge1, TEdge *edge2);
  355. bool IsContributing(const TEdge& edge) const;
  356. bool IsTopHorz(const cInt XPos);
  357. void SwapPositionsInAEL(TEdge *edge1, TEdge *edge2);
  358. void DoMaxima(TEdge *e);
  359. void ProcessHorizontals();
  360. void ProcessHorizontal(TEdge *horzEdge);
  361. void AddLocalMaxPoly(TEdge *e1, TEdge *e2, const IntPoint &pt);
  362. OutPt* AddLocalMinPoly(TEdge *e1, TEdge *e2, const IntPoint &pt);
  363. OutRec* GetOutRec(int idx);
  364. void AppendPolygon(TEdge *e1, TEdge *e2) const;
  365. void IntersectEdges(TEdge *e1, TEdge *e2, IntPoint &pt);
  366. OutRec* CreateOutRec();
  367. OutPt* AddOutPt(TEdge *e, const IntPoint &pt);
  368. OutPt* GetLastOutPt(TEdge *e);
  369. OutPt* AllocateOutPt();
  370. OutPt* DupOutPt(OutPt* outPt, bool InsertAfter);
  371. // Add the point to a list of free points.
  372. void DisposeOutPt(OutPt *pt) { pt->Next = m_OutPtsFree; m_OutPtsFree = pt; }
  373. void DisposeOutPts(OutPt*& pp) { if (pp != nullptr) { pp->Prev->Next = m_OutPtsFree; m_OutPtsFree = pp; } }
  374. void DisposeAllOutRecs();
  375. bool ProcessIntersections(const cInt topY);
  376. void BuildIntersectList(const cInt topY);
  377. void ProcessEdgesAtTopOfScanbeam(const cInt topY);
  378. void BuildResult(Paths& polys);
  379. void BuildResult2(PolyTree& polytree);
  380. void SetHoleState(TEdge *e, OutRec *outrec) const;
  381. bool FixupIntersectionOrder();
  382. void FixupOutPolygon(OutRec &outrec);
  383. void FixupOutPolyline(OutRec &outrec);
  384. bool FindOwnerFromSplitRecs(OutRec &outRec, OutRec *&currOrfl);
  385. void FixHoleLinkage(OutRec &outrec);
  386. bool JoinPoints(Join *j, OutRec* outRec1, OutRec* outRec2);
  387. bool JoinHorz(OutPt* op1, OutPt* op1b, OutPt* op2, OutPt* op2b, const IntPoint &Pt, bool DiscardLeft);
  388. void JoinCommonEdges();
  389. void DoSimplePolygons();
  390. void FixupFirstLefts1(OutRec* OldOutRec, OutRec* NewOutRec) const;
  391. void FixupFirstLefts2(OutRec* OldOutRec, OutRec* NewOutRec) const;
  392. #ifdef use_xyz
  393. void SetZ(IntPoint& pt, TEdge& e1, TEdge& e2);
  394. #endif
  395. };
  396. //------------------------------------------------------------------------------
  397. class ClipperOffset
  398. {
  399. public:
  400. ClipperOffset(double miterLimit = 2.0, double roundPrecision = 0.25, double shortestEdgeLength = 0.) :
  401. MiterLimit(miterLimit), ArcTolerance(roundPrecision), ShortestEdgeLength(shortestEdgeLength), m_lowest(-1, 0) {}
  402. ~ClipperOffset() { Clear(); }
  403. void AddPath(const Path& path, JoinType joinType, EndType endType);
  404. void AddPaths(const Paths& paths, JoinType joinType, EndType endType);
  405. void Execute(Paths& solution, double delta);
  406. void Execute(PolyTree& solution, double delta);
  407. void Clear();
  408. double MiterLimit;
  409. double ArcTolerance;
  410. double ShortestEdgeLength;
  411. private:
  412. Paths m_destPolys;
  413. Path m_srcPoly;
  414. Path m_destPoly;
  415. std::vector<DoublePoint> m_normals;
  416. double m_delta, m_sinA, m_sin, m_cos;
  417. double m_miterLim, m_StepsPerRad;
  418. IntPoint m_lowest;
  419. PolyNode m_polyNodes;
  420. void FixOrientations();
  421. void DoOffset(double delta);
  422. void OffsetPoint(int j, int& k, JoinType jointype);
  423. void DoSquare(int j, int k);
  424. void DoMiter(int j, int k, double r);
  425. void DoRound(int j, int k);
  426. };
  427. //------------------------------------------------------------------------------
  428. class clipperException : public std::exception
  429. {
  430. public:
  431. clipperException(const char* description): m_descr(description) {}
  432. virtual ~clipperException() throw() {}
  433. virtual const char* what() const throw() {return m_descr.c_str();}
  434. private:
  435. std::string m_descr;
  436. };
  437. //------------------------------------------------------------------------------
  438. } //ClipperLib namespace
  439. #endif //clipper_hpp