clipper.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. /*******************************************************************************
  2. * *
  3. * Author : Angus Johnson *
  4. * Version : 6.4.2 *
  5. * Date : 27 February 2017 *
  6. * Website : http://www.angusj.com *
  7. * Copyright : Angus Johnson 2010-2017 *
  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. #pragma once
  34. #ifndef clipper_hpp
  35. #define clipper_hpp
  36. #define CLIPPER_VERSION "6.4.2"
  37. // use_int32: When enabled 32bit ints are used instead of 64bit ints. This
  38. // improve performance but coordinate values are limited to the range +/- 46340
  39. //#define use_int32
  40. // use_xyz: adds a Z member to IntPoint. Adds a minor cost to perfomance.
  41. //#define use_xyz
  42. // use_lines: Enables line clipping. Adds a very minor cost to performance.
  43. #define use_lines
  44. // use_deprecated: Enables temporary support for the obsolete functions
  45. //#define use_deprecated
  46. #include <cstdlib>
  47. #include <cstring>
  48. #include <functional>
  49. #include <list>
  50. #include <ostream>
  51. #include <queue>
  52. #include <set>
  53. #include <stdexcept>
  54. #include <vector>
  55. namespace ClipperLib {
  56. enum ClipType { ctIntersection, ctUnion, ctDifference, ctXor };
  57. enum PolyType { ptSubject, ptClip };
  58. // By far the most widely used winding rules for polygon filling are
  59. // EvenOdd & NonZero (GDI, GDI+, XLib, OpenGL, Cairo, AGG, Quartz, SVG, Gr32)
  60. // Others rules include Positive, Negative and ABS_GTR_EQ_TWO (only in OpenGL)
  61. // see http://glprogramming.com/red/chapter11.html
  62. enum PolyFillType { pftEvenOdd, pftNonZero, pftPositive, pftNegative };
  63. #ifdef use_int32
  64. typedef int cInt;
  65. static cInt const loRange = 0x7FFF;
  66. static cInt const hiRange = 0x7FFF;
  67. #else
  68. typedef signed long long cInt;
  69. static cInt const loRange = 0x3FFFFFFF;
  70. static cInt const hiRange = 0x3FFFFFFFFFFFFFFFLL;
  71. typedef signed long long long64; // used by Int128 class
  72. typedef unsigned long long ulong64;
  73. #endif
  74. struct IntPoint {
  75. cInt X;
  76. cInt Y;
  77. #ifdef use_xyz
  78. cInt Z;
  79. IntPoint(cInt x = 0, cInt y = 0, cInt z = 0) : X(x), Y(y), Z(z){};
  80. #else
  81. IntPoint(cInt x = 0, cInt y = 0) : X(x), Y(y){};
  82. #endif
  83. friend inline bool operator==(const IntPoint &a, const IntPoint &b) {
  84. return a.X == b.X && a.Y == b.Y;
  85. }
  86. friend inline bool operator!=(const IntPoint &a, const IntPoint &b) {
  87. return a.X != b.X || a.Y != b.Y;
  88. }
  89. };
  90. //------------------------------------------------------------------------------
  91. typedef std::vector<IntPoint> Path;
  92. typedef std::vector<Path> Paths;
  93. inline Path &operator<<(Path &poly, const IntPoint &p) {
  94. poly.push_back(p);
  95. return poly;
  96. }
  97. inline Paths &operator<<(Paths &polys, const Path &p) {
  98. polys.push_back(p);
  99. return polys;
  100. }
  101. std::ostream &operator<<(std::ostream &s, const IntPoint &p);
  102. std::ostream &operator<<(std::ostream &s, const Path &p);
  103. std::ostream &operator<<(std::ostream &s, const Paths &p);
  104. struct DoublePoint {
  105. double X;
  106. double Y;
  107. DoublePoint(double x = 0, double y = 0) : X(x), Y(y) {}
  108. DoublePoint(IntPoint ip) : X((double)ip.X), Y((double)ip.Y) {}
  109. };
  110. //------------------------------------------------------------------------------
  111. #ifdef use_xyz
  112. typedef void (*ZFillCallback)(IntPoint &e1bot, IntPoint &e1top, IntPoint &e2bot,
  113. IntPoint &e2top, IntPoint &pt);
  114. #endif
  115. enum InitOptions {
  116. ioReverseSolution = 1,
  117. ioStrictlySimple = 2,
  118. ioPreserveCollinear = 4
  119. };
  120. enum JoinType { jtSquare, jtRound, jtMiter };
  121. enum EndType {
  122. etClosedPolygon,
  123. etClosedLine,
  124. etOpenButt,
  125. etOpenSquare,
  126. etOpenRound
  127. };
  128. class PolyNode;
  129. typedef std::vector<PolyNode *> PolyNodes;
  130. class PolyNode {
  131. public:
  132. PolyNode();
  133. virtual ~PolyNode(){};
  134. Path Contour;
  135. PolyNodes Childs;
  136. PolyNode *Parent;
  137. PolyNode *GetNext() const;
  138. bool IsHole() const;
  139. bool IsOpen() const;
  140. int ChildCount() const;
  141. private:
  142. // PolyNode& operator =(PolyNode& other);
  143. unsigned Index; // node index in Parent.Childs
  144. bool m_IsOpen;
  145. JoinType m_jointype;
  146. EndType m_endtype;
  147. PolyNode *GetNextSiblingUp() const;
  148. void AddChild(PolyNode &child);
  149. friend class Clipper; // to access Index
  150. friend class ClipperOffset;
  151. };
  152. class PolyTree : public PolyNode {
  153. public:
  154. ~PolyTree() { Clear(); };
  155. PolyNode *GetFirst() const;
  156. void Clear();
  157. int Total() const;
  158. private:
  159. // PolyTree& operator =(PolyTree& other);
  160. PolyNodes AllNodes;
  161. friend class Clipper; // to access AllNodes
  162. };
  163. bool Orientation(const Path &poly);
  164. double Area(const Path &poly);
  165. int PointInPolygon(const IntPoint &pt, const Path &path);
  166. void SimplifyPolygon(const Path &in_poly, Paths &out_polys,
  167. PolyFillType fillType = pftEvenOdd);
  168. void SimplifyPolygons(const Paths &in_polys, Paths &out_polys,
  169. PolyFillType fillType = pftEvenOdd);
  170. void SimplifyPolygons(Paths &polys, PolyFillType fillType = pftEvenOdd);
  171. void CleanPolygon(const Path &in_poly, Path &out_poly, double distance = 1.415);
  172. void CleanPolygon(Path &poly, double distance = 1.415);
  173. void CleanPolygons(const Paths &in_polys, Paths &out_polys,
  174. double distance = 1.415);
  175. void CleanPolygons(Paths &polys, double distance = 1.415);
  176. void MinkowskiSum(const Path &pattern, const Path &path, Paths &solution,
  177. bool pathIsClosed);
  178. void MinkowskiSum(const Path &pattern, const Paths &paths, Paths &solution,
  179. bool pathIsClosed);
  180. void MinkowskiDiff(const Path &poly1, const Path &poly2, Paths &solution);
  181. void PolyTreeToPaths(const PolyTree &polytree, Paths &paths);
  182. void ClosedPathsFromPolyTree(const PolyTree &polytree, Paths &paths);
  183. void OpenPathsFromPolyTree(PolyTree &polytree, Paths &paths);
  184. void ReversePath(Path &p);
  185. void ReversePaths(Paths &p);
  186. struct IntRect {
  187. cInt left;
  188. cInt top;
  189. cInt right;
  190. cInt bottom;
  191. };
  192. // enums that are used internally ...
  193. enum EdgeSide { esLeft = 1, esRight = 2 };
  194. // forward declarations (for stuff used internally) ...
  195. struct TEdge;
  196. struct IntersectNode;
  197. struct LocalMinimum;
  198. struct OutPt;
  199. struct OutRec;
  200. struct Join;
  201. typedef std::vector<OutRec *> PolyOutList;
  202. typedef std::vector<TEdge *> EdgeList;
  203. typedef std::vector<Join *> JoinList;
  204. typedef std::vector<IntersectNode *> IntersectList;
  205. //------------------------------------------------------------------------------
  206. // ClipperBase is the ancestor to the Clipper class. It should not be
  207. // instantiated directly. This class simply abstracts the conversion of sets of
  208. // polygon coordinates into edge objects that are stored in a LocalMinima list.
  209. class ClipperBase {
  210. public:
  211. ClipperBase();
  212. virtual ~ClipperBase();
  213. virtual bool AddPath(const Path &pg, PolyType PolyTyp, bool Closed);
  214. bool AddPaths(const Paths &ppg, PolyType PolyTyp, bool Closed);
  215. virtual void Clear();
  216. IntRect GetBounds();
  217. bool PreserveCollinear() { return m_PreserveCollinear; };
  218. void PreserveCollinear(bool value) { m_PreserveCollinear = value; };
  219. protected:
  220. void DisposeLocalMinimaList();
  221. TEdge *AddBoundsToLML(TEdge *e, bool IsClosed);
  222. virtual void Reset();
  223. TEdge *ProcessBound(TEdge *E, bool IsClockwise);
  224. void InsertScanbeam(const cInt Y);
  225. bool PopScanbeam(cInt &Y);
  226. bool LocalMinimaPending();
  227. bool PopLocalMinima(cInt Y, const LocalMinimum *&locMin);
  228. OutRec *CreateOutRec();
  229. void DisposeAllOutRecs();
  230. void DisposeOutRec(PolyOutList::size_type index);
  231. void SwapPositionsInAEL(TEdge *edge1, TEdge *edge2);
  232. void DeleteFromAEL(TEdge *e);
  233. void UpdateEdgeIntoAEL(TEdge *&e);
  234. typedef std::vector<LocalMinimum> MinimaList;
  235. MinimaList::iterator m_CurrentLM;
  236. MinimaList m_MinimaList;
  237. bool m_UseFullRange;
  238. EdgeList m_edges;
  239. bool m_PreserveCollinear;
  240. bool m_HasOpenPaths;
  241. PolyOutList m_PolyOuts;
  242. TEdge *m_ActiveEdges;
  243. typedef std::priority_queue<cInt> ScanbeamList;
  244. ScanbeamList m_Scanbeam;
  245. };
  246. //------------------------------------------------------------------------------
  247. class Clipper : public virtual ClipperBase {
  248. public:
  249. Clipper(int initOptions = 0);
  250. bool Execute(ClipType clipType, Paths &solution,
  251. PolyFillType fillType = pftEvenOdd);
  252. bool Execute(ClipType clipType, Paths &solution, PolyFillType subjFillType,
  253. PolyFillType clipFillType);
  254. bool Execute(ClipType clipType, PolyTree &polytree,
  255. PolyFillType fillType = pftEvenOdd);
  256. bool Execute(ClipType clipType, PolyTree &polytree, PolyFillType subjFillType,
  257. PolyFillType clipFillType);
  258. bool ReverseSolution() { return m_ReverseOutput; };
  259. void ReverseSolution(bool value) { m_ReverseOutput = value; };
  260. bool StrictlySimple() { return m_StrictSimple; };
  261. void StrictlySimple(bool value) { m_StrictSimple = value; };
  262. // set the callback function for z value filling on intersections (otherwise Z
  263. // is 0)
  264. #ifdef use_xyz
  265. void ZFillFunction(ZFillCallback zFillFunc);
  266. #endif
  267. protected:
  268. virtual bool ExecuteInternal();
  269. private:
  270. JoinList m_Joins;
  271. JoinList m_GhostJoins;
  272. IntersectList m_IntersectList;
  273. ClipType m_ClipType;
  274. typedef std::list<cInt> MaximaList;
  275. MaximaList m_Maxima;
  276. TEdge *m_SortedEdges;
  277. bool m_ExecuteLocked;
  278. PolyFillType m_ClipFillType;
  279. PolyFillType m_SubjFillType;
  280. bool m_ReverseOutput;
  281. bool m_UsingPolyTree;
  282. bool m_StrictSimple;
  283. #ifdef use_xyz
  284. ZFillCallback m_ZFill; // custom callback
  285. #endif
  286. void SetWindingCount(TEdge &edge);
  287. bool IsEvenOddFillType(const TEdge &edge) const;
  288. bool IsEvenOddAltFillType(const TEdge &edge) const;
  289. void InsertLocalMinimaIntoAEL(const cInt botY);
  290. void InsertEdgeIntoAEL(TEdge *edge, TEdge *startEdge);
  291. void AddEdgeToSEL(TEdge *edge);
  292. bool PopEdgeFromSEL(TEdge *&edge);
  293. void CopyAELToSEL();
  294. void DeleteFromSEL(TEdge *e);
  295. void SwapPositionsInSEL(TEdge *edge1, TEdge *edge2);
  296. bool IsContributing(const TEdge &edge) const;
  297. bool IsTopHorz(const cInt XPos);
  298. void DoMaxima(TEdge *e);
  299. void ProcessHorizontals();
  300. void ProcessHorizontal(TEdge *horzEdge);
  301. void AddLocalMaxPoly(TEdge *e1, TEdge *e2, const IntPoint &pt);
  302. OutPt *AddLocalMinPoly(TEdge *e1, TEdge *e2, const IntPoint &pt);
  303. OutRec *GetOutRec(int idx);
  304. void AppendPolygon(TEdge *e1, TEdge *e2);
  305. void IntersectEdges(TEdge *e1, TEdge *e2, IntPoint &pt);
  306. OutPt *AddOutPt(TEdge *e, const IntPoint &pt);
  307. OutPt *GetLastOutPt(TEdge *e);
  308. bool ProcessIntersections(const cInt topY);
  309. void BuildIntersectList(const cInt topY);
  310. void ProcessIntersectList();
  311. void ProcessEdgesAtTopOfScanbeam(const cInt topY);
  312. void BuildResult(Paths &polys);
  313. void BuildResult2(PolyTree &polytree);
  314. void SetHoleState(TEdge *e, OutRec *outrec);
  315. void DisposeIntersectNodes();
  316. bool FixupIntersectionOrder();
  317. void FixupOutPolygon(OutRec &outrec);
  318. void FixupOutPolyline(OutRec &outrec);
  319. bool IsHole(TEdge *e);
  320. bool FindOwnerFromSplitRecs(OutRec &outRec, OutRec *&currOrfl);
  321. void FixHoleLinkage(OutRec &outrec);
  322. void AddJoin(OutPt *op1, OutPt *op2, const IntPoint offPt);
  323. void ClearJoins();
  324. void ClearGhostJoins();
  325. void AddGhostJoin(OutPt *op, const IntPoint offPt);
  326. bool JoinPoints(Join *j, OutRec *outRec1, OutRec *outRec2);
  327. void JoinCommonEdges();
  328. void DoSimplePolygons();
  329. void FixupFirstLefts1(OutRec *OldOutRec, OutRec *NewOutRec);
  330. void FixupFirstLefts2(OutRec *InnerOutRec, OutRec *OuterOutRec);
  331. void FixupFirstLefts3(OutRec *OldOutRec, OutRec *NewOutRec);
  332. #ifdef use_xyz
  333. void SetZ(IntPoint &pt, TEdge &e1, TEdge &e2);
  334. #endif
  335. };
  336. //------------------------------------------------------------------------------
  337. class ClipperOffset {
  338. public:
  339. ClipperOffset(double miterLimit = 2.0, double roundPrecision = 0.25);
  340. ~ClipperOffset();
  341. void AddPath(const Path &path, JoinType joinType, EndType endType);
  342. void AddPaths(const Paths &paths, JoinType joinType, EndType endType);
  343. void Execute(Paths &solution, double delta);
  344. void Execute(PolyTree &solution, double delta);
  345. void Clear();
  346. double MiterLimit;
  347. double ArcTolerance;
  348. private:
  349. Paths m_destPolys;
  350. Path m_srcPoly;
  351. Path m_destPoly;
  352. std::vector<DoublePoint> m_normals;
  353. double m_delta, m_sinA, m_sin, m_cos;
  354. double m_miterLim, m_StepsPerRad;
  355. IntPoint m_lowest;
  356. PolyNode m_polyNodes;
  357. void FixOrientations();
  358. void DoOffset(double delta);
  359. void OffsetPoint(int j, int &k, JoinType jointype);
  360. void DoSquare(int j, int k);
  361. void DoMiter(int j, int k, double r);
  362. void DoRound(int j, int k);
  363. };
  364. //------------------------------------------------------------------------------
  365. class clipperException : public std::exception {
  366. public:
  367. clipperException(const char *description) : m_descr(description) {}
  368. virtual ~clipperException() throw() {}
  369. virtual const char *what() const throw() { return m_descr.c_str(); }
  370. private:
  371. std::string m_descr;
  372. };
  373. //------------------------------------------------------------------------------
  374. } // ClipperLib namespace
  375. #endif // clipper_hpp