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