clipper.hpp 15 KB

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