clipper.cpp 134 KB

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