1 /*
2     SPDX-FileCopyrightText: 2010-2017 Angus Johnson <http://www.angusj.com>
3     SPDX-License-Identifier: MIT
4 
5     Attributions:
6     The code in this library is an extension of Bala Vatti's clipping algorithm:
7     "A generic solution to polygon clipping"
8     Communications of the ACM, Vol 35, Issue 7 (July 1992) pp 56-63.
9     http://portal.acm.org/citation.cfm?id=129906
10 
11     Computer graphics and geometric modeling: implementation and algorithms
12     By Max K. Agoston
13     Springer; 1 edition (January 4, 2005)
14     https://books.google.com/books?q=vatti+clipping+agoston
15 
16     See also:
17     "Polygon Offsetting by Computing Winding Numbers"
18     Paper no. DETC2005-85513 pp. 565-575
19     ASME 2005 International Design Engineering Technical Conferences
20     and Computers and Information in Engineering Conference (IDETC/CIE2005)
21     September 24-28, 2005 , Long Beach, California, USA
22     https://www.me.berkeley.edu/~mcmains/pubs/DAC05OffsetPolygon.pdf
23 
24 */
25 
26 #ifndef clipper_hpp
27 #define clipper_hpp
28 
29 #define CLIPPER_VERSION "6.4.2"
30 
31 //use_int32: When enabled 32bit ints are used instead of 64bit ints. This
32 //improve performance but coordinate values are limited to the range +/- 46340
33 //#define use_int32
34 
35 //use_xyz: adds a Z member to IntPoint. Adds a minor cost to performance.
36 //#define use_xyz
37 
38 //use_lines: Enables line clipping. Adds a very minor cost to performance.
39 #define use_lines
40 
41 //use_deprecated: Enables temporary support for the obsolete functions
42 //#define use_deprecated
43 
44 #include <vector>
45 #include <list>
46 #include <set>
47 #include <stdexcept>
48 #include <cstring>
49 #include <cstdlib>
50 #include <ostream>
51 #include <functional>
52 #include <queue>
53 
54 namespace ClipperLib {
55 
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 https://glprogramming.com/red/chapter11.html
62 enum PolyFillType { pftEvenOdd, pftNonZero, pftPositive, pftNegative };
63 
64 #ifdef use_int32
65   typedef int cInt;
66   static cInt const loRange = 0x7FFF;
67   static cInt const hiRange = 0x7FFF;
68 #else
69   using cInt = long long;
70   static cInt const loRange = 0x3FFFFFFF;
71   static cInt const hiRange = 0x3FFFFFFFFFFFFFFFLL;
72   using long64 = long long;     //used by Int128 class
73   using ulong64 = unsigned long long;
74 
75 #endif
76 
77 struct IntPoint {
78   cInt X;
79   cInt Y;
80 #ifdef use_xyz
81   cInt Z;
IntPointClipperLib::IntPoint82   IntPoint(cInt x = 0, cInt y = 0, cInt z = 0): X(x), Y(y), Z(z) {};
83 #else
IntPointClipperLib::IntPoint84   IntPoint(cInt x = 0, cInt y = 0): X(x), Y(y) {};
85 #endif
86 
operator ==(const IntPoint & a,const IntPoint & b)87   friend inline bool operator== (const IntPoint& a, const IntPoint& b)
88   {
89     return a.X == b.X && a.Y == b.Y;
90   }
operator !=(const IntPoint & a,const IntPoint & b)91   friend inline bool operator!= (const IntPoint& a, const IntPoint& b)
92   {
93     return a.X != b.X  || a.Y != b.Y;
94   }
95 };
96 //------------------------------------------------------------------------------
97 
98 using Path = std::vector<IntPoint>;
99 using Paths = std::vector<Path>;
100 
operator <<(Path & poly,const IntPoint & p)101 inline Path& operator <<(Path& poly, const IntPoint& p) {poly.push_back(p); return poly;}
operator <<(Paths & polys,const Path & p)102 inline Paths& operator <<(Paths& polys, const Path& p) {polys.push_back(p); return polys;}
103 
104 std::ostream& operator <<(std::ostream &s, const IntPoint &p);
105 std::ostream& operator <<(std::ostream &s, const Path &p);
106 std::ostream& operator <<(std::ostream &s, const Paths &p);
107 
108 struct DoublePoint
109 {
110   double X;
111   double Y;
DoublePointClipperLib::DoublePoint112   DoublePoint(double x = 0, double y = 0) : X(x), Y(y) {}
DoublePointClipperLib::DoublePoint113   DoublePoint(IntPoint ip) : X((double)ip.X), Y((double)ip.Y) {}
114 };
115 //------------------------------------------------------------------------------
116 
117 #ifdef use_xyz
118 typedef void (*ZFillCallback)(IntPoint& e1bot, IntPoint& e1top, IntPoint& e2bot, IntPoint& e2top, IntPoint& pt);
119 #endif
120 
121 enum InitOptions {ioReverseSolution = 1, ioStrictlySimple = 2, ioPreserveCollinear = 4};
122 enum JoinType {jtSquare, jtRound, jtMiter};
123 enum EndType {etClosedPolygon, etClosedLine, etOpenButt, etOpenSquare, etOpenRound};
124 
125 class PolyNode;
126 using PolyNodes = std::vector<PolyNode *>;
127 
128 class PolyNode
129 {
130 public:
131     PolyNode();
~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     unsigned Index; //node index in Parent.Childs
142     bool m_IsOpen;
143     JoinType m_jointype;
144     EndType m_endtype;
145     PolyNode* GetNextSiblingUp() const;
146     void AddChild(PolyNode& child);
147     friend class Clipper; //to access Index
148     friend class ClipperOffset;
149 };
150 
151 class PolyTree: public PolyNode
152 {
153 public:
~PolyTree()154     ~PolyTree() override{Clear();};
155     PolyNode* GetFirst() const;
156     void Clear();
157     int Total() const;
158 private:
159     PolyNodes AllNodes;
160     friend class Clipper; //to access AllNodes
161 };
162 
163 bool Orientation(const Path &poly);
164 double Area(const Path &poly);
165 int PointInPolygon(const IntPoint &pt, const Path &path);
166 
167 void SimplifyPolygon(const Path &in_poly, Paths &out_polys, PolyFillType fillType = pftEvenOdd);
168 void SimplifyPolygons(const Paths &in_polys, Paths &out_polys, PolyFillType fillType = pftEvenOdd);
169 void SimplifyPolygons(Paths &polys, PolyFillType fillType = pftEvenOdd);
170 
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, double distance = 1.415);
174 void CleanPolygons(Paths& polys, double distance = 1.415);
175 
176 void MinkowskiSum(const Path& pattern, const Path& path, Paths& solution, bool pathIsClosed);
177 void MinkowskiSum(const Path& pattern, const Paths& paths, Paths& solution, bool pathIsClosed);
178 void MinkowskiDiff(const Path& poly1, const Path& poly2, Paths& solution);
179 
180 void PolyTreeToPaths(const PolyTree& polytree, Paths& paths);
181 void ClosedPathsFromPolyTree(const PolyTree& polytree, Paths& paths);
182 void OpenPathsFromPolyTree(PolyTree& polytree, Paths& paths);
183 
184 void ReversePath(Path& p);
185 void ReversePaths(Paths& p);
186 
187 struct IntRect { cInt left; cInt top; cInt right; cInt bottom; };
188 
189 //enums that are used internally ...
190 enum EdgeSide { esLeft = 1, esRight = 2};
191 
192 //forward declarations (for stuff used internally) ...
193 struct TEdge;
194 struct IntersectNode;
195 struct LocalMinimum;
196 struct OutPt;
197 struct OutRec;
198 struct Join;
199 
200 using PolyOutList = std::vector<OutRec *>;
201 using EdgeList = std::vector<TEdge *>;
202 using JoinList = std::vector<Join *>;
203 using IntersectList = std::vector<IntersectNode *>;
204 
205 //------------------------------------------------------------------------------
206 
207 //ClipperBase is the ancestor to the Clipper class. It should not be
208 //instantiated directly. This class simply abstracts the conversion of sets of
209 //polygon coordinates into edge objects that are stored in a LocalMinima list.
210 class ClipperBase
211 {
212 public:
213   ClipperBase();
214   virtual ~ClipperBase();
215   virtual bool AddPath(const Path &pg, PolyType PolyTyp, bool Closed);
216   bool AddPaths(const Paths &ppg, PolyType PolyTyp, bool Closed);
217   virtual void Clear();
218   IntRect GetBounds();
PreserveCollinear()219   bool PreserveCollinear() {return m_PreserveCollinear;};
PreserveCollinear(bool value)220   void PreserveCollinear(bool value) {m_PreserveCollinear = value;};
221 protected:
222   void DisposeLocalMinimaList();
223   TEdge* AddBoundsToLML(TEdge *e, bool IsClosed);
224   virtual void Reset();
225   TEdge* ProcessBound(TEdge* E, bool IsClockwise);
226   void InsertScanbeam(const cInt Y);
227   bool PopScanbeam(cInt &Y);
228   bool LocalMinimaPending();
229   bool PopLocalMinima(cInt Y, const LocalMinimum *&locMin);
230   OutRec* CreateOutRec();
231   void DisposeAllOutRecs();
232   void DisposeOutRec(PolyOutList::size_type index);
233   void SwapPositionsInAEL(TEdge *edge1, TEdge *edge2);
234   void DeleteFromAEL(TEdge *e);
235   void UpdateEdgeIntoAEL(TEdge *&e);
236 
237   using MinimaList = std::vector<LocalMinimum>;
238   MinimaList::iterator m_CurrentLM;
239   MinimaList           m_MinimaList;
240 
241   bool              m_UseFullRange;
242   EdgeList          m_edges;
243   bool              m_PreserveCollinear;
244   bool              m_HasOpenPaths;
245   PolyOutList       m_PolyOuts;
246   TEdge           *m_ActiveEdges;
247 
248   using ScanbeamList = std::priority_queue<cInt>;
249   ScanbeamList     m_Scanbeam;
250 };
251 //------------------------------------------------------------------------------
252 
253 class Clipper : public virtual ClipperBase
254 {
255 public:
256   Clipper(int initOptions = 0);
257   bool Execute(ClipType clipType,
258       Paths &solution,
259       PolyFillType fillType = pftEvenOdd);
260   bool Execute(ClipType clipType,
261       Paths &solution,
262       PolyFillType subjFillType,
263       PolyFillType clipFillType);
264   bool Execute(ClipType clipType,
265       PolyTree &polytree,
266       PolyFillType fillType = pftEvenOdd);
267   bool Execute(ClipType clipType,
268       PolyTree &polytree,
269       PolyFillType subjFillType,
270       PolyFillType clipFillType);
ReverseSolution()271   bool ReverseSolution() { return m_ReverseOutput; };
ReverseSolution(bool value)272   void ReverseSolution(bool value) {m_ReverseOutput = value;};
StrictlySimple()273   bool StrictlySimple() {return m_StrictSimple;};
StrictlySimple(bool value)274   void StrictlySimple(bool value) {m_StrictSimple = value;};
275   //set the callback function for z value filling on intersections (otherwise Z is 0)
276 #ifdef use_xyz
277   void ZFillFunction(ZFillCallback zFillFunc);
278 #endif
279 protected:
280   virtual bool ExecuteInternal();
281 private:
282   JoinList         m_Joins;
283   JoinList         m_GhostJoins;
284   IntersectList    m_IntersectList;
285   ClipType         m_ClipType;
286   using MaximaList = std::list<cInt>;
287   MaximaList       m_Maxima;
288   TEdge           *m_SortedEdges;
289   bool             m_ExecuteLocked;
290   PolyFillType     m_ClipFillType;
291   PolyFillType     m_SubjFillType;
292   bool             m_ReverseOutput;
293   bool             m_UsingPolyTree;
294   bool             m_StrictSimple;
295 #ifdef use_xyz
296   ZFillCallback   m_ZFill; //custom callback
297 #endif
298   void SetWindingCount(TEdge& edge);
299   bool IsEvenOddFillType(const TEdge& edge) const;
300   bool IsEvenOddAltFillType(const TEdge& edge) const;
301   void InsertLocalMinimaIntoAEL(const cInt botY);
302   void InsertEdgeIntoAEL(TEdge *edge, TEdge* startEdge);
303   void AddEdgeToSEL(TEdge *edge);
304   bool PopEdgeFromSEL(TEdge *&edge);
305   void CopyAELToSEL();
306   void DeleteFromSEL(TEdge *e);
307   void SwapPositionsInSEL(TEdge *edge1, TEdge *edge2);
308   bool IsContributing(const TEdge& edge) const;
309   bool IsTopHorz(const cInt XPos);
310   void DoMaxima(TEdge *e);
311   void ProcessHorizontals();
312   void ProcessHorizontal(TEdge *horzEdge);
313   void AddLocalMaxPoly(TEdge *e1, TEdge *e2, const IntPoint &pt);
314   OutPt* AddLocalMinPoly(TEdge *e1, TEdge *e2, const IntPoint &pt);
315   OutRec* GetOutRec(int idx);
316   void AppendPolygon(TEdge *e1, TEdge *e2);
317   void IntersectEdges(TEdge *e1, TEdge *e2, IntPoint &pt);
318   OutPt* AddOutPt(TEdge *e, const IntPoint &pt);
319   OutPt* GetLastOutPt(TEdge *e);
320   bool ProcessIntersections(const cInt topY);
321   void BuildIntersectList(const cInt topY);
322   void ProcessIntersectList();
323   void ProcessEdgesAtTopOfScanbeam(const cInt topY);
324   void BuildResult(Paths& polys);
325   void BuildResult2(PolyTree& polytree);
326   void SetHoleState(TEdge *e, OutRec *outrec);
327   void DisposeIntersectNodes();
328   bool FixupIntersectionOrder();
329   void FixupOutPolygon(OutRec &outrec);
330   void FixupOutPolyline(OutRec &outrec);
331   bool IsHole(TEdge *e);
332   bool FindOwnerFromSplitRecs(OutRec &outRec, OutRec *&currOrfl);
333   void FixHoleLinkage(OutRec &outrec);
334   void AddJoin(OutPt *op1, OutPt *op2, const IntPoint offPt);
335   void ClearJoins();
336   void ClearGhostJoins();
337   void AddGhostJoin(OutPt *op, const IntPoint offPt);
338   bool JoinPoints(Join *j, OutRec* outRec1, OutRec* outRec2);
339   void JoinCommonEdges();
340   void DoSimplePolygons();
341   void FixupFirstLefts1(OutRec* OldOutRec, OutRec* NewOutRec);
342   void FixupFirstLefts2(OutRec* InnerOutRec, OutRec* OuterOutRec);
343   void FixupFirstLefts3(OutRec* OldOutRec, OutRec* NewOutRec);
344 #ifdef use_xyz
345   void SetZ(IntPoint& pt, TEdge& e1, TEdge& e2);
346 #endif
347 };
348 //------------------------------------------------------------------------------
349 
350 class ClipperOffset
351 {
352 public:
353   ClipperOffset(double miterLimit = 2.0, double roundPrecision = 0.25);
354   ~ClipperOffset();
355   void AddPath(const Path& path, JoinType joinType, EndType endType);
356   void AddPaths(const Paths& paths, JoinType joinType, EndType endType);
357   void Execute(Paths& solution, double delta);
358   void Execute(PolyTree& solution, double delta);
359   void Clear();
360   double MiterLimit;
361   double ArcTolerance;
362 private:
363   Paths m_destPolys;
364   Path m_srcPoly;
365   Path m_destPoly;
366   std::vector<DoublePoint> m_normals;
367   double m_delta, m_sinA, m_sin, m_cos;
368   double m_miterLim, m_StepsPerRad;
369   IntPoint m_lowest;
370   PolyNode m_polyNodes;
371 
372   void FixOrientations();
373   void DoOffset(double delta);
374   void OffsetPoint(int j, int& k, JoinType jointype);
375   void DoSquare(int j, int k);
376   void DoMiter(int j, int k, double r);
377   void DoRound(int j, int k);
378 };
379 //------------------------------------------------------------------------------
380 
381 class clipperException : public std::exception
382 {
383   public:
clipperException(const char * description)384     clipperException(const char* description): m_descr(description) {}
~clipperException()385     ~clipperException() throw() override {}
what() const386     const char* what() const throw() override {return m_descr.c_str();}
387   private:
388     std::string m_descr;
389 };
390 //------------------------------------------------------------------------------
391 
392 } //ClipperLib namespace
393 
394 #endif //clipper_hpp
395 
396 
397