Clipper.cs 185 KB

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