You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

455 lines
16 KiB

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