source: XIOS/dev/branch_yushan/extern/remap/src/clipper.cpp @ 1085

Last change on this file since 1085 was 1073, checked in by yushan, 7 years ago

add test_omp ; Using threads : modif for context_initialize

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