clipper.h 15 KB

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