Ingen beskrivning
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Clipper.cs 187KB

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