clipper.cs 164 KB

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