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