source: XIOS/trunk/extern/remap/src/clipper.cpp @ 852

Last change on this file since 852 was 688, checked in by mhnguyen, 9 years ago

Integrating remap library into XIOS

+) Change name of some files of remap library to be compatible with XIOS
+) Implement function to fill in automatically boundary longitude and latitude

Test
+) On Curie
+) test_remap correct

  • Property svn:executable set to *
File size: 136.8 KB
Line 
1/*******************************************************************************
2*                                                                              *
3* Author    :  Angus Johnson                                                   *
4* Version   :  6.2.9                                                           *
5* Date      :  16 February 2015                                                *
6* Website   :  http://www.angusj.com                                           *
7* Copyright :  Angus Johnson 2010-2015                                         *
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/*******************************************************************************
35*                                                                              *
36* This is a translation of the Delphi Clipper library and the naming style     *
37* used has retained a Delphi flavour.                                          *
38*                                                                              *
39*******************************************************************************/
40
41#include "clipper.hpp"
42#include <cmath>
43#include <vector>
44#include <algorithm>
45#include <stdexcept>
46#include <cstring>
47#include <cstdlib>
48#include <ostream>
49#include <functional>
50
51namespace ClipperLib {
52
53static double const pi = 3.141592653589793238;
54static double const two_pi = pi *2;
55static double const def_arc_tolerance = 0.25;
56
57enum Direction { dRightToLeft, dLeftToRight };
58
59static int const Unassigned = -1;  //edge not currently 'owning' a solution
60static int const Skip = -2;        //edge that would otherwise close a path
61
62#define HORIZONTAL (-1.0E+40)
63#define TOLERANCE (1.0e-20)
64#define NEAR_ZERO(val) (((val) > -TOLERANCE) && ((val) < TOLERANCE))
65
66struct TEdge {
67  IntPoint Bot;
68  IntPoint Curr;
69  IntPoint Top;
70  IntPoint Delta;
71  double Dx;
72  PolyType PolyTyp;
73  EdgeSide Side;
74  int WindDelta; //1 or -1 depending on winding direction
75  int WindCnt;
76  int WindCnt2; //winding count of the opposite polytype
77  int OutIdx;
78  TEdge *Next;
79  TEdge *Prev;
80  TEdge *NextInLML;
81  TEdge *NextInAEL;
82  TEdge *PrevInAEL;
83  TEdge *NextInSEL;
84  TEdge *PrevInSEL;
85};
86
87struct IntersectNode {
88  TEdge          *Edge1;
89  TEdge          *Edge2;
90  IntPoint        Pt;
91};
92
93struct LocalMinimum {
94  cInt          Y;
95  TEdge        *LeftBound;
96  TEdge        *RightBound;
97};
98
99struct OutPt;
100
101struct OutRec {
102  int       Idx;
103  bool      IsHole;
104  bool      IsOpen;
105  OutRec   *FirstLeft;  //see comments in clipper.pas
106  PolyNode *PolyNd;
107  OutPt    *Pts;
108  OutPt    *BottomPt;
109};
110
111struct OutPt {
112  int       Idx;
113  IntPoint  Pt;
114  OutPt    *Next;
115  OutPt    *Prev;
116};
117
118struct Join {
119  OutPt    *OutPt1;
120  OutPt    *OutPt2;
121  IntPoint  OffPt;
122};
123
124struct LocMinSorter
125{
126  inline bool operator()(const LocalMinimum& locMin1, const LocalMinimum& locMin2)
127  {
128    return locMin2.Y < locMin1.Y;
129  }
130};
131
132//------------------------------------------------------------------------------
133//------------------------------------------------------------------------------
134
135inline cInt Round(double val)
136{
137  if ((val < 0)) return static_cast<cInt>(val - 0.5); 
138  else return static_cast<cInt>(val + 0.5);
139}
140//------------------------------------------------------------------------------
141
142inline cInt Abs(cInt val)
143{
144  return val < 0 ? -val : val;
145}
146
147//------------------------------------------------------------------------------
148// PolyTree methods ...
149//------------------------------------------------------------------------------
150
151void PolyTree::Clear()
152{
153    for (PolyNodes::size_type i = 0; i < AllNodes.size(); ++i)
154      delete AllNodes[i];
155    AllNodes.resize(0); 
156    Childs.resize(0);
157}
158//------------------------------------------------------------------------------
159
160PolyNode* PolyTree::GetFirst() const
161{
162  if (!Childs.empty())
163      return Childs[0];
164  else
165      return 0;
166}
167//------------------------------------------------------------------------------
168
169int PolyTree::Total() const
170{
171  int result = (int)AllNodes.size();
172  //with negative offsets, ignore the hidden outer polygon ...
173  if (result > 0 && Childs[0] != AllNodes[0]) result--;
174  return result;
175}
176
177//------------------------------------------------------------------------------
178// PolyNode methods ...
179//------------------------------------------------------------------------------
180
181PolyNode::PolyNode(): Childs(), Parent(0), Index(0), m_IsOpen(false)
182{
183}
184//------------------------------------------------------------------------------
185
186int PolyNode::ChildCount() const
187{
188  return (int)Childs.size();
189}
190//------------------------------------------------------------------------------
191
192void PolyNode::AddChild(PolyNode& child)
193{
194  unsigned cnt = (unsigned)Childs.size();
195  Childs.push_back(&child);
196  child.Parent = this;
197  child.Index = cnt;
198}
199//------------------------------------------------------------------------------
200
201PolyNode* PolyNode::GetNext() const
202{ 
203  if (!Childs.empty()) 
204      return Childs[0]; 
205  else
206      return GetNextSiblingUp();   
207} 
208//------------------------------------------------------------------------------
209
210PolyNode* PolyNode::GetNextSiblingUp() const
211{ 
212  if (!Parent) //protects against PolyTree.GetNextSiblingUp()
213      return 0;
214  else if (Index == Parent->Childs.size() - 1)
215      return Parent->GetNextSiblingUp();
216  else
217      return Parent->Childs[Index + 1];
218} 
219//------------------------------------------------------------------------------
220
221bool PolyNode::IsHole() const
222{ 
223  bool result = true;
224  PolyNode* node = Parent;
225  while (node)
226  {
227      result = !result;
228      node = node->Parent;
229  }
230  return result;
231} 
232//------------------------------------------------------------------------------
233
234bool PolyNode::IsOpen() const
235{ 
236  return m_IsOpen;
237} 
238//------------------------------------------------------------------------------
239
240#ifndef use_int32
241
242//------------------------------------------------------------------------------
243// Int128 class (enables safe math on signed 64bit integers)
244// eg Int128 val1((long64)9223372036854775807); //ie 2^63 -1
245//    Int128 val2((long64)9223372036854775807);
246//    Int128 val3 = val1 * val2;
247//    val3.AsString => "85070591730234615847396907784232501249" (8.5e+37)
248//------------------------------------------------------------------------------
249
250class Int128
251{
252  public:
253    ulong64 lo;
254    long64 hi;
255
256    Int128(long64 _lo = 0)
257    {
258      lo = (ulong64)_lo;   
259      if (_lo < 0)  hi = -1; else hi = 0; 
260    }
261
262
263    Int128(const Int128 &val): lo(val.lo), hi(val.hi){}
264
265    Int128(const long64& _hi, const ulong64& _lo): lo(_lo), hi(_hi){}
266   
267    Int128& operator = (const long64 &val)
268    {
269      lo = (ulong64)val;
270      if (val < 0) hi = -1; else hi = 0;
271      return *this;
272    }
273
274    bool operator == (const Int128 &val) const
275      {return (hi == val.hi && lo == val.lo);}
276
277    bool operator != (const Int128 &val) const
278      { return !(*this == val);}
279
280    bool operator > (const Int128 &val) const
281    {
282      if (hi != val.hi)
283        return hi > val.hi;
284      else
285        return lo > val.lo;
286    }
287
288    bool operator < (const Int128 &val) const
289    {
290      if (hi != val.hi)
291        return hi < val.hi;
292      else
293        return lo < val.lo;
294    }
295
296    bool operator >= (const Int128 &val) const
297      { return !(*this < val);}
298
299    bool operator <= (const Int128 &val) const
300      { return !(*this > val);}
301
302    Int128& operator += (const Int128 &rhs)
303    {
304      hi += rhs.hi;
305      lo += rhs.lo;
306      if (lo < rhs.lo) hi++;
307      return *this;
308    }
309
310    Int128 operator + (const Int128 &rhs) const
311    {
312      Int128 result(*this);
313      result+= rhs;
314      return result;
315    }
316
317    Int128& operator -= (const Int128 &rhs)
318    {
319      *this += -rhs;
320      return *this;
321    }
322
323    Int128 operator - (const Int128 &rhs) const
324    {
325      Int128 result(*this);
326      result -= rhs;
327      return result;
328    }
329
330    Int128 operator-() const //unary negation
331    {
332      if (lo == 0)
333        return Int128(-hi, 0);
334      else
335        return Int128(~hi, ~lo + 1);
336    }
337
338    operator double() const
339    {
340      const double shift64 = 18446744073709551616.0; //2^64
341      if (hi < 0)
342      {
343        if (lo == 0) return (double)hi * shift64;
344        else return -(double)(~lo + ~hi * shift64);
345      }
346      else
347        return (double)(lo + hi * shift64);
348    }
349
350};
351//------------------------------------------------------------------------------
352
353Int128 Int128Mul (long64 lhs, long64 rhs)
354{
355  bool negate = (lhs < 0) != (rhs < 0);
356
357  if (lhs < 0) lhs = -lhs;
358  ulong64 int1Hi = ulong64(lhs) >> 32;
359  ulong64 int1Lo = ulong64(lhs & 0xFFFFFFFF);
360
361  if (rhs < 0) rhs = -rhs;
362  ulong64 int2Hi = ulong64(rhs) >> 32;
363  ulong64 int2Lo = ulong64(rhs & 0xFFFFFFFF);
364
365  //nb: see comments in clipper.pas
366  ulong64 a = int1Hi * int2Hi;
367  ulong64 b = int1Lo * int2Lo;
368  ulong64 c = int1Hi * int2Lo + int1Lo * int2Hi;
369
370  Int128 tmp;
371  tmp.hi = long64(a + (c >> 32));
372  tmp.lo = long64(c << 32);
373  tmp.lo += long64(b);
374  if (tmp.lo < b) tmp.hi++;
375  if (negate) tmp = -tmp;
376  return tmp;
377};
378#endif
379
380//------------------------------------------------------------------------------
381// Miscellaneous global functions
382//------------------------------------------------------------------------------
383
384bool Orientation(const Path &poly)
385{
386    return Area(poly) >= 0;
387}
388//------------------------------------------------------------------------------
389
390double Area(const Path &poly)
391{
392  int size = (int)poly.size();
393  if (size < 3) return 0;
394
395  double a = 0;
396  for (int i = 0, j = size -1; i < size; ++i)
397  {
398    a += ((double)poly[j].X + poly[i].X) * ((double)poly[j].Y - poly[i].Y);
399    j = i;
400  }
401  return -a * 0.5;
402}
403//------------------------------------------------------------------------------
404
405double Area(const OutRec &outRec)
406{
407  OutPt *op = outRec.Pts;
408  if (!op) return 0;
409  double a = 0;
410  do {
411    a +=  (double)(op->Prev->Pt.X + op->Pt.X) * (double)(op->Prev->Pt.Y - op->Pt.Y);
412    op = op->Next;
413  } while (op != outRec.Pts);
414  return a * 0.5;
415}
416//------------------------------------------------------------------------------
417
418bool PointIsVertex(const IntPoint &Pt, OutPt *pp)
419{
420  OutPt *pp2 = pp;
421  do
422  {
423    if (pp2->Pt == Pt) return true;
424    pp2 = pp2->Next;
425  }
426  while (pp2 != pp);
427  return false;
428}
429//------------------------------------------------------------------------------
430
431//See "The Point in Polygon Problem for Arbitrary Polygons" by Hormann & Agathos
432//http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.88.5498&rep=rep1&type=pdf
433int PointInPolygon(const IntPoint &pt, const Path &path)
434{
435  //returns 0 if false, +1 if true, -1 if pt ON polygon boundary
436  int result = 0;
437  size_t cnt = path.size();
438  if (cnt < 3) return 0;
439  IntPoint ip = path[0];
440  for(size_t i = 1; i <= cnt; ++i)
441  {
442    IntPoint ipNext = (i == cnt ? path[0] : path[i]);
443    if (ipNext.Y == pt.Y)
444    {
445        if ((ipNext.X == pt.X) || (ip.Y == pt.Y && 
446          ((ipNext.X > pt.X) == (ip.X < pt.X)))) return -1;
447    }
448    if ((ip.Y < pt.Y) != (ipNext.Y < pt.Y))
449    {
450      if (ip.X >= pt.X)
451      {
452        if (ipNext.X > pt.X) result = 1 - result;
453        else
454        {
455          double d = (double)(ip.X - pt.X) * (ipNext.Y - pt.Y) - 
456            (double)(ipNext.X - pt.X) * (ip.Y - pt.Y);
457          if (!d) return -1;
458          if ((d > 0) == (ipNext.Y > ip.Y)) result = 1 - result;
459        }
460      } else
461      {
462        if (ipNext.X > pt.X)
463        {
464          double d = (double)(ip.X - pt.X) * (ipNext.Y - pt.Y) - 
465            (double)(ipNext.X - pt.X) * (ip.Y - pt.Y);
466          if (!d) return -1;
467          if ((d > 0) == (ipNext.Y > ip.Y)) result = 1 - result;
468        }
469      }
470    }
471    ip = ipNext;
472  } 
473  return result;
474}
475//------------------------------------------------------------------------------
476
477int PointInPolygon (const IntPoint &pt, OutPt *op)
478{
479  //returns 0 if false, +1 if true, -1 if pt ON polygon boundary
480  int result = 0;
481  OutPt* startOp = op;
482  for(;;)
483  {
484    if (op->Next->Pt.Y == pt.Y)
485    {
486        if ((op->Next->Pt.X == pt.X) || (op->Pt.Y == pt.Y && 
487          ((op->Next->Pt.X > pt.X) == (op->Pt.X < pt.X)))) return -1;
488    }
489    if ((op->Pt.Y < pt.Y) != (op->Next->Pt.Y < pt.Y))
490    {
491      if (op->Pt.X >= pt.X)
492      {
493        if (op->Next->Pt.X > pt.X) result = 1 - result;
494        else
495        {
496          double d = (double)(op->Pt.X - pt.X) * (op->Next->Pt.Y - pt.Y) - 
497            (double)(op->Next->Pt.X - pt.X) * (op->Pt.Y - pt.Y);
498          if (!d) return -1;
499          if ((d > 0) == (op->Next->Pt.Y > op->Pt.Y)) result = 1 - result;
500        }
501      } else
502      {
503        if (op->Next->Pt.X > pt.X)
504        {
505          double d = (double)(op->Pt.X - pt.X) * (op->Next->Pt.Y - pt.Y) - 
506            (double)(op->Next->Pt.X - pt.X) * (op->Pt.Y - pt.Y);
507          if (!d) return -1;
508          if ((d > 0) == (op->Next->Pt.Y > op->Pt.Y)) result = 1 - result;
509        }
510      }
511    } 
512    op = op->Next;
513    if (startOp == op) break;
514  } 
515  return result;
516}
517//------------------------------------------------------------------------------
518
519bool Poly2ContainsPoly1(OutPt *OutPt1, OutPt *OutPt2)
520{
521  OutPt* op = OutPt1;
522  do
523  {
524    //nb: PointInPolygon returns 0 if false, +1 if true, -1 if pt on polygon
525    int res = PointInPolygon(op->Pt, OutPt2);
526    if (res >= 0) return res > 0;
527    op = op->Next; 
528  }
529  while (op != OutPt1);
530  return true; 
531}
532//----------------------------------------------------------------------
533
534bool SlopesEqual(const TEdge &e1, const TEdge &e2, bool UseFullInt64Range)
535{
536#ifndef use_int32
537  if (UseFullInt64Range)
538    return Int128Mul(e1.Delta.Y, e2.Delta.X) == Int128Mul(e1.Delta.X, e2.Delta.Y);
539  else 
540#endif
541    return e1.Delta.Y * e2.Delta.X == e1.Delta.X * e2.Delta.Y;
542}
543//------------------------------------------------------------------------------
544
545bool SlopesEqual(const IntPoint pt1, const IntPoint pt2,
546  const IntPoint pt3, bool UseFullInt64Range)
547{
548#ifndef use_int32
549  if (UseFullInt64Range)
550    return Int128Mul(pt1.Y-pt2.Y, pt2.X-pt3.X) == Int128Mul(pt1.X-pt2.X, pt2.Y-pt3.Y);
551  else 
552#endif
553    return (pt1.Y-pt2.Y)*(pt2.X-pt3.X) == (pt1.X-pt2.X)*(pt2.Y-pt3.Y);
554}
555//------------------------------------------------------------------------------
556
557bool SlopesEqual(const IntPoint pt1, const IntPoint pt2,
558  const IntPoint pt3, const IntPoint pt4, bool UseFullInt64Range)
559{
560#ifndef use_int32
561  if (UseFullInt64Range)
562    return Int128Mul(pt1.Y-pt2.Y, pt3.X-pt4.X) == Int128Mul(pt1.X-pt2.X, pt3.Y-pt4.Y);
563  else 
564#endif
565    return (pt1.Y-pt2.Y)*(pt3.X-pt4.X) == (pt1.X-pt2.X)*(pt3.Y-pt4.Y);
566}
567//------------------------------------------------------------------------------
568
569inline bool IsHorizontal(TEdge &e)
570{
571  return e.Delta.Y == 0;
572}
573//------------------------------------------------------------------------------
574
575inline double GetDx(const IntPoint pt1, const IntPoint pt2)
576{
577  return (pt1.Y == pt2.Y) ?
578    HORIZONTAL : (double)(pt2.X - pt1.X) / (pt2.Y - pt1.Y);
579}
580//---------------------------------------------------------------------------
581
582inline void SetDx(TEdge &e)
583{
584  e.Delta.X = (e.Top.X - e.Bot.X);
585  e.Delta.Y = (e.Top.Y - e.Bot.Y);
586
587  if (e.Delta.Y == 0) e.Dx = HORIZONTAL;
588  else e.Dx = (double)(e.Delta.X) / e.Delta.Y;
589}
590//---------------------------------------------------------------------------
591
592inline void SwapSides(TEdge &Edge1, TEdge &Edge2)
593{
594  EdgeSide Side =  Edge1.Side;
595  Edge1.Side = Edge2.Side;
596  Edge2.Side = Side;
597}
598//------------------------------------------------------------------------------
599
600inline void SwapPolyIndexes(TEdge &Edge1, TEdge &Edge2)
601{
602  int OutIdx =  Edge1.OutIdx;
603  Edge1.OutIdx = Edge2.OutIdx;
604  Edge2.OutIdx = OutIdx;
605}
606//------------------------------------------------------------------------------
607
608inline cInt TopX(TEdge &edge, const cInt currentY)
609{
610  return ( currentY == edge.Top.Y ) ?
611    edge.Top.X : edge.Bot.X + Round(edge.Dx *(currentY - edge.Bot.Y));
612}
613//------------------------------------------------------------------------------
614
615void IntersectPoint(TEdge &Edge1, TEdge &Edge2, IntPoint &ip)
616{
617#ifdef use_xyz 
618  ip.Z = 0;
619#endif
620
621  double b1, b2;
622  if (Edge1.Dx == Edge2.Dx)
623  {
624    ip.Y = Edge1.Curr.Y;
625    ip.X = TopX(Edge1, ip.Y);
626    return;
627  }
628  else if (Edge1.Delta.X == 0)
629  {
630    ip.X = Edge1.Bot.X;
631    if (IsHorizontal(Edge2))
632      ip.Y = Edge2.Bot.Y;
633    else
634    {
635      b2 = Edge2.Bot.Y - (Edge2.Bot.X / Edge2.Dx);
636      ip.Y = Round(ip.X / Edge2.Dx + b2);
637    }
638  }
639  else if (Edge2.Delta.X == 0)
640  {
641    ip.X = Edge2.Bot.X;
642    if (IsHorizontal(Edge1))
643      ip.Y = Edge1.Bot.Y;
644    else
645    {
646      b1 = Edge1.Bot.Y - (Edge1.Bot.X / Edge1.Dx);
647      ip.Y = Round(ip.X / Edge1.Dx + b1);
648    }
649  } 
650  else 
651  {
652    b1 = Edge1.Bot.X - Edge1.Bot.Y * Edge1.Dx;
653    b2 = Edge2.Bot.X - Edge2.Bot.Y * Edge2.Dx;
654    double q = (b2-b1) / (Edge1.Dx - Edge2.Dx);
655    ip.Y = Round(q);
656    if (std::fabs(Edge1.Dx) < std::fabs(Edge2.Dx))
657      ip.X = Round(Edge1.Dx * q + b1);
658    else 
659      ip.X = Round(Edge2.Dx * q + b2);
660  }
661
662  if (ip.Y < Edge1.Top.Y || ip.Y < Edge2.Top.Y) 
663  {
664    if (Edge1.Top.Y > Edge2.Top.Y)
665      ip.Y = Edge1.Top.Y;
666    else
667      ip.Y = Edge2.Top.Y;
668    if (std::fabs(Edge1.Dx) < std::fabs(Edge2.Dx))
669      ip.X = TopX(Edge1, ip.Y);
670    else
671      ip.X = TopX(Edge2, ip.Y);
672  } 
673  //finally, don't allow 'ip' to be BELOW curr.Y (ie bottom of scanbeam) ...
674  if (ip.Y > Edge1.Curr.Y)
675  {
676    ip.Y = Edge1.Curr.Y;
677    //use the more vertical edge to derive X ...
678    if (std::fabs(Edge1.Dx) > std::fabs(Edge2.Dx))
679      ip.X = TopX(Edge2, ip.Y); else
680      ip.X = TopX(Edge1, ip.Y);
681  }
682}
683//------------------------------------------------------------------------------
684
685void ReversePolyPtLinks(OutPt *pp)
686{
687  if (!pp) return;
688  OutPt *pp1, *pp2;
689  pp1 = pp;
690  do {
691  pp2 = pp1->Next;
692  pp1->Next = pp1->Prev;
693  pp1->Prev = pp2;
694  pp1 = pp2;
695  } while( pp1 != pp );
696}
697//------------------------------------------------------------------------------
698
699void DisposeOutPts(OutPt*& pp)
700{
701  if (pp == 0) return;
702    pp->Prev->Next = 0;
703  while( pp )
704  {
705    OutPt *tmpPp = pp;
706    pp = pp->Next;
707    delete tmpPp;
708  }
709}
710//------------------------------------------------------------------------------
711
712inline void InitEdge(TEdge* e, TEdge* eNext, TEdge* ePrev, const IntPoint& Pt)
713{
714  std::memset(e, 0, sizeof(TEdge));
715  e->Next = eNext;
716  e->Prev = ePrev;
717  e->Curr = Pt;
718  e->OutIdx = Unassigned;
719}
720//------------------------------------------------------------------------------
721
722void InitEdge2(TEdge& e, PolyType Pt)
723{
724  if (e.Curr.Y >= e.Next->Curr.Y)
725  {
726    e.Bot = e.Curr;
727    e.Top = e.Next->Curr;
728  } else
729  {
730    e.Top = e.Curr;
731    e.Bot = e.Next->Curr;
732  }
733  SetDx(e);
734  e.PolyTyp = Pt;
735}
736//------------------------------------------------------------------------------
737
738TEdge* RemoveEdge(TEdge* e)
739{
740  //removes e from double_linked_list (but without removing from memory)
741  e->Prev->Next = e->Next;
742  e->Next->Prev = e->Prev;
743  TEdge* result = e->Next;
744  e->Prev = 0; //flag as removed (see ClipperBase.Clear)
745  return result;
746}
747//------------------------------------------------------------------------------
748
749inline void ReverseHorizontal(TEdge &e)
750{
751  //swap horizontal edges' Top and Bottom x's so they follow the natural
752  //progression of the bounds - ie so their xbots will align with the
753  //adjoining lower edge. [Helpful in the ProcessHorizontal() method.]
754  std::swap(e.Top.X, e.Bot.X);
755#ifdef use_xyz 
756  std::swap(e.Top.Z, e.Bot.Z);
757#endif
758}
759//------------------------------------------------------------------------------
760
761void SwapPoints(IntPoint &pt1, IntPoint &pt2)
762{
763  IntPoint tmp = pt1;
764  pt1 = pt2;
765  pt2 = tmp;
766}
767//------------------------------------------------------------------------------
768
769bool GetOverlapSegment(IntPoint pt1a, IntPoint pt1b, IntPoint pt2a,
770  IntPoint pt2b, IntPoint &pt1, IntPoint &pt2)
771{
772  //precondition: segments are Collinear.
773  if (Abs(pt1a.X - pt1b.X) > Abs(pt1a.Y - pt1b.Y))
774  {
775    if (pt1a.X > pt1b.X) SwapPoints(pt1a, pt1b);
776    if (pt2a.X > pt2b.X) SwapPoints(pt2a, pt2b);
777    if (pt1a.X > pt2a.X) pt1 = pt1a; else pt1 = pt2a;
778    if (pt1b.X < pt2b.X) pt2 = pt1b; else pt2 = pt2b;
779    return pt1.X < pt2.X;
780  } else
781  {
782    if (pt1a.Y < pt1b.Y) SwapPoints(pt1a, pt1b);
783    if (pt2a.Y < pt2b.Y) SwapPoints(pt2a, pt2b);
784    if (pt1a.Y < pt2a.Y) pt1 = pt1a; else pt1 = pt2a;
785    if (pt1b.Y > pt2b.Y) pt2 = pt1b; else pt2 = pt2b;
786    return pt1.Y > pt2.Y;
787  }
788}
789//------------------------------------------------------------------------------
790
791bool FirstIsBottomPt(const OutPt* btmPt1, const OutPt* btmPt2)
792{
793  OutPt *p = btmPt1->Prev;
794  while ((p->Pt == btmPt1->Pt) && (p != btmPt1)) p = p->Prev;
795  double dx1p = std::fabs(GetDx(btmPt1->Pt, p->Pt));
796  p = btmPt1->Next;
797  while ((p->Pt == btmPt1->Pt) && (p != btmPt1)) p = p->Next;
798  double dx1n = std::fabs(GetDx(btmPt1->Pt, p->Pt));
799
800  p = btmPt2->Prev;
801  while ((p->Pt == btmPt2->Pt) && (p != btmPt2)) p = p->Prev;
802  double dx2p = std::fabs(GetDx(btmPt2->Pt, p->Pt));
803  p = btmPt2->Next;
804  while ((p->Pt == btmPt2->Pt) && (p != btmPt2)) p = p->Next;
805  double dx2n = std::fabs(GetDx(btmPt2->Pt, p->Pt));
806  return (dx1p >= dx2p && dx1p >= dx2n) || (dx1n >= dx2p && dx1n >= dx2n);
807}
808//------------------------------------------------------------------------------
809
810OutPt* GetBottomPt(OutPt *pp)
811{
812  OutPt* dups = 0;
813  OutPt* p = pp->Next;
814  while (p != pp)
815  {
816    if (p->Pt.Y > pp->Pt.Y)
817    {
818      pp = p;
819      dups = 0;
820    }
821    else if (p->Pt.Y == pp->Pt.Y && p->Pt.X <= pp->Pt.X)
822    {
823      if (p->Pt.X < pp->Pt.X)
824      {
825        dups = 0;
826        pp = p;
827      } else
828      {
829        if (p->Next != pp && p->Prev != pp) dups = p;
830      }
831    }
832    p = p->Next;
833  }
834  if (dups)
835  {
836    //there appears to be at least 2 vertices at BottomPt so ...
837    while (dups != p)
838    {
839      if (!FirstIsBottomPt(p, dups)) pp = dups;
840      dups = dups->Next;
841      while (dups->Pt != pp->Pt) dups = dups->Next;
842    }
843  }
844  return pp;
845}
846//------------------------------------------------------------------------------
847
848bool Pt2IsBetweenPt1AndPt3(const IntPoint pt1,
849  const IntPoint pt2, const IntPoint pt3)
850{
851  if ((pt1 == pt3) || (pt1 == pt2) || (pt3 == pt2))
852    return false;
853  else if (pt1.X != pt3.X)
854    return (pt2.X > pt1.X) == (pt2.X < pt3.X);
855  else
856    return (pt2.Y > pt1.Y) == (pt2.Y < pt3.Y);
857}
858//------------------------------------------------------------------------------
859
860bool HorzSegmentsOverlap(cInt seg1a, cInt seg1b, cInt seg2a, cInt seg2b)
861{
862  if (seg1a > seg1b) std::swap(seg1a, seg1b);
863  if (seg2a > seg2b) std::swap(seg2a, seg2b);
864  return (seg1a < seg2b) && (seg2a < seg1b);
865}
866
867//------------------------------------------------------------------------------
868// ClipperBase class methods ...
869//------------------------------------------------------------------------------
870
871ClipperBase::ClipperBase() //constructor
872{
873  m_CurrentLM = m_MinimaList.begin(); //begin() == end() here
874  m_UseFullRange = false;
875}
876//------------------------------------------------------------------------------
877
878ClipperBase::~ClipperBase() //destructor
879{
880  Clear();
881}
882//------------------------------------------------------------------------------
883
884void RangeTest(const IntPoint& Pt, bool& useFullRange)
885{
886  if (useFullRange)
887  {
888    if (Pt.X > hiRange || Pt.Y > hiRange || -Pt.X > hiRange || -Pt.Y > hiRange) 
889      throw "Coordinate outside allowed range";
890  }
891  else if (Pt.X > loRange|| Pt.Y > loRange || -Pt.X > loRange || -Pt.Y > loRange) 
892  {
893    useFullRange = true;
894    RangeTest(Pt, useFullRange);
895  }
896}
897//------------------------------------------------------------------------------
898
899TEdge* FindNextLocMin(TEdge* E)
900{
901  for (;;)
902  {
903    while (E->Bot != E->Prev->Bot || E->Curr == E->Top) E = E->Next;
904    if (!IsHorizontal(*E) && !IsHorizontal(*E->Prev)) break;
905    while (IsHorizontal(*E->Prev)) E = E->Prev;
906    TEdge* E2 = E;
907    while (IsHorizontal(*E)) E = E->Next;
908    if (E->Top.Y == E->Prev->Bot.Y) continue; //ie just an intermediate horz.
909    if (E2->Prev->Bot.X < E->Bot.X) E = E2;
910    break;
911  }
912  return E;
913}
914//------------------------------------------------------------------------------
915
916TEdge* ClipperBase::ProcessBound(TEdge* E, bool NextIsForward)
917{
918  TEdge *Result = E;
919  TEdge *Horz = 0;
920
921  if (E->OutIdx == Skip)
922  {
923    //if edges still remain in the current bound beyond the skip edge then
924    //create another LocMin and call ProcessBound once more
925    if (NextIsForward)
926    {
927      while (E->Top.Y == E->Next->Bot.Y) E = E->Next;
928      //don't include top horizontals when parsing a bound a second time,
929      //they will be contained in the opposite bound ...
930      while (E != Result && IsHorizontal(*E)) E = E->Prev;
931    }
932    else
933    {
934      while (E->Top.Y == E->Prev->Bot.Y) E = E->Prev;
935      while (E != Result && IsHorizontal(*E)) E = E->Next;
936    }
937
938    if (E == Result)
939    {
940      if (NextIsForward) Result = E->Next;
941      else Result = E->Prev;
942    }
943    else
944    {
945      //there are more edges in the bound beyond result starting with E
946      if (NextIsForward)
947        E = Result->Next;
948      else
949        E = Result->Prev;
950      MinimaList::value_type locMin;
951      locMin.Y = E->Bot.Y;
952      locMin.LeftBound = 0;
953      locMin.RightBound = E;
954      E->WindDelta = 0;
955      Result = ProcessBound(E, NextIsForward);
956      m_MinimaList.push_back(locMin);
957    }
958    return Result;
959  }
960
961  TEdge *EStart;
962
963  if (IsHorizontal(*E))
964  {
965    //We need to be careful with open paths because this may not be a
966    //true local minima (ie E may be following a skip edge).
967    //Also, consecutive horz. edges may start heading left before going right.
968    if (NextIsForward) 
969      EStart = E->Prev;
970    else 
971      EStart = E->Next;
972    if (IsHorizontal(*EStart)) //ie an adjoining horizontal skip edge
973      {
974        if (EStart->Bot.X != E->Bot.X && EStart->Top.X != E->Bot.X)
975          ReverseHorizontal(*E);
976      }
977      else if (EStart->Bot.X != E->Bot.X)
978        ReverseHorizontal(*E);
979  }
980 
981  EStart = E;
982  if (NextIsForward)
983  {
984    while (Result->Top.Y == Result->Next->Bot.Y && Result->Next->OutIdx != Skip)
985      Result = Result->Next;
986    if (IsHorizontal(*Result) && Result->Next->OutIdx != Skip)
987    {
988      //nb: at the top of a bound, horizontals are added to the bound
989      //only when the preceding edge attaches to the horizontal's left vertex
990      //unless a Skip edge is encountered when that becomes the top divide
991      Horz = Result;
992      while (IsHorizontal(*Horz->Prev)) Horz = Horz->Prev;
993      if (Horz->Prev->Top.X > Result->Next->Top.X) Result = Horz->Prev;
994    }
995    while (E != Result) 
996    {
997      E->NextInLML = E->Next;
998      if (IsHorizontal(*E) && E != EStart &&
999        E->Bot.X != E->Prev->Top.X) ReverseHorizontal(*E);
1000      E = E->Next;
1001    }
1002    if (IsHorizontal(*E) && E != EStart && E->Bot.X != E->Prev->Top.X) 
1003      ReverseHorizontal(*E);
1004    Result = Result->Next; //move to the edge just beyond current bound
1005  } else
1006  {
1007    while (Result->Top.Y == Result->Prev->Bot.Y && Result->Prev->OutIdx != Skip) 
1008      Result = Result->Prev;
1009    if (IsHorizontal(*Result) && Result->Prev->OutIdx != Skip)
1010    {
1011      Horz = Result;
1012      while (IsHorizontal(*Horz->Next)) Horz = Horz->Next;
1013      if (Horz->Next->Top.X == Result->Prev->Top.X ||
1014          Horz->Next->Top.X > Result->Prev->Top.X) Result = Horz->Next;
1015    }
1016
1017    while (E != Result)
1018    {
1019      E->NextInLML = E->Prev;
1020      if (IsHorizontal(*E) && E != EStart && E->Bot.X != E->Next->Top.X) 
1021        ReverseHorizontal(*E);
1022      E = E->Prev;
1023    }
1024    if (IsHorizontal(*E) && E != EStart && E->Bot.X != E->Next->Top.X) 
1025      ReverseHorizontal(*E);
1026    Result = Result->Prev; //move to the edge just beyond current bound
1027  }
1028
1029  return Result;
1030}
1031//------------------------------------------------------------------------------
1032
1033bool ClipperBase::AddPath(const Path &pg, PolyType PolyTyp, bool Closed)
1034{
1035#ifdef use_lines
1036  if (!Closed && PolyTyp == ptClip)
1037    throw clipperException("AddPath: Open paths must be subject.");
1038#else
1039  if (!Closed)
1040    throw clipperException("AddPath: Open paths have been disabled.");
1041#endif
1042
1043  int highI = (int)pg.size() -1;
1044  if (Closed) while (highI > 0 && (pg[highI] == pg[0])) --highI;
1045  while (highI > 0 && (pg[highI] == pg[highI -1])) --highI;
1046  if ((Closed && highI < 2) || (!Closed && highI < 1)) return false;
1047
1048  //create a new edge array ...
1049  TEdge *edges = new TEdge [highI +1];
1050
1051  bool IsFlat = true;
1052  //1. Basic (first) edge initialization ...
1053  try
1054  {
1055    edges[1].Curr = pg[1];
1056    RangeTest(pg[0], m_UseFullRange);
1057    RangeTest(pg[highI], m_UseFullRange);
1058    InitEdge(&edges[0], &edges[1], &edges[highI], pg[0]);
1059    InitEdge(&edges[highI], &edges[0], &edges[highI-1], pg[highI]);
1060    for (int i = highI - 1; i >= 1; --i)
1061    {
1062      RangeTest(pg[i], m_UseFullRange);
1063      InitEdge(&edges[i], &edges[i+1], &edges[i-1], pg[i]);
1064    }
1065  }
1066  catch(...)
1067  {
1068    delete [] edges;
1069    throw; //range test fails
1070  }
1071  TEdge *eStart = &edges[0];
1072
1073  //2. Remove duplicate vertices, and (when closed) collinear edges ...
1074  TEdge *E = eStart, *eLoopStop = eStart;
1075  for (;;)
1076  {
1077    //nb: allows matching start and end points when not Closed ...
1078    if (E->Curr == E->Next->Curr && (Closed || E->Next != eStart))
1079    {
1080      if (E == E->Next) break;
1081      if (E == eStart) eStart = E->Next;
1082      E = RemoveEdge(E);
1083      eLoopStop = E;
1084      continue;
1085    }
1086    if (E->Prev == E->Next) 
1087      break; //only two vertices
1088    else if (Closed &&
1089      SlopesEqual(E->Prev->Curr, E->Curr, E->Next->Curr, m_UseFullRange) && 
1090      (!m_PreserveCollinear ||
1091      !Pt2IsBetweenPt1AndPt3(E->Prev->Curr, E->Curr, E->Next->Curr)))
1092    {
1093      //Collinear edges are allowed for open paths but in closed paths
1094      //the default is to merge adjacent collinear edges into a single edge.
1095      //However, if the PreserveCollinear property is enabled, only overlapping
1096      //collinear edges (ie spikes) will be removed from closed paths.
1097      if (E == eStart) eStart = E->Next;
1098      E = RemoveEdge(E);
1099      E = E->Prev;
1100      eLoopStop = E;
1101      continue;
1102    }
1103    E = E->Next;
1104    if ((E == eLoopStop) || (!Closed && E->Next == eStart)) break;
1105  }
1106
1107  if ((!Closed && (E == E->Next)) || (Closed && (E->Prev == E->Next)))
1108  {
1109    delete [] edges;
1110    return false;
1111  }
1112
1113  if (!Closed)
1114  { 
1115    m_HasOpenPaths = true;
1116    eStart->Prev->OutIdx = Skip;
1117  }
1118
1119  //3. Do second stage of edge initialization ...
1120  E = eStart;
1121  do
1122  {
1123    InitEdge2(*E, PolyTyp);
1124    E = E->Next;
1125    if (IsFlat && E->Curr.Y != eStart->Curr.Y) IsFlat = false;
1126  }
1127  while (E != eStart);
1128
1129  //4. Finally, add edge bounds to LocalMinima list ...
1130
1131  //Totally flat paths must be handled differently when adding them
1132  //to LocalMinima list to avoid endless loops etc ...
1133  if (IsFlat) 
1134  {
1135    if (Closed) 
1136    {
1137      delete [] edges;
1138      return false;
1139    }
1140    E->Prev->OutIdx = Skip;
1141    MinimaList::value_type locMin;
1142    locMin.Y = E->Bot.Y;
1143    locMin.LeftBound = 0;
1144    locMin.RightBound = E;
1145    locMin.RightBound->Side = esRight;
1146    locMin.RightBound->WindDelta = 0;
1147    for (;;)
1148    {
1149      if (E->Bot.X != E->Prev->Top.X) ReverseHorizontal(*E);
1150      if (E->Next->OutIdx == Skip) break;
1151      E->NextInLML = E->Next;
1152      E = E->Next;
1153    }
1154    m_MinimaList.push_back(locMin);
1155    m_edges.push_back(edges);
1156          return true;
1157  }
1158
1159  m_edges.push_back(edges);
1160  bool leftBoundIsForward;
1161  TEdge* EMin = 0;
1162
1163  //workaround to avoid an endless loop in the while loop below when
1164  //open paths have matching start and end points ...
1165  if (E->Prev->Bot == E->Prev->Top) E = E->Next;
1166
1167  for (;;)
1168  {
1169    E = FindNextLocMin(E);
1170    if (E == EMin) break;
1171    else if (!EMin) EMin = E;
1172
1173    //E and E.Prev now share a local minima (left aligned if horizontal).
1174    //Compare their slopes to find which starts which bound ...
1175    MinimaList::value_type locMin;
1176    locMin.Y = E->Bot.Y;
1177    if (E->Dx < E->Prev->Dx) 
1178    {
1179      locMin.LeftBound = E->Prev;
1180      locMin.RightBound = E;
1181      leftBoundIsForward = false; //Q.nextInLML = Q.prev
1182    } else
1183    {
1184      locMin.LeftBound = E;
1185      locMin.RightBound = E->Prev;
1186      leftBoundIsForward = true; //Q.nextInLML = Q.next
1187    }
1188    locMin.LeftBound->Side = esLeft;
1189    locMin.RightBound->Side = esRight;
1190
1191    if (!Closed) locMin.LeftBound->WindDelta = 0;
1192    else if (locMin.LeftBound->Next == locMin.RightBound)
1193      locMin.LeftBound->WindDelta = -1;
1194    else locMin.LeftBound->WindDelta = 1;
1195    locMin.RightBound->WindDelta = -locMin.LeftBound->WindDelta;
1196
1197    E = ProcessBound(locMin.LeftBound, leftBoundIsForward);
1198    if (E->OutIdx == Skip) E = ProcessBound(E, leftBoundIsForward);
1199
1200    TEdge* E2 = ProcessBound(locMin.RightBound, !leftBoundIsForward);
1201    if (E2->OutIdx == Skip) E2 = ProcessBound(E2, !leftBoundIsForward);
1202
1203    if (locMin.LeftBound->OutIdx == Skip)
1204      locMin.LeftBound = 0;
1205    else if (locMin.RightBound->OutIdx == Skip)
1206      locMin.RightBound = 0;
1207    m_MinimaList.push_back(locMin);
1208    if (!leftBoundIsForward) E = E2;
1209  }
1210  return true;
1211}
1212//------------------------------------------------------------------------------
1213
1214bool ClipperBase::AddPaths(const Paths &ppg, PolyType PolyTyp, bool Closed)
1215{
1216  bool result = false;
1217  for (Paths::size_type i = 0; i < ppg.size(); ++i)
1218    if (AddPath(ppg[i], PolyTyp, Closed)) result = true;
1219  return result;
1220}
1221//------------------------------------------------------------------------------
1222
1223void ClipperBase::Clear()
1224{
1225  DisposeLocalMinimaList();
1226  for (EdgeList::size_type i = 0; i < m_edges.size(); ++i)
1227  {
1228    //for each edge array in turn, find the first used edge and
1229    //check for and remove any hiddenPts in each edge in the array.
1230    TEdge* edges = m_edges[i];
1231    delete [] edges;
1232  }
1233  m_edges.clear();
1234  m_UseFullRange = false;
1235  m_HasOpenPaths = false;
1236}
1237//------------------------------------------------------------------------------
1238
1239void ClipperBase::Reset()
1240{
1241  m_CurrentLM = m_MinimaList.begin();
1242  if (m_CurrentLM == m_MinimaList.end()) return; //ie nothing to process
1243  std::sort(m_MinimaList.begin(), m_MinimaList.end(), LocMinSorter());
1244
1245  //reset all edges ...
1246  for (MinimaList::iterator lm = m_MinimaList.begin(); lm != m_MinimaList.end(); ++lm)
1247  {
1248    TEdge* e = lm->LeftBound;
1249    if (e)
1250    {
1251      e->Curr = e->Bot;
1252      e->Side = esLeft;
1253      e->OutIdx = Unassigned;
1254    }
1255
1256    e = lm->RightBound;
1257    if (e)
1258    {
1259      e->Curr = e->Bot;
1260      e->Side = esRight;
1261      e->OutIdx = Unassigned;
1262    }
1263  }
1264}
1265//------------------------------------------------------------------------------
1266
1267void ClipperBase::DisposeLocalMinimaList()
1268{
1269  m_MinimaList.clear();
1270  m_CurrentLM = m_MinimaList.begin();
1271}
1272//------------------------------------------------------------------------------
1273
1274void ClipperBase::PopLocalMinima()
1275{
1276  if (m_CurrentLM == m_MinimaList.end()) return;
1277  ++m_CurrentLM;
1278}
1279//------------------------------------------------------------------------------
1280
1281IntRect ClipperBase::GetBounds()
1282{
1283  IntRect result;
1284  MinimaList::iterator lm = m_MinimaList.begin();
1285  if (lm == m_MinimaList.end())
1286  {
1287    result.left = result.top = result.right = result.bottom = 0;
1288    return result;
1289  }
1290  result.left = lm->LeftBound->Bot.X;
1291  result.top = lm->LeftBound->Bot.Y;
1292  result.right = lm->LeftBound->Bot.X;
1293  result.bottom = lm->LeftBound->Bot.Y;
1294  while (lm != m_MinimaList.end())
1295  {
1296    result.bottom = std::max(result.bottom, lm->LeftBound->Bot.Y);
1297    TEdge* e = lm->LeftBound;
1298    for (;;) {
1299      TEdge* bottomE = e;
1300      while (e->NextInLML)
1301      {
1302        if (e->Bot.X < result.left) result.left = e->Bot.X;
1303        if (e->Bot.X > result.right) result.right = e->Bot.X;
1304        e = e->NextInLML;
1305      }
1306      result.left = std::min(result.left, e->Bot.X);
1307      result.right = std::max(result.right, e->Bot.X);
1308      result.left = std::min(result.left, e->Top.X);
1309      result.right = std::max(result.right, e->Top.X);
1310      result.top = std::min(result.top, e->Top.Y);
1311      if (bottomE == lm->LeftBound) e = lm->RightBound;
1312      else break;
1313    }
1314    ++lm;
1315  }
1316  return result;
1317}
1318
1319//------------------------------------------------------------------------------
1320// TClipper methods ...
1321//------------------------------------------------------------------------------
1322
1323Clipper::Clipper(int initOptions) : ClipperBase() //constructor
1324{
1325  m_ActiveEdges = 0;
1326  m_SortedEdges = 0;
1327  m_ExecuteLocked = false;
1328  m_UseFullRange = false;
1329  m_ReverseOutput = ((initOptions & ioReverseSolution) != 0);
1330  m_StrictSimple = ((initOptions & ioStrictlySimple) != 0);
1331  m_PreserveCollinear = ((initOptions & ioPreserveCollinear) != 0);
1332  m_HasOpenPaths = false;
1333#ifdef use_xyz 
1334  m_ZFill = 0;
1335#endif
1336}
1337//------------------------------------------------------------------------------
1338
1339Clipper::~Clipper() //destructor
1340{
1341  Clear();
1342}
1343//------------------------------------------------------------------------------
1344
1345#ifdef use_xyz 
1346void Clipper::ZFillFunction(ZFillCallback zFillFunc)
1347{ 
1348  m_ZFill = zFillFunc;
1349}
1350//------------------------------------------------------------------------------
1351#endif
1352
1353void Clipper::Reset()
1354{
1355  ClipperBase::Reset();
1356  m_Scanbeam = ScanbeamList();
1357  m_Maxima = MaximaList();
1358  m_ActiveEdges = 0;
1359  m_SortedEdges = 0;
1360  for (MinimaList::iterator lm = m_MinimaList.begin(); lm != m_MinimaList.end(); ++lm)
1361    InsertScanbeam(lm->Y);
1362}
1363//------------------------------------------------------------------------------
1364
1365bool Clipper::Execute(ClipType clipType, Paths &solution, PolyFillType fillType)
1366{
1367    return Execute(clipType, solution, fillType, fillType);
1368}
1369//------------------------------------------------------------------------------
1370
1371bool Clipper::Execute(ClipType clipType, PolyTree &polytree, PolyFillType fillType)
1372{
1373    return Execute(clipType, polytree, fillType, fillType);
1374}
1375//------------------------------------------------------------------------------
1376
1377bool Clipper::Execute(ClipType clipType, Paths &solution,
1378    PolyFillType subjFillType, PolyFillType clipFillType)
1379{
1380  if( m_ExecuteLocked ) return false;
1381  if (m_HasOpenPaths)
1382    throw clipperException("Error: PolyTree struct is needed for open path clipping.");
1383  m_ExecuteLocked = true;
1384  solution.resize(0);
1385  m_SubjFillType = subjFillType;
1386  m_ClipFillType = clipFillType;
1387  m_ClipType = clipType;
1388  m_UsingPolyTree = false;
1389  bool succeeded = ExecuteInternal();
1390  if (succeeded) BuildResult(solution);
1391  DisposeAllOutRecs();
1392  m_ExecuteLocked = false;
1393  return succeeded;
1394}
1395//------------------------------------------------------------------------------
1396
1397bool Clipper::Execute(ClipType clipType, PolyTree& polytree,
1398    PolyFillType subjFillType, PolyFillType clipFillType)
1399{
1400  if( m_ExecuteLocked ) return false;
1401  m_ExecuteLocked = true;
1402  m_SubjFillType = subjFillType;
1403  m_ClipFillType = clipFillType;
1404  m_ClipType = clipType;
1405  m_UsingPolyTree = true;
1406  bool succeeded = ExecuteInternal();
1407  if (succeeded) BuildResult2(polytree);
1408  DisposeAllOutRecs();
1409  m_ExecuteLocked = false;
1410  return succeeded;
1411}
1412//------------------------------------------------------------------------------
1413
1414void Clipper::FixHoleLinkage(OutRec &outrec)
1415{
1416  //skip OutRecs that (a) contain outermost polygons or
1417  //(b) already have the correct owner/child linkage ...
1418  if (!outrec.FirstLeft ||               
1419      (outrec.IsHole != outrec.FirstLeft->IsHole &&
1420      outrec.FirstLeft->Pts)) return;
1421
1422  OutRec* orfl = outrec.FirstLeft;
1423  while (orfl && ((orfl->IsHole == outrec.IsHole) || !orfl->Pts))
1424      orfl = orfl->FirstLeft;
1425  outrec.FirstLeft = orfl;
1426}
1427//------------------------------------------------------------------------------
1428
1429bool Clipper::ExecuteInternal()
1430{
1431  bool succeeded = true;
1432  try {
1433    Reset();
1434    if (m_CurrentLM == m_MinimaList.end()) return true;
1435    cInt botY = PopScanbeam();
1436    do {
1437      InsertLocalMinimaIntoAEL(botY);
1438      ProcessHorizontals();
1439          ClearGhostJoins();
1440          if (m_Scanbeam.empty()) break;
1441      cInt topY = PopScanbeam();
1442      succeeded = ProcessIntersections(topY);
1443      if (!succeeded) break;
1444      ProcessEdgesAtTopOfScanbeam(topY);
1445      botY = topY;
1446    } while (!m_Scanbeam.empty() || m_CurrentLM != m_MinimaList.end());
1447  }
1448  catch(...) 
1449  {
1450    succeeded = false;
1451  }
1452
1453  if (succeeded)
1454  {
1455    //fix orientations ...
1456    for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
1457    {
1458      OutRec *outRec = m_PolyOuts[i];
1459      if (!outRec->Pts || outRec->IsOpen) continue;
1460      if ((outRec->IsHole ^ m_ReverseOutput) == (Area(*outRec) > 0))
1461        ReversePolyPtLinks(outRec->Pts);
1462    }
1463
1464    if (!m_Joins.empty()) JoinCommonEdges();
1465
1466    //unfortunately FixupOutPolygon() must be done after JoinCommonEdges()
1467    for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
1468    {
1469      OutRec *outRec = m_PolyOuts[i];
1470      if (!outRec->Pts) continue;
1471      if (outRec->IsOpen)
1472        FixupOutPolyline(*outRec);
1473      else
1474        FixupOutPolygon(*outRec);
1475    }
1476
1477    if (m_StrictSimple) DoSimplePolygons();
1478  }
1479
1480  ClearJoins();
1481  ClearGhostJoins();
1482  return succeeded;
1483}
1484//------------------------------------------------------------------------------
1485
1486void Clipper::InsertScanbeam(const cInt Y)
1487{
1488    m_Scanbeam.push(Y);
1489}
1490//------------------------------------------------------------------------------
1491
1492cInt Clipper::PopScanbeam()
1493{
1494    const cInt Y = m_Scanbeam.top();
1495    m_Scanbeam.pop();
1496    while (!m_Scanbeam.empty() && Y == m_Scanbeam.top()) { m_Scanbeam.pop(); } // Pop duplicates.
1497    return Y;
1498}
1499//------------------------------------------------------------------------------
1500
1501void Clipper::DisposeAllOutRecs(){
1502  for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
1503    DisposeOutRec(i);
1504  m_PolyOuts.clear();
1505}
1506//------------------------------------------------------------------------------
1507
1508void Clipper::DisposeOutRec(PolyOutList::size_type index)
1509{
1510  OutRec *outRec = m_PolyOuts[index];
1511  if (outRec->Pts) DisposeOutPts(outRec->Pts);
1512  delete outRec;
1513  m_PolyOuts[index] = 0;
1514}
1515//------------------------------------------------------------------------------
1516
1517void Clipper::SetWindingCount(TEdge &edge)
1518{
1519  TEdge *e = edge.PrevInAEL;
1520  //find the edge of the same polytype that immediately preceeds 'edge' in AEL
1521  while (&& ((e->PolyTyp != edge.PolyTyp) || (e->WindDelta == 0))) e = e->PrevInAEL;
1522  if (!e)
1523  {
1524    edge.WindCnt = (edge.WindDelta == 0 ? 1 : edge.WindDelta);
1525    edge.WindCnt2 = 0;
1526    e = m_ActiveEdges; //ie get ready to calc WindCnt2
1527  }   
1528  else if (edge.WindDelta == 0 && m_ClipType != ctUnion)
1529  {
1530    edge.WindCnt = 1;
1531    edge.WindCnt2 = e->WindCnt2;
1532    e = e->NextInAEL; //ie get ready to calc WindCnt2
1533  }
1534  else if (IsEvenOddFillType(edge))
1535  {
1536    //EvenOdd filling ...
1537    if (edge.WindDelta == 0)
1538    {
1539      //are we inside a subj polygon ...
1540      bool Inside = true;
1541      TEdge *e2 = e->PrevInAEL;
1542      while (e2)
1543      {
1544        if (e2->PolyTyp == e->PolyTyp && e2->WindDelta != 0) 
1545          Inside = !Inside;
1546        e2 = e2->PrevInAEL;
1547      }
1548      edge.WindCnt = (Inside ? 0 : 1);
1549    }
1550    else
1551    {
1552      edge.WindCnt = edge.WindDelta;
1553    }
1554    edge.WindCnt2 = e->WindCnt2;
1555    e = e->NextInAEL; //ie get ready to calc WindCnt2
1556  } 
1557  else
1558  {
1559    //nonZero, Positive or Negative filling ...
1560    if (e->WindCnt * e->WindDelta < 0)
1561    {
1562      //prev edge is 'decreasing' WindCount (WC) toward zero
1563      //so we're outside the previous polygon ...
1564      if (Abs(e->WindCnt) > 1)
1565      {
1566        //outside prev poly but still inside another.
1567        //when reversing direction of prev poly use the same WC
1568        if (e->WindDelta * edge.WindDelta < 0) edge.WindCnt = e->WindCnt;
1569        //otherwise continue to 'decrease' WC ...
1570        else edge.WindCnt = e->WindCnt + edge.WindDelta;
1571      } 
1572      else
1573        //now outside all polys of same polytype so set own WC ...
1574        edge.WindCnt = (edge.WindDelta == 0 ? 1 : edge.WindDelta);
1575    } else
1576    {
1577      //prev edge is 'increasing' WindCount (WC) away from zero
1578      //so we're inside the previous polygon ...
1579      if (edge.WindDelta == 0) 
1580        edge.WindCnt = (e->WindCnt < 0 ? e->WindCnt - 1 : e->WindCnt + 1);
1581      //if wind direction is reversing prev then use same WC
1582      else if (e->WindDelta * edge.WindDelta < 0) edge.WindCnt = e->WindCnt;
1583      //otherwise add to WC ...
1584      else edge.WindCnt = e->WindCnt + edge.WindDelta;
1585    }
1586    edge.WindCnt2 = e->WindCnt2;
1587    e = e->NextInAEL; //ie get ready to calc WindCnt2
1588  }
1589
1590  //update WindCnt2 ...
1591  if (IsEvenOddAltFillType(edge))
1592  {
1593    //EvenOdd filling ...
1594    while (e != &edge)
1595    {
1596      if (e->WindDelta != 0)
1597        edge.WindCnt2 = (edge.WindCnt2 == 0 ? 1 : 0);
1598      e = e->NextInAEL;
1599    }
1600  } else
1601  {
1602    //nonZero, Positive or Negative filling ...
1603    while ( e != &edge )
1604    {
1605      edge.WindCnt2 += e->WindDelta;
1606      e = e->NextInAEL;
1607    }
1608  }
1609}
1610//------------------------------------------------------------------------------
1611
1612bool Clipper::IsEvenOddFillType(const TEdge& edge) const
1613{
1614  if (edge.PolyTyp == ptSubject)
1615    return m_SubjFillType == pftEvenOdd; else
1616    return m_ClipFillType == pftEvenOdd;
1617}
1618//------------------------------------------------------------------------------
1619
1620bool Clipper::IsEvenOddAltFillType(const TEdge& edge) const
1621{
1622  if (edge.PolyTyp == ptSubject)
1623    return m_ClipFillType == pftEvenOdd; else
1624    return m_SubjFillType == pftEvenOdd;
1625}
1626//------------------------------------------------------------------------------
1627
1628bool Clipper::IsContributing(const TEdge& edge) const
1629{
1630  PolyFillType pft, pft2;
1631  if (edge.PolyTyp == ptSubject)
1632  {
1633    pft = m_SubjFillType;
1634    pft2 = m_ClipFillType;
1635  } else
1636  {
1637    pft = m_ClipFillType;
1638    pft2 = m_SubjFillType;
1639  }
1640
1641  switch(pft)
1642  {
1643    case pftEvenOdd:
1644      //return false if a subj line has been flagged as inside a subj polygon
1645      if (edge.WindDelta == 0 && edge.WindCnt != 1) return false;
1646      break;
1647    case pftNonZero:
1648      if (Abs(edge.WindCnt) != 1) return false;
1649      break;
1650    case pftPositive:
1651      if (edge.WindCnt != 1) return false;
1652      break;
1653    default: //pftNegative
1654      if (edge.WindCnt != -1) return false;
1655  }
1656
1657  switch(m_ClipType)
1658  {
1659    case ctIntersection:
1660      switch(pft2)
1661      {
1662        case pftEvenOdd:
1663        case pftNonZero:
1664          return (edge.WindCnt2 != 0);
1665        case pftPositive:
1666          return (edge.WindCnt2 > 0);
1667        default: 
1668          return (edge.WindCnt2 < 0);
1669      }
1670      break;
1671    case ctUnion:
1672      switch(pft2)
1673      {
1674        case pftEvenOdd:
1675        case pftNonZero:
1676          return (edge.WindCnt2 == 0);
1677        case pftPositive:
1678          return (edge.WindCnt2 <= 0);
1679        default: 
1680          return (edge.WindCnt2 >= 0);
1681      }
1682      break;
1683    case ctDifference:
1684      if (edge.PolyTyp == ptSubject)
1685        switch(pft2)
1686        {
1687          case pftEvenOdd:
1688          case pftNonZero:
1689            return (edge.WindCnt2 == 0);
1690          case pftPositive:
1691            return (edge.WindCnt2 <= 0);
1692          default: 
1693            return (edge.WindCnt2 >= 0);
1694        }
1695      else
1696        switch(pft2)
1697        {
1698          case pftEvenOdd:
1699          case pftNonZero:
1700            return (edge.WindCnt2 != 0);
1701          case pftPositive:
1702            return (edge.WindCnt2 > 0);
1703          default: 
1704            return (edge.WindCnt2 < 0);
1705        }
1706      break;
1707    case ctXor:
1708      if (edge.WindDelta == 0) //XOr always contributing unless open
1709        switch(pft2)
1710        {
1711          case pftEvenOdd:
1712          case pftNonZero:
1713            return (edge.WindCnt2 == 0);
1714          case pftPositive:
1715            return (edge.WindCnt2 <= 0);
1716          default: 
1717            return (edge.WindCnt2 >= 0);
1718        }
1719      else 
1720        return true;
1721      break;
1722    default:
1723      return true;
1724  }
1725}
1726//------------------------------------------------------------------------------
1727
1728OutPt* Clipper::AddLocalMinPoly(TEdge *e1, TEdge *e2, const IntPoint &Pt)
1729{
1730  OutPt* result;
1731  TEdge *e, *prevE;
1732  if (IsHorizontal(*e2) || ( e1->Dx > e2->Dx ))
1733  {
1734    result = AddOutPt(e1, Pt);
1735    e2->OutIdx = e1->OutIdx;
1736    e1->Side = esLeft;
1737    e2->Side = esRight;
1738    e = e1;
1739    if (e->PrevInAEL == e2)
1740      prevE = e2->PrevInAEL; 
1741    else
1742      prevE = e->PrevInAEL;
1743  } else
1744  {
1745    result = AddOutPt(e2, Pt);
1746    e1->OutIdx = e2->OutIdx;
1747    e1->Side = esRight;
1748    e2->Side = esLeft;
1749    e = e2;
1750    if (e->PrevInAEL == e1)
1751        prevE = e1->PrevInAEL;
1752    else
1753        prevE = e->PrevInAEL;
1754  }
1755
1756  if (prevE && prevE->OutIdx >= 0 &&
1757      (TopX(*prevE, Pt.Y) == TopX(*e, Pt.Y)) &&
1758      SlopesEqual(*e, *prevE, m_UseFullRange) &&
1759      (e->WindDelta != 0) && (prevE->WindDelta != 0))
1760  {
1761    OutPt* outPt = AddOutPt(prevE, Pt);
1762    AddJoin(result, outPt, e->Top);
1763  }
1764  return result;
1765}
1766//------------------------------------------------------------------------------
1767
1768void Clipper::AddLocalMaxPoly(TEdge *e1, TEdge *e2, const IntPoint &Pt)
1769{
1770  AddOutPt( e1, Pt );
1771  if (e2->WindDelta == 0) AddOutPt(e2, Pt);
1772  if( e1->OutIdx == e2->OutIdx )
1773  {
1774    e1->OutIdx = Unassigned;
1775    e2->OutIdx = Unassigned;
1776  }
1777  else if (e1->OutIdx < e2->OutIdx) 
1778    AppendPolygon(e1, e2); 
1779  else 
1780    AppendPolygon(e2, e1);
1781}
1782//------------------------------------------------------------------------------
1783
1784void Clipper::AddEdgeToSEL(TEdge *edge)
1785{
1786  //SEL pointers in PEdge are reused to build a list of horizontal edges.
1787  //However, we don't need to worry about order with horizontal edge processing.
1788  if( !m_SortedEdges )
1789  {
1790    m_SortedEdges = edge;
1791    edge->PrevInSEL = 0;
1792    edge->NextInSEL = 0;
1793  }
1794  else
1795  {
1796    edge->NextInSEL = m_SortedEdges;
1797    edge->PrevInSEL = 0;
1798    m_SortedEdges->PrevInSEL = edge;
1799    m_SortedEdges = edge;
1800  }
1801}
1802//------------------------------------------------------------------------------
1803
1804void Clipper::CopyAELToSEL()
1805{
1806  TEdge* e = m_ActiveEdges;
1807  m_SortedEdges = e;
1808  while ( e )
1809  {
1810    e->PrevInSEL = e->PrevInAEL;
1811    e->NextInSEL = e->NextInAEL;
1812    e = e->NextInAEL;
1813  }
1814}
1815//------------------------------------------------------------------------------
1816
1817void Clipper::AddJoin(OutPt *op1, OutPt *op2, const IntPoint OffPt)
1818{
1819  Join* j = new Join;
1820  j->OutPt1 = op1;
1821  j->OutPt2 = op2;
1822  j->OffPt = OffPt;
1823  m_Joins.push_back(j);
1824}
1825//------------------------------------------------------------------------------
1826
1827void Clipper::ClearJoins()
1828{
1829  for (JoinList::size_type i = 0; i < m_Joins.size(); i++)
1830    delete m_Joins[i];
1831  m_Joins.resize(0);
1832}
1833//------------------------------------------------------------------------------
1834
1835void Clipper::ClearGhostJoins()
1836{
1837  for (JoinList::size_type i = 0; i < m_GhostJoins.size(); i++)
1838    delete m_GhostJoins[i];
1839  m_GhostJoins.resize(0);
1840}
1841//------------------------------------------------------------------------------
1842
1843void Clipper::AddGhostJoin(OutPt *op, const IntPoint OffPt)
1844{
1845  Join* j = new Join;
1846  j->OutPt1 = op;
1847  j->OutPt2 = 0;
1848  j->OffPt = OffPt;
1849  m_GhostJoins.push_back(j);
1850}
1851//------------------------------------------------------------------------------
1852
1853void Clipper::InsertLocalMinimaIntoAEL(const cInt botY)
1854{
1855  while (m_CurrentLM != m_MinimaList.end() && (m_CurrentLM->Y == botY))
1856  {
1857    TEdge* lb = m_CurrentLM->LeftBound;
1858    TEdge* rb = m_CurrentLM->RightBound;
1859    PopLocalMinima();
1860    OutPt *Op1 = 0;
1861    if (!lb)
1862    {
1863      //nb: don't insert LB into either AEL or SEL
1864      InsertEdgeIntoAEL(rb, 0);
1865      SetWindingCount(*rb);
1866      if (IsContributing(*rb))
1867        Op1 = AddOutPt(rb, rb->Bot); 
1868    } 
1869    else if (!rb)
1870    {
1871      InsertEdgeIntoAEL(lb, 0);
1872      SetWindingCount(*lb);
1873      if (IsContributing(*lb))
1874        Op1 = AddOutPt(lb, lb->Bot);
1875      InsertScanbeam(lb->Top.Y);
1876    }
1877    else
1878    {
1879      InsertEdgeIntoAEL(lb, 0);
1880      InsertEdgeIntoAEL(rb, lb);
1881      SetWindingCount( *lb );
1882      rb->WindCnt = lb->WindCnt;
1883      rb->WindCnt2 = lb->WindCnt2;
1884      if (IsContributing(*lb))
1885        Op1 = AddLocalMinPoly(lb, rb, lb->Bot);     
1886      InsertScanbeam(lb->Top.Y);
1887    }
1888
1889     if (rb)
1890     {
1891       if(IsHorizontal(*rb)) AddEdgeToSEL(rb);
1892       else InsertScanbeam( rb->Top.Y );
1893     }
1894
1895    if (!lb || !rb) continue;
1896
1897    //if any output polygons share an edge, they'll need joining later ...
1898    if (Op1 && IsHorizontal(*rb) && 
1899      m_GhostJoins.size() > 0 && (rb->WindDelta != 0))
1900    {
1901      for (JoinList::size_type i = 0; i < m_GhostJoins.size(); ++i)
1902      {
1903        Join* jr = m_GhostJoins[i];
1904        //if the horizontal Rb and a 'ghost' horizontal overlap, then convert
1905        //the 'ghost' join to a real join ready for later ...
1906        if (HorzSegmentsOverlap(jr->OutPt1->Pt.X, jr->OffPt.X, rb->Bot.X, rb->Top.X))
1907          AddJoin(jr->OutPt1, Op1, jr->OffPt);
1908      }
1909    }
1910
1911    if (lb->OutIdx >= 0 && lb->PrevInAEL && 
1912      lb->PrevInAEL->Curr.X == lb->Bot.X &&
1913      lb->PrevInAEL->OutIdx >= 0 &&
1914      SlopesEqual(*lb->PrevInAEL, *lb, m_UseFullRange) &&
1915      (lb->WindDelta != 0) && (lb->PrevInAEL->WindDelta != 0))
1916    {
1917        OutPt *Op2 = AddOutPt(lb->PrevInAEL, lb->Bot);
1918        AddJoin(Op1, Op2, lb->Top);
1919    }
1920
1921    if(lb->NextInAEL != rb)
1922    {
1923
1924      if (rb->OutIdx >= 0 && rb->PrevInAEL->OutIdx >= 0 &&
1925        SlopesEqual(*rb->PrevInAEL, *rb, m_UseFullRange) &&
1926        (rb->WindDelta != 0) && (rb->PrevInAEL->WindDelta != 0))
1927      {
1928          OutPt *Op2 = AddOutPt(rb->PrevInAEL, rb->Bot);
1929          AddJoin(Op1, Op2, rb->Top);
1930      }
1931
1932      TEdge* e = lb->NextInAEL;
1933      if (e)
1934      {
1935        while( e != rb )
1936        {
1937          //nb: For calculating winding counts etc, IntersectEdges() assumes
1938          //that param1 will be to the Right of param2 ABOVE the intersection ...
1939          IntersectEdges(rb , e , lb->Curr); //order important here
1940          e = e->NextInAEL;
1941        }
1942      }
1943    }
1944   
1945  }
1946}
1947//------------------------------------------------------------------------------
1948
1949void Clipper::DeleteFromAEL(TEdge *e)
1950{
1951  TEdge* AelPrev = e->PrevInAEL;
1952  TEdge* AelNext = e->NextInAEL;
1953  if(  !AelPrev &&  !AelNext && (e != m_ActiveEdges) ) return; //already deleted
1954  if( AelPrev ) AelPrev->NextInAEL = AelNext;
1955  else m_ActiveEdges = AelNext;
1956  if( AelNext ) AelNext->PrevInAEL = AelPrev;
1957  e->NextInAEL = 0;
1958  e->PrevInAEL = 0;
1959}
1960//------------------------------------------------------------------------------
1961
1962void Clipper::DeleteFromSEL(TEdge *e)
1963{
1964  TEdge* SelPrev = e->PrevInSEL;
1965  TEdge* SelNext = e->NextInSEL;
1966  if( !SelPrev &&  !SelNext && (e != m_SortedEdges) ) return; //already deleted
1967  if( SelPrev ) SelPrev->NextInSEL = SelNext;
1968  else m_SortedEdges = SelNext;
1969  if( SelNext ) SelNext->PrevInSEL = SelPrev;
1970  e->NextInSEL = 0;
1971  e->PrevInSEL = 0;
1972}
1973//------------------------------------------------------------------------------
1974
1975#ifdef use_xyz
1976void Clipper::SetZ(IntPoint& pt, TEdge& e1, TEdge& e2)
1977{
1978  if (pt.Z != 0 || !m_ZFill) return;
1979  else if (pt == e1.Bot) pt.Z = e1.Bot.Z;
1980  else if (pt == e1.Top) pt.Z = e1.Top.Z;
1981  else if (pt == e2.Bot) pt.Z = e2.Bot.Z;
1982  else if (pt == e2.Top) pt.Z = e2.Top.Z;
1983  else (*m_ZFill)(e1.Bot, e1.Top, e2.Bot, e2.Top, pt); 
1984}
1985//------------------------------------------------------------------------------
1986#endif
1987
1988void Clipper::IntersectEdges(TEdge *e1, TEdge *e2, IntPoint &Pt)
1989{
1990  bool e1Contributing = ( e1->OutIdx >= 0 );
1991  bool e2Contributing = ( e2->OutIdx >= 0 );
1992
1993#ifdef use_xyz
1994        SetZ(Pt, *e1, *e2);
1995#endif
1996
1997#ifdef use_lines
1998  //if either edge is on an OPEN path ...
1999  if (e1->WindDelta == 0 || e2->WindDelta == 0)
2000  {
2001    //ignore subject-subject open path intersections UNLESS they
2002    //are both open paths, AND they are both 'contributing maximas' ...
2003        if (e1->WindDelta == 0 && e2->WindDelta == 0) return;
2004
2005    //if intersecting a subj line with a subj poly ...
2006    else if (e1->PolyTyp == e2->PolyTyp && 
2007      e1->WindDelta != e2->WindDelta && m_ClipType == ctUnion)
2008    {
2009      if (e1->WindDelta == 0)
2010      {
2011        if (e2Contributing)
2012        {
2013          AddOutPt(e1, Pt);
2014          if (e1Contributing) e1->OutIdx = Unassigned;
2015        }
2016      }
2017      else
2018      {
2019        if (e1Contributing)
2020        {
2021          AddOutPt(e2, Pt);
2022          if (e2Contributing) e2->OutIdx = Unassigned;
2023        }
2024      }
2025    }
2026    else if (e1->PolyTyp != e2->PolyTyp)
2027    {
2028      //toggle subj open path OutIdx on/off when Abs(clip.WndCnt) == 1 ...
2029      if ((e1->WindDelta == 0) && abs(e2->WindCnt) == 1 && 
2030        (m_ClipType != ctUnion || e2->WindCnt2 == 0))
2031      {
2032        AddOutPt(e1, Pt);
2033        if (e1Contributing) e1->OutIdx = Unassigned;
2034      }
2035      else if ((e2->WindDelta == 0) && (abs(e1->WindCnt) == 1) && 
2036        (m_ClipType != ctUnion || e1->WindCnt2 == 0))
2037      {
2038        AddOutPt(e2, Pt);
2039        if (e2Contributing) e2->OutIdx = Unassigned;
2040      }
2041    }
2042    return;
2043  }
2044#endif
2045
2046  //update winding counts...
2047  //assumes that e1 will be to the Right of e2 ABOVE the intersection
2048  if ( e1->PolyTyp == e2->PolyTyp )
2049  {
2050    if ( IsEvenOddFillType( *e1) )
2051    {
2052      int oldE1WindCnt = e1->WindCnt;
2053      e1->WindCnt = e2->WindCnt;
2054      e2->WindCnt = oldE1WindCnt;
2055    } else
2056    {
2057      if (e1->WindCnt + e2->WindDelta == 0 ) e1->WindCnt = -e1->WindCnt;
2058      else e1->WindCnt += e2->WindDelta;
2059      if ( e2->WindCnt - e1->WindDelta == 0 ) e2->WindCnt = -e2->WindCnt;
2060      else e2->WindCnt -= e1->WindDelta;
2061    }
2062  } else
2063  {
2064    if (!IsEvenOddFillType(*e2)) e1->WindCnt2 += e2->WindDelta;
2065    else e1->WindCnt2 = ( e1->WindCnt2 == 0 ) ? 1 : 0;
2066    if (!IsEvenOddFillType(*e1)) e2->WindCnt2 -= e1->WindDelta;
2067    else e2->WindCnt2 = ( e2->WindCnt2 == 0 ) ? 1 : 0;
2068  }
2069
2070  PolyFillType e1FillType, e2FillType, e1FillType2, e2FillType2;
2071  if (e1->PolyTyp == ptSubject)
2072  {
2073    e1FillType = m_SubjFillType;
2074    e1FillType2 = m_ClipFillType;
2075  } else
2076  {
2077    e1FillType = m_ClipFillType;
2078    e1FillType2 = m_SubjFillType;
2079  }
2080  if (e2->PolyTyp == ptSubject)
2081  {
2082    e2FillType = m_SubjFillType;
2083    e2FillType2 = m_ClipFillType;
2084  } else
2085  {
2086    e2FillType = m_ClipFillType;
2087    e2FillType2 = m_SubjFillType;
2088  }
2089
2090  cInt e1Wc, e2Wc;
2091  switch (e1FillType)
2092  {
2093    case pftPositive: e1Wc = e1->WindCnt; break;
2094    case pftNegative: e1Wc = -e1->WindCnt; break;
2095    default: e1Wc = Abs(e1->WindCnt);
2096  }
2097  switch(e2FillType)
2098  {
2099    case pftPositive: e2Wc = e2->WindCnt; break;
2100    case pftNegative: e2Wc = -e2->WindCnt; break;
2101    default: e2Wc = Abs(e2->WindCnt);
2102  }
2103
2104  if ( e1Contributing && e2Contributing )
2105  {
2106    if ((e1Wc != 0 && e1Wc != 1) || (e2Wc != 0 && e2Wc != 1) ||
2107      (e1->PolyTyp != e2->PolyTyp && m_ClipType != ctXor) )
2108    {
2109      AddLocalMaxPoly(e1, e2, Pt); 
2110    }
2111    else
2112    {
2113      AddOutPt(e1, Pt);
2114      AddOutPt(e2, Pt);
2115      SwapSides( *e1 , *e2 );
2116      SwapPolyIndexes( *e1 , *e2 );
2117    }
2118  }
2119  else if ( e1Contributing )
2120  {
2121    if (e2Wc == 0 || e2Wc == 1) 
2122    {
2123      AddOutPt(e1, Pt);
2124      SwapSides(*e1, *e2);
2125      SwapPolyIndexes(*e1, *e2);
2126    }
2127  }
2128  else if ( e2Contributing )
2129  {
2130    if (e1Wc == 0 || e1Wc == 1) 
2131    {
2132      AddOutPt(e2, Pt);
2133      SwapSides(*e1, *e2);
2134      SwapPolyIndexes(*e1, *e2);
2135    }
2136  } 
2137  else if ( (e1Wc == 0 || e1Wc == 1) && (e2Wc == 0 || e2Wc == 1))
2138  {
2139    //neither edge is currently contributing ...
2140
2141    cInt e1Wc2, e2Wc2;
2142    switch (e1FillType2)
2143    {
2144      case pftPositive: e1Wc2 = e1->WindCnt2; break;
2145      case pftNegative : e1Wc2 = -e1->WindCnt2; break;
2146      default: e1Wc2 = Abs(e1->WindCnt2);
2147    }
2148    switch (e2FillType2)
2149    {
2150      case pftPositive: e2Wc2 = e2->WindCnt2; break;
2151      case pftNegative: e2Wc2 = -e2->WindCnt2; break;
2152      default: e2Wc2 = Abs(e2->WindCnt2);
2153    }
2154
2155    if (e1->PolyTyp != e2->PolyTyp)
2156    {
2157      AddLocalMinPoly(e1, e2, Pt);
2158    }
2159    else if (e1Wc == 1 && e2Wc == 1)
2160      switch( m_ClipType ) {
2161        case ctIntersection:
2162          if (e1Wc2 > 0 && e2Wc2 > 0)
2163            AddLocalMinPoly(e1, e2, Pt);
2164          break;
2165        case ctUnion:
2166          if ( e1Wc2 <= 0 && e2Wc2 <= 0 )
2167            AddLocalMinPoly(e1, e2, Pt);
2168          break;
2169        case ctDifference:
2170          if (((e1->PolyTyp == ptClip) && (e1Wc2 > 0) && (e2Wc2 > 0)) ||
2171              ((e1->PolyTyp == ptSubject) && (e1Wc2 <= 0) && (e2Wc2 <= 0)))
2172                AddLocalMinPoly(e1, e2, Pt);
2173          break;
2174        case ctXor:
2175          AddLocalMinPoly(e1, e2, Pt);
2176      }
2177    else
2178      SwapSides( *e1, *e2 );
2179  }
2180}
2181//------------------------------------------------------------------------------
2182
2183void Clipper::SetHoleState(TEdge *e, OutRec *outrec)
2184{
2185  bool IsHole = false;
2186  TEdge *e2 = e->PrevInAEL;
2187  while (e2)
2188  {
2189    if (e2->OutIdx >= 0 && e2->WindDelta != 0)
2190    {
2191      IsHole = !IsHole;
2192      if (! outrec->FirstLeft)
2193        outrec->FirstLeft = m_PolyOuts[e2->OutIdx];
2194    }
2195    e2 = e2->PrevInAEL;
2196  }
2197  if (IsHole) outrec->IsHole = true;
2198}
2199//------------------------------------------------------------------------------
2200
2201OutRec* GetLowermostRec(OutRec *outRec1, OutRec *outRec2)
2202{
2203  //work out which polygon fragment has the correct hole state ...
2204  if (!outRec1->BottomPt) 
2205    outRec1->BottomPt = GetBottomPt(outRec1->Pts);
2206  if (!outRec2->BottomPt) 
2207    outRec2->BottomPt = GetBottomPt(outRec2->Pts);
2208  OutPt *OutPt1 = outRec1->BottomPt;
2209  OutPt *OutPt2 = outRec2->BottomPt;
2210  if (OutPt1->Pt.Y > OutPt2->Pt.Y) return outRec1;
2211  else if (OutPt1->Pt.Y < OutPt2->Pt.Y) return outRec2;
2212  else if (OutPt1->Pt.X < OutPt2->Pt.X) return outRec1;
2213  else if (OutPt1->Pt.X > OutPt2->Pt.X) return outRec2;
2214  else if (OutPt1->Next == OutPt1) return outRec2;
2215  else if (OutPt2->Next == OutPt2) return outRec1;
2216  else if (FirstIsBottomPt(OutPt1, OutPt2)) return outRec1;
2217  else return outRec2;
2218}
2219//------------------------------------------------------------------------------
2220
2221bool Param1RightOfParam2(OutRec* outRec1, OutRec* outRec2)
2222{
2223  do
2224  {
2225    outRec1 = outRec1->FirstLeft;
2226    if (outRec1 == outRec2) return true;
2227  } while (outRec1);
2228  return false;
2229}
2230//------------------------------------------------------------------------------
2231
2232OutRec* Clipper::GetOutRec(int Idx)
2233{
2234  OutRec* outrec = m_PolyOuts[Idx];
2235  while (outrec != m_PolyOuts[outrec->Idx])
2236    outrec = m_PolyOuts[outrec->Idx];
2237  return outrec;
2238}
2239//------------------------------------------------------------------------------
2240
2241void Clipper::AppendPolygon(TEdge *e1, TEdge *e2)
2242{
2243  //get the start and ends of both output polygons ...
2244  OutRec *outRec1 = m_PolyOuts[e1->OutIdx];
2245  OutRec *outRec2 = m_PolyOuts[e2->OutIdx];
2246
2247  OutRec *holeStateRec;
2248  if (Param1RightOfParam2(outRec1, outRec2)) 
2249    holeStateRec = outRec2;
2250  else if (Param1RightOfParam2(outRec2, outRec1)) 
2251    holeStateRec = outRec1;
2252  else 
2253    holeStateRec = GetLowermostRec(outRec1, outRec2);
2254
2255  //get the start and ends of both output polygons and
2256  //join e2 poly onto e1 poly and delete pointers to e2 ...
2257
2258  OutPt* p1_lft = outRec1->Pts;
2259  OutPt* p1_rt = p1_lft->Prev;
2260  OutPt* p2_lft = outRec2->Pts;
2261  OutPt* p2_rt = p2_lft->Prev;
2262
2263  EdgeSide Side;
2264  //join e2 poly onto e1 poly and delete pointers to e2 ...
2265  if(  e1->Side == esLeft )
2266  {
2267    if(  e2->Side == esLeft )
2268    {
2269      //z y x a b c
2270      ReversePolyPtLinks(p2_lft);
2271      p2_lft->Next = p1_lft;
2272      p1_lft->Prev = p2_lft;
2273      p1_rt->Next = p2_rt;
2274      p2_rt->Prev = p1_rt;
2275      outRec1->Pts = p2_rt;
2276    } else
2277    {
2278      //x y z a b c
2279      p2_rt->Next = p1_lft;
2280      p1_lft->Prev = p2_rt;
2281      p2_lft->Prev = p1_rt;
2282      p1_rt->Next = p2_lft;
2283      outRec1->Pts = p2_lft;
2284    }
2285    Side = esLeft;
2286  } else
2287  {
2288    if(  e2->Side == esRight )
2289    {
2290      //a b c z y x
2291      ReversePolyPtLinks(p2_lft);
2292      p1_rt->Next = p2_rt;
2293      p2_rt->Prev = p1_rt;
2294      p2_lft->Next = p1_lft;
2295      p1_lft->Prev = p2_lft;
2296    } else
2297    {
2298      //a b c x y z
2299      p1_rt->Next = p2_lft;
2300      p2_lft->Prev = p1_rt;
2301      p1_lft->Prev = p2_rt;
2302      p2_rt->Next = p1_lft;
2303    }
2304    Side = esRight;
2305  }
2306
2307  outRec1->BottomPt = 0;
2308  if (holeStateRec == outRec2)
2309  {
2310    if (outRec2->FirstLeft != outRec1)
2311      outRec1->FirstLeft = outRec2->FirstLeft;
2312    outRec1->IsHole = outRec2->IsHole;
2313  }
2314  outRec2->Pts = 0;
2315  outRec2->BottomPt = 0;
2316  outRec2->FirstLeft = outRec1;
2317
2318  int OKIdx = e1->OutIdx;
2319  int ObsoleteIdx = e2->OutIdx;
2320
2321  e1->OutIdx = Unassigned; //nb: safe because we only get here via AddLocalMaxPoly
2322  e2->OutIdx = Unassigned;
2323
2324  TEdge* e = m_ActiveEdges;
2325  while( e )
2326  {
2327    if( e->OutIdx == ObsoleteIdx )
2328    {
2329      e->OutIdx = OKIdx;
2330      e->Side = Side;
2331      break;
2332    }
2333    e = e->NextInAEL;
2334  }
2335
2336  outRec2->Idx = outRec1->Idx;
2337}
2338//------------------------------------------------------------------------------
2339
2340OutRec* Clipper::CreateOutRec()
2341{
2342  OutRec* result = new OutRec;
2343  result->IsHole = false;
2344  result->IsOpen = false;
2345  result->FirstLeft = 0;
2346  result->Pts = 0;
2347  result->BottomPt = 0;
2348  result->PolyNd = 0;
2349  m_PolyOuts.push_back(result);
2350  result->Idx = (int)m_PolyOuts.size()-1;
2351  return result;
2352}
2353//------------------------------------------------------------------------------
2354
2355OutPt* Clipper::AddOutPt(TEdge *e, const IntPoint &pt)
2356{
2357  if(  e->OutIdx < 0 )
2358  {
2359    OutRec *outRec = CreateOutRec();
2360    outRec->IsOpen = (e->WindDelta == 0);
2361    OutPt* newOp = new OutPt;
2362    outRec->Pts = newOp;
2363    newOp->Idx = outRec->Idx;
2364    newOp->Pt = pt;
2365    newOp->Next = newOp;
2366    newOp->Prev = newOp;
2367    if (!outRec->IsOpen)
2368      SetHoleState(e, outRec);
2369    e->OutIdx = outRec->Idx;
2370    return newOp;
2371  } else
2372  {
2373    OutRec *outRec = m_PolyOuts[e->OutIdx];
2374    //OutRec.Pts is the 'Left-most' point & OutRec.Pts.Prev is the 'Right-most'
2375    OutPt* op = outRec->Pts;
2376
2377        bool ToFront = (e->Side == esLeft);
2378        if (ToFront && (pt == op->Pt)) return op;
2379    else if (!ToFront && (pt == op->Prev->Pt)) return op->Prev;
2380
2381    OutPt* newOp = new OutPt;
2382    newOp->Idx = outRec->Idx;
2383    newOp->Pt = pt;
2384    newOp->Next = op;
2385    newOp->Prev = op->Prev;
2386    newOp->Prev->Next = newOp;
2387    op->Prev = newOp;
2388    if (ToFront) outRec->Pts = newOp;
2389    return newOp;
2390  }
2391}
2392//------------------------------------------------------------------------------
2393
2394OutPt* Clipper::GetLastOutPt(TEdge *e)
2395{
2396        OutRec *outRec = m_PolyOuts[e->OutIdx];
2397        if (e->Side == esLeft)
2398                return outRec->Pts;
2399        else
2400                return outRec->Pts->Prev;
2401}
2402//------------------------------------------------------------------------------
2403
2404void Clipper::ProcessHorizontals()
2405{
2406  TEdge* horzEdge = m_SortedEdges;
2407  while(horzEdge)
2408  {
2409    DeleteFromSEL(horzEdge);
2410    ProcessHorizontal(horzEdge);
2411    horzEdge = m_SortedEdges;
2412  }
2413}
2414//------------------------------------------------------------------------------
2415
2416inline bool IsMinima(TEdge *e)
2417{
2418  return e  && (e->Prev->NextInLML != e) && (e->Next->NextInLML != e);
2419}
2420//------------------------------------------------------------------------------
2421
2422inline bool IsMaxima(TEdge *e, const cInt Y)
2423{
2424  return e && e->Top.Y == Y && !e->NextInLML;
2425}
2426//------------------------------------------------------------------------------
2427
2428inline bool IsIntermediate(TEdge *e, const cInt Y)
2429{
2430  return e->Top.Y == Y && e->NextInLML;
2431}
2432//------------------------------------------------------------------------------
2433
2434TEdge *GetMaximaPair(TEdge *e)
2435{
2436  TEdge* result = 0;
2437  if ((e->Next->Top == e->Top) && !e->Next->NextInLML)
2438    result = e->Next;
2439  else if ((e->Prev->Top == e->Top) && !e->Prev->NextInLML)
2440    result = e->Prev;
2441
2442  if (result && (result->OutIdx == Skip ||
2443    //result is false if both NextInAEL & PrevInAEL are nil & not horizontal ...
2444    (result->NextInAEL == result->PrevInAEL && !IsHorizontal(*result))))
2445      return 0;
2446  return result;
2447}
2448//------------------------------------------------------------------------------
2449
2450void Clipper::SwapPositionsInAEL(TEdge *Edge1, TEdge *Edge2)
2451{
2452  //check that one or other edge hasn't already been removed from AEL ...
2453  if (Edge1->NextInAEL == Edge1->PrevInAEL || 
2454    Edge2->NextInAEL == Edge2->PrevInAEL) return;
2455
2456  if(  Edge1->NextInAEL == Edge2 )
2457  {
2458    TEdge* Next = Edge2->NextInAEL;
2459    if( Next ) Next->PrevInAEL = Edge1;
2460    TEdge* Prev = Edge1->PrevInAEL;
2461    if( Prev ) Prev->NextInAEL = Edge2;
2462    Edge2->PrevInAEL = Prev;
2463    Edge2->NextInAEL = Edge1;
2464    Edge1->PrevInAEL = Edge2;
2465    Edge1->NextInAEL = Next;
2466  }
2467  else if(  Edge2->NextInAEL == Edge1 )
2468  {
2469    TEdge* Next = Edge1->NextInAEL;
2470    if( Next ) Next->PrevInAEL = Edge2;
2471    TEdge* Prev = Edge2->PrevInAEL;
2472    if( Prev ) Prev->NextInAEL = Edge1;
2473    Edge1->PrevInAEL = Prev;
2474    Edge1->NextInAEL = Edge2;
2475    Edge2->PrevInAEL = Edge1;
2476    Edge2->NextInAEL = Next;
2477  }
2478  else
2479  {
2480    TEdge* Next = Edge1->NextInAEL;
2481    TEdge* Prev = Edge1->PrevInAEL;
2482    Edge1->NextInAEL = Edge2->NextInAEL;
2483    if( Edge1->NextInAEL ) Edge1->NextInAEL->PrevInAEL = Edge1;
2484    Edge1->PrevInAEL = Edge2->PrevInAEL;
2485    if( Edge1->PrevInAEL ) Edge1->PrevInAEL->NextInAEL = Edge1;
2486    Edge2->NextInAEL = Next;
2487    if( Edge2->NextInAEL ) Edge2->NextInAEL->PrevInAEL = Edge2;
2488    Edge2->PrevInAEL = Prev;
2489    if( Edge2->PrevInAEL ) Edge2->PrevInAEL->NextInAEL = Edge2;
2490  }
2491
2492  if( !Edge1->PrevInAEL ) m_ActiveEdges = Edge1;
2493  else if( !Edge2->PrevInAEL ) m_ActiveEdges = Edge2;
2494}
2495//------------------------------------------------------------------------------
2496
2497void Clipper::SwapPositionsInSEL(TEdge *Edge1, TEdge *Edge2)
2498{
2499  if(  !( Edge1->NextInSEL ) &&  !( Edge1->PrevInSEL ) ) return;
2500  if(  !( Edge2->NextInSEL ) &&  !( Edge2->PrevInSEL ) ) return;
2501
2502  if(  Edge1->NextInSEL == Edge2 )
2503  {
2504    TEdge* Next = Edge2->NextInSEL;
2505    if( Next ) Next->PrevInSEL = Edge1;
2506    TEdge* Prev = Edge1->PrevInSEL;
2507    if( Prev ) Prev->NextInSEL = Edge2;
2508    Edge2->PrevInSEL = Prev;
2509    Edge2->NextInSEL = Edge1;
2510    Edge1->PrevInSEL = Edge2;
2511    Edge1->NextInSEL = Next;
2512  }
2513  else if(  Edge2->NextInSEL == Edge1 )
2514  {
2515    TEdge* Next = Edge1->NextInSEL;
2516    if( Next ) Next->PrevInSEL = Edge2;
2517    TEdge* Prev = Edge2->PrevInSEL;
2518    if( Prev ) Prev->NextInSEL = Edge1;
2519    Edge1->PrevInSEL = Prev;
2520    Edge1->NextInSEL = Edge2;
2521    Edge2->PrevInSEL = Edge1;
2522    Edge2->NextInSEL = Next;
2523  }
2524  else
2525  {
2526    TEdge* Next = Edge1->NextInSEL;
2527    TEdge* Prev = Edge1->PrevInSEL;
2528    Edge1->NextInSEL = Edge2->NextInSEL;
2529    if( Edge1->NextInSEL ) Edge1->NextInSEL->PrevInSEL = Edge1;
2530    Edge1->PrevInSEL = Edge2->PrevInSEL;
2531    if( Edge1->PrevInSEL ) Edge1->PrevInSEL->NextInSEL = Edge1;
2532    Edge2->NextInSEL = Next;
2533    if( Edge2->NextInSEL ) Edge2->NextInSEL->PrevInSEL = Edge2;
2534    Edge2->PrevInSEL = Prev;
2535    if( Edge2->PrevInSEL ) Edge2->PrevInSEL->NextInSEL = Edge2;
2536  }
2537
2538  if( !Edge1->PrevInSEL ) m_SortedEdges = Edge1;
2539  else if( !Edge2->PrevInSEL ) m_SortedEdges = Edge2;
2540}
2541//------------------------------------------------------------------------------
2542
2543TEdge* GetNextInAEL(TEdge *e, Direction dir)
2544{
2545  return dir == dLeftToRight ? e->NextInAEL : e->PrevInAEL;
2546}
2547//------------------------------------------------------------------------------
2548
2549void GetHorzDirection(TEdge& HorzEdge, Direction& Dir, cInt& Left, cInt& Right)
2550{
2551  if (HorzEdge.Bot.X < HorzEdge.Top.X)
2552  {
2553    Left = HorzEdge.Bot.X;
2554    Right = HorzEdge.Top.X;
2555    Dir = dLeftToRight;
2556  } else
2557  {
2558    Left = HorzEdge.Top.X;
2559    Right = HorzEdge.Bot.X;
2560    Dir = dRightToLeft;
2561  }
2562}
2563//------------------------------------------------------------------------
2564
2565/*******************************************************************************
2566* Notes: Horizontal edges (HEs) at scanline intersections (ie at the Top or    *
2567* Bottom of a scanbeam) are processed as if layered. The order in which HEs    *
2568* are processed doesn't matter. HEs intersect with other HE Bot.Xs only [#]    *
2569* (or they could intersect with Top.Xs only, ie EITHER Bot.Xs OR Top.Xs),      *
2570* and with other non-horizontal edges [*]. Once these intersections are        *
2571* processed, intermediate HEs then 'promote' the Edge above (NextInLML) into   *
2572* the AEL. These 'promoted' edges may in turn intersect [%] with other HEs.    *
2573*******************************************************************************/
2574
2575void Clipper::ProcessHorizontal(TEdge *horzEdge)
2576{
2577  Direction dir;
2578  cInt horzLeft, horzRight;
2579  bool IsOpen = (horzEdge->OutIdx >= 0 && m_PolyOuts[horzEdge->OutIdx]->IsOpen);
2580
2581  GetHorzDirection(*horzEdge, dir, horzLeft, horzRight);
2582
2583  TEdge* eLastHorz = horzEdge, *eMaxPair = 0;
2584  while (eLastHorz->NextInLML && IsHorizontal(*eLastHorz->NextInLML)) 
2585    eLastHorz = eLastHorz->NextInLML;
2586  if (!eLastHorz->NextInLML)
2587    eMaxPair = GetMaximaPair(eLastHorz);
2588
2589  MaximaList::const_iterator maxIt;
2590  MaximaList::const_reverse_iterator maxRit;
2591  if (m_Maxima.size() > 0)
2592  {
2593      //get the first maxima in range (X) ...
2594      if (dir == dLeftToRight)
2595      {
2596          maxIt = m_Maxima.begin();
2597          while (maxIt != m_Maxima.end() && *maxIt <= horzEdge->Bot.X) maxIt++;
2598          if (maxIt != m_Maxima.end() && *maxIt >= eLastHorz->Top.X)
2599              maxIt = m_Maxima.end();
2600      }
2601      else
2602      {
2603          maxRit = m_Maxima.rbegin();
2604          while (maxRit != m_Maxima.rend() && *maxRit > horzEdge->Bot.X) maxRit++;
2605          if (maxRit != m_Maxima.rend() && *maxRit <= eLastHorz->Top.X)
2606              maxRit = m_Maxima.rend();
2607      }
2608  }
2609
2610  OutPt* op1 = 0;
2611
2612  for (;;) //loop through consec. horizontal edges
2613  {
2614                 
2615    bool IsLastHorz = (horzEdge == eLastHorz);
2616    TEdge* e = GetNextInAEL(horzEdge, dir);
2617    while(e)
2618    {
2619
2620        //this code block inserts extra coords into horizontal edges (in output
2621        //polygons) whereever maxima touch these horizontal edges. This helps
2622        //'simplifying' polygons (ie if the Simplify property is set).
2623        if (m_Maxima.size() > 0)
2624        {
2625            if (dir == dLeftToRight)
2626            {
2627                while (maxIt != m_Maxima.end() && *maxIt < e->Curr.X) 
2628                {
2629                  if (horzEdge->OutIdx >= 0 && !IsOpen)
2630                    AddOutPt(horzEdge, IntPoint(*maxIt, horzEdge->Bot.Y));
2631                  maxIt++;
2632                }
2633            }
2634            else
2635            {
2636                while (maxRit != m_Maxima.rend() && *maxRit > e->Curr.X)
2637                {
2638                  if (horzEdge->OutIdx >= 0 && !IsOpen)
2639                    AddOutPt(horzEdge, IntPoint(*maxRit, horzEdge->Bot.Y));
2640                  maxRit++;
2641                }
2642            }
2643        };
2644
2645        if ((dir == dLeftToRight && e->Curr.X > horzRight) ||
2646                        (dir == dRightToLeft && e->Curr.X < horzLeft)) break;
2647
2648                //Also break if we've got to the end of an intermediate horizontal edge ...
2649                //nb: Smaller Dx's are to the right of larger Dx's ABOVE the horizontal.
2650                if (e->Curr.X == horzEdge->Top.X && horzEdge->NextInLML && 
2651                        e->Dx < horzEdge->NextInLML->Dx) break;
2652
2653    if (horzEdge->OutIdx >= 0 && !IsOpen)  //note: may be done multiple times
2654                {
2655            op1 = AddOutPt(horzEdge, e->Curr);
2656                        TEdge* eNextHorz = m_SortedEdges;
2657                        while (eNextHorz)
2658                        {
2659                                if (eNextHorz->OutIdx >= 0 &&
2660                                        HorzSegmentsOverlap(horzEdge->Bot.X,
2661                                        horzEdge->Top.X, eNextHorz->Bot.X, eNextHorz->Top.X))
2662                                {
2663                    OutPt* op2 = GetLastOutPt(eNextHorz);
2664                    AddJoin(op2, op1, eNextHorz->Top);
2665                                }
2666                                eNextHorz = eNextHorz->NextInSEL;
2667                        }
2668                        AddGhostJoin(op1, horzEdge->Bot);
2669                }
2670               
2671                //OK, so far we're still in range of the horizontal Edge  but make sure
2672        //we're at the last of consec. horizontals when matching with eMaxPair
2673        if(e == eMaxPair && IsLastHorz)
2674        {
2675          if (horzEdge->OutIdx >= 0)
2676            AddLocalMaxPoly(horzEdge, eMaxPair, horzEdge->Top);
2677          DeleteFromAEL(horzEdge);
2678          DeleteFromAEL(eMaxPair);
2679          return;
2680        }
2681       
2682                if(dir == dLeftToRight)
2683        {
2684          IntPoint Pt = IntPoint(e->Curr.X, horzEdge->Curr.Y);
2685          IntersectEdges(horzEdge, e, Pt);
2686        }
2687        else
2688        {
2689          IntPoint Pt = IntPoint(e->Curr.X, horzEdge->Curr.Y);
2690          IntersectEdges( e, horzEdge, Pt);
2691        }
2692        TEdge* eNext = GetNextInAEL(e, dir);
2693        SwapPositionsInAEL( horzEdge, e );
2694        e = eNext;
2695    } //end while(e)
2696
2697        //Break out of loop if HorzEdge.NextInLML is not also horizontal ...
2698        if (!horzEdge->NextInLML || !IsHorizontal(*horzEdge->NextInLML)) break;
2699
2700        UpdateEdgeIntoAEL(horzEdge);
2701    if (horzEdge->OutIdx >= 0) AddOutPt(horzEdge, horzEdge->Bot);
2702    GetHorzDirection(*horzEdge, dir, horzLeft, horzRight);
2703
2704  } //end for (;;)
2705
2706  if (horzEdge->OutIdx >= 0 && !op1)
2707  {
2708      op1 = GetLastOutPt(horzEdge);
2709      TEdge* eNextHorz = m_SortedEdges;
2710      while (eNextHorz)
2711      {
2712          if (eNextHorz->OutIdx >= 0 &&
2713              HorzSegmentsOverlap(horzEdge->Bot.X,
2714              horzEdge->Top.X, eNextHorz->Bot.X, eNextHorz->Top.X))
2715          {
2716              OutPt* op2 = GetLastOutPt(eNextHorz);
2717              AddJoin(op2, op1, eNextHorz->Top);
2718          }
2719          eNextHorz = eNextHorz->NextInSEL;
2720      }
2721      AddGhostJoin(op1, horzEdge->Top);
2722  }
2723
2724  if (horzEdge->NextInLML)
2725  {
2726    if(horzEdge->OutIdx >= 0)
2727    {
2728      op1 = AddOutPt( horzEdge, horzEdge->Top);
2729      UpdateEdgeIntoAEL(horzEdge);
2730      if (horzEdge->WindDelta == 0) return;
2731      //nb: HorzEdge is no longer horizontal here
2732      TEdge* ePrev = horzEdge->PrevInAEL;
2733      TEdge* eNext = horzEdge->NextInAEL;
2734      if (ePrev && ePrev->Curr.X == horzEdge->Bot.X &&
2735        ePrev->Curr.Y == horzEdge->Bot.Y && ePrev->WindDelta != 0 &&
2736        (ePrev->OutIdx >= 0 && ePrev->Curr.Y > ePrev->Top.Y &&
2737        SlopesEqual(*horzEdge, *ePrev, m_UseFullRange)))
2738      {
2739        OutPt* op2 = AddOutPt(ePrev, horzEdge->Bot);
2740        AddJoin(op1, op2, horzEdge->Top);
2741      }
2742      else if (eNext && eNext->Curr.X == horzEdge->Bot.X &&
2743        eNext->Curr.Y == horzEdge->Bot.Y && eNext->WindDelta != 0 &&
2744        eNext->OutIdx >= 0 && eNext->Curr.Y > eNext->Top.Y &&
2745        SlopesEqual(*horzEdge, *eNext, m_UseFullRange))
2746      {
2747        OutPt* op2 = AddOutPt(eNext, horzEdge->Bot);
2748        AddJoin(op1, op2, horzEdge->Top);
2749      }
2750    }
2751    else
2752      UpdateEdgeIntoAEL(horzEdge); 
2753  }
2754  else
2755  {
2756    if (horzEdge->OutIdx >= 0) AddOutPt(horzEdge, horzEdge->Top);
2757    DeleteFromAEL(horzEdge);
2758  }
2759}
2760//------------------------------------------------------------------------------
2761
2762void Clipper::UpdateEdgeIntoAEL(TEdge *&e)
2763{
2764  if( !e->NextInLML ) throw
2765    clipperException("UpdateEdgeIntoAEL: invalid call");
2766
2767  e->NextInLML->OutIdx = e->OutIdx;
2768  TEdge* AelPrev = e->PrevInAEL;
2769  TEdge* AelNext = e->NextInAEL;
2770  if (AelPrev) AelPrev->NextInAEL = e->NextInLML;
2771  else m_ActiveEdges = e->NextInLML;
2772  if (AelNext) AelNext->PrevInAEL = e->NextInLML;
2773  e->NextInLML->Side = e->Side;
2774  e->NextInLML->WindDelta = e->WindDelta;
2775  e->NextInLML->WindCnt = e->WindCnt;
2776  e->NextInLML->WindCnt2 = e->WindCnt2;
2777  e = e->NextInLML;
2778  e->Curr = e->Bot;
2779  e->PrevInAEL = AelPrev;
2780  e->NextInAEL = AelNext;
2781  if (!IsHorizontal(*e)) InsertScanbeam(e->Top.Y);
2782}
2783//------------------------------------------------------------------------------
2784
2785bool Clipper::ProcessIntersections(const cInt topY)
2786{
2787  if( !m_ActiveEdges ) return true;
2788  try {
2789    BuildIntersectList(topY);
2790    size_t IlSize = m_IntersectList.size();
2791    if (IlSize == 0) return true;
2792    if (IlSize == 1 || FixupIntersectionOrder()) ProcessIntersectList();
2793    else return false;
2794  }
2795  catch(...) 
2796  {
2797    m_SortedEdges = 0;
2798    DisposeIntersectNodes();
2799    throw clipperException("ProcessIntersections error");
2800  }
2801  m_SortedEdges = 0;
2802  return true;
2803}
2804//------------------------------------------------------------------------------
2805
2806void Clipper::DisposeIntersectNodes()
2807{
2808  for (size_t i = 0; i < m_IntersectList.size(); ++i )
2809    delete m_IntersectList[i];
2810  m_IntersectList.clear();
2811}
2812//------------------------------------------------------------------------------
2813
2814void Clipper::BuildIntersectList(const cInt topY)
2815{
2816  if ( !m_ActiveEdges ) return;
2817
2818  //prepare for sorting ...
2819  TEdge* e = m_ActiveEdges;
2820  m_SortedEdges = e;
2821  while( e )
2822  {
2823    e->PrevInSEL = e->PrevInAEL;
2824    e->NextInSEL = e->NextInAEL;
2825    e->Curr.X = TopX( *e, topY );
2826    e = e->NextInAEL;
2827  }
2828
2829  //bubblesort ...
2830  bool isModified;
2831  do
2832  {
2833    isModified = false;
2834    e = m_SortedEdges;
2835    while( e->NextInSEL )
2836    {
2837      TEdge *eNext = e->NextInSEL;
2838      IntPoint Pt;
2839      if(e->Curr.X > eNext->Curr.X)
2840      {
2841        IntersectPoint(*e, *eNext, Pt);
2842        IntersectNode * newNode = new IntersectNode;
2843        newNode->Edge1 = e;
2844        newNode->Edge2 = eNext;
2845        newNode->Pt = Pt;
2846        m_IntersectList.push_back(newNode);
2847
2848        SwapPositionsInSEL(e, eNext);
2849        isModified = true;
2850      }
2851      else
2852        e = eNext;
2853    }
2854    if( e->PrevInSEL ) e->PrevInSEL->NextInSEL = 0;
2855    else break;
2856  }
2857  while ( isModified );
2858  m_SortedEdges = 0; //important
2859}
2860//------------------------------------------------------------------------------
2861
2862
2863void Clipper::ProcessIntersectList()
2864{
2865  for (size_t i = 0; i < m_IntersectList.size(); ++i)
2866  {
2867    IntersectNode* iNode = m_IntersectList[i];
2868    {
2869      IntersectEdges( iNode->Edge1, iNode->Edge2, iNode->Pt);
2870      SwapPositionsInAEL( iNode->Edge1 , iNode->Edge2 );
2871    }
2872    delete iNode;
2873  }
2874  m_IntersectList.clear();
2875}
2876//------------------------------------------------------------------------------
2877
2878bool IntersectListSort(IntersectNode* node1, IntersectNode* node2)
2879{
2880  return node2->Pt.Y < node1->Pt.Y;
2881}
2882//------------------------------------------------------------------------------
2883
2884inline bool EdgesAdjacent(const IntersectNode &inode)
2885{
2886  return (inode.Edge1->NextInSEL == inode.Edge2) ||
2887    (inode.Edge1->PrevInSEL == inode.Edge2);
2888}
2889//------------------------------------------------------------------------------
2890
2891bool Clipper::FixupIntersectionOrder()
2892{
2893  //pre-condition: intersections are sorted Bottom-most first.
2894  //Now it's crucial that intersections are made only between adjacent edges,
2895  //so to ensure this the order of intersections may need adjusting ...
2896  CopyAELToSEL();
2897  std::sort(m_IntersectList.begin(), m_IntersectList.end(), IntersectListSort);
2898  size_t cnt = m_IntersectList.size();
2899  for (size_t i = 0; i < cnt; ++i) 
2900  {
2901    if (!EdgesAdjacent(*m_IntersectList[i]))
2902    {
2903      size_t j = i + 1;
2904      while (j < cnt && !EdgesAdjacent(*m_IntersectList[j])) j++;
2905      if (j == cnt)  return false;
2906      std::swap(m_IntersectList[i], m_IntersectList[j]);
2907    }
2908    SwapPositionsInSEL(m_IntersectList[i]->Edge1, m_IntersectList[i]->Edge2);
2909  }
2910  return true;
2911}
2912//------------------------------------------------------------------------------
2913
2914void Clipper::DoMaxima(TEdge *e)
2915{
2916  TEdge* eMaxPair = GetMaximaPair(e);
2917  if (!eMaxPair)
2918  {
2919    if (e->OutIdx >= 0)
2920      AddOutPt(e, e->Top);
2921    DeleteFromAEL(e);
2922    return;
2923  }
2924
2925  TEdge* eNext = e->NextInAEL;
2926  while(eNext && eNext != eMaxPair)
2927  {
2928    IntersectEdges(e, eNext, e->Top);
2929    SwapPositionsInAEL(e, eNext);
2930    eNext = e->NextInAEL;
2931  }
2932
2933  if(e->OutIdx == Unassigned && eMaxPair->OutIdx == Unassigned)
2934  {
2935    DeleteFromAEL(e);
2936    DeleteFromAEL(eMaxPair);
2937  }
2938  else if( e->OutIdx >= 0 && eMaxPair->OutIdx >= 0 )
2939  {
2940    if (e->OutIdx >= 0) AddLocalMaxPoly(e, eMaxPair, e->Top);
2941    DeleteFromAEL(e);
2942    DeleteFromAEL(eMaxPair);
2943  }
2944#ifdef use_lines
2945  else if (e->WindDelta == 0)
2946  {
2947    if (e->OutIdx >= 0) 
2948    {
2949      AddOutPt(e, e->Top);
2950      e->OutIdx = Unassigned;
2951    }
2952    DeleteFromAEL(e);
2953
2954    if (eMaxPair->OutIdx >= 0)
2955    {
2956      AddOutPt(eMaxPair, e->Top);
2957      eMaxPair->OutIdx = Unassigned;
2958    }
2959    DeleteFromAEL(eMaxPair);
2960  } 
2961#endif
2962  else throw clipperException("DoMaxima error");
2963}
2964//------------------------------------------------------------------------------
2965
2966void Clipper::ProcessEdgesAtTopOfScanbeam(const cInt topY)
2967{
2968  TEdge* e = m_ActiveEdges;
2969  while( e )
2970  {
2971    //1. process maxima, treating them as if they're 'bent' horizontal edges,
2972    //   but exclude maxima with horizontal edges. nb: e can't be a horizontal.
2973    bool IsMaximaEdge = IsMaxima(e, topY);
2974
2975    if(IsMaximaEdge)
2976    {
2977      TEdge* eMaxPair = GetMaximaPair(e);
2978      IsMaximaEdge = (!eMaxPair || !IsHorizontal(*eMaxPair));
2979    }
2980
2981    if(IsMaximaEdge)
2982    {
2983      if (m_StrictSimple) m_Maxima.push_back(e->Top.X);
2984      TEdge* ePrev = e->PrevInAEL;
2985      DoMaxima(e);
2986      if( !ePrev ) e = m_ActiveEdges;
2987      else e = ePrev->NextInAEL;
2988    }
2989    else
2990    {
2991      //2. promote horizontal edges, otherwise update Curr.X and Curr.Y ...
2992      if (IsIntermediate(e, topY) && IsHorizontal(*e->NextInLML))
2993      {
2994        UpdateEdgeIntoAEL(e);
2995        if (e->OutIdx >= 0)
2996          AddOutPt(e, e->Bot);
2997        AddEdgeToSEL(e);
2998      } 
2999      else
3000      {
3001        e->Curr.X = TopX( *e, topY );
3002        e->Curr.Y = topY;
3003      }
3004
3005      //When StrictlySimple and 'e' is being touched by another edge, then
3006      //make sure both edges have a vertex here ...
3007      if (m_StrictSimple)
3008      { 
3009        TEdge* ePrev = e->PrevInAEL;
3010        if ((e->OutIdx >= 0) && (e->WindDelta != 0) && ePrev && (ePrev->OutIdx >= 0) &&
3011          (ePrev->Curr.X == e->Curr.X) && (ePrev->WindDelta != 0))
3012        {
3013          IntPoint pt = e->Curr;
3014#ifdef use_xyz
3015          SetZ(pt, *ePrev, *e);
3016#endif
3017          OutPt* op = AddOutPt(ePrev, pt);
3018          OutPt* op2 = AddOutPt(e, pt);
3019          AddJoin(op, op2, pt); //StrictlySimple (type-3) join
3020        }
3021      }
3022
3023      e = e->NextInAEL;
3024    }
3025  }
3026
3027  //3. Process horizontals at the Top of the scanbeam ...
3028  m_Maxima.sort();
3029  ProcessHorizontals();
3030  m_Maxima.clear();
3031
3032  //4. Promote intermediate vertices ...
3033  e = m_ActiveEdges;
3034  while(e)
3035  {
3036    if(IsIntermediate(e, topY))
3037    {
3038      OutPt* op = 0;
3039      if( e->OutIdx >= 0 ) 
3040        op = AddOutPt(e, e->Top);
3041      UpdateEdgeIntoAEL(e);
3042
3043      //if output polygons share an edge, they'll need joining later ...
3044      TEdge* ePrev = e->PrevInAEL;
3045      TEdge* eNext = e->NextInAEL;
3046      if (ePrev && ePrev->Curr.X == e->Bot.X &&
3047        ePrev->Curr.Y == e->Bot.Y && op &&
3048        ePrev->OutIdx >= 0 && ePrev->Curr.Y > ePrev->Top.Y &&
3049        SlopesEqual(*e, *ePrev, m_UseFullRange) &&
3050        (e->WindDelta != 0) && (ePrev->WindDelta != 0))
3051      {
3052        OutPt* op2 = AddOutPt(ePrev, e->Bot);
3053        AddJoin(op, op2, e->Top);
3054      }
3055      else if (eNext && eNext->Curr.X == e->Bot.X &&
3056        eNext->Curr.Y == e->Bot.Y && op &&
3057        eNext->OutIdx >= 0 && eNext->Curr.Y > eNext->Top.Y &&
3058        SlopesEqual(*e, *eNext, m_UseFullRange) &&
3059        (e->WindDelta != 0) && (eNext->WindDelta != 0))
3060      {
3061        OutPt* op2 = AddOutPt(eNext, e->Bot);
3062        AddJoin(op, op2, e->Top);
3063      }
3064    }
3065    e = e->NextInAEL;
3066  }
3067}
3068//------------------------------------------------------------------------------
3069
3070void Clipper::FixupOutPolyline(OutRec &outrec)
3071{
3072  OutPt *pp = outrec.Pts;
3073  OutPt *lastPP = pp->Prev;
3074  while (pp != lastPP)
3075  {
3076    pp = pp->Next;
3077    if (pp->Pt == pp->Prev->Pt)
3078    {
3079      if (pp == lastPP) lastPP = pp->Prev;
3080      OutPt *tmpPP = pp->Prev;
3081      tmpPP->Next = pp->Next;
3082      pp->Next->Prev = tmpPP;
3083      delete pp;
3084      pp = tmpPP;
3085    }
3086  }
3087
3088  if (pp == pp->Prev)
3089  {
3090    DisposeOutPts(pp);
3091    outrec.Pts = 0;
3092    return;
3093  }
3094}
3095//------------------------------------------------------------------------------
3096
3097void Clipper::FixupOutPolygon(OutRec &outrec)
3098{
3099    //FixupOutPolygon() - removes duplicate points and simplifies consecutive
3100    //parallel edges by removing the middle vertex.
3101    OutPt *lastOK = 0;
3102    outrec.BottomPt = 0;
3103    OutPt *pp = outrec.Pts;
3104    bool preserveCol = m_PreserveCollinear || m_StrictSimple;
3105
3106    for (;;)
3107    {
3108        if (pp->Prev == pp || pp->Prev == pp->Next)
3109        {
3110            DisposeOutPts(pp);
3111            outrec.Pts = 0;
3112            return;
3113        }
3114
3115        //test for duplicate points and collinear edges ...
3116        if ((pp->Pt == pp->Next->Pt) || (pp->Pt == pp->Prev->Pt) ||
3117            (SlopesEqual(pp->Prev->Pt, pp->Pt, pp->Next->Pt, m_UseFullRange) &&
3118            (!preserveCol || !Pt2IsBetweenPt1AndPt3(pp->Prev->Pt, pp->Pt, pp->Next->Pt))))
3119        {
3120            lastOK = 0;
3121            OutPt *tmp = pp;
3122            pp->Prev->Next = pp->Next;
3123            pp->Next->Prev = pp->Prev;
3124            pp = pp->Prev;
3125            delete tmp;
3126        }
3127        else if (pp == lastOK) break;
3128        else
3129        {
3130            if (!lastOK) lastOK = pp;
3131            pp = pp->Next;
3132        }
3133    }
3134    outrec.Pts = pp;
3135}
3136//------------------------------------------------------------------------------
3137
3138int PointCount(OutPt *Pts)
3139{
3140    if (!Pts) return 0;
3141    int result = 0;
3142    OutPt* p = Pts;
3143    do
3144    {
3145        result++;
3146        p = p->Next;
3147    }
3148    while (p != Pts);
3149    return result;
3150}
3151//------------------------------------------------------------------------------
3152
3153void Clipper::BuildResult(Paths &polys)
3154{
3155  polys.reserve(m_PolyOuts.size());
3156  for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
3157  {
3158    if (!m_PolyOuts[i]->Pts) continue;
3159    Path pg;
3160    OutPt* p = m_PolyOuts[i]->Pts->Prev;
3161    int cnt = PointCount(p);
3162    if (cnt < 2) continue;
3163    pg.reserve(cnt);
3164    for (int i = 0; i < cnt; ++i)
3165    {
3166      pg.push_back(p->Pt);
3167      p = p->Prev;
3168    }
3169    polys.push_back(pg);
3170  }
3171}
3172//------------------------------------------------------------------------------
3173
3174void Clipper::BuildResult2(PolyTree& polytree)
3175{
3176    polytree.Clear();
3177    polytree.AllNodes.reserve(m_PolyOuts.size());
3178    //add each output polygon/contour to polytree ...
3179    for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); i++)
3180    {
3181        OutRec* outRec = m_PolyOuts[i];
3182        int cnt = PointCount(outRec->Pts);
3183        if ((outRec->IsOpen && cnt < 2) || (!outRec->IsOpen && cnt < 3)) continue;
3184        FixHoleLinkage(*outRec);
3185        PolyNode* pn = new PolyNode();
3186        //nb: polytree takes ownership of all the PolyNodes
3187        polytree.AllNodes.push_back(pn);
3188        outRec->PolyNd = pn;
3189        pn->Parent = 0;
3190        pn->Index = 0;
3191        pn->Contour.reserve(cnt);
3192        OutPt *op = outRec->Pts->Prev;
3193        for (int j = 0; j < cnt; j++)
3194        {
3195            pn->Contour.push_back(op->Pt);
3196            op = op->Prev;
3197        }
3198    }
3199
3200    //fixup PolyNode links etc ...
3201    polytree.Childs.reserve(m_PolyOuts.size());
3202    for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); i++)
3203    {
3204        OutRec* outRec = m_PolyOuts[i];
3205        if (!outRec->PolyNd) continue;
3206        if (outRec->IsOpen) 
3207        {
3208          outRec->PolyNd->m_IsOpen = true;
3209          polytree.AddChild(*outRec->PolyNd);
3210        }
3211        else if (outRec->FirstLeft && outRec->FirstLeft->PolyNd) 
3212          outRec->FirstLeft->PolyNd->AddChild(*outRec->PolyNd);
3213        else
3214          polytree.AddChild(*outRec->PolyNd);
3215    }
3216}
3217//------------------------------------------------------------------------------
3218
3219void SwapIntersectNodes(IntersectNode &int1, IntersectNode &int2)
3220{
3221  //just swap the contents (because fIntersectNodes is a single-linked-list)
3222  IntersectNode inode = int1; //gets a copy of Int1
3223  int1.Edge1 = int2.Edge1;
3224  int1.Edge2 = int2.Edge2;
3225  int1.Pt = int2.Pt;
3226  int2.Edge1 = inode.Edge1;
3227  int2.Edge2 = inode.Edge2;
3228  int2.Pt = inode.Pt;
3229}
3230//------------------------------------------------------------------------------
3231
3232inline bool E2InsertsBeforeE1(TEdge &e1, TEdge &e2)
3233{
3234  if (e2.Curr.X == e1.Curr.X) 
3235  {
3236    if (e2.Top.Y > e1.Top.Y)
3237      return e2.Top.X < TopX(e1, e2.Top.Y); 
3238      else return e1.Top.X > TopX(e2, e1.Top.Y);
3239  } 
3240  else return e2.Curr.X < e1.Curr.X;
3241}
3242//------------------------------------------------------------------------------
3243
3244bool GetOverlap(const cInt a1, const cInt a2, const cInt b1, const cInt b2, 
3245    cInt& Left, cInt& Right)
3246{
3247  if (a1 < a2)
3248  {
3249    if (b1 < b2) {Left = std::max(a1,b1); Right = std::min(a2,b2);}
3250    else {Left = std::max(a1,b2); Right = std::min(a2,b1);}
3251  } 
3252  else
3253  {
3254    if (b1 < b2) {Left = std::max(a2,b1); Right = std::min(a1,b2);}
3255    else {Left = std::max(a2,b2); Right = std::min(a1,b1);}
3256  }
3257  return Left < Right;
3258}
3259//------------------------------------------------------------------------------
3260
3261inline void UpdateOutPtIdxs(OutRec& outrec)
3262{ 
3263  OutPt* op = outrec.Pts;
3264  do
3265  {
3266    op->Idx = outrec.Idx;
3267    op = op->Prev;
3268  }
3269  while(op != outrec.Pts);
3270}
3271//------------------------------------------------------------------------------
3272
3273void Clipper::InsertEdgeIntoAEL(TEdge *edge, TEdge* startEdge)
3274{
3275  if(!m_ActiveEdges)
3276  {
3277    edge->PrevInAEL = 0;
3278    edge->NextInAEL = 0;
3279    m_ActiveEdges = edge;
3280  }
3281  else if(!startEdge && E2InsertsBeforeE1(*m_ActiveEdges, *edge))
3282  {
3283      edge->PrevInAEL = 0;
3284      edge->NextInAEL = m_ActiveEdges;
3285      m_ActiveEdges->PrevInAEL = edge;
3286      m_ActiveEdges = edge;
3287  } 
3288  else
3289  {
3290    if(!startEdge) startEdge = m_ActiveEdges;
3291    while(startEdge->NextInAEL  && 
3292      !E2InsertsBeforeE1(*startEdge->NextInAEL , *edge))
3293        startEdge = startEdge->NextInAEL;
3294    edge->NextInAEL = startEdge->NextInAEL;
3295    if(startEdge->NextInAEL) startEdge->NextInAEL->PrevInAEL = edge;
3296    edge->PrevInAEL = startEdge;
3297    startEdge->NextInAEL = edge;
3298  }
3299}
3300//----------------------------------------------------------------------
3301
3302OutPt* DupOutPt(OutPt* outPt, bool InsertAfter)
3303{
3304  OutPt* result = new OutPt;
3305  result->Pt = outPt->Pt;
3306  result->Idx = outPt->Idx;
3307  if (InsertAfter)
3308  {
3309    result->Next = outPt->Next;
3310    result->Prev = outPt;
3311    outPt->Next->Prev = result;
3312    outPt->Next = result;
3313  } 
3314  else
3315  {
3316    result->Prev = outPt->Prev;
3317    result->Next = outPt;
3318    outPt->Prev->Next = result;
3319    outPt->Prev = result;
3320  }
3321  return result;
3322}
3323//------------------------------------------------------------------------------
3324
3325bool JoinHorz(OutPt* op1, OutPt* op1b, OutPt* op2, OutPt* op2b,
3326  const IntPoint Pt, bool DiscardLeft)
3327{
3328  Direction Dir1 = (op1->Pt.X > op1b->Pt.X ? dRightToLeft : dLeftToRight);
3329  Direction Dir2 = (op2->Pt.X > op2b->Pt.X ? dRightToLeft : dLeftToRight);
3330  if (Dir1 == Dir2) return false;
3331
3332  //When DiscardLeft, we want Op1b to be on the Left of Op1, otherwise we
3333  //want Op1b to be on the Right. (And likewise with Op2 and Op2b.)
3334  //So, to facilitate this while inserting Op1b and Op2b ...
3335  //when DiscardLeft, make sure we're AT or RIGHT of Pt before adding Op1b,
3336  //otherwise make sure we're AT or LEFT of Pt. (Likewise with Op2b.)
3337  if (Dir1 == dLeftToRight) 
3338  {
3339    while (op1->Next->Pt.X <= Pt.X && 
3340      op1->Next->Pt.X >= op1->Pt.X && op1->Next->Pt.Y == Pt.Y) 
3341        op1 = op1->Next;
3342    if (DiscardLeft && (op1->Pt.X != Pt.X)) op1 = op1->Next;
3343    op1b = DupOutPt(op1, !DiscardLeft);
3344    if (op1b->Pt != Pt) 
3345    {
3346      op1 = op1b;
3347      op1->Pt = Pt;
3348      op1b = DupOutPt(op1, !DiscardLeft);
3349    }
3350  } 
3351  else
3352  {
3353    while (op1->Next->Pt.X >= Pt.X && 
3354      op1->Next->Pt.X <= op1->Pt.X && op1->Next->Pt.Y == Pt.Y) 
3355        op1 = op1->Next;
3356    if (!DiscardLeft && (op1->Pt.X != Pt.X)) op1 = op1->Next;
3357    op1b = DupOutPt(op1, DiscardLeft);
3358    if (op1b->Pt != Pt)
3359    {
3360      op1 = op1b;
3361      op1->Pt = Pt;
3362      op1b = DupOutPt(op1, DiscardLeft);
3363    }
3364  }
3365
3366  if (Dir2 == dLeftToRight)
3367  {
3368    while (op2->Next->Pt.X <= Pt.X && 
3369      op2->Next->Pt.X >= op2->Pt.X && op2->Next->Pt.Y == Pt.Y)
3370        op2 = op2->Next;
3371    if (DiscardLeft && (op2->Pt.X != Pt.X)) op2 = op2->Next;
3372    op2b = DupOutPt(op2, !DiscardLeft);
3373    if (op2b->Pt != Pt)
3374    {
3375      op2 = op2b;
3376      op2->Pt = Pt;
3377      op2b = DupOutPt(op2, !DiscardLeft);
3378    };
3379  } else
3380  {
3381    while (op2->Next->Pt.X >= Pt.X && 
3382      op2->Next->Pt.X <= op2->Pt.X && op2->Next->Pt.Y == Pt.Y) 
3383        op2 = op2->Next;
3384    if (!DiscardLeft && (op2->Pt.X != Pt.X)) op2 = op2->Next;
3385    op2b = DupOutPt(op2, DiscardLeft);
3386    if (op2b->Pt != Pt)
3387    {
3388      op2 = op2b;
3389      op2->Pt = Pt;
3390      op2b = DupOutPt(op2, DiscardLeft);
3391    };
3392  };
3393
3394  if ((Dir1 == dLeftToRight) == DiscardLeft)
3395  {
3396    op1->Prev = op2;
3397    op2->Next = op1;
3398    op1b->Next = op2b;
3399    op2b->Prev = op1b;
3400  }
3401  else
3402  {
3403    op1->Next = op2;
3404    op2->Prev = op1;
3405    op1b->Prev = op2b;
3406    op2b->Next = op1b;
3407  }
3408  return true;
3409}
3410//------------------------------------------------------------------------------
3411
3412bool Clipper::JoinPoints(Join *j, OutRec* outRec1, OutRec* outRec2)
3413{
3414  OutPt *op1 = j->OutPt1, *op1b;
3415  OutPt *op2 = j->OutPt2, *op2b;
3416
3417  //There are 3 kinds of joins for output polygons ...
3418  //1. Horizontal joins where Join.OutPt1 & Join.OutPt2 are vertices anywhere
3419  //along (horizontal) collinear edges (& Join.OffPt is on the same horizontal).
3420  //2. Non-horizontal joins where Join.OutPt1 & Join.OutPt2 are at the same
3421  //location at the Bottom of the overlapping segment (& Join.OffPt is above).
3422  //3. StrictSimple joins where edges touch but are not collinear and where
3423  //Join.OutPt1, Join.OutPt2 & Join.OffPt all share the same point.
3424  bool isHorizontal = (j->OutPt1->Pt.Y == j->OffPt.Y);
3425
3426  if (isHorizontal  && (j->OffPt == j->OutPt1->Pt) &&
3427  (j->OffPt == j->OutPt2->Pt))
3428  {
3429    //Strictly Simple join ...
3430    if (outRec1 != outRec2) return false;
3431    op1b = j->OutPt1->Next;
3432    while (op1b != op1 && (op1b->Pt == j->OffPt)) 
3433      op1b = op1b->Next;
3434    bool reverse1 = (op1b->Pt.Y > j->OffPt.Y);
3435    op2b = j->OutPt2->Next;
3436    while (op2b != op2 && (op2b->Pt == j->OffPt)) 
3437      op2b = op2b->Next;
3438    bool reverse2 = (op2b->Pt.Y > j->OffPt.Y);
3439    if (reverse1 == reverse2) return false;
3440    if (reverse1)
3441    {
3442      op1b = DupOutPt(op1, false);
3443      op2b = DupOutPt(op2, true);
3444      op1->Prev = op2;
3445      op2->Next = op1;
3446      op1b->Next = op2b;
3447      op2b->Prev = op1b;
3448      j->OutPt1 = op1;
3449      j->OutPt2 = op1b;
3450      return true;
3451    } else
3452    {
3453      op1b = DupOutPt(op1, true);
3454      op2b = DupOutPt(op2, false);
3455      op1->Next = op2;
3456      op2->Prev = op1;
3457      op1b->Prev = op2b;
3458      op2b->Next = op1b;
3459      j->OutPt1 = op1;
3460      j->OutPt2 = op1b;
3461      return true;
3462    }
3463  } 
3464  else if (isHorizontal)
3465  {
3466    //treat horizontal joins differently to non-horizontal joins since with
3467    //them we're not yet sure where the overlapping is. OutPt1.Pt & OutPt2.Pt
3468    //may be anywhere along the horizontal edge.
3469    op1b = op1;
3470    while (op1->Prev->Pt.Y == op1->Pt.Y && op1->Prev != op1b && op1->Prev != op2)
3471      op1 = op1->Prev;
3472    while (op1b->Next->Pt.Y == op1b->Pt.Y && op1b->Next != op1 && op1b->Next != op2)
3473      op1b = op1b->Next;
3474    if (op1b->Next == op1 || op1b->Next == op2) return false; //a flat 'polygon'
3475
3476    op2b = op2;
3477    while (op2->Prev->Pt.Y == op2->Pt.Y && op2->Prev != op2b && op2->Prev != op1b)
3478      op2 = op2->Prev;
3479    while (op2b->Next->Pt.Y == op2b->Pt.Y && op2b->Next != op2 && op2b->Next != op1)
3480      op2b = op2b->Next;
3481    if (op2b->Next == op2 || op2b->Next == op1) return false; //a flat 'polygon'
3482
3483    cInt Left, Right;
3484    //Op1 --> Op1b & Op2 --> Op2b are the extremites of the horizontal edges
3485    if (!GetOverlap(op1->Pt.X, op1b->Pt.X, op2->Pt.X, op2b->Pt.X, Left, Right))
3486      return false;
3487
3488    //DiscardLeftSide: when overlapping edges are joined, a spike will created
3489    //which needs to be cleaned up. However, we don't want Op1 or Op2 caught up
3490    //on the discard Side as either may still be needed for other joins ...
3491    IntPoint Pt;
3492    bool DiscardLeftSide;
3493    if (op1->Pt.X >= Left && op1->Pt.X <= Right) 
3494    {
3495      Pt = op1->Pt; DiscardLeftSide = (op1->Pt.X > op1b->Pt.X);
3496    } 
3497    else if (op2->Pt.X >= Left&& op2->Pt.X <= Right) 
3498    {
3499      Pt = op2->Pt; DiscardLeftSide = (op2->Pt.X > op2b->Pt.X);
3500    } 
3501    else if (op1b->Pt.X >= Left && op1b->Pt.X <= Right)
3502    {
3503      Pt = op1b->Pt; DiscardLeftSide = op1b->Pt.X > op1->Pt.X;
3504    } 
3505    else
3506    {
3507      Pt = op2b->Pt; DiscardLeftSide = (op2b->Pt.X > op2->Pt.X);
3508    }
3509    j->OutPt1 = op1; j->OutPt2 = op2;
3510    return JoinHorz(op1, op1b, op2, op2b, Pt, DiscardLeftSide);
3511  } else
3512  {
3513    //nb: For non-horizontal joins ...
3514    //    1. Jr.OutPt1.Pt.Y == Jr.OutPt2.Pt.Y
3515    //    2. Jr.OutPt1.Pt > Jr.OffPt.Y
3516
3517    //make sure the polygons are correctly oriented ...
3518    op1b = op1->Next;
3519    while ((op1b->Pt == op1->Pt) && (op1b != op1)) op1b = op1b->Next;
3520    bool Reverse1 = ((op1b->Pt.Y > op1->Pt.Y) ||
3521      !SlopesEqual(op1->Pt, op1b->Pt, j->OffPt, m_UseFullRange));
3522    if (Reverse1)
3523    {
3524      op1b = op1->Prev;
3525      while ((op1b->Pt == op1->Pt) && (op1b != op1)) op1b = op1b->Prev;
3526      if ((op1b->Pt.Y > op1->Pt.Y) ||
3527        !SlopesEqual(op1->Pt, op1b->Pt, j->OffPt, m_UseFullRange)) return false;
3528    };
3529    op2b = op2->Next;
3530    while ((op2b->Pt == op2->Pt) && (op2b != op2))op2b = op2b->Next;
3531    bool Reverse2 = ((op2b->Pt.Y > op2->Pt.Y) ||
3532      !SlopesEqual(op2->Pt, op2b->Pt, j->OffPt, m_UseFullRange));
3533    if (Reverse2)
3534    {
3535      op2b = op2->Prev;
3536      while ((op2b->Pt == op2->Pt) && (op2b != op2)) op2b = op2b->Prev;
3537      if ((op2b->Pt.Y > op2->Pt.Y) ||
3538        !SlopesEqual(op2->Pt, op2b->Pt, j->OffPt, m_UseFullRange)) return false;
3539    }
3540
3541    if ((op1b == op1) || (op2b == op2) || (op1b == op2b) ||
3542      ((outRec1 == outRec2) && (Reverse1 == Reverse2))) return false;
3543
3544    if (Reverse1)
3545    {
3546      op1b = DupOutPt(op1, false);
3547      op2b = DupOutPt(op2, true);
3548      op1->Prev = op2;
3549      op2->Next = op1;
3550      op1b->Next = op2b;
3551      op2b->Prev = op1b;
3552      j->OutPt1 = op1;
3553      j->OutPt2 = op1b;
3554      return true;
3555    } else
3556    {
3557      op1b = DupOutPt(op1, true);
3558      op2b = DupOutPt(op2, false);
3559      op1->Next = op2;
3560      op2->Prev = op1;
3561      op1b->Prev = op2b;
3562      op2b->Next = op1b;
3563      j->OutPt1 = op1;
3564      j->OutPt2 = op1b;
3565      return true;
3566    }
3567  }
3568}
3569//----------------------------------------------------------------------
3570
3571static OutRec* ParseFirstLeft(OutRec* FirstLeft)
3572{
3573  while (FirstLeft && !FirstLeft->Pts)
3574    FirstLeft = FirstLeft->FirstLeft;
3575  return FirstLeft;
3576}
3577//------------------------------------------------------------------------------
3578
3579void Clipper::FixupFirstLefts1(OutRec* OldOutRec, OutRec* NewOutRec)
3580{ 
3581  //tests if NewOutRec contains the polygon before reassigning FirstLeft
3582  for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
3583  {
3584    OutRec* outRec = m_PolyOuts[i];
3585    if (!outRec->Pts || !outRec->FirstLeft) continue;
3586    OutRec* firstLeft = ParseFirstLeft(outRec->FirstLeft);
3587    if (firstLeft == OldOutRec)
3588    {
3589      if (Poly2ContainsPoly1(outRec->Pts, NewOutRec->Pts))
3590        outRec->FirstLeft = NewOutRec;
3591    }
3592  }
3593}
3594//----------------------------------------------------------------------
3595
3596void Clipper::FixupFirstLefts2(OutRec* OldOutRec, OutRec* NewOutRec)
3597{ 
3598  //reassigns FirstLeft WITHOUT testing if NewOutRec contains the polygon
3599  for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
3600  {
3601    OutRec* outRec = m_PolyOuts[i];
3602    if (outRec->FirstLeft == OldOutRec) outRec->FirstLeft = NewOutRec;
3603  }
3604}
3605//----------------------------------------------------------------------
3606
3607void Clipper::JoinCommonEdges()
3608{
3609  for (JoinList::size_type i = 0; i < m_Joins.size(); i++)
3610  {
3611    Join* join = m_Joins[i];
3612
3613    OutRec *outRec1 = GetOutRec(join->OutPt1->Idx);
3614    OutRec *outRec2 = GetOutRec(join->OutPt2->Idx);
3615
3616    if (!outRec1->Pts || !outRec2->Pts) continue;
3617    if (outRec1->IsOpen || outRec2->IsOpen) continue;
3618
3619    //get the polygon fragment with the correct hole state (FirstLeft)
3620    //before calling JoinPoints() ...
3621    OutRec *holeStateRec;
3622    if (outRec1 == outRec2) holeStateRec = outRec1;
3623    else if (Param1RightOfParam2(outRec1, outRec2)) holeStateRec = outRec2;
3624    else if (Param1RightOfParam2(outRec2, outRec1)) holeStateRec = outRec1;
3625    else holeStateRec = GetLowermostRec(outRec1, outRec2);
3626
3627    if (!JoinPoints(join, outRec1, outRec2)) continue;
3628
3629    if (outRec1 == outRec2)
3630    {
3631      //instead of joining two polygons, we've just created a new one by
3632      //splitting one polygon into two.
3633      outRec1->Pts = join->OutPt1;
3634      outRec1->BottomPt = 0;
3635      outRec2 = CreateOutRec();
3636      outRec2->Pts = join->OutPt2;
3637
3638      //update all OutRec2.Pts Idx's ...
3639      UpdateOutPtIdxs(*outRec2);
3640
3641      //We now need to check every OutRec.FirstLeft pointer. If it points
3642      //to OutRec1 it may need to point to OutRec2 instead ...
3643      if (m_UsingPolyTree)
3644        for (PolyOutList::size_type j = 0; j < m_PolyOuts.size() - 1; j++)
3645        {
3646          OutRec* oRec = m_PolyOuts[j];
3647          if (!oRec->Pts || ParseFirstLeft(oRec->FirstLeft) != outRec1 ||
3648            oRec->IsHole == outRec1->IsHole) continue;
3649          if (Poly2ContainsPoly1(oRec->Pts, join->OutPt2))
3650            oRec->FirstLeft = outRec2;
3651        }
3652
3653      if (Poly2ContainsPoly1(outRec2->Pts, outRec1->Pts))
3654      {
3655        //outRec2 is contained by outRec1 ...
3656        outRec2->IsHole = !outRec1->IsHole;
3657        outRec2->FirstLeft = outRec1;
3658
3659        //fixup FirstLeft pointers that may need reassigning to OutRec1
3660        if (m_UsingPolyTree) FixupFirstLefts2(outRec2, outRec1);
3661
3662        if ((outRec2->IsHole ^ m_ReverseOutput) == (Area(*outRec2) > 0))
3663          ReversePolyPtLinks(outRec2->Pts);
3664           
3665      } else if (Poly2ContainsPoly1(outRec1->Pts, outRec2->Pts))
3666      {
3667        //outRec1 is contained by outRec2 ...
3668        outRec2->IsHole = outRec1->IsHole;
3669        outRec1->IsHole = !outRec2->IsHole;
3670        outRec2->FirstLeft = outRec1->FirstLeft;
3671        outRec1->FirstLeft = outRec2;
3672
3673        //fixup FirstLeft pointers that may need reassigning to OutRec1
3674        if (m_UsingPolyTree) FixupFirstLefts2(outRec1, outRec2);
3675
3676        if ((outRec1->IsHole ^ m_ReverseOutput) == (Area(*outRec1) > 0))
3677          ReversePolyPtLinks(outRec1->Pts);
3678      } 
3679      else
3680      {
3681        //the 2 polygons are completely separate ...
3682        outRec2->IsHole = outRec1->IsHole;
3683        outRec2->FirstLeft = outRec1->FirstLeft;
3684
3685        //fixup FirstLeft pointers that may need reassigning to OutRec2
3686        if (m_UsingPolyTree) FixupFirstLefts1(outRec1, outRec2);
3687      }
3688     
3689    } else
3690    {
3691      //joined 2 polygons together ...
3692
3693      outRec2->Pts = 0;
3694      outRec2->BottomPt = 0;
3695      outRec2->Idx = outRec1->Idx;
3696
3697      outRec1->IsHole = holeStateRec->IsHole;
3698      if (holeStateRec == outRec2) 
3699        outRec1->FirstLeft = outRec2->FirstLeft;
3700      outRec2->FirstLeft = outRec1;
3701
3702      //fixup FirstLeft pointers that may need reassigning to OutRec1
3703      if (m_UsingPolyTree) FixupFirstLefts2(outRec2, outRec1);
3704    }
3705  }
3706}
3707
3708//------------------------------------------------------------------------------
3709// ClipperOffset support functions ...
3710//------------------------------------------------------------------------------
3711
3712DoublePoint GetUnitNormal(const IntPoint &pt1, const IntPoint &pt2)
3713{
3714  if(pt2.X == pt1.X && pt2.Y == pt1.Y) 
3715    return DoublePoint(0, 0);
3716
3717  double Dx = (double)(pt2.X - pt1.X);
3718  double dy = (double)(pt2.Y - pt1.Y);
3719  double f = 1 *1.0/ std::sqrt( Dx*Dx + dy*dy );
3720  Dx *= f;
3721  dy *= f;
3722  return DoublePoint(dy, -Dx);
3723}
3724
3725//------------------------------------------------------------------------------
3726// ClipperOffset class
3727//------------------------------------------------------------------------------
3728
3729ClipperOffset::ClipperOffset(double miterLimit, double arcTolerance)
3730{
3731  this->MiterLimit = miterLimit;
3732  this->ArcTolerance = arcTolerance;
3733  m_lowest.X = -1;
3734}
3735//------------------------------------------------------------------------------
3736
3737ClipperOffset::~ClipperOffset()
3738{
3739  Clear();
3740}
3741//------------------------------------------------------------------------------
3742
3743void ClipperOffset::Clear()
3744{
3745  for (int i = 0; i < m_polyNodes.ChildCount(); ++i)
3746    delete m_polyNodes.Childs[i];
3747  m_polyNodes.Childs.clear();
3748  m_lowest.X = -1;
3749}
3750//------------------------------------------------------------------------------
3751
3752void ClipperOffset::AddPath(const Path& path, JoinType joinType, EndType endType)
3753{
3754  int highI = (int)path.size() - 1;
3755  if (highI < 0) return;
3756  PolyNode* newNode = new PolyNode();
3757  newNode->m_jointype = joinType;
3758  newNode->m_endtype = endType;
3759
3760  //strip duplicate points from path and also get index to the lowest point ...
3761  if (endType == etClosedLine || endType == etClosedPolygon)
3762    while (highI > 0 && path[0] == path[highI]) highI--;
3763  newNode->Contour.reserve(highI + 1);
3764  newNode->Contour.push_back(path[0]);
3765  int j = 0, k = 0;
3766  for (int i = 1; i <= highI; i++)
3767    if (newNode->Contour[j] != path[i])
3768    {
3769      j++;
3770      newNode->Contour.push_back(path[i]);
3771      if (path[i].Y > newNode->Contour[k].Y ||
3772        (path[i].Y == newNode->Contour[k].Y &&
3773        path[i].X < newNode->Contour[k].X)) k = j;
3774    }
3775  if (endType == etClosedPolygon && j < 2)
3776  {
3777    delete newNode;
3778    return;
3779  }
3780  m_polyNodes.AddChild(*newNode);
3781
3782  //if this path's lowest pt is lower than all the others then update m_lowest
3783  if (endType != etClosedPolygon) return;
3784  if (m_lowest.X < 0)
3785    m_lowest = IntPoint(m_polyNodes.ChildCount() - 1, k);
3786  else
3787  {
3788    IntPoint ip = m_polyNodes.Childs[(int)m_lowest.X]->Contour[(int)m_lowest.Y];
3789    if (newNode->Contour[k].Y > ip.Y ||
3790      (newNode->Contour[k].Y == ip.Y &&
3791      newNode->Contour[k].X < ip.X))
3792      m_lowest = IntPoint(m_polyNodes.ChildCount() - 1, k);
3793  }
3794}
3795//------------------------------------------------------------------------------
3796
3797void ClipperOffset::AddPaths(const Paths& paths, JoinType joinType, EndType endType)
3798{
3799  for (Paths::size_type i = 0; i < paths.size(); ++i)
3800    AddPath(paths[i], joinType, endType);
3801}
3802//------------------------------------------------------------------------------
3803
3804void ClipperOffset::FixOrientations()
3805{
3806  //fixup orientations of all closed paths if the orientation of the
3807  //closed path with the lowermost vertex is wrong ...
3808  if (m_lowest.X >= 0 && 
3809    !Orientation(m_polyNodes.Childs[(int)m_lowest.X]->Contour))
3810  {
3811    for (int i = 0; i < m_polyNodes.ChildCount(); ++i)
3812    {
3813      PolyNode& node = *m_polyNodes.Childs[i];
3814      if (node.m_endtype == etClosedPolygon ||
3815        (node.m_endtype == etClosedLine && Orientation(node.Contour)))
3816          ReversePath(node.Contour);
3817    }
3818  } else
3819  {
3820    for (int i = 0; i < m_polyNodes.ChildCount(); ++i)
3821    {
3822      PolyNode& node = *m_polyNodes.Childs[i];
3823      if (node.m_endtype == etClosedLine && !Orientation(node.Contour))
3824        ReversePath(node.Contour);
3825    }
3826  }
3827}
3828//------------------------------------------------------------------------------
3829
3830void ClipperOffset::Execute(Paths& solution, double delta)
3831{
3832  solution.clear();
3833  FixOrientations();
3834  DoOffset(delta);
3835 
3836  //now clean up 'corners' ...
3837  Clipper clpr;
3838  clpr.AddPaths(m_destPolys, ptSubject, true);
3839  if (delta > 0)
3840  {
3841    clpr.Execute(ctUnion, solution, pftPositive, pftPositive);
3842  }
3843  else
3844  {
3845    IntRect r = clpr.GetBounds();
3846    Path outer(4);
3847    outer[0] = IntPoint(r.left - 10, r.bottom + 10);
3848    outer[1] = IntPoint(r.right + 10, r.bottom + 10);
3849    outer[2] = IntPoint(r.right + 10, r.top - 10);
3850    outer[3] = IntPoint(r.left - 10, r.top - 10);
3851
3852    clpr.AddPath(outer, ptSubject, true);
3853    clpr.ReverseSolution(true);
3854    clpr.Execute(ctUnion, solution, pftNegative, pftNegative);
3855    if (solution.size() > 0) solution.erase(solution.begin());
3856  }
3857}
3858//------------------------------------------------------------------------------
3859
3860void ClipperOffset::Execute(PolyTree& solution, double delta)
3861{
3862  solution.Clear();
3863  FixOrientations();
3864  DoOffset(delta);
3865
3866  //now clean up 'corners' ...
3867  Clipper clpr;
3868  clpr.AddPaths(m_destPolys, ptSubject, true);
3869  if (delta > 0)
3870  {
3871    clpr.Execute(ctUnion, solution, pftPositive, pftPositive);
3872  }
3873  else
3874  {
3875    IntRect r = clpr.GetBounds();
3876    Path outer(4);
3877    outer[0] = IntPoint(r.left - 10, r.bottom + 10);
3878    outer[1] = IntPoint(r.right + 10, r.bottom + 10);
3879    outer[2] = IntPoint(r.right + 10, r.top - 10);
3880    outer[3] = IntPoint(r.left - 10, r.top - 10);
3881
3882    clpr.AddPath(outer, ptSubject, true);
3883    clpr.ReverseSolution(true);
3884    clpr.Execute(ctUnion, solution, pftNegative, pftNegative);
3885    //remove the outer PolyNode rectangle ...
3886    if (solution.ChildCount() == 1 && solution.Childs[0]->ChildCount() > 0)
3887    {
3888      PolyNode* outerNode = solution.Childs[0];
3889      solution.Childs.reserve(outerNode->ChildCount());
3890      solution.Childs[0] = outerNode->Childs[0];
3891      solution.Childs[0]->Parent = outerNode->Parent;
3892      for (int i = 1; i < outerNode->ChildCount(); ++i)
3893        solution.AddChild(*outerNode->Childs[i]);
3894    }
3895    else
3896      solution.Clear();
3897  }
3898}
3899//------------------------------------------------------------------------------
3900
3901void ClipperOffset::DoOffset(double delta)
3902{
3903  m_destPolys.clear();
3904  m_delta = delta;
3905
3906  //if Zero offset, just copy any CLOSED polygons to m_p and return ...
3907  if (NEAR_ZERO(delta)) 
3908  {
3909    m_destPolys.reserve(m_polyNodes.ChildCount());
3910    for (int i = 0; i < m_polyNodes.ChildCount(); i++)
3911    {
3912      PolyNode& node = *m_polyNodes.Childs[i];
3913      if (node.m_endtype == etClosedPolygon)
3914        m_destPolys.push_back(node.Contour);
3915    }
3916    return;
3917  }
3918
3919  //see offset_triginometry3.svg in the documentation folder ...
3920  if (MiterLimit > 2) m_miterLim = 2/(MiterLimit * MiterLimit);
3921  else m_miterLim = 0.5;
3922
3923  double y;
3924  if (ArcTolerance <= 0.0) y = def_arc_tolerance;
3925  else if (ArcTolerance > std::fabs(delta) * def_arc_tolerance) 
3926    y = std::fabs(delta) * def_arc_tolerance;
3927  else y = ArcTolerance;
3928  //see offset_triginometry2.svg in the documentation folder ...
3929  double steps = pi / std::acos(1 - y / std::fabs(delta));
3930  if (steps > std::fabs(delta) * pi) 
3931    steps = std::fabs(delta) * pi;  //ie excessive precision check
3932  m_sin = std::sin(two_pi / steps);
3933  m_cos = std::cos(two_pi / steps);
3934  m_StepsPerRad = steps / two_pi;
3935  if (delta < 0.0) m_sin = -m_sin;
3936
3937  m_destPolys.reserve(m_polyNodes.ChildCount() * 2);
3938  for (int i = 0; i < m_polyNodes.ChildCount(); i++)
3939  {
3940    PolyNode& node = *m_polyNodes.Childs[i];
3941    m_srcPoly = node.Contour;
3942
3943    int len = (int)m_srcPoly.size();
3944    if (len == 0 || (delta <= 0 && (len < 3 || node.m_endtype != etClosedPolygon)))
3945        continue;
3946
3947    m_destPoly.clear();
3948    if (len == 1)
3949    {
3950      if (node.m_jointype == jtRound)
3951      {
3952        double X = 1.0, Y = 0.0;
3953        for (cInt j = 1; j <= steps; j++)
3954        {
3955          m_destPoly.push_back(IntPoint(
3956            Round(m_srcPoly[0].X + X * delta),
3957            Round(m_srcPoly[0].Y + Y * delta)));
3958          double X2 = X;
3959          X = X * m_cos - m_sin * Y;
3960          Y = X2 * m_sin + Y * m_cos;
3961        }
3962      }
3963      else
3964      {
3965        double X = -1.0, Y = -1.0;
3966        for (int j = 0; j < 4; ++j)
3967        {
3968          m_destPoly.push_back(IntPoint(
3969            Round(m_srcPoly[0].X + X * delta),
3970            Round(m_srcPoly[0].Y + Y * delta)));
3971          if (X < 0) X = 1;
3972          else if (Y < 0) Y = 1;
3973          else X = -1;
3974        }
3975      }
3976      m_destPolys.push_back(m_destPoly);
3977      continue;
3978    }
3979    //build m_normals ...
3980    m_normals.clear();
3981    m_normals.reserve(len);
3982    for (int j = 0; j < len - 1; ++j)
3983      m_normals.push_back(GetUnitNormal(m_srcPoly[j], m_srcPoly[j + 1]));
3984    if (node.m_endtype == etClosedLine || node.m_endtype == etClosedPolygon)
3985      m_normals.push_back(GetUnitNormal(m_srcPoly[len - 1], m_srcPoly[0]));
3986    else
3987      m_normals.push_back(DoublePoint(m_normals[len - 2]));
3988
3989    if (node.m_endtype == etClosedPolygon)
3990    {
3991      int k = len - 1;
3992      for (int j = 0; j < len; ++j)
3993        OffsetPoint(j, k, node.m_jointype);
3994      m_destPolys.push_back(m_destPoly);
3995    }
3996    else if (node.m_endtype == etClosedLine)
3997    {
3998      int k = len - 1;
3999      for (int j = 0; j < len; ++j)
4000        OffsetPoint(j, k, node.m_jointype);
4001      m_destPolys.push_back(m_destPoly);
4002      m_destPoly.clear();
4003      //re-build m_normals ...
4004      DoublePoint n = m_normals[len -1];
4005      for (int j = len - 1; j > 0; j--)
4006        m_normals[j] = DoublePoint(-m_normals[j - 1].X, -m_normals[j - 1].Y);
4007      m_normals[0] = DoublePoint(-n.X, -n.Y);
4008      k = 0;
4009      for (int j = len - 1; j >= 0; j--)
4010        OffsetPoint(j, k, node.m_jointype);
4011      m_destPolys.push_back(m_destPoly);
4012    }
4013    else
4014    {
4015      int k = 0;
4016      for (int j = 1; j < len - 1; ++j)
4017        OffsetPoint(j, k, node.m_jointype);
4018
4019      IntPoint pt1;
4020      if (node.m_endtype == etOpenButt)
4021      {
4022        int j = len - 1;
4023        pt1 = IntPoint((cInt)Round(m_srcPoly[j].X + m_normals[j].X *
4024          delta), (cInt)Round(m_srcPoly[j].Y + m_normals[j].Y * delta));
4025        m_destPoly.push_back(pt1);
4026        pt1 = IntPoint((cInt)Round(m_srcPoly[j].X - m_normals[j].X *
4027          delta), (cInt)Round(m_srcPoly[j].Y - m_normals[j].Y * delta));
4028        m_destPoly.push_back(pt1);
4029      }
4030      else
4031      {
4032        int j = len - 1;
4033        k = len - 2;
4034        m_sinA = 0;
4035        m_normals[j] = DoublePoint(-m_normals[j].X, -m_normals[j].Y);
4036        if (node.m_endtype == etOpenSquare)
4037          DoSquare(j, k);
4038        else
4039          DoRound(j, k);
4040      }
4041
4042      //re-build m_normals ...
4043      for (int j = len - 1; j > 0; j--)
4044        m_normals[j] = DoublePoint(-m_normals[j - 1].X, -m_normals[j - 1].Y);
4045      m_normals[0] = DoublePoint(-m_normals[1].X, -m_normals[1].Y);
4046
4047      k = len - 1;
4048      for (int j = k - 1; j > 0; --j) OffsetPoint(j, k, node.m_jointype);
4049
4050      if (node.m_endtype == etOpenButt)
4051      {
4052        pt1 = IntPoint((cInt)Round(m_srcPoly[0].X - m_normals[0].X * delta),
4053          (cInt)Round(m_srcPoly[0].Y - m_normals[0].Y * delta));
4054        m_destPoly.push_back(pt1);
4055        pt1 = IntPoint((cInt)Round(m_srcPoly[0].X + m_normals[0].X * delta),
4056          (cInt)Round(m_srcPoly[0].Y + m_normals[0].Y * delta));
4057        m_destPoly.push_back(pt1);
4058      }
4059      else
4060      {
4061        k = 1;
4062        m_sinA = 0;
4063        if (node.m_endtype == etOpenSquare)
4064          DoSquare(0, 1);
4065        else
4066          DoRound(0, 1);
4067      }
4068      m_destPolys.push_back(m_destPoly);
4069    }
4070  }
4071}
4072//------------------------------------------------------------------------------
4073
4074void ClipperOffset::OffsetPoint(int j, int& k, JoinType jointype)
4075{
4076  //cross product ...
4077  m_sinA = (m_normals[k].X * m_normals[j].Y - m_normals[j].X * m_normals[k].Y);
4078  if (std::fabs(m_sinA * m_delta) < 1.0) 
4079  {
4080    //dot product ...
4081    double cosA = (m_normals[k].X * m_normals[j].X + m_normals[j].Y * m_normals[k].Y ); 
4082    if (cosA > 0) // angle => 0 degrees
4083    {
4084      m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + m_normals[k].X * m_delta),
4085        Round(m_srcPoly[j].Y + m_normals[k].Y * m_delta)));
4086      return; 
4087    }
4088    //else angle => 180 degrees   
4089  }
4090  else if (m_sinA > 1.0) m_sinA = 1.0;
4091  else if (m_sinA < -1.0) m_sinA = -1.0;
4092
4093  if (m_sinA * m_delta < 0)
4094  {
4095    m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + m_normals[k].X * m_delta),
4096      Round(m_srcPoly[j].Y + m_normals[k].Y * m_delta)));
4097    m_destPoly.push_back(m_srcPoly[j]);
4098    m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + m_normals[j].X * m_delta),
4099      Round(m_srcPoly[j].Y + m_normals[j].Y * m_delta)));
4100  }
4101  else
4102    switch (jointype)
4103    {
4104      case jtMiter:
4105        {
4106          double r = 1 + (m_normals[j].X * m_normals[k].X +
4107            m_normals[j].Y * m_normals[k].Y);
4108          if (r >= m_miterLim) DoMiter(j, k, r); else DoSquare(j, k);
4109          break;
4110        }
4111      case jtSquare: DoSquare(j, k); break;
4112      case jtRound: DoRound(j, k); break;
4113    }
4114  k = j;
4115}
4116//------------------------------------------------------------------------------
4117
4118void ClipperOffset::DoSquare(int j, int k)
4119{
4120  double dx = std::tan(std::atan2(m_sinA,
4121      m_normals[k].X * m_normals[j].X + m_normals[k].Y * m_normals[j].Y) / 4);
4122  m_destPoly.push_back(IntPoint(
4123      Round(m_srcPoly[j].X + m_delta * (m_normals[k].X - m_normals[k].Y * dx)),
4124      Round(m_srcPoly[j].Y + m_delta * (m_normals[k].Y + m_normals[k].X * dx))));
4125  m_destPoly.push_back(IntPoint(
4126      Round(m_srcPoly[j].X + m_delta * (m_normals[j].X + m_normals[j].Y * dx)),
4127      Round(m_srcPoly[j].Y + m_delta * (m_normals[j].Y - m_normals[j].X * dx))));
4128}
4129//------------------------------------------------------------------------------
4130
4131void ClipperOffset::DoMiter(int j, int k, double r)
4132{
4133  double q = m_delta / r;
4134  m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + (m_normals[k].X + m_normals[j].X) * q),
4135      Round(m_srcPoly[j].Y + (m_normals[k].Y + m_normals[j].Y) * q)));
4136}
4137//------------------------------------------------------------------------------
4138
4139void ClipperOffset::DoRound(int j, int k)
4140{
4141  double a = std::atan2(m_sinA,
4142  m_normals[k].X * m_normals[j].X + m_normals[k].Y * m_normals[j].Y);
4143  int steps = std::max((int)Round(m_StepsPerRad * std::fabs(a)), 1);
4144
4145  double X = m_normals[k].X, Y = m_normals[k].Y, X2;
4146  for (int i = 0; i < steps; ++i)
4147  {
4148    m_destPoly.push_back(IntPoint(
4149        Round(m_srcPoly[j].X + X * m_delta),
4150        Round(m_srcPoly[j].Y + Y * m_delta)));
4151    X2 = X;
4152    X = X * m_cos - m_sin * Y;
4153    Y = X2 * m_sin + Y * m_cos;
4154  }
4155  m_destPoly.push_back(IntPoint(
4156  Round(m_srcPoly[j].X + m_normals[j].X * m_delta),
4157  Round(m_srcPoly[j].Y + m_normals[j].Y * m_delta)));
4158}
4159
4160//------------------------------------------------------------------------------
4161// Miscellaneous public functions
4162//------------------------------------------------------------------------------
4163
4164void Clipper::DoSimplePolygons()
4165{
4166  PolyOutList::size_type i = 0;
4167  while (i < m_PolyOuts.size()) 
4168  {
4169    OutRec* outrec = m_PolyOuts[i++];
4170    OutPt* op = outrec->Pts;
4171    if (!op || outrec->IsOpen) continue;
4172    do //for each Pt in Polygon until duplicate found do ...
4173    {
4174      OutPt* op2 = op->Next;
4175      while (op2 != outrec->Pts) 
4176      {
4177        if ((op->Pt == op2->Pt) && op2->Next != op && op2->Prev != op) 
4178        {
4179          //split the polygon into two ...
4180          OutPt* op3 = op->Prev;
4181          OutPt* op4 = op2->Prev;
4182          op->Prev = op4;
4183          op4->Next = op;
4184          op2->Prev = op3;
4185          op3->Next = op2;
4186
4187          outrec->Pts = op;
4188          OutRec* outrec2 = CreateOutRec();
4189          outrec2->Pts = op2;
4190          UpdateOutPtIdxs(*outrec2);
4191          if (Poly2ContainsPoly1(outrec2->Pts, outrec->Pts))
4192          {
4193            //OutRec2 is contained by OutRec1 ...
4194            outrec2->IsHole = !outrec->IsHole;
4195            outrec2->FirstLeft = outrec;
4196            if (m_UsingPolyTree) FixupFirstLefts2(outrec2, outrec);
4197          }
4198          else
4199            if (Poly2ContainsPoly1(outrec->Pts, outrec2->Pts))
4200          {
4201            //OutRec1 is contained by OutRec2 ...
4202            outrec2->IsHole = outrec->IsHole;
4203            outrec->IsHole = !outrec2->IsHole;
4204            outrec2->FirstLeft = outrec->FirstLeft;
4205            outrec->FirstLeft = outrec2;
4206            if (m_UsingPolyTree) FixupFirstLefts2(outrec, outrec2);
4207            }
4208            else
4209          {
4210            //the 2 polygons are separate ...
4211            outrec2->IsHole = outrec->IsHole;
4212            outrec2->FirstLeft = outrec->FirstLeft;
4213            if (m_UsingPolyTree) FixupFirstLefts1(outrec, outrec2);
4214            }
4215          op2 = op; //ie get ready for the Next iteration
4216        }
4217        op2 = op2->Next;
4218      }
4219      op = op->Next;
4220    }
4221    while (op != outrec->Pts);
4222  }
4223}
4224//------------------------------------------------------------------------------
4225
4226void ReversePath(Path& p)
4227{
4228  std::reverse(p.begin(), p.end());
4229}
4230//------------------------------------------------------------------------------
4231
4232void ReversePaths(Paths& p)
4233{
4234  for (Paths::size_type i = 0; i < p.size(); ++i)
4235    ReversePath(p[i]);
4236}
4237//------------------------------------------------------------------------------
4238
4239void SimplifyPolygon(const Path &in_poly, Paths &out_polys, PolyFillType fillType)
4240{
4241  Clipper c;
4242  c.StrictlySimple(true);
4243  c.AddPath(in_poly, ptSubject, true);
4244  c.Execute(ctUnion, out_polys, fillType, fillType);
4245}
4246//------------------------------------------------------------------------------
4247
4248void SimplifyPolygons(const Paths &in_polys, Paths &out_polys, PolyFillType fillType)
4249{
4250  Clipper c;
4251  c.StrictlySimple(true);
4252  c.AddPaths(in_polys, ptSubject, true);
4253  c.Execute(ctUnion, out_polys, fillType, fillType);
4254}
4255//------------------------------------------------------------------------------
4256
4257void SimplifyPolygons(Paths &polys, PolyFillType fillType)
4258{
4259  SimplifyPolygons(polys, polys, fillType);
4260}
4261//------------------------------------------------------------------------------
4262
4263inline double DistanceSqrd(const IntPoint& pt1, const IntPoint& pt2)
4264{
4265  double Dx = ((double)pt1.X - pt2.X);
4266  double dy = ((double)pt1.Y - pt2.Y);
4267  return (Dx*Dx + dy*dy);
4268}
4269//------------------------------------------------------------------------------
4270
4271double DistanceFromLineSqrd(
4272  const IntPoint& pt, const IntPoint& ln1, const IntPoint& ln2)
4273{
4274  //The equation of a line in general form (Ax + By + C = 0)
4275  //given 2 points (x¹,y¹) & (x²,y²) is ...
4276  //(y¹ - y²)x + (x² - x¹)y + (y² - y¹)x¹ - (x² - x¹)y¹ = 0
4277  //A = (y¹ - y²); B = (x² - x¹); C = (y² - y¹)x¹ - (x² - x¹)y¹
4278  //perpendicular distance of point (x³,y³) = (Ax³ + By³ + C)/Sqrt(A² + B²)
4279  //see http://en.wikipedia.org/wiki/Perpendicular_distance
4280  double A = double(ln1.Y - ln2.Y);
4281  double B = double(ln2.X - ln1.X);
4282  double C = A * ln1.+ B * ln1.Y;
4283  C = A * pt.X + B * pt.Y - C;
4284  return (C * C) / (A * A + B * B);
4285}
4286//---------------------------------------------------------------------------
4287
4288bool SlopesNearCollinear(const IntPoint& pt1, 
4289    const IntPoint& pt2, const IntPoint& pt3, double distSqrd)
4290{
4291  //this function is more accurate when the point that's geometrically
4292  //between the other 2 points is the one that's tested for distance.
4293  //ie makes it more likely to pick up 'spikes' ...
4294        if (Abs(pt1.X - pt2.X) > Abs(pt1.Y - pt2.Y))
4295        {
4296    if ((pt1.X > pt2.X) == (pt1.X < pt3.X))
4297      return DistanceFromLineSqrd(pt1, pt2, pt3) < distSqrd;
4298    else if ((pt2.X > pt1.X) == (pt2.X < pt3.X))
4299      return DistanceFromLineSqrd(pt2, pt1, pt3) < distSqrd;
4300                else
4301            return DistanceFromLineSqrd(pt3, pt1, pt2) < distSqrd;
4302        }
4303        else
4304        {
4305    if ((pt1.Y > pt2.Y) == (pt1.Y < pt3.Y))
4306      return DistanceFromLineSqrd(pt1, pt2, pt3) < distSqrd;
4307    else if ((pt2.Y > pt1.Y) == (pt2.Y < pt3.Y))
4308      return DistanceFromLineSqrd(pt2, pt1, pt3) < distSqrd;
4309                else
4310      return DistanceFromLineSqrd(pt3, pt1, pt2) < distSqrd;
4311        }
4312}
4313//------------------------------------------------------------------------------
4314
4315bool PointsAreClose(IntPoint pt1, IntPoint pt2, double distSqrd)
4316{
4317    double Dx = (double)pt1.X - pt2.X;
4318    double dy = (double)pt1.Y - pt2.Y;
4319    return ((Dx * Dx) + (dy * dy) <= distSqrd);
4320}
4321//------------------------------------------------------------------------------
4322
4323OutPt* ExcludeOp(OutPt* op)
4324{
4325  OutPt* result = op->Prev;
4326  result->Next = op->Next;
4327  op->Next->Prev = result;
4328  result->Idx = 0;
4329  return result;
4330}
4331//------------------------------------------------------------------------------
4332
4333void CleanPolygon(const Path& in_poly, Path& out_poly, double distance)
4334{
4335  //distance = proximity in units/pixels below which vertices
4336  //will be stripped. Default ~= sqrt(2).
4337 
4338  size_t size = in_poly.size();
4339 
4340  if (size == 0) 
4341  {
4342    out_poly.clear();
4343    return;
4344  }
4345
4346  OutPt* outPts = new OutPt[size];
4347  for (size_t i = 0; i < size; ++i)
4348  {
4349    outPts[i].Pt = in_poly[i];
4350    outPts[i].Next = &outPts[(i + 1) % size];
4351    outPts[i].Next->Prev = &outPts[i];
4352    outPts[i].Idx = 0;
4353  }
4354
4355  double distSqrd = distance * distance;
4356  OutPt* op = &outPts[0];
4357  while (op->Idx == 0 && op->Next != op->Prev) 
4358  {
4359    if (PointsAreClose(op->Pt, op->Prev->Pt, distSqrd))
4360    {
4361      op = ExcludeOp(op);
4362      size--;
4363    } 
4364    else if (PointsAreClose(op->Prev->Pt, op->Next->Pt, distSqrd))
4365    {
4366      ExcludeOp(op->Next);
4367      op = ExcludeOp(op);
4368      size -= 2;
4369    }
4370    else if (SlopesNearCollinear(op->Prev->Pt, op->Pt, op->Next->Pt, distSqrd))
4371    {
4372      op = ExcludeOp(op);
4373      size--;
4374    }
4375    else
4376    {
4377      op->Idx = 1;
4378      op = op->Next;
4379    }
4380  }
4381
4382  if (size < 3) size = 0;
4383  out_poly.resize(size);
4384  for (size_t i = 0; i < size; ++i)
4385  {
4386    out_poly[i] = op->Pt;
4387    op = op->Next;
4388  }
4389  delete [] outPts;
4390}
4391//------------------------------------------------------------------------------
4392
4393void CleanPolygon(Path& poly, double distance)
4394{
4395  CleanPolygon(poly, poly, distance);
4396}
4397//------------------------------------------------------------------------------
4398
4399void CleanPolygons(const Paths& in_polys, Paths& out_polys, double distance)
4400{
4401  for (Paths::size_type i = 0; i < in_polys.size(); ++i)
4402    CleanPolygon(in_polys[i], out_polys[i], distance);
4403}
4404//------------------------------------------------------------------------------
4405
4406void CleanPolygons(Paths& polys, double distance)
4407{
4408  CleanPolygons(polys, polys, distance);
4409}
4410//------------------------------------------------------------------------------
4411
4412void Minkowski(const Path& poly, const Path& path, 
4413  Paths& solution, bool isSum, bool isClosed)
4414{
4415  int delta = (isClosed ? 1 : 0);
4416  size_t polyCnt = poly.size();
4417  size_t pathCnt = path.size();
4418  Paths pp;
4419  pp.reserve(pathCnt);
4420  if (isSum)
4421    for (size_t i = 0; i < pathCnt; ++i)
4422    {
4423      Path p;
4424      p.reserve(polyCnt);
4425      for (size_t j = 0; j < poly.size(); ++j)
4426        p.push_back(IntPoint(path[i].X + poly[j].X, path[i].Y + poly[j].Y));
4427      pp.push_back(p);
4428    }
4429  else
4430    for (size_t i = 0; i < pathCnt; ++i)
4431    {
4432      Path p;
4433      p.reserve(polyCnt);
4434      for (size_t j = 0; j < poly.size(); ++j)
4435        p.push_back(IntPoint(path[i].X - poly[j].X, path[i].Y - poly[j].Y));
4436      pp.push_back(p);
4437    }
4438
4439  solution.clear();
4440  solution.reserve((pathCnt + delta) * (polyCnt + 1));
4441  for (size_t i = 0; i < pathCnt - 1 + delta; ++i)
4442    for (size_t j = 0; j < polyCnt; ++j)
4443    {
4444      Path quad;
4445      quad.reserve(4);
4446      quad.push_back(pp[i % pathCnt][j % polyCnt]);
4447      quad.push_back(pp[(i + 1) % pathCnt][j % polyCnt]);
4448      quad.push_back(pp[(i + 1) % pathCnt][(j + 1) % polyCnt]);
4449      quad.push_back(pp[i % pathCnt][(j + 1) % polyCnt]);
4450      if (!Orientation(quad)) ReversePath(quad);
4451      solution.push_back(quad);
4452    }
4453}
4454//------------------------------------------------------------------------------
4455
4456void MinkowskiSum(const Path& pattern, const Path& path, Paths& solution, bool pathIsClosed)
4457{
4458  Minkowski(pattern, path, solution, true, pathIsClosed);
4459  Clipper c;
4460  c.AddPaths(solution, ptSubject, true);
4461  c.Execute(ctUnion, solution, pftNonZero, pftNonZero);
4462}
4463//------------------------------------------------------------------------------
4464
4465void TranslatePath(const Path& input, Path& output, const IntPoint delta)
4466{
4467  //precondition: input != output
4468  output.resize(input.size());
4469  for (size_t i = 0; i < input.size(); ++i)
4470    output[i] = IntPoint(input[i].X + delta.X, input[i].Y + delta.Y);
4471}
4472//------------------------------------------------------------------------------
4473
4474void MinkowskiSum(const Path& pattern, const Paths& paths, Paths& solution, bool pathIsClosed)
4475{
4476  Clipper c;
4477  for (size_t i = 0; i < paths.size(); ++i)
4478  {
4479    Paths tmp;
4480    Minkowski(pattern, paths[i], tmp, true, pathIsClosed);
4481    c.AddPaths(tmp, ptSubject, true);
4482    if (pathIsClosed)
4483    {
4484      Path tmp2;
4485      TranslatePath(paths[i], tmp2, pattern[0]);
4486      c.AddPath(tmp2, ptClip, true);
4487    }
4488  }
4489    c.Execute(ctUnion, solution, pftNonZero, pftNonZero);
4490}
4491//------------------------------------------------------------------------------
4492
4493void MinkowskiDiff(const Path& poly1, const Path& poly2, Paths& solution)
4494{
4495  Minkowski(poly1, poly2, solution, false, true);
4496  Clipper c;
4497  c.AddPaths(solution, ptSubject, true);
4498  c.Execute(ctUnion, solution, pftNonZero, pftNonZero);
4499}
4500//------------------------------------------------------------------------------
4501
4502enum NodeType {ntAny, ntOpen, ntClosed};
4503
4504void AddPolyNodeToPaths(const PolyNode& polynode, NodeType nodetype, Paths& paths)
4505{
4506  bool match = true;
4507  if (nodetype == ntClosed) match = !polynode.IsOpen();
4508  else if (nodetype == ntOpen) return;
4509
4510  if (!polynode.Contour.empty() && match)
4511    paths.push_back(polynode.Contour);
4512  for (int i = 0; i < polynode.ChildCount(); ++i)
4513    AddPolyNodeToPaths(*polynode.Childs[i], nodetype, paths);
4514}
4515//------------------------------------------------------------------------------
4516
4517void PolyTreeToPaths(const PolyTree& polytree, Paths& paths)
4518{
4519  paths.resize(0); 
4520  paths.reserve(polytree.Total());
4521  AddPolyNodeToPaths(polytree, ntAny, paths);
4522}
4523//------------------------------------------------------------------------------
4524
4525void ClosedPathsFromPolyTree(const PolyTree& polytree, Paths& paths)
4526{
4527  paths.resize(0); 
4528  paths.reserve(polytree.Total());
4529  AddPolyNodeToPaths(polytree, ntClosed, paths);
4530}
4531//------------------------------------------------------------------------------
4532
4533void OpenPathsFromPolyTree(PolyTree& polytree, Paths& paths)
4534{
4535  paths.resize(0); 
4536  paths.reserve(polytree.Total());
4537  //Open paths are top level only, so ...
4538  for (int i = 0; i < polytree.ChildCount(); ++i)
4539    if (polytree.Childs[i]->IsOpen())
4540      paths.push_back(polytree.Childs[i]->Contour);
4541}
4542//------------------------------------------------------------------------------
4543
4544std::ostream& operator <<(std::ostream &s, const IntPoint &p)
4545{
4546  s << "(" << p.X << "," << p.Y << ")";
4547  return s;
4548}
4549//------------------------------------------------------------------------------
4550
4551std::ostream& operator <<(std::ostream &s, const Path &p)
4552{
4553  if (p.empty()) return s;
4554  Path::size_type last = p.size() -1;
4555  for (Path::size_type i = 0; i < last; i++)
4556    s << "(" << p[i].X << "," << p[i].Y << "), ";
4557  s << "(" << p[last].X << "," << p[last].Y << ")\n";
4558  return s;
4559}
4560//------------------------------------------------------------------------------
4561
4562std::ostream& operator <<(std::ostream &s, const Paths &p)
4563{
4564  for (Paths::size_type i = 0; i < p.size(); i++)
4565    s << p[i];
4566  s << "\n";
4567  return s;
4568}
4569//------------------------------------------------------------------------------
4570
4571} //ClipperLib namespace
Note: See TracBrowser for help on using the repository browser.